test262-runner.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832
  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 <fcntl.h>
  26. #include <signal.h>
  27. #include <unistd.h>
  28. #if !defined(AK_OS_MACOS) && !defined(AK_OS_EMSCRIPTEN) && !defined(AK_OS_GNU_HURD)
  29. // Only used to disable core dumps
  30. # include <sys/prctl.h>
  31. #endif
  32. static ByteString s_current_test = "";
  33. static bool s_parse_only = false;
  34. static ByteString 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. ByteString type;
  45. ByteString details;
  46. ByteString 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_byte_string(),
  58. ""
  59. };
  60. }
  61. return ScriptOrModuleProgram { script_or_error.release_value() };
  62. }
  63. static Result<ScriptOrModuleProgram, TestError> parse_program(JS::Realm& realm, StringView source, StringView filepath, JS::Program::Type program_type)
  64. {
  65. if (program_type == JS::Program::Type::Script)
  66. return parse_program<JS::Script>(realm, source, filepath);
  67. return parse_program<JS::SourceTextModule>(realm, source, filepath);
  68. }
  69. template<typename InterpreterT>
  70. static Result<void, TestError> run_program(InterpreterT& interpreter, ScriptOrModuleProgram& program)
  71. {
  72. auto result = program.visit(
  73. [&](auto& visitor) {
  74. return interpreter.run(*visitor);
  75. });
  76. if (result.is_error()) {
  77. auto error_value = *result.throw_completion().value();
  78. TestError error;
  79. error.phase = NegativePhase::Runtime;
  80. if (error_value.is_object()) {
  81. auto& object = error_value.as_object();
  82. auto name = object.get_without_side_effects("name");
  83. if (!name.is_empty() && !name.is_accessor()) {
  84. error.type = name.to_string_without_side_effects().to_byte_string();
  85. } else {
  86. auto constructor = object.get_without_side_effects("constructor");
  87. if (constructor.is_object()) {
  88. name = constructor.as_object().get_without_side_effects("name");
  89. if (!name.is_undefined())
  90. error.type = name.to_string_without_side_effects().to_byte_string();
  91. }
  92. }
  93. auto message = object.get_without_side_effects("message");
  94. if (!message.is_empty() && !message.is_accessor())
  95. error.details = message.to_string_without_side_effects().to_byte_string();
  96. }
  97. if (error.type.is_empty())
  98. error.type = error_value.to_string_without_side_effects().to_byte_string();
  99. return error;
  100. }
  101. return {};
  102. }
  103. static HashMap<ByteString, ByteString> s_cached_harness_files;
  104. static Result<StringView, TestError> read_harness_file(StringView harness_file)
  105. {
  106. auto cache = s_cached_harness_files.find(harness_file);
  107. if (cache == s_cached_harness_files.end()) {
  108. auto file_or_error = Core::File::open(ByteString::formatted("{}{}", s_harness_file_directory, harness_file), Core::File::OpenMode::Read);
  109. if (file_or_error.is_error()) {
  110. return TestError {
  111. NegativePhase::Harness,
  112. "filesystem",
  113. ByteString::formatted("Could not open file: {}", harness_file),
  114. harness_file
  115. };
  116. }
  117. auto contents_or_error = file_or_error.value()->read_until_eof();
  118. if (contents_or_error.is_error()) {
  119. return TestError {
  120. NegativePhase::Harness,
  121. "filesystem",
  122. ByteString::formatted("Could not read file: {}", harness_file),
  123. harness_file
  124. };
  125. }
  126. StringView contents_view = contents_or_error.value();
  127. s_cached_harness_files.set(harness_file, contents_view.to_byte_string());
  128. cache = s_cached_harness_files.find(harness_file);
  129. VERIFY(cache != s_cached_harness_files.end());
  130. }
  131. return cache->value.view();
  132. }
  133. static Result<JS::NonnullGCPtr<JS::Script>, TestError> parse_harness_files(JS::Realm& realm, StringView harness_file)
  134. {
  135. auto source_or_error = read_harness_file(harness_file);
  136. if (source_or_error.is_error())
  137. return source_or_error.release_error();
  138. auto program_or_error = parse_program<JS::Script>(realm, source_or_error.value(), harness_file);
  139. if (program_or_error.is_error()) {
  140. return TestError {
  141. NegativePhase::Harness,
  142. program_or_error.error().type,
  143. program_or_error.error().details,
  144. harness_file
  145. };
  146. }
  147. return program_or_error.release_value().get<JS::NonnullGCPtr<JS::Script>>();
  148. }
  149. enum class StrictMode {
  150. Both,
  151. NoStrict,
  152. OnlyStrict
  153. };
  154. enum class SkipTest {
  155. No,
  156. Yes,
  157. };
  158. static constexpr auto sta_harness_file = "sta.js"sv;
  159. static constexpr auto assert_harness_file = "assert.js"sv;
  160. static constexpr auto async_include = "doneprintHandle.js"sv;
  161. struct TestMetadata {
  162. Vector<StringView> harness_files { sta_harness_file, assert_harness_file };
  163. SkipTest skip_test { SkipTest::No };
  164. StrictMode strict_mode { StrictMode::Both };
  165. JS::Program::Type program_type { JS::Program::Type::Script };
  166. bool is_async { false };
  167. bool is_negative { false };
  168. NegativePhase phase { NegativePhase::ParseOrEarly };
  169. StringView type;
  170. };
  171. static Result<void, TestError> run_test(StringView source, StringView filepath, TestMetadata const& metadata)
  172. {
  173. if (s_parse_only || (metadata.is_negative && metadata.phase == NegativePhase::ParseOrEarly && metadata.program_type != JS::Program::Type::Module)) {
  174. // Creating the vm and interpreter is heavy so we just parse directly here.
  175. // We can also skip if we know the test is supposed to fail during parse
  176. // time. Unfortunately the phases of modules are not as clear and thus we
  177. // only do this for scripts. See also the comment at the end of verify_test.
  178. auto parser = JS::Parser(JS::Lexer(source, filepath), metadata.program_type);
  179. auto program_or_error = parser.parse_program();
  180. if (parser.has_errors()) {
  181. return TestError {
  182. NegativePhase::ParseOrEarly,
  183. "SyntaxError",
  184. parser.errors()[0].to_byte_string(),
  185. ""
  186. };
  187. }
  188. return {};
  189. }
  190. auto vm = MUST(JS::VM::create());
  191. vm->set_dynamic_imports_allowed(true);
  192. JS::GCPtr<JS::Realm> realm;
  193. JS::GCPtr<JS::Test262::GlobalObject> global_object;
  194. auto root_execution_context = MUST(JS::Realm::initialize_host_defined_realm(
  195. *vm,
  196. [&](JS::Realm& realm_) -> JS::GlobalObject* {
  197. realm = &realm_;
  198. global_object = vm->heap().allocate_without_realm<JS::Test262::GlobalObject>(realm_);
  199. return global_object;
  200. },
  201. nullptr));
  202. auto program_or_error = parse_program(*realm, source, filepath, metadata.program_type);
  203. if (program_or_error.is_error())
  204. return program_or_error.release_error();
  205. for (auto& harness_file : metadata.harness_files) {
  206. auto harness_program_or_error = parse_harness_files(*realm, harness_file);
  207. if (harness_program_or_error.is_error())
  208. return harness_program_or_error.release_error();
  209. ScriptOrModuleProgram harness_program { harness_program_or_error.release_value() };
  210. auto result = run_program(vm->bytecode_interpreter(), harness_program);
  211. if (result.is_error()) {
  212. return TestError {
  213. NegativePhase::Harness,
  214. result.error().type,
  215. result.error().details,
  216. harness_file
  217. };
  218. }
  219. }
  220. return run_program(vm->bytecode_interpreter(), program_or_error.value());
  221. }
  222. static Result<TestMetadata, ByteString> extract_metadata(StringView source)
  223. {
  224. auto lines = source.lines();
  225. TestMetadata metadata;
  226. bool parsing_negative = false;
  227. ByteString failed_message;
  228. auto parse_list = [&](StringView line) {
  229. auto start = line.find('[');
  230. if (!start.has_value())
  231. return Vector<StringView> {};
  232. Vector<StringView> items;
  233. auto end = line.find_last(']');
  234. if (!end.has_value() || end.value() <= start.value()) {
  235. failed_message = ByteString::formatted("Can't parse list in '{}'", line);
  236. return items;
  237. }
  238. auto list = line.substring_view(start.value() + 1, end.value() - start.value() - 1);
  239. for (auto const& item : list.split_view(","sv))
  240. items.append(item.trim_whitespace(TrimMode::Both));
  241. return items;
  242. };
  243. auto second_word = [&](StringView line) {
  244. auto separator = line.find(' ');
  245. if (!separator.has_value() || separator.value() >= (line.length() - 1u)) {
  246. failed_message = ByteString::formatted("Can't parse value after space in '{}'", line);
  247. return ""sv;
  248. }
  249. return line.substring_view(separator.value() + 1);
  250. };
  251. Vector<StringView> include_list;
  252. bool parsing_includes_list = false;
  253. bool has_phase = false;
  254. for (auto raw_line : lines) {
  255. if (!failed_message.is_empty())
  256. break;
  257. if (raw_line.starts_with("---*/"sv)) {
  258. if (parsing_includes_list) {
  259. for (auto& file : include_list)
  260. metadata.harness_files.append(file);
  261. }
  262. return metadata;
  263. }
  264. auto line = raw_line.trim_whitespace();
  265. if (parsing_includes_list) {
  266. if (line.starts_with('-')) {
  267. include_list.append(second_word(line));
  268. continue;
  269. } else {
  270. if (include_list.is_empty()) {
  271. failed_message = "Supposed to parse a list but found no entries";
  272. break;
  273. }
  274. for (auto& file : include_list)
  275. metadata.harness_files.append(file);
  276. include_list.clear();
  277. parsing_includes_list = false;
  278. }
  279. }
  280. if (parsing_negative) {
  281. if (line.starts_with("phase:"sv)) {
  282. auto phase = second_word(line);
  283. has_phase = true;
  284. if (phase == "early"sv || phase == "parse"sv) {
  285. metadata.phase = NegativePhase::ParseOrEarly;
  286. } else if (phase == "resolution"sv) {
  287. metadata.phase = NegativePhase::Resolution;
  288. } else if (phase == "runtime"sv) {
  289. metadata.phase = NegativePhase::Runtime;
  290. } else {
  291. has_phase = false;
  292. failed_message = ByteString::formatted("Unknown negative phase: {}", phase);
  293. break;
  294. }
  295. } else if (line.starts_with("type:"sv)) {
  296. metadata.type = second_word(line);
  297. } else {
  298. if (!has_phase) {
  299. failed_message = "Failed to find phase in negative attributes";
  300. break;
  301. }
  302. if (metadata.type.is_empty()) {
  303. failed_message = "Failed to find type in negative attributes";
  304. break;
  305. }
  306. parsing_negative = false;
  307. }
  308. }
  309. if (line.starts_with("flags:"sv)) {
  310. auto flags = parse_list(line);
  311. for (auto flag : flags) {
  312. if (flag == "raw"sv) {
  313. metadata.strict_mode = StrictMode::NoStrict;
  314. metadata.harness_files.clear();
  315. } else if (flag == "noStrict"sv) {
  316. metadata.strict_mode = StrictMode::NoStrict;
  317. } else if (flag == "onlyStrict"sv) {
  318. metadata.strict_mode = StrictMode::OnlyStrict;
  319. } else if (flag == "module"sv) {
  320. VERIFY(metadata.strict_mode == StrictMode::Both);
  321. metadata.program_type = JS::Program::Type::Module;
  322. metadata.strict_mode = StrictMode::NoStrict;
  323. } else if (flag == "async"sv) {
  324. metadata.harness_files.append(async_include);
  325. metadata.is_async = true;
  326. } else if (flag == "CanBlockIsFalse"sv) {
  327. if (JS::agent_can_suspend())
  328. metadata.skip_test = SkipTest::Yes;
  329. }
  330. }
  331. } else if (line.starts_with("includes:"sv)) {
  332. auto files = parse_list(line);
  333. if (files.is_empty()) {
  334. parsing_includes_list = true;
  335. } else {
  336. for (auto& file : files)
  337. metadata.harness_files.append(file);
  338. }
  339. } else if (line.starts_with("negative:"sv)) {
  340. metadata.is_negative = true;
  341. parsing_negative = true;
  342. }
  343. }
  344. if (failed_message.is_empty())
  345. failed_message = ByteString::formatted("Never reached end of comment '---*/'");
  346. return failed_message;
  347. }
  348. static bool verify_test(Result<void, TestError>& result, TestMetadata const& metadata, JsonObject& output)
  349. {
  350. if (result.is_error()) {
  351. if (result.error().phase == NegativePhase::Harness) {
  352. output.set("harness_error", true);
  353. output.set("harness_file", result.error().harness_file);
  354. output.set("result", "harness_error");
  355. } else if (result.error().phase == NegativePhase::Runtime) {
  356. auto& error_type = result.error().type;
  357. auto& error_details = result.error().details;
  358. if ((error_type == "InternalError"sv && error_details.starts_with("TODO("sv))
  359. || (error_type == "Test262Error"sv && error_details.ends_with(" but got a InternalError"sv))) {
  360. output.set("todo_error", true);
  361. output.set("result", "todo_error");
  362. }
  363. }
  364. }
  365. if (metadata.is_async && output.has("output"sv)) {
  366. auto output_messages = output.get_byte_string("output"sv);
  367. VERIFY(output_messages.has_value());
  368. if (output_messages->contains("AsyncTestFailure:InternalError: TODO("sv)) {
  369. output.set("todo_error", true);
  370. output.set("result", "todo_error");
  371. }
  372. }
  373. auto phase_to_string = [](NegativePhase phase) {
  374. switch (phase) {
  375. case NegativePhase::ParseOrEarly:
  376. return "parse";
  377. case NegativePhase::Resolution:
  378. return "resolution";
  379. case NegativePhase::Runtime:
  380. return "runtime";
  381. case NegativePhase::Harness:
  382. return "harness";
  383. }
  384. VERIFY_NOT_REACHED();
  385. };
  386. auto error_to_json = [&phase_to_string](TestError const& error) {
  387. JsonObject error_object;
  388. error_object.set("phase", phase_to_string(error.phase));
  389. error_object.set("type", error.type);
  390. error_object.set("details", error.details);
  391. return error_object;
  392. };
  393. JsonValue expected_error;
  394. JsonValue got_error;
  395. ScopeGuard set_error = [&] {
  396. JsonObject error_object;
  397. error_object.set("expected", expected_error);
  398. error_object.set("got", got_error);
  399. output.set("error", error_object);
  400. };
  401. if (!metadata.is_negative) {
  402. if (!result.is_error())
  403. return true;
  404. got_error = JsonValue { error_to_json(result.error()) };
  405. return false;
  406. }
  407. JsonObject expected_error_object;
  408. expected_error_object.set("phase", phase_to_string(metadata.phase));
  409. expected_error_object.set("type", metadata.type.to_byte_string());
  410. expected_error = expected_error_object;
  411. if (!result.is_error()) {
  412. if (s_parse_only && metadata.phase != NegativePhase::ParseOrEarly) {
  413. // Expected non-parse error but did not get it but we never got to that phase.
  414. return true;
  415. }
  416. return false;
  417. }
  418. auto const& error = result.error();
  419. got_error = JsonValue { error_to_json(error) };
  420. if (metadata.program_type == JS::Program::Type::Module && metadata.type == "SyntaxError"sv) {
  421. // NOTE: Since the "phase" of negative results is both not defined and hard to
  422. // track throughout the entire Module life span we will just accept any
  423. // SyntaxError as the correct one.
  424. // See for example:
  425. // - test/language/module-code/instn-star-err-not-found.js
  426. // - test/language/module-code/instn-resolve-err-syntax-1.js
  427. // - test/language/import/json-invalid.js
  428. // The first fails in runtime because there is no 'x' to export
  429. // However this is during the linking phase of the upper module.
  430. // Whereas the second fails with a SyntaxError because the linked module
  431. // has one.
  432. // The third test is the same as the second, upper module is fine but
  433. // import a module with SyntaxError, however here the phase is runtime.
  434. // In conclusion all the test which would cause the initial module to not
  435. // be evaluated !should! have '$DONOTEVALUATE();' at the top causing a
  436. // Reference error, meaning we just ignore the phase in the SyntaxError case.
  437. return error.type == metadata.type;
  438. }
  439. return error.phase == metadata.phase && error.type == metadata.type;
  440. }
  441. static bool extract_harness_directory(ByteString const& test_file_path)
  442. {
  443. auto test_directory_index = test_file_path.find("test/"sv);
  444. if (!test_directory_index.has_value()) {
  445. warnln("Attempted to find harness directory from test file '{}', but did not find 'test/'", test_file_path);
  446. return false;
  447. }
  448. s_harness_file_directory = ByteString::formatted("{}harness/", test_file_path.substring_view(0, test_directory_index.value()));
  449. return true;
  450. }
  451. static FILE* saved_stdout_fd;
  452. static bool g_in_assert = false;
  453. [[noreturn]] static void handle_failed_assert(char const* assert_failed_message)
  454. {
  455. if (!g_in_assert) {
  456. // Just in case we trigger an assert while creating the JSON output just
  457. // immediately stop if we are already in a failed assert.
  458. g_in_assert = true;
  459. JsonObject assert_fail_result;
  460. assert_fail_result.set("test", s_current_test);
  461. assert_fail_result.set("assert_fail", true);
  462. assert_fail_result.set("result", "assert_fail");
  463. assert_fail_result.set("output", assert_failed_message);
  464. outln(saved_stdout_fd, "RESULT {}{}", assert_fail_result.to_byte_string(), '\0');
  465. // (Attempt to) Ensure that messages are written before quitting.
  466. fflush(saved_stdout_fd);
  467. fflush(stderr);
  468. }
  469. exit(12);
  470. }
  471. // FIXME: Use a SIGABRT handler here instead of overriding internal libc assertion handlers.
  472. // Fixing this will likely require updating the test driver as well to pull the assertion failure
  473. // message out of stderr rather than from the json object printed to stdout.
  474. // FIXME: This likely doesn't even work with our custom ak_verification_failed handler
  475. #pragma push_macro("NDEBUG")
  476. // Apple headers do not expose the declaration of __assert_rtn when NDEBUG is set.
  477. #undef NDEBUG
  478. #include <assert.h>
  479. #ifdef AK_OS_MACOS
  480. extern "C" __attribute__((__noreturn__)) void __assert_rtn(char const* function, char const* file, int line, char const* assertion)
  481. #elifdef 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. #pragma pop_macro("NDEBUG")
  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. }