Skip to content

Truly independent web browser

LibJS/JIT: Probe the native stack on Windows

Aliaksandr Kalenike6fe4206a1b1
diff --git a/Libraries/LibJS/JIT/ARCHITECTURE.md b/Libraries/LibJS/JIT/ARCHITECTURE.md
index 6f9b5886e94..814a9bd99cd 100644
--- a/Libraries/LibJS/JIT/ARCHITECTURE.md
+++ b/Libraries/LibJS/JIT/ARCHITECTURE.md
@@ -451,6 +451,12 @@ explicitly:
- The interpreter calls the runtime functions in `interpreter::runtime_functions` with the Win64
convention on Windows, so `runtime_function_addresses()` gives JIT code System V forwarders to
them there.
+- Windows commits a thread's stack as code touches its guard pages, so JIT code that moves the
+ stack pointer goes through `emit_prologue()` or `allocate_stack()`, which touch the pages on the
+ way down (with the stack probes in `asm::x86_64`, which the Wasm JIT shares). Code that moves it
+ any other way can skip the guard pages and fault. Compiled functions check the native stack limit
+ before they touch their frames, with `emit_prologue_unprobed()` and `probe_frame()`, so that a
+ frame that does not fit makes the code exit instead of touching past the end of the stack.
## 9. Speculation and exits
diff --git a/Libraries/LibJS/JIT/Rust/src/asm/macro_assembler.rs b/Libraries/LibJS/JIT/Rust/src/asm/macro_assembler.rs
index 7ca8ef519b8..6232ca18631 100644
--- a/Libraries/LibJS/JIT/Rust/src/asm/macro_assembler.rs
+++ b/Libraries/LibJS/JIT/Rust/src/asm/macro_assembler.rs
@@ -281,6 +281,19 @@ 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. On
+ /// Windows, which commits a thread's stack as code touches its guard pages, this touches the pages on the way.
+ fn allocate_stack(&mut self, bytes: i64) {
+ self.sub64_imm(Self::STACK_POINTER, Self::STACK_POINTER, bytes);
+ }
}
diff --git a/Libraries/LibJS/JIT/Rust/src/asm/x86_64/macro_assembler.rs b/Libraries/LibJS/JIT/Rust/src/asm/x86_64/macro_assembler.rs
index 30a09f7a864..256f6e90af2 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
@@ -144,6 +144,11 @@ impl BranchGroups for MacroAssembler {
}
impl MacroAssembler {
+ /// The bytes the prologue of `frame` moves the stack pointer down by after saving the general purpose registers.
+ fn reserved_frame_bytes(frame: &MachineFrame) -> u32 {
+ frame.locals_size + 8 * frame.saved_fprs.len() as u32
+ }
+
/// `dst = lhs op rhs` for a commutative operation.
fn commutative(&mut self, op: AluOp, width: Width, dst: Gpr, lhs: Gpr, rhs: Gpr) {
if dst == lhs {
@@ -1112,27 +1117,42 @@ 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() {
self.assembler.push(register);
}
- let reserved = frame.locals_size + 8 * frame.saved_fprs.len() as u32;
+ let reserved = Self::reserved_frame_bytes(frame);
if reserved != 0 {
self.assembler.sub_ri(W64, RSP, reserved as i32);
}
+ // NB: The saved registers are within a page of the pushes, which touched the stack.
for (i, register) in frame.saved_fprs.iter().enumerate() {
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;
+ 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));
+ self.assembler.probe_stack(SCRATCH, RSP, Some(reserved));
+ }
+ }
+
fn emit_epilogue(&mut self, frame: &MachineFrame) {
for (i, register) in frame.saved_fprs.iter().enumerate() {
let offset = frame.locals_size + 8 * i as u32;
self.assembler.movsd_rm(register, &Address::new(RSP, offset as i32));
}
- let reserved = frame.locals_size + 8 * frame.saved_fprs.len() as u32;
+ let reserved = Self::reserved_frame_bytes(frame);
if reserved != 0 {
self.assembler.add_ri(W64, RSP, reserved as i32);
}
@@ -1141,4 +1161,20 @@ impl PortableMacroAssembler for MacroAssembler {
}
self.assembler.pop(RBP);
}
+
+ fn allocate_stack(&mut self, bytes: i64) {
+ if PROBES_STACK {
+ // NB: The prologue may have moved the stack pointer without touching where it ended up.
+ self.assembler.mov_rm(W32, SCRATCH, &Address::new(RSP, 0));
+ let bytes = i32::try_from(bytes).expect("stack allocations are smaller than 2 GiB");
+ if needs_stack_probes(bytes) {
+ self.assembler.mov_rr(W64, SCRATCH2, RSP);
+ self.assembler.lea(W64, SCRATCH, &Address::new(RSP, -bytes));
+ self.assembler.probe_stack(SCRATCH2, SCRATCH, Some(bytes));
+ self.assembler.mov_rr(W64, RSP, SCRATCH);
+ return;
+ }
+ }
+ self.sub64_imm(RSP, RSP, bytes);
+ }
}
diff --git a/Libraries/LibJS/JIT/Rust/src/asm/x86_64/mod.rs b/Libraries/LibJS/JIT/Rust/src/asm/x86_64/mod.rs
index d764e57eff0..c4356c31264 100644
--- a/Libraries/LibJS/JIT/Rust/src/asm/x86_64/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/asm/x86_64/mod.rs
@@ -9,6 +9,7 @@
mod extended;
mod macro_assembler;
mod sse;
+mod stack_probes;
#[cfg(test)]
mod tests;
@@ -24,6 +25,8 @@ pub use extended::VexOperand;
pub use extended::VexPrefix;
pub use macro_assembler::MacroAssembler;
pub use sse::CpuFeatures;
+pub use stack_probes::PROBES_STACK;
+pub use stack_probes::needs_stack_probes;
use super::Address;
use super::Fpr;
diff --git a/Libraries/LibJS/JIT/Rust/src/asm/x86_64/stack_probes.rs b/Libraries/LibJS/JIT/Rust/src/asm/x86_64/stack_probes.rs
new file mode 100644
index 00000000000..9963fcf805b
--- /dev/null
+++ b/Libraries/LibJS/JIT/Rust/src/asm/x86_64/stack_probes.rs
@@ -0,0 +1,68 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Stack probes, for the JITs of both LibJS and LibWasm. Windows commits a thread's stack as code touches the guard
+//! pages below the committed part, and code that skips past them faults. So code that takes stack touches the pages
+//! it takes from the top down, each touch at most a page below the one before. Reading a guard page commits it just
+//! as well as writing it, and keeps what is on the stack.
+
+use super::Address;
+use super::AluOp;
+use super::Assembler;
+use super::Cond;
+use super::Gpr;
+use super::Width;
+
+/// Whether code that takes stack has to touch it.
+pub const PROBES_STACK: bool = cfg!(windows);
+
+/// How far apart the touches are: the page size.
+const STACK_PROBE_INTERVAL: i32 = 4096;
+
+/// Code that takes less stack than this does not touch it. Two such takes in a row, or one and the return address of a
+/// call, stay within a page of what was touched last, so that nothing is skipped however they fall on the pages.
+const STACK_PROBE_THRESHOLD: i32 = STACK_PROBE_INTERVAL / 2;
+
+/// Up to this many touches above the bottom one are emitted one by one, and more take a loop.
+const UNROLLED_STACK_PROBES: i32 = 4;
+
+/// Whether code that takes `size` bytes of stack has to touch them.
+pub const fn needs_stack_probes(size: i32) -> bool {
+ PROBES_STACK && size >= STACK_PROBE_THRESHOLD
+}
+
+impl Assembler {
+ /// Touches the stack from the address in `top`, which is at most a page below what was touched last, down to the
+ /// address in `bottom`: every page in between, then `bottom` itself. `size` is `top - bottom` if it is known when
+ /// the code is generated, which keeps small ranges from taking a loop. Clobbers `top` and the flags.
+ pub fn probe_stack(&mut self, top: Gpr, bottom: Gpr, size: Option<i32>) {
+ match size {
+ Some(size) if size <= (UNROLLED_STACK_PROBES + 1) * STACK_PROBE_INTERVAL => {
+ let mut offset = STACK_PROBE_INTERVAL;
+ while offset < size {
+ self.touch_stack(&Address::new(top, -offset), top);
+ offset += STACK_PROBE_INTERVAL;
+ }
+ }
+ _ => {
+ let (again, done) = (self.new_label(), self.new_label());
+ self.bind(again);
+ self.sub_ri(Width::W64, top, STACK_PROBE_INTERVAL);
+ self.cmp_rr(Width::W64, top, bottom);
+ self.jcc(Cond::BelowOrEqual, done);
+ self.touch_stack(&Address::new(top, 0), top);
+ self.jmp(again);
+ self.bind(done);
+ }
+ }
+ self.touch_stack(&Address::new(bottom, 0), top);
+ }
+
+ /// Reads the stack at `address` by comparing it with `register`, which keeps every register as it is.
+ fn touch_stack(&mut self, address: &Address, register: Gpr) {
+ self.alu_rm(AluOp::Cmp, Width::W32, register, address);
+ }
+}
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/arrays.rs b/Libraries/LibJS/JIT/Rust/src/codegen/arrays.rs
index a4484eb2bf7..f0c19001b8b 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/arrays.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/arrays.rs
@@ -26,7 +26,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
let count = self.graph.node(node).inputs.len() - 3;
let bytes = ((count * 8 + 15) & !15) as i64;
if bytes != 0 {
- self.masm.sub64_imm(M::STACK_POINTER, M::STACK_POINTER, bytes);
+ self.masm.allocate_stack(bytes);
}
for index in 0..count {
let address = Address::new(M::STACK_POINTER, (index * 8) as i32);
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/call.rs b/Libraries/LibJS/JIT/Rust/src/codegen/call.rs
index 03b24a868f0..f13545c3c83 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/call.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/call.rs
@@ -1032,7 +1032,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
})?;
let argument_bytes = (8 * i64::from(argument_count) + 15) & !15;
if argument_bytes != 0 {
- self.masm.sub64_imm(M::STACK_POINTER, M::STACK_POINTER, argument_bytes);
+ self.masm.allocate_stack(argument_bytes);
}
for (index, argument) in (0u32..).zip(arguments) {
let address = Address::new(M::STACK_POINTER, super::checked_i32(8 * u64::from(index))?);
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
index 58671e0470d..625951595c2 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
@@ -931,18 +931,21 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
fn emit_prologue(&mut self) {
self.annotate(CodeAnnotation::Prologue);
let frame = self.frame;
- self.masm.emit_prologue(&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]);
- let root_frame = self.local_address(self.locals.root_frame);
- self.masm.store64(&root_frame, self.pinned.frame);
// 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.
+ // 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.
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 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.
diff --git a/Tests/LibJS/JIT/programs/large-native-stack-frames.js b/Tests/LibJS/JIT/programs/large-native-stack-frames.js
new file mode 100644
index 00000000000..f465a12666d
--- /dev/null
+++ b/Tests/LibJS/JIT/programs/large-native-stack-frames.js
@@ -0,0 +1,37 @@
+// JIT code passes the arguments of some calls on the native stack, and keeps the operands of some slow paths in its
+// native stack frame. Neither may skip over the guard pages that Windows keeps below the committed part of a thread's
+// stack, which fault when skipped. The second use is larger than the first, so that it also goes beyond what was ever
+// used by more than the guard pages.
+function operands(count) {
+ return Array.from({ length: count }, () => "value").join(", ");
+}
+
+// NB: A call of a native function goes through the call stub, which takes its arguments on the native stack.
+const callWithManyArguments = Function("callee", "value", `return callee(${operands(24000)});`);
+
+// NB: An array literal has its elements in the operand record of its slow path, in the frame. The frames also have to
+// get past each other, and are larger than what JIT code leaves of the native stack when it stops calling
+// deeper, so that a frame that recursing runs into the end of the stack with must not be touched at all.
+const createLargeArray = Function(
+ "value",
+ "depth",
+ `
+ const below = depth > 0 ? createLargeArray(value, depth - 1) : 0;
+ const array = [${operands(64000)}];
+ return below + array.length;
+`
+);
+
+for (let warmup = 0; warmup < 500; warmup++) {
+ callWithManyArguments(Math.max, warmup);
+ createLargeArray(warmup, 0);
+}
+
+print(callWithManyArguments(Math.max, 1));
+for (const depth of [1, 2, 4, 8]) print(createLargeArray(1, depth));
+
+try {
+ createLargeArray(1, Infinity);
+} catch (error) {
+ print(error instanceof InternalError);
+}