test262-runner.cpp 29 KB

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