Skip to content

Truly independent web browser

LibJS: Map JIT code and the JIT entry table on Windows

Aliaksandr Kalenik3a31aa4ce0c4
diff --git a/Libraries/LibJS/Rust/src/jit/entry_table.rs b/Libraries/LibJS/Rust/src/jit/entry_table.rs
index fea07a910d5..cc79fd80f29 100644
--- a/Libraries/LibJS/Rust/src/jit/entry_table.rs
+++ b/Libraries/LibJS/Rust/src/jit/entry_table.rs
@@ -11,7 +11,8 @@
//! frame), the executable it belongs to, and the executable's JIT code. Executables keep only their slot number, which
//! JIT code and the runtime mask into the table and check against the slot's owner. Nothing in the GC heap points at
//! JIT code, so a corrupted executable can at worst name the slot of another executable, which the owner check
-//! catches.
+//! catches. On Windows, which commits slots as they get used, it can also name a slot past the ones in use, which
+//! faults.
use core::cell::{Cell, RefCell};
use core::ffi::c_void;
@@ -21,7 +22,7 @@ use super::code::JitCode;
use crate::gc::defer_gc::DeferGc;
use crate::gc::sweep::Sweep;
-#[cfg(feature = "address-sanitizer")]
+#[cfg(all(feature = "address-sanitizer", not(windows)))]
unsafe extern "C" {
fn __lsan_register_root_region(start: *const c_void, size: usize);
fn __lsan_unregister_root_region(start: *const c_void, size: usize);
@@ -44,6 +45,11 @@ const JIT_ENTRY_TABLE_SIZE: usize = 3 * JIT_ENTRY_TABLE_CAPACITY * 8;
/// The slot of executables without one. Its entry has the interpreter run the frame, and it has no owner.
pub const NO_JIT_ENTRY_SLOT: u32 = 0;
+/// Windows has no mappings that take no commit charge until they are written to, and every worker would pay for the
+/// whole table. The arrays get committed together, this many slots at a time.
+#[cfg(windows)]
+const SLOTS_COMMITTED_AT_ONCE: u32 = (64 * 1024 / 8) as u32;
+
/// One reserved mapping of three parallel arrays, indexed by slot: the entries (`*const c_void`), the owners (the
/// address of the owning executable's head, as `u64`) and the code (`Option<Box<JitCode>>`). Its address stays the
/// same for the VM's life, so JIT code embeds it.
@@ -58,29 +64,39 @@ pub struct JitEntryTable {
impl JitEntryTable {
pub fn new(not_compiled_entry: *const c_void) -> Self {
+ #[cfg(not(windows))]
// SAFETY: A fresh anonymous mapping, which no one else uses. Its pages read as zeroes until written: no owner
// and no code in every slot.
let base = unsafe {
- libc::mmap(
+ let base = libc::mmap(
core::ptr::null_mut(),
JIT_ENTRY_TABLE_SIZE,
libc::PROT_READ | libc::PROT_WRITE,
libc::MAP_PRIVATE | libc::MAP_ANONYMOUS | libc::MAP_NORESERVE,
-1,
0,
- )
+ );
+ assert!(base != libc::MAP_FAILED, "mapping the JIT entry table failed");
+ base.cast::<u8>()
};
- assert!(base != libc::MAP_FAILED, "mapping the JIT entry table failed");
+ // NB: Pages read as zeroes once committed: no owner and no code in every slot.
+ #[cfg(windows)]
+ let base = ak::windows_code_memory::reserve(JIT_ENTRY_TABLE_SIZE);
let table = Self {
- base: NonNull::new(base.cast()).expect("mmap does not return null"),
+ base: NonNull::new(base).expect("mapping the JIT entry table failed"),
not_compiled_entry,
next_slot: Cell::new(NO_JIT_ENTRY_SLOT + 1),
free_slots: RefCell::default(),
};
+ #[cfg(windows)]
+ assert!(
+ table.commit_slots_from(NO_JIT_ENTRY_SLOT),
+ "committing the JIT entry table failed"
+ );
table.entry_cell(NO_JIT_ENTRY_SLOT).set(not_compiled_entry);
// NB: The leak checker does not look into mappings for pointers, and would report the JIT code of a VM that
// lives until the process exits (js) as leaked.
- #[cfg(feature = "address-sanitizer")]
+ #[cfg(all(feature = "address-sanitizer", not(windows)))]
// SAFETY: The code of the table is inside its mapping, which lives as long as the table.
unsafe {
__lsan_register_root_region(table.code_start(), JIT_ENTRY_TABLE_SIZE - JIT_ENTRY_TABLE_CODE_OFFSET);
@@ -88,7 +104,26 @@ impl JitEntryTable {
table
}
- #[cfg(feature = "address-sanitizer")]
+ /// Commits the next `SLOTS_COMMITTED_AT_ONCE` slots from `slot`, a multiple of that, in all three arrays. Returns
+ /// whether that worked, which only fails when the system is out of commit.
+ #[cfg(windows)]
+ fn commit_slots_from(&self, slot: u32) -> bool {
+ [0, JIT_ENTRY_TABLE_OWNERS_OFFSET, JIT_ENTRY_TABLE_CODE_OFFSET]
+ .into_iter()
+ .all(|array_offset| {
+ let offset = array_offset + 8 * slot as usize;
+ // SAFETY: Slots are inside the table, and the capacity is a multiple of how many get committed at
+ // once. Committing pages again keeps what they hold.
+ unsafe {
+ ak::windows_code_memory::make_writable(
+ self.base.as_ptr().add(offset),
+ 8 * SLOTS_COMMITTED_AT_ONCE as usize,
+ )
+ }
+ })
+ }
+
+ #[cfg(all(feature = "address-sanitizer", not(windows)))]
fn code_start(&self) -> *const c_void {
// NB: The offset is inside the mapping.
self.base.as_ptr().wrapping_add(JIT_ENTRY_TABLE_CODE_OFFSET).cast()
@@ -132,7 +167,7 @@ impl JitEntryTable {
}
/// A slot for the executable whose head is at `owner`, with the not compiled entry, or `NO_JIT_ENTRY_SLOT` if the
- /// table is full.
+ /// table is full (on Windows, also if the system is out of commit for more slots).
pub fn allocate(&self, owner: u64) -> u32 {
let slot = match self.free_slots.borrow_mut().pop() {
Some(slot) => slot,
@@ -141,6 +176,11 @@ impl JitEntryTable {
if slot as usize == JIT_ENTRY_TABLE_CAPACITY {
return NO_JIT_ENTRY_SLOT;
}
+ // NB: The next allocation tries again.
+ #[cfg(windows)]
+ if slot.is_multiple_of(SLOTS_COMMITTED_AT_ONCE) && !self.commit_slots_from(slot) {
+ return NO_JIT_ENTRY_SLOT;
+ }
self.next_slot.set(slot + 1);
slot
}
@@ -201,14 +241,20 @@ impl Drop for JitEntryTable {
for slot in 0..self.next_slot.get() {
drop(self.code_cell(slot).take());
}
- #[cfg(feature = "address-sanitizer")]
+ #[cfg(all(feature = "address-sanitizer", not(windows)))]
// SAFETY: The region registered when the table was made.
unsafe {
__lsan_unregister_root_region(self.code_start(), JIT_ENTRY_TABLE_SIZE - JIT_ENTRY_TABLE_CODE_OFFSET);
}
// SAFETY: The table's mapping, which nothing uses anymore.
+ #[cfg(not(windows))]
unsafe {
libc::munmap(self.base.as_ptr().cast(), JIT_ENTRY_TABLE_SIZE);
}
+ // SAFETY: As above.
+ #[cfg(windows)]
+ unsafe {
+ ak::windows_code_memory::release(self.base.as_ptr());
+ }
}
}
diff --git a/Libraries/LibJS/Rust/src/jit/executable_memory.rs b/Libraries/LibJS/Rust/src/jit/executable_memory.rs
index fa58f131d14..a47bf12eee2 100644
--- a/Libraries/LibJS/Rust/src/jit/executable_memory.rs
+++ b/Libraries/LibJS/Rust/src/jit/executable_memory.rs
@@ -10,7 +10,8 @@
//! (and not executable) for the duration of the copy: memory is never writable and executable at once. On Linux
//! x86-64 with memory protection keys, the pages are writable and executable, but a protection key keeps every thread
//! from writing them except the one writing code, while it writes. On macOS, chunks are MAP_JIT mappings whose write
-//! protection is toggled per thread instead.
+//! protection is toggled per thread instead. On Windows, chunks are only reserved, and pages get committed when code is
+//! first written to them.
//!
//! Every VM has its own chunks, which only the VM's thread writes and runs code in, so flipping the protection of
//! pages that hold other installed code is safe.
@@ -18,15 +19,32 @@
use core::cell::RefCell;
use std::rc::Rc;
+#[cfg(windows)]
+use ak::windows_code_memory;
+
const CHUNK_SIZE: usize = 4 * 1024 * 1024;
const ALLOCATION_ALIGNMENT: usize = 64;
+/// How much of the start of a chunk holds no code.
+#[cfg(windows)]
+const CHUNK_HEADER_SIZE: usize = windows_code_memory::UNWIND_INFO_SIZE;
+#[cfg(not(windows))]
+const CHUNK_HEADER_SIZE: usize = 0;
+
+const _: () = assert!(CHUNK_HEADER_SIZE.is_multiple_of(ALLOCATION_ALIGNMENT));
+
+#[cfg(not(windows))]
fn page_size() -> usize {
// SAFETY: sysconf() has no preconditions.
let size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
usize::try_from(size).expect("the page size is positive")
}
+#[cfg(windows)]
+fn page_size() -> usize {
+ windows_code_memory::PAGE_SIZE
+}
+
fn align_up(value: usize, alignment: usize) -> usize {
value.div_ceil(alignment) * alignment
}
@@ -76,7 +94,7 @@ unsafe extern "C" {
fn sys_icache_invalidate(start: *mut libc::c_void, length: libc::size_t);
}
-#[cfg(not(target_os = "macos"))]
+#[cfg(not(any(target_os = "macos", windows)))]
unsafe extern "C" {
/// The compiler runtime's instruction cache flush (a no-op on x86-64).
fn __clear_cache(start: *mut libc::c_char, end: *mut libc::c_char);
@@ -111,7 +129,17 @@ impl Chunk {
has_protection_key: false,
}
}
- #[cfg(not(target_os = "macos"))]
+ #[cfg(windows)]
+ {
+ let chunk = windows_code_memory::reserve(size);
+ assert!(!chunk.is_null(), "reserving JIT code memory failed");
+ Self {
+ start: chunk,
+ size,
+ has_protection_key: false,
+ }
+ }
+ #[cfg(not(any(target_os = "macos", windows)))]
{
// SAFETY: An anonymous mapping has no preconditions.
let chunk = unsafe {
@@ -159,7 +187,15 @@ impl Drop for Chunk {
fn drop(&mut self) {
// SAFETY: The chunk was mapped with this size. Every block of it holds the allocator that owns the chunk, so
// no code lives in it anymore when it drops.
- unsafe { libc::munmap(self.start.cast(), self.size) };
+ #[cfg(not(windows))]
+ unsafe {
+ libc::munmap(self.start.cast(), self.size);
+ }
+ // SAFETY: As above.
+ #[cfg(windows)]
+ unsafe {
+ windows_code_memory::release(self.start);
+ }
}
}
@@ -200,7 +236,23 @@ fn write_codes_in_chunk(chunk: &Chunk, writes: &[CodeWrite<'_>]) {
unsafe { sys_icache_invalidate(write.destination.cast(), write.code.len()) };
}
}
- #[cfg(not(target_os = "macos"))]
+ // NB: Making a page writable commits it, so pages between the writes stay as they are.
+ #[cfg(windows)]
+ {
+ let runs = written_page_runs(writes);
+ for &(start, end) in &runs {
+ // SAFETY: The pages lie in a reserved chunk, and no code runs while this thread writes it.
+ let writable = unsafe { windows_code_memory::make_writable(start as *mut u8, end - start) };
+ assert!(writable, "making JIT code writable failed");
+ }
+ copy_all();
+ for &(start, end) in &runs {
+ // SAFETY: The pages were committed above.
+ let executable = unsafe { windows_code_memory::make_executable(start as *mut u8, end - start) };
+ assert!(executable, "making JIT code executable failed");
+ }
+ }
+ #[cfg(not(any(target_os = "macos", windows)))]
{
let page_mask = !(page_size() - 1);
let page_start = writes
@@ -228,6 +280,29 @@ fn write_codes_in_chunk(chunk: &Chunk, writes: &[CodeWrite<'_>]) {
}
}
+/// The pages the writes go to, as runs of consecutive pages in the order of their addresses, each from its first page
+/// to the end of its last.
+#[cfg(windows)]
+fn written_page_runs(writes: &[CodeWrite<'_>]) -> Vec<(usize, usize)> {
+ let page_mask = !(page_size() - 1);
+ let mut pages: Vec<(usize, usize)> = writes
+ .iter()
+ .map(|write| {
+ let start = write.destination as usize;
+ (start & page_mask, align_up(start + write.code.len(), page_size()))
+ })
+ .collect();
+ pages.sort_unstable();
+ let mut runs: Vec<(usize, usize)> = Vec::with_capacity(pages.len());
+ for (start, end) in pages {
+ match runs.last_mut() {
+ Some(run) if start <= run.1 => run.1 = run.1.max(end),
+ _ => runs.push((start, end)),
+ }
+ }
+ runs
+}
+
#[derive(Clone, Copy)]
struct FreeBlock {
start: *mut u8,
@@ -265,12 +340,12 @@ impl CodeAllocator {
return address;
}
- let chunk = Chunk::map(CHUNK_SIZE.max(align_up(size, page_size())));
- let start = chunk.start;
- let chunk_size = chunk.size;
+ let chunk = Chunk::map(CHUNK_SIZE.max(align_up(CHUNK_HEADER_SIZE + size, page_size())));
+ let start = chunk.start.wrapping_add(CHUNK_HEADER_SIZE);
+ let code_size = chunk.size - CHUNK_HEADER_SIZE;
self.chunks.push(chunk);
- if chunk_size > size {
- self.free(start.wrapping_add(size), chunk_size - size);
+ if code_size > size {
+ self.free(start.wrapping_add(size), code_size - size);
}
start
}
diff --git a/Libraries/LibJS/Rust/src/lib.rs b/Libraries/LibJS/Rust/src/lib.rs
index e69a93c2aa6..e75afe2a5fc 100644
--- a/Libraries/LibJS/Rust/src/lib.rs
+++ b/Libraries/LibJS/Rust/src/lib.rs
@@ -114,6 +114,8 @@ pub mod host;
pub mod interpreter;
#[cfg(all(not(test), feature = "jit"))]
pub mod jit;
+#[cfg(all(feature = "jit", windows, not(target_arch = "x86_64")))]
+compile_error!("the JIT supports Windows on x86-64 only: build without the jit feature (ENABLE_JS_JIT=OFF)");
// NB: Without the JIT, the runtime sees the same interface to it, with nothing behind it.
#[cfg(all(not(test), not(feature = "jit")))]
#[path = "jit/disabled.rs"]