test262-runner.cpp 29 KB

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