test262-runner.cpp 30 KB

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