Interpreter.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. /*
  2. * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Debug.h>
  7. #include <AK/TemporaryChange.h>
  8. #include <LibJS/AST.h>
  9. #include <LibJS/Bytecode/BasicBlock.h>
  10. #include <LibJS/Bytecode/Generator.h>
  11. #include <LibJS/Bytecode/Instruction.h>
  12. #include <LibJS/Bytecode/Interpreter.h>
  13. #include <LibJS/Bytecode/Op.h>
  14. #include <LibJS/Interpreter.h>
  15. #include <LibJS/Runtime/GlobalEnvironment.h>
  16. #include <LibJS/Runtime/GlobalObject.h>
  17. #include <LibJS/Runtime/Realm.h>
  18. namespace JS::Bytecode {
  19. static bool s_bytecode_interpreter_enabled = false;
  20. bool Interpreter::enabled()
  21. {
  22. return s_bytecode_interpreter_enabled;
  23. }
  24. void Interpreter::set_enabled(bool enabled)
  25. {
  26. s_bytecode_interpreter_enabled = enabled;
  27. }
  28. bool g_dump_bytecode = false;
  29. Interpreter::Interpreter(VM& vm)
  30. : m_vm(vm)
  31. {
  32. }
  33. Interpreter::~Interpreter()
  34. {
  35. }
  36. void Interpreter::visit_edges(Cell::Visitor& visitor)
  37. {
  38. if (m_return_value.has_value())
  39. visitor.visit(*m_return_value);
  40. if (m_saved_exception.has_value())
  41. visitor.visit(*m_saved_exception);
  42. for (auto& frame : m_call_frames) {
  43. frame.visit([&](auto& value) { value->visit_edges(visitor); });
  44. }
  45. }
  46. // 16.1.6 ScriptEvaluation ( scriptRecord ), https://tc39.es/ecma262/#sec-runtime-semantics-scriptevaluation
  47. ThrowCompletionOr<Value> Interpreter::run(Script& script_record, JS::GCPtr<Environment> lexical_environment_override)
  48. {
  49. auto& vm = this->vm();
  50. // 1. Let globalEnv be scriptRecord.[[Realm]].[[GlobalEnv]].
  51. auto& global_environment = script_record.realm().global_environment();
  52. // 2. Let scriptContext be a new ECMAScript code execution context.
  53. ExecutionContext script_context(vm.heap());
  54. // 3. Set the Function of scriptContext to null.
  55. // NOTE: This was done during execution context construction.
  56. // 4. Set the Realm of scriptContext to scriptRecord.[[Realm]].
  57. script_context.realm = &script_record.realm();
  58. // 5. Set the ScriptOrModule of scriptContext to scriptRecord.
  59. script_context.script_or_module = NonnullGCPtr<Script>(script_record);
  60. // 6. Set the VariableEnvironment of scriptContext to globalEnv.
  61. script_context.variable_environment = &global_environment;
  62. // 7. Set the LexicalEnvironment of scriptContext to globalEnv.
  63. script_context.lexical_environment = &global_environment;
  64. // Non-standard: Override the lexical environment if requested.
  65. if (lexical_environment_override)
  66. script_context.lexical_environment = lexical_environment_override;
  67. // 8. Set the PrivateEnvironment of scriptContext to null.
  68. // NOTE: This isn't in the spec, but we require it.
  69. script_context.is_strict_mode = script_record.parse_node().is_strict_mode();
  70. // FIXME: 9. Suspend the currently running execution context.
  71. // 10. Push scriptContext onto the execution context stack; scriptContext is now the running execution context.
  72. TRY(vm.push_execution_context(script_context, {}));
  73. // 11. Let script be scriptRecord.[[ECMAScriptCode]].
  74. auto& script = script_record.parse_node();
  75. // 12. Let result be Completion(GlobalDeclarationInstantiation(script, globalEnv)).
  76. auto instantiation_result = script.global_declaration_instantiation(vm, global_environment);
  77. Completion result = instantiation_result.is_throw_completion() ? instantiation_result.throw_completion() : normal_completion({});
  78. // 13. If result.[[Type]] is normal, then
  79. if (result.type() == Completion::Type::Normal) {
  80. auto executable_result = JS::Bytecode::Generator::generate(script);
  81. if (executable_result.is_error()) {
  82. if (auto error_string = executable_result.error().to_string(); error_string.is_error())
  83. result = vm.template throw_completion<JS::InternalError>(vm.error_message(JS::VM::ErrorMessage::OutOfMemory));
  84. else if (error_string = String::formatted("TODO({})", error_string.value()); error_string.is_error())
  85. result = vm.template throw_completion<JS::InternalError>(vm.error_message(JS::VM::ErrorMessage::OutOfMemory));
  86. else
  87. result = JS::throw_completion(JS::InternalError::create(realm(), error_string.release_value()));
  88. } else {
  89. auto executable = executable_result.release_value();
  90. if (g_dump_bytecode)
  91. executable->dump();
  92. // a. Set result to the result of evaluating script.
  93. auto result_or_error = run_and_return_frame(script_record.realm(), *executable, nullptr);
  94. if (result_or_error.value.is_error())
  95. result = result_or_error.value.release_error();
  96. else
  97. result = result_or_error.frame->registers[0];
  98. }
  99. }
  100. // 14. If result.[[Type]] is normal and result.[[Value]] is empty, then
  101. if (result.type() == Completion::Type::Normal && !result.value().has_value()) {
  102. // a. Set result to NormalCompletion(undefined).
  103. result = normal_completion(js_undefined());
  104. }
  105. // FIXME: 15. Suspend scriptContext and remove it from the execution context stack.
  106. vm.pop_execution_context();
  107. // 16. Assert: The execution context stack is not empty.
  108. VERIFY(!vm.execution_context_stack().is_empty());
  109. // FIXME: 17. Resume the context that is now on the top of the execution context stack as the running execution context.
  110. // At this point we may have already run any queued promise jobs via on_call_stack_emptied,
  111. // in which case this is a no-op.
  112. // FIXME: These three should be moved out of Interpreter::run and give the host an option to run these, as it's up to the host when these get run.
  113. // https://tc39.es/ecma262/#sec-jobs for jobs and https://tc39.es/ecma262/#_ref_3508 for ClearKeptObjects
  114. // finish_execution_generation is particularly an issue for LibWeb, as the HTML spec wants to run it specifically after performing a microtask checkpoint.
  115. // The promise and registry cleanup queues don't cause LibWeb an issue, as LibWeb overrides the hooks that push onto these queues.
  116. vm.run_queued_promise_jobs();
  117. vm.run_queued_finalization_registry_cleanup_jobs();
  118. vm.finish_execution_generation();
  119. // 18. Return ? result.
  120. if (result.is_abrupt()) {
  121. VERIFY(result.type() == Completion::Type::Throw);
  122. return result.release_error();
  123. }
  124. VERIFY(result.value().has_value());
  125. return *result.value();
  126. }
  127. ThrowCompletionOr<Value> Interpreter::run(SourceTextModule& module)
  128. {
  129. // FIXME: This is not a entry point as defined in the spec, but is convenient.
  130. // To avoid work we use link_and_eval_module however that can already be
  131. // dangerous if the vm loaded other modules.
  132. auto& vm = this->vm();
  133. TRY(vm.link_and_eval_module(Badge<Bytecode::Interpreter> {}, module));
  134. vm.run_queued_promise_jobs();
  135. vm.run_queued_finalization_registry_cleanup_jobs();
  136. return js_undefined();
  137. }
  138. Interpreter::ValueAndFrame Interpreter::run_and_return_frame(Realm& realm, Executable& executable, BasicBlock const* entry_point, CallFrame* in_frame)
  139. {
  140. dbgln_if(JS_BYTECODE_DEBUG, "Bytecode::Interpreter will run unit {:p}", &executable);
  141. TemporaryChange restore_executable { m_current_executable, &executable };
  142. TemporaryChange restore_saved_jump { m_scheduled_jump, static_cast<BasicBlock const*>(nullptr) };
  143. TemporaryChange restore_saved_exception { m_saved_exception, {} };
  144. bool pushed_execution_context = false;
  145. ExecutionContext execution_context(vm().heap());
  146. if (vm().execution_context_stack().is_empty() || !vm().running_execution_context().lexical_environment) {
  147. // The "normal" interpreter pushes an execution context without environment so in that case we also want to push one.
  148. execution_context.this_value = &realm.global_object();
  149. static DeprecatedFlyString global_execution_context_name = "(*BC* global execution context)";
  150. execution_context.function_name = global_execution_context_name;
  151. execution_context.lexical_environment = &realm.global_environment();
  152. execution_context.variable_environment = &realm.global_environment();
  153. execution_context.realm = realm;
  154. execution_context.is_strict_mode = executable.is_strict_mode;
  155. vm().push_execution_context(execution_context);
  156. pushed_execution_context = true;
  157. }
  158. TemporaryChange restore_current_block { m_current_block, entry_point ?: executable.basic_blocks.first() };
  159. if (in_frame)
  160. push_call_frame(in_frame, executable.number_of_registers);
  161. else
  162. push_call_frame(make<CallFrame>(), executable.number_of_registers);
  163. TemporaryChange restore_this_value { m_this_value, {} };
  164. for (;;) {
  165. Bytecode::InstructionStreamIterator pc(m_current_block->instruction_stream());
  166. TemporaryChange temp_change { m_pc, &pc };
  167. // FIXME: This is getting kinda spaghetti-y
  168. bool will_jump = false;
  169. bool will_return = false;
  170. bool will_yield = false;
  171. while (!pc.at_end()) {
  172. auto& instruction = *pc;
  173. auto ran_or_error = instruction.execute(*this);
  174. if (ran_or_error.is_error()) {
  175. auto exception_value = *ran_or_error.throw_completion().value();
  176. m_saved_exception = exception_value;
  177. if (unwind_contexts().is_empty())
  178. break;
  179. auto& unwind_context = unwind_contexts().last();
  180. if (unwind_context.executable != m_current_executable)
  181. break;
  182. if (unwind_context.handler && !unwind_context.handler_called) {
  183. vm().running_execution_context().lexical_environment = unwind_context.lexical_environment;
  184. m_current_block = unwind_context.handler;
  185. unwind_context.handler_called = true;
  186. accumulator() = exception_value;
  187. m_saved_exception = {};
  188. will_jump = true;
  189. break;
  190. }
  191. if (unwind_context.finalizer) {
  192. m_current_block = unwind_context.finalizer;
  193. // If an exception was thrown inside the corresponding `catch` block, we need to rethrow it
  194. // from the `finally` block. But if the exception is from the `try` block, and has already been
  195. // handled by `catch`, we swallow it.
  196. if (!unwind_context.handler_called)
  197. m_saved_exception = {};
  198. will_jump = true;
  199. break;
  200. }
  201. // An unwind context with no handler or finalizer? We have nowhere to jump, and continuing on will make us crash on the next `Call` to a non-native function if there's an exception! So let's crash here instead.
  202. // If you run into this, you probably forgot to remove the current unwind_context somewhere.
  203. VERIFY_NOT_REACHED();
  204. }
  205. if (m_pending_jump.has_value()) {
  206. m_current_block = m_pending_jump.release_value();
  207. will_jump = true;
  208. break;
  209. }
  210. if (m_return_value.has_value()) {
  211. will_return = true;
  212. // Note: A `yield` statement will not go through a finally statement,
  213. // hence we need to set a flag to not do so,
  214. // but we generate a Yield Operation in the case of returns in
  215. // generators as well, so we need to check if it will actually
  216. // continue or is a `return` in disguise
  217. will_yield = (instruction.type() == Instruction::Type::Yield && static_cast<Op::Yield const&>(instruction).continuation().has_value()) || instruction.type() == Instruction::Type::Await;
  218. break;
  219. }
  220. ++pc;
  221. }
  222. if (will_jump)
  223. continue;
  224. if (!unwind_contexts().is_empty() && !will_yield) {
  225. auto& unwind_context = unwind_contexts().last();
  226. if (unwind_context.executable == m_current_executable && unwind_context.finalizer) {
  227. reg(Register::saved_return_value()) = m_return_value.release_value();
  228. m_current_block = unwind_context.finalizer;
  229. // the unwind_context will be pop'ed when entering the finally block
  230. continue;
  231. }
  232. }
  233. if (pc.at_end())
  234. break;
  235. if (m_saved_exception.has_value())
  236. break;
  237. if (will_return)
  238. break;
  239. }
  240. dbgln_if(JS_BYTECODE_DEBUG, "Bytecode::Interpreter did run unit {:p}", &executable);
  241. if constexpr (JS_BYTECODE_DEBUG) {
  242. for (size_t i = 0; i < registers().size(); ++i) {
  243. String value_string;
  244. if (registers()[i].is_empty())
  245. value_string = MUST("(empty)"_string);
  246. else
  247. value_string = MUST(registers()[i].to_string_without_side_effects());
  248. dbgln("[{:3}] {}", i, value_string);
  249. }
  250. }
  251. auto saved_return_value = reg(Register::saved_return_value());
  252. auto frame = pop_call_frame();
  253. Value return_value = js_undefined();
  254. if (m_return_value.has_value()) {
  255. return_value = m_return_value.release_value();
  256. } else if (!saved_return_value.is_empty()) {
  257. return_value = saved_return_value;
  258. }
  259. // NOTE: The return value from a called function is put into $0 in the caller context.
  260. if (!m_call_frames.is_empty())
  261. call_frame().registers[0] = return_value;
  262. // At this point we may have already run any queued promise jobs via on_call_stack_emptied,
  263. // in which case this is a no-op.
  264. vm().run_queued_promise_jobs();
  265. if (pushed_execution_context) {
  266. VERIFY(&vm().running_execution_context() == &execution_context);
  267. vm().pop_execution_context();
  268. }
  269. vm().finish_execution_generation();
  270. if (m_saved_exception.has_value()) {
  271. Value thrown_value = m_saved_exception.value();
  272. m_saved_exception = {};
  273. if (auto* call_frame = frame.get_pointer<NonnullOwnPtr<CallFrame>>())
  274. return { throw_completion(thrown_value), move(*call_frame) };
  275. return { throw_completion(thrown_value), nullptr };
  276. }
  277. if (auto* call_frame = frame.get_pointer<NonnullOwnPtr<CallFrame>>())
  278. return { return_value, move(*call_frame) };
  279. return { return_value, nullptr };
  280. }
  281. void Interpreter::enter_unwind_context(Optional<Label> handler_target, Optional<Label> finalizer_target)
  282. {
  283. unwind_contexts().empend(
  284. m_current_executable,
  285. handler_target.has_value() ? &handler_target->block() : nullptr,
  286. finalizer_target.has_value() ? &finalizer_target->block() : nullptr,
  287. vm().running_execution_context().lexical_environment);
  288. }
  289. void Interpreter::leave_unwind_context()
  290. {
  291. unwind_contexts().take_last();
  292. }
  293. ThrowCompletionOr<void> Interpreter::continue_pending_unwind(Label const& resume_label)
  294. {
  295. if (m_saved_exception.has_value()) {
  296. return throw_completion(m_saved_exception.release_value());
  297. }
  298. if (!saved_return_value().is_empty()) {
  299. do_return(saved_return_value());
  300. return {};
  301. }
  302. if (m_scheduled_jump) {
  303. // FIXME: If we `break` or `continue` in the finally, we need to clear
  304. // this field
  305. jump(Label { *m_scheduled_jump });
  306. m_scheduled_jump = nullptr;
  307. } else {
  308. jump(resume_label);
  309. }
  310. return {};
  311. }
  312. VM::InterpreterExecutionScope Interpreter::ast_interpreter_scope(Realm& realm)
  313. {
  314. if (!m_ast_interpreter)
  315. m_ast_interpreter = JS::Interpreter::create_with_existing_realm(realm);
  316. return { *m_ast_interpreter };
  317. }
  318. size_t Interpreter::pc() const
  319. {
  320. return m_pc ? m_pc->offset() : 0;
  321. }
  322. DeprecatedString Interpreter::debug_position() const
  323. {
  324. return DeprecatedString::formatted("{}:{:2}:{:4x}", m_current_executable->name, m_current_block->name(), pc());
  325. }
  326. ThrowCompletionOr<NonnullOwnPtr<Bytecode::Executable>> compile(VM& vm, ASTNode const& node, FunctionKind kind, DeprecatedFlyString const& name)
  327. {
  328. auto executable_result = Bytecode::Generator::generate(node, kind);
  329. if (executable_result.is_error())
  330. return vm.throw_completion<InternalError>(ErrorType::NotImplemented, TRY_OR_THROW_OOM(vm, executable_result.error().to_string()));
  331. auto bytecode_executable = executable_result.release_value();
  332. bytecode_executable->name = name;
  333. if (Bytecode::g_dump_bytecode)
  334. bytecode_executable->dump();
  335. return bytecode_executable;
  336. }
  337. Realm& Interpreter::realm()
  338. {
  339. return *m_vm.current_realm();
  340. }
  341. void Interpreter::push_call_frame(Variant<NonnullOwnPtr<CallFrame>, CallFrame*> frame, size_t register_count)
  342. {
  343. m_call_frames.append(move(frame));
  344. this->call_frame().registers.resize(register_count);
  345. m_current_call_frame = this->call_frame().registers;
  346. }
  347. Variant<NonnullOwnPtr<CallFrame>, CallFrame*> Interpreter::pop_call_frame()
  348. {
  349. auto frame = m_call_frames.take_last();
  350. m_current_call_frame = m_call_frames.is_empty() ? Span<Value> {} : this->call_frame().registers;
  351. return frame;
  352. }
  353. }