test262-runner.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815
  1. /*
  2. * Copyright (c) 2021, Linus Groh <linusg@serenityos.org>
  3. * Copyright (c) 2021-2022, David Tuin <davidot@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/DeprecatedString.h>
  8. #include <AK/Format.h>
  9. #include <AK/JsonObject.h>
  10. #include <AK/Result.h>
  11. #include <AK/ScopeGuard.h>
  12. #include <AK/Vector.h>
  13. #include <LibCore/ArgsParser.h>
  14. #include <LibCore/File.h>
  15. #include <LibJS/Bytecode/BasicBlock.h>
  16. #include <LibJS/Bytecode/Generator.h>
  17. #include <LibJS/Bytecode/Interpreter.h>
  18. #include <LibJS/Contrib/Test262/GlobalObject.h>
  19. #include <LibJS/Parser.h>
  20. #include <LibJS/Runtime/VM.h>
  21. #include <LibJS/Runtime/ValueInlines.h>
  22. #include <LibJS/Script.h>
  23. #include <LibJS/SourceTextModule.h>
  24. #include <fcntl.h>
  25. #include <signal.h>
  26. #include <unistd.h>
  27. #if !defined(AK_OS_MACOS) && !defined(AK_OS_EMSCRIPTEN) && !defined(AK_OS_GNU_HURD)
  28. // Only used to disable core dumps
  29. # include <sys/prctl.h>
  30. #endif
  31. static DeprecatedString s_current_test = "";
  32. static bool s_parse_only = false;
  33. static DeprecatedString s_harness_file_directory;
  34. static bool s_automatic_harness_detection_mode = false;
  35. enum class NegativePhase {
  36. ParseOrEarly,
  37. Resolution,
  38. Runtime,
  39. Harness
  40. };
  41. struct TestError {
  42. NegativePhase phase { NegativePhase::ParseOrEarly };
  43. DeprecatedString type;
  44. DeprecatedString details;
  45. DeprecatedString harness_file;
  46. };
  47. using ScriptOrModuleProgram = Variant<JS::NonnullGCPtr<JS::Script>, JS::NonnullGCPtr<JS::SourceTextModule>>;
  48. template<typename ScriptType>
  49. static Result<ScriptOrModuleProgram, TestError> parse_program(JS::Realm& realm, StringView source, StringView filepath)
  50. {
  51. auto script_or_error = ScriptType::parse(source, realm, filepath);
  52. if (script_or_error.is_error()) {
  53. return TestError {
  54. NegativePhase::ParseOrEarly,
  55. "SyntaxError",
  56. script_or_error.error()[0].to_deprecated_string(),
  57. ""
  58. };
  59. }
  60. return ScriptOrModuleProgram { script_or_error.release_value() };
  61. }
  62. static Result<ScriptOrModuleProgram, TestError> parse_program(JS::Realm& realm, StringView source, StringView filepath, JS::Program::Type program_type)
  63. {
  64. if (program_type == JS::Program::Type::Script)
  65. return parse_program<JS::Script>(realm, source, filepath);
  66. return parse_program<JS::SourceTextModule>(realm, source, filepath);
  67. }
  68. template<typename InterpreterT>
  69. static Result<void, TestError> run_program(InterpreterT& interpreter, ScriptOrModuleProgram& program)
  70. {
  71. auto result = program.visit(
  72. [&](auto& visitor) {
  73. return interpreter.run(*visitor);
  74. });
  75. if (result.is_error()) {
  76. auto error_value = *result.throw_completion().value();
  77. TestError error;
  78. error.phase = NegativePhase::Runtime;
  79. if (error_value.is_object()) {
  80. auto& object = error_value.as_object();
  81. auto name = object.get_without_side_effects("name");
  82. if (!name.is_empty() && !name.is_accessor()) {
  83. error.type = name.to_string_without_side_effects().to_deprecated_string();
  84. } else {
  85. auto constructor = object.get_without_side_effects("constructor");
  86. if (constructor.is_object()) {
  87. name = constructor.as_object().get_without_side_effects("name");
  88. if (!name.is_undefined())
  89. error.type = name.to_string_without_side_effects().to_deprecated_string();
  90. }
  91. }
  92. auto message = object.get_without_side_effects("message");
  93. if (!message.is_empty() && !message.is_accessor())
  94. error.details = message.to_string_without_side_effects().to_deprecated_string();
  95. }
  96. if (error.type.is_empty())
  97. error.type = error_value.to_string_without_side_effects().to_deprecated_string();
  98. return error;
  99. }
  100. return {};
  101. }
  102. static HashMap<DeprecatedString, DeprecatedString> s_cached_harness_files;
  103. static Result<StringView, TestError> read_harness_file(StringView harness_file)
  104. {
  105. auto cache = s_cached_harness_files.find(harness_file);
  106. if (cache == s_cached_harness_files.end()) {
  107. auto file_or_error = Core::File::open(DeprecatedString::formatted("{}{}", s_harness_file_directory, harness_file), Core::File::OpenMode::Read);
  108. if (file_or_error.is_error()) {
  109. return TestError {
  110. NegativePhase::Harness,
  111. "filesystem",
  112. DeprecatedString::formatted("Could not open file: {}", harness_file),
  113. harness_file
  114. };
  115. }
  116. auto contents_or_error = file_or_error.value()->read_until_eof();
  117. if (contents_or_error.is_error()) {
  118. return TestError {
  119. NegativePhase::Harness,
  120. "filesystem",
  121. DeprecatedString::formatted("Could not read file: {}", harness_file),
  122. harness_file
  123. };
  124. }
  125. StringView contents_view = contents_or_error.value();
  126. s_cached_harness_files.set(harness_file, contents_view.to_deprecated_string());
  127. cache = s_cached_harness_files.find(harness_file);
  128. VERIFY(cache != s_cached_harness_files.end());
  129. }
  130. return cache->value.view();
  131. }
  132. static Result<JS::NonnullGCPtr<JS::Script>, TestError> parse_harness_files(JS::Realm& realm, StringView harness_file)
  133. {
  134. auto source_or_error = read_harness_file(harness_file);
  135. if (source_or_error.is_error())
  136. return source_or_error.release_error();
  137. auto program_or_error = parse_program<JS::Script>(realm, source_or_error.value(), harness_file);
  138. if (program_or_error.is_error()) {
  139. return TestError {
  140. NegativePhase::Harness,
  141. program_or_error.error().type,
  142. program_or_error.error().details,
  143. harness_file
  144. };
  145. }
  146. return program_or_error.release_value().get<JS::NonnullGCPtr<JS::Script>>();
  147. }
  148. enum class StrictMode {
  149. Both,
  150. NoStrict,
  151. OnlyStrict
  152. };
  153. static constexpr auto sta_harness_file = "sta.js"sv;
  154. static constexpr auto assert_harness_file = "assert.js"sv;
  155. static constexpr auto async_include = "doneprintHandle.js"sv;
  156. struct TestMetadata {
  157. Vector<StringView> harness_files { sta_harness_file, assert_harness_file };
  158. StrictMode strict_mode { StrictMode::Both };
  159. JS::Program::Type program_type { JS::Program::Type::Script };
  160. bool is_async { false };
  161. bool is_negative { false };
  162. NegativePhase phase { NegativePhase::ParseOrEarly };
  163. StringView type;
  164. };
  165. static Result<void, TestError> run_test(StringView source, StringView filepath, TestMetadata const& metadata)
  166. {
  167. if (s_parse_only || (metadata.is_negative && metadata.phase == NegativePhase::ParseOrEarly && metadata.program_type != JS::Program::Type::Module)) {
  168. // Creating the vm and interpreter is heavy so we just parse directly here.
  169. // We can also skip if we know the test is supposed to fail during parse
  170. // time. Unfortunately the phases of modules are not as clear and thus we
  171. // only do this for scripts. See also the comment at the end of verify_test.
  172. auto parser = JS::Parser(JS::Lexer(source, filepath), metadata.program_type);
  173. auto program_or_error = parser.parse_program();
  174. if (parser.has_errors()) {
  175. return TestError {
  176. NegativePhase::ParseOrEarly,
  177. "SyntaxError",
  178. parser.errors()[0].to_deprecated_string(),
  179. ""
  180. };
  181. }
  182. return {};
  183. }
  184. auto vm = MUST(JS::VM::create());
  185. vm->enable_default_host_import_module_dynamically_hook();
  186. JS::GCPtr<JS::Realm> realm;
  187. JS::GCPtr<JS::Test262::GlobalObject> global_object;
  188. auto root_execution_context = MUST(JS::Realm::initialize_host_defined_realm(
  189. *vm,
  190. [&](JS::Realm& realm_) -> JS::GlobalObject* {
  191. realm = &realm_;
  192. global_object = vm->heap().allocate_without_realm<JS::Test262::GlobalObject>(realm_);
  193. return global_object;
  194. },
  195. nullptr));
  196. auto program_or_error = parse_program(*realm, source, filepath, metadata.program_type);
  197. if (program_or_error.is_error())
  198. return program_or_error.release_error();
  199. for (auto& harness_file : metadata.harness_files) {
  200. auto harness_program_or_error = parse_harness_files(*realm, harness_file);
  201. if (harness_program_or_error.is_error())
  202. return harness_program_or_error.release_error();
  203. ScriptOrModuleProgram harness_program { harness_program_or_error.release_value() };
  204. auto result = run_program(vm->bytecode_interpreter(), harness_program);
  205. if (result.is_error()) {
  206. return TestError {
  207. NegativePhase::Harness,
  208. result.error().type,
  209. result.error().details,
  210. harness_file
  211. };
  212. }
  213. }
  214. return run_program(vm->bytecode_interpreter(), program_or_error.value());
  215. }
  216. static Result<TestMetadata, DeprecatedString> extract_metadata(StringView source)
  217. {
  218. auto lines = source.lines();
  219. TestMetadata metadata;
  220. bool parsing_negative = false;
  221. DeprecatedString failed_message;
  222. auto parse_list = [&](StringView line) {
  223. auto start = line.find('[');
  224. if (!start.has_value())
  225. return Vector<StringView> {};
  226. Vector<StringView> items;
  227. auto end = line.find_last(']');
  228. if (!end.has_value() || end.value() <= start.value()) {
  229. failed_message = DeprecatedString::formatted("Can't parse list in '{}'", line);
  230. return items;
  231. }
  232. auto list = line.substring_view(start.value() + 1, end.value() - start.value() - 1);
  233. for (auto const& item : list.split_view(","sv))
  234. items.append(item.trim_whitespace(TrimMode::Both));
  235. return items;
  236. };
  237. auto second_word = [&](StringView line) {
  238. auto separator = line.find(' ');
  239. if (!separator.has_value() || separator.value() >= (line.length() - 1u)) {
  240. failed_message = DeprecatedString::formatted("Can't parse value after space in '{}'", line);
  241. return ""sv;
  242. }
  243. return line.substring_view(separator.value() + 1);
  244. };
  245. Vector<StringView> include_list;
  246. bool parsing_includes_list = false;
  247. bool has_phase = false;
  248. for (auto raw_line : lines) {
  249. if (!failed_message.is_empty())
  250. break;
  251. if (raw_line.starts_with("---*/"sv)) {
  252. if (parsing_includes_list) {
  253. for (auto& file : include_list)
  254. metadata.harness_files.append(file);
  255. }
  256. return metadata;
  257. }
  258. auto line = raw_line.trim_whitespace();
  259. if (parsing_includes_list) {
  260. if (line.starts_with('-')) {
  261. include_list.append(second_word(line));
  262. continue;
  263. } else {
  264. if (include_list.is_empty()) {
  265. failed_message = "Supposed to parse a list but found no entries";
  266. break;
  267. }
  268. for (auto& file : include_list)
  269. metadata.harness_files.append(file);
  270. include_list.clear();
  271. parsing_includes_list = false;
  272. }
  273. }
  274. if (parsing_negative) {
  275. if (line.starts_with("phase:"sv)) {
  276. auto phase = second_word(line);
  277. has_phase = true;
  278. if (phase == "early"sv || phase == "parse"sv) {
  279. metadata.phase = NegativePhase::ParseOrEarly;
  280. } else if (phase == "resolution"sv) {
  281. metadata.phase = NegativePhase::Resolution;
  282. } else if (phase == "runtime"sv) {
  283. metadata.phase = NegativePhase::Runtime;
  284. } else {
  285. has_phase = false;
  286. failed_message = DeprecatedString::formatted("Unknown negative phase: {}", phase);
  287. break;
  288. }
  289. } else if (line.starts_with("type:"sv)) {
  290. metadata.type = second_word(line);
  291. } else {
  292. if (!has_phase) {
  293. failed_message = "Failed to find phase in negative attributes";
  294. break;
  295. }
  296. if (metadata.type.is_empty()) {
  297. failed_message = "Failed to find type in negative attributes";
  298. break;
  299. }
  300. parsing_negative = false;
  301. }
  302. }
  303. if (line.starts_with("flags:"sv)) {
  304. auto flags = parse_list(line);
  305. for (auto flag : flags) {
  306. if (flag == "raw"sv) {
  307. metadata.strict_mode = StrictMode::NoStrict;
  308. metadata.harness_files.clear();
  309. } else if (flag == "noStrict"sv) {
  310. metadata.strict_mode = StrictMode::NoStrict;
  311. } else if (flag == "onlyStrict"sv) {
  312. metadata.strict_mode = StrictMode::OnlyStrict;
  313. } else if (flag == "module"sv) {
  314. VERIFY(metadata.strict_mode == StrictMode::Both);
  315. metadata.program_type = JS::Program::Type::Module;
  316. metadata.strict_mode = StrictMode::NoStrict;
  317. } else if (flag == "async"sv) {
  318. metadata.harness_files.append(async_include);
  319. metadata.is_async = true;
  320. }
  321. }
  322. } else if (line.starts_with("includes:"sv)) {
  323. auto files = parse_list(line);
  324. if (files.is_empty()) {
  325. parsing_includes_list = true;
  326. } else {
  327. for (auto& file : files)
  328. metadata.harness_files.append(file);
  329. }
  330. } else if (line.starts_with("negative:"sv)) {
  331. metadata.is_negative = true;
  332. parsing_negative = true;
  333. }
  334. }
  335. if (failed_message.is_empty())
  336. failed_message = DeprecatedString::formatted("Never reached end of comment '---*/'");
  337. return failed_message;
  338. }
  339. static bool verify_test(Result<void, TestError>& result, TestMetadata const& metadata, JsonObject& output)
  340. {
  341. if (result.is_error()) {
  342. if (result.error().phase == NegativePhase::Harness) {
  343. output.set("harness_error", true);
  344. output.set("harness_file", result.error().harness_file);
  345. output.set("result", "harness_error");
  346. } else if (result.error().phase == NegativePhase::Runtime) {
  347. auto& error_type = result.error().type;
  348. auto& error_details = result.error().details;
  349. if ((error_type == "InternalError"sv && error_details.starts_with("TODO("sv))
  350. || (error_type == "Test262Error"sv && error_details.ends_with(" but got a InternalError"sv))) {
  351. output.set("todo_error", true);
  352. output.set("result", "todo_error");
  353. }
  354. }
  355. }
  356. if (metadata.is_async && output.has("output"sv)) {
  357. auto output_messages = output.get_deprecated_string("output"sv);
  358. VERIFY(output_messages.has_value());
  359. if (output_messages->contains("AsyncTestFailure:InternalError: TODO("sv)) {
  360. output.set("todo_error", true);
  361. output.set("result", "todo_error");
  362. }
  363. }
  364. auto phase_to_string = [](NegativePhase phase) {
  365. switch (phase) {
  366. case NegativePhase::ParseOrEarly:
  367. return "parse";
  368. case NegativePhase::Resolution:
  369. return "resolution";
  370. case NegativePhase::Runtime:
  371. return "runtime";
  372. case NegativePhase::Harness:
  373. return "harness";
  374. }
  375. VERIFY_NOT_REACHED();
  376. };
  377. auto error_to_json = [&phase_to_string](TestError const& error) {
  378. JsonObject error_object;
  379. error_object.set("phase", phase_to_string(error.phase));
  380. error_object.set("type", error.type);
  381. error_object.set("details", error.details);
  382. return error_object;
  383. };
  384. JsonValue expected_error;
  385. JsonValue got_error;
  386. ScopeGuard set_error = [&] {
  387. JsonObject error_object;
  388. error_object.set("expected", expected_error);
  389. error_object.set("got", got_error);
  390. output.set("error", error_object);
  391. };
  392. if (!metadata.is_negative) {
  393. if (!result.is_error())
  394. return true;
  395. got_error = JsonValue { error_to_json(result.error()) };
  396. return false;
  397. }
  398. JsonObject expected_error_object;
  399. expected_error_object.set("phase", phase_to_string(metadata.phase));
  400. expected_error_object.set("type", metadata.type.to_deprecated_string());
  401. expected_error = expected_error_object;
  402. if (!result.is_error()) {
  403. if (s_parse_only && metadata.phase != NegativePhase::ParseOrEarly) {
  404. // Expected non-parse error but did not get it but we never got to that phase.
  405. return true;
  406. }
  407. return false;
  408. }
  409. auto const& error = result.error();
  410. got_error = JsonValue { error_to_json(error) };
  411. if (metadata.program_type == JS::Program::Type::Module && metadata.type == "SyntaxError"sv) {
  412. // NOTE: Since the "phase" of negative results is both not defined and hard to
  413. // track throughout the entire Module life span we will just accept any
  414. // SyntaxError as the correct one.
  415. // See for example:
  416. // - test/language/module-code/instn-star-err-not-found.js
  417. // - test/language/module-code/instn-resolve-err-syntax-1.js
  418. // - test/language/import/json-invalid.js
  419. // The first fails in runtime because there is no 'x' to export
  420. // However this is during the linking phase of the upper module.
  421. // Whereas the second fails with a SyntaxError because the linked module
  422. // has one.
  423. // The third test is the same as the second, upper module is fine but
  424. // import a module with SyntaxError, however here the phase is runtime.
  425. // In conclusion all the test which would cause the initial module to not
  426. // be evaluated !should! have '$DONOTEVALUATE();' at the top causing a
  427. // Reference error, meaning we just ignore the phase in the SyntaxError case.
  428. return error.type == metadata.type;
  429. }
  430. return error.phase == metadata.phase && error.type == metadata.type;
  431. }
  432. static bool extract_harness_directory(DeprecatedString const& test_file_path)
  433. {
  434. auto test_directory_index = test_file_path.find("test/"sv);
  435. if (!test_directory_index.has_value()) {
  436. warnln("Attempted to find harness directory from test file '{}', but did not find 'test/'", test_file_path);
  437. return false;
  438. }
  439. s_harness_file_directory = DeprecatedString::formatted("{}harness/", test_file_path.substring_view(0, test_directory_index.value()));
  440. return true;
  441. }
  442. static FILE* saved_stdout_fd;
  443. static bool g_in_assert = false;
  444. [[noreturn]] static void handle_failed_assert(char const* assert_failed_message)
  445. {
  446. if (!g_in_assert) {
  447. // Just in case we trigger an assert while creating the JSON output just
  448. // immediately stop if we are already in a failed assert.
  449. g_in_assert = true;
  450. JsonObject assert_fail_result;
  451. assert_fail_result.set("test", s_current_test);
  452. assert_fail_result.set("assert_fail", true);
  453. assert_fail_result.set("result", "assert_fail");
  454. assert_fail_result.set("output", assert_failed_message);
  455. outln(saved_stdout_fd, "RESULT {}{}", assert_fail_result.to_deprecated_string(), '\0');
  456. // (Attempt to) Ensure that messages are written before quitting.
  457. fflush(saved_stdout_fd);
  458. fflush(stderr);
  459. }
  460. exit(12);
  461. }
  462. // FIXME: Use a SIGABRT handler here instead of overriding internal libc assertion handlers.
  463. // Fixing this will likely require updating the test driver as well to pull the assertion failure
  464. // message out of stderr rather than from the json object printed to stdout.
  465. #ifdef AK_OS_SERENITY
  466. void __assertion_failed(char const* assertion)
  467. {
  468. handle_failed_assert(assertion);
  469. }
  470. #else
  471. # ifdef ASSERT_FAIL_HAS_INT /* Set by CMake */
  472. extern "C" __attribute__((__noreturn__)) void __assert_fail(char const* assertion, char const* file, int line, char const* function)
  473. # else
  474. extern "C" __attribute__((__noreturn__)) void __assert_fail(char const* assertion, char const* file, unsigned int line, char const* function)
  475. # endif
  476. {
  477. auto full_message = DeprecatedString::formatted("{}:{}: {}: Assertion `{}' failed.", file, line, function, assertion);
  478. handle_failed_assert(full_message.characters());
  479. }
  480. #endif
  481. constexpr int exit_wrong_arguments = 2;
  482. constexpr int exit_stdout_setup_failed = 1;
  483. constexpr int exit_setup_input_failure = 7;
  484. constexpr int exit_read_file_failure = 3;
  485. int main(int argc, char** argv)
  486. {
  487. Vector<StringView> arguments;
  488. arguments.ensure_capacity(argc);
  489. for (auto i = 0; i < argc; ++i)
  490. arguments.append({ argv[i], strlen(argv[i]) });
  491. int timeout = 10;
  492. bool enable_debug_printing = false;
  493. bool disable_core_dumping = false;
  494. Core::ArgsParser args_parser;
  495. args_parser.set_general_help("LibJS test262 runner for streaming tests");
  496. args_parser.add_option(s_harness_file_directory, "Directory containing the harness files", "harness-location", 'l', "harness-files");
  497. args_parser.add_option(s_parse_only, "Only parse the files", "parse-only", 'p');
  498. args_parser.add_option(timeout, "Seconds before test should timeout", "timeout", 't', "seconds");
  499. args_parser.add_option(enable_debug_printing, "Enable debug printing", "debug", 'd');
  500. args_parser.add_option(disable_core_dumping, "Disable core dumping", "disable-core-dump", 0);
  501. args_parser.parse(arguments);
  502. #ifdef AK_OS_GNU_HURD
  503. if (disable_core_dumping)
  504. setenv("CRASHSERVER", "/servers/crash-kill", true);
  505. #elif !defined(AK_OS_MACOS) && !defined(AK_OS_EMSCRIPTEN)
  506. if (disable_core_dumping && prctl(PR_SET_DUMPABLE, 0, 0, 0) < 0) {
  507. perror("prctl(PR_SET_DUMPABLE)");
  508. return exit_wrong_arguments;
  509. }
  510. #endif
  511. if (s_harness_file_directory.is_empty()) {
  512. s_automatic_harness_detection_mode = true;
  513. } else if (!s_harness_file_directory.ends_with('/')) {
  514. s_harness_file_directory = DeprecatedString::formatted("{}/", s_harness_file_directory);
  515. }
  516. if (timeout <= 0) {
  517. warnln("timeout must be at least 1");
  518. return exit_wrong_arguments;
  519. }
  520. AK::set_debug_enabled(enable_debug_printing);
  521. // The piping stuff is based on https://stackoverflow.com/a/956269.
  522. constexpr auto BUFFER_SIZE = 1 * KiB;
  523. char buffer[BUFFER_SIZE] = {};
  524. auto saved_stdout = dup(STDOUT_FILENO);
  525. if (saved_stdout < 0) {
  526. perror("dup");
  527. return exit_stdout_setup_failed;
  528. }
  529. saved_stdout_fd = fdopen(saved_stdout, "w");
  530. if (!saved_stdout_fd) {
  531. perror("fdopen");
  532. return exit_stdout_setup_failed;
  533. }
  534. int stdout_pipe[2];
  535. if (pipe(stdout_pipe) < 0) {
  536. perror("pipe");
  537. return exit_stdout_setup_failed;
  538. }
  539. auto flags = fcntl(stdout_pipe[0], F_GETFL);
  540. flags |= O_NONBLOCK;
  541. fcntl(stdout_pipe[0], F_SETFL, flags);
  542. auto flags2 = fcntl(stdout_pipe[1], F_GETFL);
  543. flags2 |= O_NONBLOCK;
  544. fcntl(stdout_pipe[1], F_SETFL, flags2);
  545. if (dup2(stdout_pipe[1], STDOUT_FILENO) < 0) {
  546. perror("dup2");
  547. return exit_stdout_setup_failed;
  548. }
  549. if (close(stdout_pipe[1]) < 0) {
  550. perror("close");
  551. return exit_stdout_setup_failed;
  552. }
  553. auto collect_output = [&] {
  554. fflush(stdout);
  555. auto nread = read(stdout_pipe[0], buffer, BUFFER_SIZE);
  556. Optional<DeprecatedString> value;
  557. if (nread > 0) {
  558. value = DeprecatedString { buffer, static_cast<size_t>(nread) };
  559. while (nread > 0) {
  560. nread = read(stdout_pipe[0], buffer, BUFFER_SIZE);
  561. }
  562. }
  563. return value;
  564. };
  565. #define ARM_TIMER() \
  566. alarm(timeout)
  567. #define DISARM_TIMER() \
  568. alarm(0)
  569. auto standard_input_or_error = Core::File::standard_input();
  570. if (standard_input_or_error.is_error())
  571. return exit_setup_input_failure;
  572. Array<u8, 1024> input_buffer {};
  573. auto buffered_standard_input_or_error = Core::InputBufferedFile::create(standard_input_or_error.release_value());
  574. if (buffered_standard_input_or_error.is_error())
  575. return exit_setup_input_failure;
  576. auto& buffered_input_stream = buffered_standard_input_or_error.value();
  577. size_t count = 0;
  578. while (!buffered_input_stream->is_eof()) {
  579. auto path_or_error = buffered_input_stream->read_line(input_buffer);
  580. if (path_or_error.is_error() || path_or_error.value().is_empty())
  581. continue;
  582. auto& path = path_or_error.value();
  583. s_current_test = path;
  584. if (s_automatic_harness_detection_mode) {
  585. if (!extract_harness_directory(path))
  586. return exit_read_file_failure;
  587. s_automatic_harness_detection_mode = false;
  588. VERIFY(!s_harness_file_directory.is_empty());
  589. }
  590. auto file_or_error = Core::File::open(path, Core::File::OpenMode::Read);
  591. if (file_or_error.is_error()) {
  592. warnln("Could not open file: {}", path);
  593. return exit_read_file_failure;
  594. }
  595. auto& file = file_or_error.value();
  596. count++;
  597. DeprecatedString source_with_strict;
  598. static StringView use_strict = "'use strict';\n"sv;
  599. static size_t strict_length = use_strict.length();
  600. {
  601. auto contents_or_error = file->read_until_eof();
  602. if (contents_or_error.is_error()) {
  603. warnln("Could not read contents of file: {}", path);
  604. return exit_read_file_failure;
  605. }
  606. auto& contents = contents_or_error.value();
  607. StringBuilder builder { contents.size() + strict_length };
  608. builder.append(use_strict);
  609. builder.append(contents);
  610. source_with_strict = builder.to_deprecated_string();
  611. }
  612. StringView with_strict = source_with_strict.view();
  613. StringView original_contents = source_with_strict.substring_view(strict_length);
  614. JsonObject result_object;
  615. result_object.set("test", path);
  616. ScopeGuard output_guard = [&] {
  617. outln(saved_stdout_fd, "RESULT {}{}", result_object.to_deprecated_string(), '\0');
  618. fflush(saved_stdout_fd);
  619. };
  620. auto metadata_or_error = extract_metadata(original_contents);
  621. if (metadata_or_error.is_error()) {
  622. result_object.set("result", "metadata_error");
  623. result_object.set("metadata_error", true);
  624. result_object.set("metadata_output", metadata_or_error.error());
  625. continue;
  626. }
  627. auto& metadata = metadata_or_error.value();
  628. bool passed = true;
  629. if (metadata.strict_mode != StrictMode::OnlyStrict) {
  630. result_object.set("strict_mode", false);
  631. ARM_TIMER();
  632. auto result = run_test(original_contents, path, metadata);
  633. DISARM_TIMER();
  634. auto first_output = collect_output();
  635. if (first_output.has_value())
  636. result_object.set("output", *first_output);
  637. passed = verify_test(result, metadata, result_object);
  638. auto output = first_output.value_or("");
  639. if (metadata.is_async && !s_parse_only) {
  640. if (!output.contains("Test262:AsyncTestComplete"sv) || output.contains("Test262:AsyncTestFailure"sv)) {
  641. result_object.set("async_fail", true);
  642. if (!first_output.has_value())
  643. result_object.set("output", JsonValue { AK::JsonValue::Type::Null });
  644. passed = false;
  645. }
  646. }
  647. }
  648. if (passed && metadata.strict_mode != StrictMode::NoStrict) {
  649. result_object.set("strict_mode", true);
  650. ARM_TIMER();
  651. auto result = run_test(with_strict, path, metadata);
  652. DISARM_TIMER();
  653. auto first_output = collect_output();
  654. if (first_output.has_value())
  655. result_object.set("strict_output", *first_output);
  656. passed = verify_test(result, metadata, result_object);
  657. auto output = first_output.value_or("");
  658. if (metadata.is_async && !s_parse_only) {
  659. if (!output.contains("Test262:AsyncTestComplete"sv) || output.contains("Test262:AsyncTestFailure"sv)) {
  660. result_object.set("async_fail", true);
  661. if (!first_output.has_value())
  662. result_object.set("output", JsonValue { AK::JsonValue::Type::Null });
  663. passed = false;
  664. }
  665. }
  666. }
  667. if (passed)
  668. result_object.remove("strict_mode"sv);
  669. if (!result_object.has("result"sv))
  670. result_object.set("result"sv, passed ? "passed"sv : "failed"sv);
  671. }
  672. s_current_test = "";
  673. outln(saved_stdout_fd, "DONE {}", count);
  674. // After this point we have already written our output so pretend everything is fine if we get an error.
  675. if (dup2(saved_stdout, STDOUT_FILENO) < 0) {
  676. perror("dup2");
  677. return 0;
  678. }
  679. if (fclose(saved_stdout_fd) < 0) {
  680. perror("fclose");
  681. return 0;
  682. }
  683. if (close(stdout_pipe[0]) < 0) {
  684. perror("close");
  685. return 0;
  686. }
  687. return 0;
  688. }