Truly independent web browser
LibJS/JIT: Check the native stack limit before the prologue
Andreas Kling9114afccec8c
diff --git a/Libraries/LibJS/JIT/Rust/src/asm/macro_assembler.rs b/Libraries/LibJS/JIT/Rust/src/asm/macro_assembler.rsindex 6232ca18631..4bf8981a4e1 100644--- a/Libraries/LibJS/JIT/Rust/src/asm/macro_assembler.rs+++ b/Libraries/LibJS/JIT/Rust/src/asm/macro_assembler.rs@@ -281,14 +281,6 @@ pub trait PortableMacroAssembler: Sized {fn frame(saved_gprs: GprSet, saved_fprs: FprSet, locals_size: u32) -> MachineFrame;/// Sets up `frame`: links a frame pointer, saves registers, reserves locals.fn emit_prologue(&mut self, frame: &MachineFrame);- /// `emit_prologue()` without touching the locals where the stack has to be touched page by page (see- /// `allocate_stack()`), for code that checks that its frame fits on the stack before it uses the locals: it calls- /// `probe_frame()` once it did.- fn emit_prologue_unprobed(&mut self, frame: &MachineFrame) {- self.emit_prologue(frame);- }- /// Touches the locals of `frame`, set up by `emit_prologue_unprobed()`, where the stack has to be touched.- fn probe_frame(&mut self, _frame: &MachineFrame) {}/// Tears down `frame` and restores saved registers. Does not return.fn emit_epilogue(&mut self, frame: &MachineFrame);/// Moves the stack pointer down by `bytes`, for code that writes to the new stack from its lowest address up. Ondiff --git a/Libraries/LibJS/JIT/Rust/src/asm/x86_64/macro_assembler.rs b/Libraries/LibJS/JIT/Rust/src/asm/x86_64/macro_assembler.rsindex 256f6e90af2..8c9bb73f9c8 100644--- a/Libraries/LibJS/JIT/Rust/src/asm/x86_64/macro_assembler.rs+++ b/Libraries/LibJS/JIT/Rust/src/asm/x86_64/macro_assembler.rs@@ -1117,11 +1117,6 @@ impl PortableMacroAssembler for MacroAssembler {}fn emit_prologue(&mut self, frame: &MachineFrame) {- self.emit_prologue_unprobed(frame);- self.probe_frame(frame);- }-- fn emit_prologue_unprobed(&mut self, frame: &MachineFrame) {self.assembler.push(RBP);self.assembler.mov_rr(W64, RBP, RSP);for register in frame.saved_gprs.iter() {@@ -1136,10 +1131,7 @@ impl PortableMacroAssembler for MacroAssembler {let offset = frame.locals_size + 8 * i as u32;self.assembler.movsd_mr(&Address::new(RSP, offset as i32), register);}- }-- fn probe_frame(&mut self, frame: &MachineFrame) {- let reserved = Self::reserved_frame_bytes(frame) as i32;+ let reserved = reserved as i32;if needs_stack_probes(reserved) {// NB: The pushes touched the stack down to where the reserved part starts.self.assembler.lea(W64, SCRATCH, &Address::new(RSP, reserved));diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rs b/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rsindex 319aa5e9999..911676d8f9f 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rs@@ -96,6 +96,7 @@ pub fn generate_call_stub<M: PortableMacroAssembler>(runtime: &RuntimeInfo) -> Rexit_stub,resume,entry_resume: resume,+ entry_overflow: resume,exit_interpreter,sites: Vec::new(),exit_site_stubs: Vec::new(),diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rsindex 625951595c2..633122eaec4 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs@@ -284,6 +284,9 @@ struct Codegen<'a, M: PortableMacroAssembler> {resume: Label,/// Where the prologues resume in the interpreter.entry_resume: Label,+ /// Where the prologues resume in the interpreter if the frame does not fit on the native stack, before they set it+ /// up.+ entry_overflow: Label,exit_interpreter: Label,/// The nodes of the code's sites, by site index, with what they are.sites: Vec<(NodeId, SiteKind)>,@@ -416,6 +419,7 @@ pub fn generate<M: PortableMacroAssembler>(let exit_stub = masm.new_label();let resume = masm.new_label();let entry_resume = masm.new_label();+ let entry_overflow = masm.new_label();let exit_interpreter = masm.new_label();let leave_tail = masm.new_label();@@ -436,6 +440,7 @@ pub fn generate<M: PortableMacroAssembler>(exit_stub,resume,entry_resume,+ entry_overflow,exit_interpreter,sites: Vec::new(),exit_site_stubs: Vec::new(),@@ -792,6 +797,8 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {}}self.frame = M::frame(saved, saved_fprs, size);+ // NB: The prologue addresses the lowest byte of the frame relative to the stack pointer.+ checked_i32(u64::from(self.frame.caller_stack_offset))?;Ok(())}@@ -931,25 +938,31 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {fn emit_prologue(&mut self) {self.annotate(CodeAnnotation::Prologue);let frame = self.frame;- self.masm.emit_prologue_unprobed(&frame);- // NB: The VM is in its pinned register already.- self.masm.move64(self.pinned.frame, M::ARGUMENT_GPRS[1]);// Exit to the interpreter (which runs the function on its own stack,- // and reports overflows of that) if the native stack is nearly- // exhausted. No value lives in a register yet. The locals are only- // touched once the frame is known to fit: on Windows, touching a- // frame that goes past the end of the stack would crash.+ // and reports overflows of that) if the frame would go below the+ // native stack limit. This is checked before the prologue moves the+ // stack pointer or stores anything: a large frame could otherwise+ // skip past the guard page at the end of the stack.+ // NB: JIT code does not keep the pinned scratch register.+ let lowest = self.pinned.scratch;+ let frame_bottom = Address::new(M::STACK_POINTER, -(frame.caller_stack_offset as i32));+ self.masm.load_effective_address(lowest, &frame_bottom);let limit = Address::new(self.pinned.vm, self.runtime.offsets.vm_jit_native_stack_limit as i32);- let resume = self.entry_resume;- self.masm.branch_if_stack_pointer_below(&limit, resume);- self.masm.probe_frame(&frame);+ let entry_overflow = self.entry_overflow;+ self.masm+ .branch64_memory(Condition::Above, &limit, lowest, entry_overflow);++ self.masm.emit_prologue(&frame);+ // NB: The VM is in its pinned register already.+ self.masm.move64(self.pinned.frame, M::ARGUMENT_GPRS[1]);let root_frame = self.local_address(self.locals.root_frame);self.masm.store64(&root_frame, self.pinned.frame);// Materializing the frames of inlined calls must not run out of// interpreter stack, so exit if they would not all fit.if self.graph.materialized_frame_bytes != 0 {+ let resume = self.entry_resume;let offsets = self.runtime.offsets;let top = M::RETURN_GPRS[1];self.masm.load64(@@ -985,6 +998,16 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {self.masm.move_imm32(M::RETURN_GPRS[0], 0);self.emit_return(JitStatus::Resume);+ // NB: No frame is set up here, so the frame is still in its argument+ // register.+ self.annotate(CodeAnnotation::Tail("return Resume before the prologue"));+ let entry_overflow = self.entry_overflow;+ self.masm.bind(entry_overflow);+ self.emit_publish_frame_from(M::ARGUMENT_GPRS[1]);+ self.masm.move_imm32(M::RETURN_GPRS[0], 0);+ self.masm.move_imm32(M::RETURN_GPRS[1], JitStatus::Resume as u32);+ self.masm.ret();+self.annotate(CodeAnnotation::Tail("return ExitInterpreter"));let exit_interpreter = self.exit_interpreter;self.masm.bind(exit_interpreter);@@ -2231,8 +2254,13 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {/// `PublishFrame`: makes the frame the running execution context, which/// it may be already.fn emit_publish_frame(&mut self) {+ self.emit_publish_frame_from(self.pinned.frame);+ }++ /// Makes the frame in `frame` the running one.+ fn emit_publish_frame_from(&mut self, frame: Gpr) {let running = Address::new(self.pinned.vm, self.runtime.offsets.vm_running_execution_context as i32);- self.masm.store64(&running, self.pinned.frame);+ self.masm.store64(&running, frame);}/// Publishes the frame and initializes it like `Enter`, with `value` fordiff --git a/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs b/Libraries/LibJS/JIT/Rust/src/codegen/tests.rsindex bf31f7c1b07..6c07a5c2026 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs@@ -2178,9 +2178,16 @@ mod execution {let program = assemble(|_| vec![Instruction::Enter, Instruction::Return { value: a(0) }]);let (result, machine) = run_with(&program, test_layout(), &[value::int32(1)], &[], |machine| {machine.vm[1] = u64::MAX - 1;+ // NB: The code has to make the frame the running one before it resumes in the interpreter.+ machine.vm[0] = 0;});assert_eq!(result.status, RESUME);assert_eq!(machine.frame[3], 0, "the frame was not initialized");+ assert_eq!(+ machine.vm[0],+ machine.frame.as_ptr() as u64,+ "the frame is the running one"+ );}}@@ -2230,6 +2237,62 @@ fn jumps_skip_blocks_that_only_jump_on() {}}+#[test]+fn prologues_check_the_stack_limit_before_they_move_the_stack_pointer() {+ // NB: A frame larger than the headroom below the native stack limit could otherwise skip past the guard page at+ // the end of the stack, and the prologue would write past it.+ let program = assemble(|_| vec![Instruction::Enter, Instruction::Return { value: a(0) }]);+ let mut snapshot = crate::builder::tests::snapshot_for(&program, test_layout());+ snapshot.runtime = runtime();+ let x86_64 = compile_for::<crate::asm::x86_64::MacroAssembler>(&snapshot, &|_| true).unwrap();+ let aarch64 = compile_for::<crate::asm::aarch64::MacroAssembler>(&snapshot, &|_| true).unwrap();+ for (architecture, compiled, is_branch, writes_stack) in [+ (+ crate::asm::Architecture::X86_64,+ &x86_64,+ (|text: &str| text.starts_with('j') && !text.starts_with("jmp ")) as fn(&str) -> bool,+ (|text: &str| {+ let (mnemonic, operands) = text.split_once(' ').unwrap_or((text, ""));+ let destination = operands.split(',').next().unwrap_or("");+ matches!(mnemonic, "push" | "call")+ || destination == "rsp"+ || (mnemonic.starts_with("mov") && destination.contains('['))+ }) as fn(&str) -> bool,+ ),+ (+ crate::asm::Architecture::AArch64,+ &aarch64,+ |text: &str| text.starts_with("b.") || text.starts_with("cb") || text.starts_with("tb"),+ |text: &str| {+ let (mnemonic, operands) = text.split_once(' ').unwrap_or((text, ""));+ mnemonic.starts_with("st") || mnemonic == "bl" || operands.starts_with("sp,")+ },+ ),+ ] {+ let listing =+ crate::asm::disassembler::listing_with_data(architecture, &compiled.code, compiled.data_offset as usize);+ let check = listing+ .iter()+ .position(|instruction| is_branch(&instruction.text))+ .unwrap_or_else(|| panic!("{architecture:?}: the prologue does not branch"));+ assert!(check > 0);+ for instruction in &listing[..check] {+ assert!(+ !writes_stack(&instruction.text),+ "{architecture:?}: {} at {:#x} comes before the stack limit check",+ instruction.text,+ instruction.offset+ );+ }+ assert!(+ listing[check..]+ .iter()+ .any(|instruction| writes_stack(&instruction.text)),+ "{architecture:?}: the test does not recognize the prologue"+ );+ }+}+#[test]fn aarch64_code_disassembles() {let program = assemble(|label| {@@ -2263,8 +2326,13 @@ fn aarch64_code_disassembles() {let compiled = compile_for::<crate::asm::aarch64::MacroAssembler>(&snapshot, &|pc| pc != never_ran).unwrap();let lines = crate::asm::disassembler::aarch64(&compiled.code[..compiled.data_offset as usize]);let text = lines.join("\n");- // The prologue links the frame, slow paths and helpers are called through registers.- assert!(lines[0].starts_with("stp x29, x30, [sp"), "{text}");+ // The prologue links the frame right after the stack limit check, slow paths and helpers are called through+ // registers.+ let check = lines+ .iter()+ .position(|line| line.starts_with("b."))+ .expect("a stack limit check");+ assert!(lines[check + 1].starts_with("stp x29, x30, [sp"), "{text}");assert!(text.contains("blr"), "{text}");assert!(text.contains("ret"), "{text}");// NB: The slow paths of JumpLessThan and NewArray leave through sites.@@ -2276,7 +2344,11 @@ fn aarch64_code_disassembles() {let compiled = compile_for::<crate::asm::x86_64::MacroAssembler>(&snapshot, &|pc| pc != never_ran).unwrap();let lines = crate::asm::disassembler::x86_64(&compiled.code[..compiled.data_offset as usize]);- assert_eq!(lines[0], "push rbp");+ let check = lines+ .iter()+ .position(|line| line.starts_with('j'))+ .expect("a stack limit check");+ assert_eq!(lines[check + 1], "push rbp");// The dump names exits, slow paths and the shared tails on both architectures.snapshot.options.dump_asm = true;