Truly independent web browser
LibJS: Catch exceptions thrown in JIT code without leaving the code
Andreas Kling51edccfde17f
diff --git a/Libraries/LibJS/JIT/ARCHITECTURE.md b/Libraries/LibJS/JIT/ARCHITECTURE.mdindex 74df30e7580..bf346e8913d 100644--- a/Libraries/LibJS/JIT/ARCHITECTURE.md+++ b/Libraries/LibJS/JIT/ARCHITECTURE.md@@ -304,11 +304,16 @@ is compiled like any function's: its `Enter`, and for generators and async gener### 4.2 Exception handlersThe graph has no exceptional edges. An exception thrown in compiled code, or in a call it makes,-leaves the code like any slow path that does not continue: the runtime unwinds to the handler-(`Vm::handle_exception()`), which puts the exception in the frame and moves its pc to the handler,-and the leave writes the frame state of the throwing node, whose live slots include everything live-into the handler (`bytecode/liveness.rs`). The interpreter then runs the handler's `Catch`, which-compiled code never builds.+reaches its slow path's leave like any slow path that does not continue: the runtime unwinds to the+handler (`Vm::handle_exception()`), which puts the exception in the frame and moves its pc to the+handler. The frame state of the throwing node lists everything live into the handler+(`bytecode/liveness.rs`). Where the handler is in the compiled function's frame and has a catch+entry (below), the leave stub continues in compiled code (`Codegen::emit_catch_in_frame()`): it+writes the frame state into the frame with compiled stores, initializing the frame first if nothing+observed it yet, runs the handler's `Catch`, and jumps to the catch entry, which loads the values+back. Once the code is invalidated, a patched jump skips this. Otherwise the leave writes the frame+state through the runtime, and the interpreter runs the handler's `Catch`, which compiled code never+builds.Handlers start with a `Catch`, and the block after it is where the handler continues. Each handlerthat caught an exception before the compile (the value feedback of its `Catch`) gets a catch entrydiff --git a/Libraries/LibJS/JIT/Rust/src/builder/osr.rs b/Libraries/LibJS/JIT/Rust/src/builder/osr.rsindex 4903d047995..936ee5550bf 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/osr.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/osr.rs@@ -27,12 +27,12 @@//! compiled code reaches from nowhere else. The runtime enters there like at//! an on-stack replacement entry.//!-//! Exception handlers are entered the same way. An exception thrown in-//! compiled code leaves it with the frame state of the throwing instruction,-//! which lists every value live into the handler, and the interpreter runs-//! the handler's `Catch`. Each handler that caught an exception before the-//! compile gets an entry block after its `Catch`, where the interpreter then-//! continues the frame in compiled code.+//! Exception handlers are entered the same way. The frame state of an+//! instruction that throws lists every value live into its handler. Each+//! handler that caught an exception before the compile gets an entry block+//! after its `Catch`, where compiled code continues after writing that frame+//! state to the frame and running the `Catch` itself, or the interpreter+//! after running the `Catch` (see `ARCHITECTURE.md`, section 4.2).use super::AbstractFrame;use super::Flow;diff --git a/Libraries/LibJS/JIT/Rust/src/bytecode/mod.rs b/Libraries/LibJS/JIT/Rust/src/bytecode/mod.rsindex ec0ea27ab89..4ebb77cb4bb 100644--- a/Libraries/LibJS/JIT/Rust/src/bytecode/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/bytecode/mod.rs@@ -16,6 +16,9 @@ pub use instruction::*;/// exception, this value, return value and saved lexical environment.pub const RESERVED_REGISTER_COUNT: u32 = 5;+/// The reserved register holding the exception a handler receives.+pub const EXCEPTION_REGISTER: u32 = 1;+/// The reserved register holding the frame's `this` value.pub const THIS_VALUE_REGISTER: u32 = 2;diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rsindex 69354a721e1..45d27116b77 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs@@ -75,14 +75,18 @@ use crate::asm::MachineFrame;use crate::asm::PortableMacroAssembler;use crate::asm::disassembler;use crate::bytecode::DecodedInstruction;+use crate::bytecode::EXCEPTION_REGISTER;+use crate::bytecode::Instruction;use crate::bytecode::NO_YIELD_CONTINUATION;use crate::bytecode::OpCode;use crate::bytecode::OperandRole;use crate::bytecode::SlowPathAbi;use crate::bytecode::decode_instruction;use crate::bytecode::slow_path_layout;+use crate::code::CALLEE_SLOT;use crate::code::ExitKind;use crate::code::JitStatus;+use crate::code::Repr;use crate::code::Site;use crate::code::SiteKind;use crate::code::ValueLocation;@@ -437,33 +441,10 @@ pub fn generate<M: PortableMacroAssembler>(codegen.emit_frame_initialization_stub()?;let osr_entries = codegen.emit_osr_entries();- let fp_offset = |slot: u32| codegen.frame_pointer_offset(slot);let sites = codegen.sites.iter()- .map(|(node, kind)| {- let mut descriptor = site(graph, allocation, *node, *kind, &fp_offset);- // NB: A slow path call keeps the registers it saved in the saves- // area while it runs, where its exits find them.- if let Op::CallSlowPath {- saves_registers: true, ..- } = graph.node(*node).op- {- let saved = slow_path_calls::slow_path_saved_registers_of::<M>(allocation.node(*node));- let saves = codegen.save_slot_offsets(&saved);- for frame in &mut descriptor.frames {- for (_, location) in &mut frame.values {- relocate_saved_register(location, &saves);- }- }- for object in &mut descriptor.objects {- for location in &mut object.properties {- relocate_saved_register(location, &saves);- }- }- }- descriptor- })+ .map(|(node, kind)| codegen.site_descriptor(*node, *kind)).collect();let annotations = std::mem::take(&mut codegen.annotations);let invalidation_patches = codegen@@ -809,6 +790,33 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {registers}+ /// The site of kind `kind` for the frame state of `node`, with where+ /// the runtime finds each value once the code reached it.+ fn site_descriptor(&self, node: NodeId, kind: SiteKind) -> Site {+ let fp_offset = |slot: u32| self.frame_pointer_offset(slot);+ let mut descriptor = site(self.graph, self.allocation, node, kind, &fp_offset);+ // NB: A slow path call keeps the registers it saved in the saves+ // area while it runs, where its exits find them.+ if let Op::CallSlowPath {+ saves_registers: true, ..+ } = self.graph.node(node).op+ {+ let saved = slow_path_calls::slow_path_saved_registers_of::<M>(self.allocation.node(node));+ let saves = self.save_slot_offsets(&saved);+ for frame in &mut descriptor.frames {+ for (_, location) in &mut frame.values {+ relocate_saved_register(location, &saves);+ }+ }+ for object in &mut descriptor.objects {+ for location in &mut object.properties {+ relocate_saved_register(location, &saves);+ }+ }+ }+ descriptor+ }+/// The `saved` registers of a slow path call, with the frame pointer/// offsets of their words in the saves area.fn save_slot_offsets(&self, saved: &[Gpr]) -> Vec<(Gpr, i32)> {@@ -1037,6 +1045,23 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {/// Dumps every register and calls `libjs_jit_exit()` with the exit/// index in the locals.fn emit_exit_runtime_call(&mut self) {+ self.emit_register_dump();+ // NB: The compiled function's frame, which is not the running one+ // while frames of inlined calls are pushed.+ let arguments = M::ARGUMENT_GPRS;+ let root_frame = self.local_address(self.locals.root_frame);+ self.masm.load64(arguments[1], &root_frame);+ let exit_index = self.local_address(self.locals.exit_index);+ self.masm.load32(arguments[2], &exit_index);+ let dump = self.local_address(self.locals.dump);+ self.masm.load_effective_address(arguments[3], &dump);+ self.masm.move64(arguments[0], self.pinned.vm);+ self.masm.call_absolute(self.runtime.jit_exit);+ }++ /// Stores every register into the register dump in the locals, where+ /// sites find the values in registers (see `RegisterDump`).+ fn emit_register_dump(&mut self) {for encoding in 0..self.gpr_dump_count {let register = Gpr(encoding as u8);if register == M::STACK_POINTER || M::SCRATCH_GPRS.contains(register) {@@ -1053,17 +1078,6 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {let address = self.local_address(self.locals.dump + 8 * (self.gpr_dump_count + encoding));self.masm.store_double(&address, register);}- // NB: The compiled function's frame, which is not the running one- // while frames of inlined calls are pushed.- let arguments = M::ARGUMENT_GPRS;- let root_frame = self.local_address(self.locals.root_frame);- self.masm.load64(arguments[1], &root_frame);- let exit_index = self.local_address(self.locals.exit_index);- self.masm.load32(arguments[2], &exit_index);- let dump = self.local_address(self.locals.dump);- self.masm.load_effective_address(arguments[3], &dump);- self.masm.move64(arguments[0], self.pinned.vm);- self.masm.call_absolute(self.runtime.jit_exit);}/// Emits an entry point for every on-stack replacement entry block:@@ -2905,6 +2919,9 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {let exit_interpreter = self.exit_interpreter;self.masm.branch64_imm(Condition::LessThan, M::RETURN_GPRS[0], 0, exit_interpreter);+ if stub.leave_arguments.is_empty() {+ self.emit_catch_in_frame(&leave_frame)?;+ }let control = self.local_address(self.locals.leave_control);self.masm.store64(&control, M::RETURN_GPRS[0]);for (register, offset) in &leave_frame.restore {@@ -2927,6 +2944,157 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {Ok(())}+ /// Continues in the catch entry of the handler that caught an exception+ /// thrown at the node of `leave_frame` in the compiled function's frame,+ /// if the handler has one (see `builder::osr`): writes the values of the+ /// node's frame state into the frame like `translate::leave()` does,+ /// runs the handler's `Catch`, and jumps to the entry, which loads the+ /// values back. Anything else falls through to the leave, as does every+ /// exception once the code is invalidated.+ ///+ /// NB: Unlike the runtime, this leaves the dead registers and locals+ /// alone, which would take a store each at every such leave. Compiled+ /// code keeps running, and whatever leaves it later writes a whole+ /// frame state, which clears them before the interpreter sees the+ /// frame.+ fn emit_catch_in_frame(&mut self, leave_frame: &LeaveFrame) -> Result<(), CompileFailure> {+ let Some((handler_pc, exception_dst, entry_pc, entry)) = self.catch_entry_of(leave_frame.node)? else {+ return Ok(());+ };+ let descriptor = self.site_descriptor(leave_frame.node, SiteKind::Leave);+ let values = &descriptor.frames.last().expect("a site has a frame state").values;+ let writable = |location: &ValueLocation| {+ !matches!(+ location,+ ValueLocation::ArgumentsObject { .. } | ValueLocation::VirtualObject(_)+ )+ };+ if !values+ .iter()+ .all(|(slot, location)| *slot != CALLEE_SLOT && writable(location))+ {+ return Ok(());+ }+ let leave = self.masm.new_label();+ let invalidated = self.masm.patchable_nop();+ self.invalidation_points.push((invalidated, leave));+ // NB: The slow path routed the exception to the handler, in this+ // frame (see `handle_asm_exception()`).+ self.masm+ .branch64_imm(Condition::NotEqual, M::RETURN_GPRS[0], i64::from(handler_pc), leave);+ // NB: While a slow path runs in the frames of inlined calls, the+ // frame register holds the innermost one, which the exception+ // unwound.+ let (scratch, root_frame) = (self.pinned.scratch, M::RETURN_GPRS[1]);+ self.masm.load64(+ scratch,+ &Address::new(self.pinned.vm, self.runtime.offsets.vm_running_execution_context as i32),+ );+ let root_frame_local = self.local_address(self.locals.root_frame);+ self.masm.load64(root_frame, &root_frame_local);+ self.masm.branch64(Condition::NotEqual, scratch, root_frame, leave);+ let pending_exception = Address::new(+ root_frame,+ checked_i32(u64::from(self.runtime.offsets.execution_context_slots) + 8 * u64::from(EXCEPTION_REGISTER))?,+ );+ self.masm.load64(scratch, &pending_exception);+ self.masm+ .branch64_imm(Condition::Equal, scratch, value::EMPTY as i64, leave);+ self.masm.move64(self.pinned.frame, root_frame);+ for (register, offset) in &leave_frame.restore {+ let address = self.local_address(*offset);+ self.masm.load64(*register, &address);+ }+ self.emit_register_dump();+ // NB: Like the runtime, initializes a frame that nothing observed+ // yet before writing the frame state into it.+ let initialized = self.masm.new_label();+ self.branch_if_frame_initialized(initialized);+ let stub = *self+ .frame_initialization_stub+ .get_or_insert_with(|| self.masm.new_label());+ self.masm.call(stub);+ self.masm.bind(initialized);+ let value = M::RETURN_GPRS[0];+ let number = M::ARGUMENT_FPRS[0];+ for (slot, location) in values {+ match *location {+ ValueLocation::Constant(bits) => self.masm.move_imm64(value, bits),+ ValueLocation::Register(register, Repr::Float64) => {+ let address =+ self.local_address(self.locals.dump + 8 * (self.gpr_dump_count + u32::from(register)));+ self.masm.load_double(number, &address);+ self.box_number(value, number);+ }+ ValueLocation::Register(register, repr) => {+ let address = self.local_address(self.locals.dump + 8 * u32::from(register));+ self.masm.load64(value, &address);+ self.emit_box(value, value, repr);+ }+ ValueLocation::Stack(offset, Repr::Float64) => {+ self.masm.load_double(number, &Address::new(M::FRAME_POINTER, offset));+ self.box_number(value, number);+ }+ ValueLocation::Stack(offset, repr) => {+ self.masm.load64(value, &Address::new(M::FRAME_POINTER, offset));+ self.emit_box(value, value, repr);+ }+ ValueLocation::ArgumentsObject { .. } | ValueLocation::VirtualObject(_) => {+ unreachable!("frame states with objects to create leave through the runtime")+ }+ }+ let address = self.slot_address(*slot)?;+ self.masm.store64(&address, value);+ }+ // The handler's Catch.+ let exception = self.slot_address(EXCEPTION_REGISTER)?;+ self.masm.load64(value, &exception);+ let dst = self.slot_address(exception_dst)?;+ self.masm.store64(&dst, value);+ self.masm.move_imm64(value, value::EMPTY);+ self.masm.store64(&exception, value);+ // NB: The entry continues the frame there, like the interpreter's+ // entry after a Catch (see `enter_jit_code_with_frame_in_memory()`).+ let program_counter = self.frame_field(self.runtime.offsets.execution_context_program_counter);+ self.masm.store_imm32(&program_counter, entry_pc);+ let entry = self.label(entry);+ self.masm.jump(entry);+ self.masm.bind(leave);+ Ok(())+ }++ /// The pc of the handler that catches exceptions thrown at `node` in the+ /// compiled function's frame, the slot its `Catch` stores the exception+ /// in, and the pc and block of its catch entry, if it has one.+ fn catch_entry_of(&self, node: NodeId) -> Result<Option<(u32, u32, u32, BlockId)>, CompileFailure> {+ let frame_state = self.graph.node(node).frame_state.expect("leaves have a frame state");+ let root = *self+ .graph+ .frame_state_chain(frame_state)+ .last()+ .expect("a frame state chain is not empty");+ let pc = self.graph.frame_state(root).pc;+ // NB: Handler ranges do not overlap.+ let Some(handler) = self.executables[0]+ .exception_handlers+ .iter()+ .find(|handler| handler.start_offset <= pc && pc < handler.end_offset)+ else {+ return Ok(None);+ };+ let catch = self.decoded(0, handler.handler_offset)?;+ let Instruction::Catch { dst, .. } = catch.instruction else {+ return Ok(None);+ };+ let entry = self+ .graph+ .osr_entries+ .iter()+ .find(|(entry_pc, _)| *entry_pc == catch.next_pc())+ .map(|(_, block)| *block);+ Ok(entry.map(|entry| (handler.handler_offset, dst.raw(), catch.next_pc(), entry)))+ }+/// Stores the outputs of a slow path that are also its inputs back if/// the frame still runs, as the interpreter does on exceptions.fn emit_store_input_outputs(&mut self, input_outputs: &[(OutputSource, u32)]) -> Result<(), CompileFailure> {diff --git a/Tests/LibJS/Runtime/jit/exception-handlers.js b/Tests/LibJS/Runtime/jit/exception-handlers.jsindex a940a8424ee..09f08b130f4 100644--- a/Tests/LibJS/Runtime/jit/exception-handlers.js+++ b/Tests/LibJS/Runtime/jit/exception-handlers.js@@ -155,6 +155,50 @@ describe("exception handlers in compiled code", () => {expect(closes(iterable([2, 4, 5, 6]))).toBe(5006);expect(closed).toBe(1);});+ test("keep unboxed values live into handlers", () => {+ const mixed = prepared(+ "n",+ "let count = 0; let ratio = 0.5; let flag = false; let log = []; for (let i = 0; i < n; ++i) { count += 3; ratio *= 1.5; flag = !flag; try { thrower(i); } catch (e) { log.push([count, ratio, flag, e]); } } return log;"+ );+ compile(mixed, () => mixed(4));+ const expected = [];+ let count = 0;+ let ratio = 0.5;+ let flag = false;+ for (let i = 0; i < 6; ++i) {+ count += 3;+ ratio *= 1.5;+ flag = !flag;+ if (i & 1) expected.push([count, ratio, flag, i]);+ }+ expect(mixed(6)).toEqual(expected);+ });++ test("catch exceptions thrown before the frame was observed", () => {+ const first = prepared("x", "try { return thrower(x); } catch (e) { return -e; }");+ compile(first, () => [first(1), first(2)]);+ const results = [];+ for (let i = 0; i < 100; ++i) results.push(first(i));+ expect(results).toEqual(results.map((_, i) => (i & 1 ? -i : i)));+ });++ test("catch exceptions thrown by calls that invalidated the code", () => {+ const make = new Function(+ "jit",+ "class Point { constructor(x) { this.x = x; } } const read = function (point, poison) { let total = 0; try { total += point.x; poison(); total += point.x; } catch (e) { total += point.x * 10 + e; } return total; }; jit.prepare(read); return [read, Point];"+ );+ const [read, Point] = make(jit);+ const harmless = () => {};+ compile(read, () => read(new Point(1), harmless));+ const point = new Point(2);+ const poison = () => {+ Object.defineProperty(Point.prototype, "x", { get: () => 100, configurable: true });+ delete point.x;+ throw 7;+ };+ expect(read(point, poison)).toBe(2 + 100 * 10 + 7);+ expect(read({ x: 3 }, harmless)).toBe(6);+ });});describe("exception handlers in compiled generators", () => {