test262-runner.cpp 30 KB

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