Truly independent web browser
LibJS: Read instructions out of bytecode through checked views
Andreas Kling43dab2daf2d1
diff --git a/Libraries/LibJS/Rust/generate/ops.rs b/Libraries/LibJS/Rust/generate/ops.rsindex f11e9d299bd..beb9fbb92e0 100644--- a/Libraries/LibJS/Rust/generate/ops.rs+++ b/Libraries/LibJS/Rust/generate/ops.rs@@ -86,8 +86,25 @@ pub fn generate(ops: &[InstructionDefinition], ops_with_values: &BTreeSet<Stringop.name);}- out.push_str("}\n");+ // NB: Only bytecode holds instructions, so nothing outside this module can make one.+ out.push_str(" _view_of_bytecode: (),\n}\n");out.push_str(&assertions);+ let _ = writeln!(+ out,+ "// SAFETY: The struct lays out the instruction of this opcode, and is only ever a view of bytecode.\nunsafe impl super::BytecodeOp for {name} {{\n const OPCODE: u8 = crate::bytecode::instruction::OpCode::{name} as u8;\n\n fn length(&self) -> u32 {{\n {name}::length(self)\n }}\n}}",+ name = op.name+ );+ if let Some(array) = &op.array {+ let array_field = &op.fields[array.field_index];+ let count_field = field_name(&op.fields[array.count_field_index].name);+ let name = field_name(&array_field.name);+ let ty = rust_type(&array_field.ty);+ let _ = writeln!(+ out,+ "impl {op_name} {{\n /// The elements the instruction holds after its fixed fields, within the length it records.\n pub fn {name}(&self) -> &[{ty}] {{\n let count = self.{count_field} as usize;\n assert!(core::mem::offset_of!({op_name}, {name}) + count * size_of::<{ty}>() <= self.length() as usize);\n // SAFETY: The instruction is a view of bytecode that holds the length it records, which the elements are\n // within.\n unsafe {{ core::slice::from_raw_parts(self.{name}.as_ptr(), count) }}\n }}\n}}",+ op_name = op.name+ );+ }match (op.layout.size, op.layout.m_length_offset) {(Some(size), _) => {let _ = writeln!(diff --git a/Libraries/LibJS/Rust/src/bytecode/mod.rs b/Libraries/LibJS/Rust/src/bytecode/mod.rsindex 5d7d7ea1698..b0486812ee5 100644--- a/Libraries/LibJS/Rust/src/bytecode/mod.rs+++ b/Libraries/LibJS/Rust/src/bytecode/mod.rs@@ -53,7 +53,37 @@ pub mod operand;pub mod property_access;pub mod validator;+/// The view of an instruction in `op`, which lays out the instruction of its opcode in the bytecode.+///+/// # Safety+///+/// The type must lay out the instruction of `OPCODE`, and only ever be a view of bytecode that holds the instruction.#[cfg(not(test))]+pub unsafe trait BytecodeOp: Sized {+ const OPCODE: u8;++ /// The instruction's size in the bytecode.+ fn length(&self) -> u32;+}++/// The instruction at `pc` of the executable's bytecode, which has to be an `Op`.+#[cfg(not(test))]+pub fn instruction_at<Op: BytecodeOp>(executable: &executable::Executable, pc: u32) -> &Op {+ let bytes = &executable.bytecode()[pc as usize..];+ assert_eq!(bytes[0], Op::OPCODE);+ assert!(size_of::<Op>() <= bytes.len() && bytes.as_ptr().addr().is_multiple_of(align_of::<Op>()));+ // SAFETY: Executables only hold validated bytecode, so an instruction of this opcode, with the layout of Op and+ // valid fields, starts at pc.+ let instruction = unsafe { &*bytes.as_ptr().cast::<Op>() };+ assert!(instruction.length() as usize <= bytes.len());+ instruction+}++#[cfg(not(test))]+#[allow(+ clippy::manual_non_exhaustive,+ reason = "the instruction views keep code outside this module, not only other crates, from making them"+)]pub mod op {use super::encoding::*;use crate::layout::property_lookup_cache::EnvironmentCoordinate;diff --git a/Libraries/LibJS/Rust/src/interpreter/slow_paths/calls.rs b/Libraries/LibJS/Rust/src/interpreter/slow_paths/calls.rsindex 84298587b86..2dbbe85ab64 100644--- a/Libraries/LibJS/Rust/src/interpreter/slow_paths/calls.rs+++ b/Libraries/LibJS/Rust/src/interpreter/slow_paths/calls.rs@@ -155,13 +155,7 @@ pub fn get_super_constructor(vm: &Vm, pc: u32, values: &mut op::GetSuperConstruc/// The element key operands NewClass stores after its fixed fields.fn element_key_operands(instruction: &op::NewClass) -> &[OptionalOperand] {- // SAFETY: The bytecode stores the instruction's element_keys_count element key operands right after it.- unsafe {- core::slice::from_raw_parts(- instruction.element_keys.as_ptr(),- instruction.element_keys_count as usize,- )- }+ instruction.element_keys()}pub fn new_class(diff --git a/Libraries/LibJS/Rust/src/interpreter/slow_paths/control.rs b/Libraries/LibJS/Rust/src/interpreter/slow_paths/control.rsindex 155044a1164..b50b76ef2dd 100644--- a/Libraries/LibJS/Rust/src/interpreter/slow_paths/control.rs+++ b/Libraries/LibJS/Rust/src/interpreter/slow_paths/control.rs@@ -85,9 +85,7 @@ fn iterator_record_from_registers(/// The primitive values a NewPrimitiveArray instruction carries after its fixed fields.fn primitive_array_elements(instruction: &op::NewPrimitiveArray) -> &[Value] {- // SAFETY: The bytecode holds element_count values right after the fixed fields of the instruction, within the- // length it records, and it does not change while the executable that holds it is alive.- unsafe { core::slice::from_raw_parts(instruction.elements.as_ptr(), instruction.element_count as usize) }+ instruction.elements()}pub fn debugger_check_breakpoint(vm: &Vm, pc: u32) {diff --git a/Libraries/LibJS/Rust/src/interpreter/slow_paths/feedback.rs b/Libraries/LibJS/Rust/src/interpreter/slow_paths/feedback.rsindex def70afed56..6dcd8d170ce 100644--- a/Libraries/LibJS/Rust/src/interpreter/slow_paths/feedback.rs+++ b/Libraries/LibJS/Rust/src/interpreter/slow_paths/feedback.rs@@ -14,6 +14,7 @@ use crate::bytecode::feedback::{ExecutableFeedback, are_closures_of_one_function, call_feedback_flags, keyed_feedback_bits,};use crate::bytecode::instruction::OpCode;+use crate::bytecode::instruction_at;use crate::bytecode::op;use crate::interpreter::runtime_functions::SlowPathControl;use crate::interpreter::vm::Vm;@@ -179,8 +180,7 @@ pub fn record_forwarded_call(if pc as usize >= bytecode.len() || bytecode[pc as usize] != OpCode::Call as u8 {return;}- // SAFETY: The bytes at pc are a Call instruction.- let call = unsafe { &*bytecode[pc as usize..].as_ptr().cast::<op::Call>() };+ let call = instruction_at::<op::Call>(&executable, pc);let call_feedback = &feedback.call()[usize::from(call.call_feedback)];if call_feedback.target() != Some(callee) {return;diff --git a/Libraries/LibJS/Rust/src/jit/calls.rs b/Libraries/LibJS/Rust/src/jit/calls.rsindex 79ca5f95b57..14dc7a9b0e5 100644--- a/Libraries/LibJS/Rust/src/jit/calls.rs+++ b/Libraries/LibJS/Rust/src/jit/calls.rs@@ -17,6 +17,7 @@ use super::{frame_of, frames_above};use crate::bytecode::encoding::Operand;use crate::bytecode::executable::Executable;use crate::bytecode::instruction::OpCode;+use crate::bytecode::instruction_at;use crate::bytecode::op;use crate::gc::root::MarkedVec;use crate::interpreter::runtime_functions::{Runtime, RuntimeFunctions, SlowPathControl, handle_asm_exception};@@ -549,16 +550,6 @@ impl<'vm> ArgumentStorage<'vm> {}}-/// The operands that follow a call instruction with an argument list.-///-/// # Safety-///-/// `arguments` is the trailing operand array of an instruction with `count` operands after it.-unsafe fn trailing_operands(arguments: &[Operand; 0], count: u32) -> &[Operand] {- // SAFETY: As above.- unsafe { core::slice::from_raw_parts(arguments.as_ptr(), count as usize) }-}-/// Runs the generic slow path of a call instruction, and stores its result in the frame if the call returned normally./// A callee frame the slow path pushed for the interpreter to run runs to completion here, since the frame's JIT code/// waits for the call.@@ -594,13 +585,11 @@ pub unsafe extern "C" fn libjs_jit_call(vm: *const Vm, frame: *mut ExecutionContlet executable = Executable::from_head(frame_ref.executable.get().expect("the frame runs an executable"));let slots = frame_ref.slots();let load = |operand: Operand| slots[operand.0 as usize].get();- let instruction = &executable.bytecode()[pc as usize..];- let opcode = instruction[0];+ let opcode = executable.bytecode()[pc as usize];macro_rules! instruction {($op:ident) => {- // SAFETY: The bytes at pc are an instruction of this kind.- unsafe { &*instruction.as_ptr().cast::<op::$op>() }+ instruction_at::<op::$op>(&executable, pc)};}let site = |dst: Operand, length: u32| JitCallSite {@@ -614,8 +603,7 @@ pub unsafe extern "C" fn libjs_jit_call(vm: *const Vm, frame: *mut ExecutionCont_ if opcode == OpCode::Call as u8 => {let call = instruction!(Call);let site = site(call.dst, call.length());- // SAFETY: Call instructions are followed by their argument operands.- let operands = unsafe { trailing_operands(&call.arguments, call.argument_count) };+ let operands = call.arguments();let mut storage = ArgumentStorage::new(vm, operands.iter().map(|operand| load(*operand)));let arguments = storage.values();let callee = load(call.callee);@@ -635,8 +623,7 @@ pub unsafe extern "C" fn libjs_jit_call(vm: *const Vm, frame: *mut ExecutionCont_ if opcode == OpCode::CallConstruct as u8 => {let call = instruction!(CallConstruct);let site = site(call.dst, call.length());- // SAFETY: CallConstruct instructions are followed by their argument operands.- let operands = unsafe { trailing_operands(&call.arguments, call.argument_count) };+ let operands = call.arguments();let mut storage = ArgumentStorage::new(vm, operands.iter().map(|operand| load(*operand)));let arguments = storage.values();let callee = load(call.callee);@@ -658,8 +645,7 @@ pub unsafe extern "C" fn libjs_jit_call(vm: *const Vm, frame: *mut ExecutionCont_ if opcode == OpCode::CallDirectEval as u8 => {let call = instruction!(CallDirectEval);let site = site(call.dst, call.length());- // SAFETY: CallDirectEval instructions are followed by their argument operands.- let operands = unsafe { trailing_operands(&call.arguments, call.argument_count) };+ let operands = call.arguments();let mut storage = ArgumentStorage::new(vm, operands.iter().map(|operand| load(*operand)));let arguments = storage.values();let mut values = op::CallDirectEvalValues {@@ -780,15 +766,11 @@ pub unsafe extern "C" fn libjs_jit_call_forwarding_arguments(let frame_ref = frame_of(frame);frame_ref.program_counter.set(pc);let executable = Executable::from_head(frame_ref.executable.get().expect("the frame runs an executable"));- let instruction = &executable.bytecode()[pc as usize..];- if instruction[0] == OpCode::CallWithArgumentArray as u8 {- // SAFETY: The bytes at pc are a CallWithArgumentArray instruction.- let call = unsafe { &*instruction.as_ptr().cast::<op::CallWithArgumentArray>() };+ if executable.bytecode()[pc as usize] == OpCode::CallWithArgumentArray as u8 {+ let call = instruction_at::<op::CallWithArgumentArray>(&executable, pc);return call_spreading_arguments_from_jit(vm, frame, pc, call).0;}- assert_eq!(instruction[0], OpCode::Call as u8);- // SAFETY: The bytes at pc are a Call instruction.- let call = unsafe { &*instruction.as_ptr().cast::<op::Call>() };+ let call = instruction_at::<op::Call>(&executable, pc);assert_eq!(call.argument_count, 2);let slots = frame_ref.slots();let site = JitCallSite {@@ -806,8 +788,7 @@ pub unsafe extern "C" fn libjs_jit_call_forwarding_arguments(return throw_error(vm, pc, ErrorKind::TypeError, ErrorType::NotAFunction, &[&function]).0;}// NB: The argument list of the arguments object is the frame's passed arguments, which nothing changed.- // SAFETY: Call instructions are followed by their argument operands.- let operands = unsafe { trailing_operands(&call.arguments, call.argument_count) };+ let operands = call.arguments();let this_argument = slots[operands[0].0 as usize].get();let passed_argument_count = frame_ref.passed_argument_count.get() as usize;let callee = slots[call.callee.0 as usize].get();@@ -850,10 +831,7 @@ pub unsafe extern "C" fn libjs_jit_finish_direct_call(let frame = NonNull::new(frame).expect("JIT code passes its frame");let frame_ref = frame_of(frame);let executable = Executable::from_head(frame_ref.executable.get().expect("the frame runs an executable"));- let instruction = &executable.bytecode()[pc as usize..];- assert_eq!(instruction[0], OpCode::Call as u8);- // SAFETY: The bytes at pc are a Call instruction.- let call = unsafe { &*instruction.as_ptr().cast::<op::Call>() };+ let call = instruction_at::<op::Call>(&executable, pc);// NB: The callee's frame, and the frames of the calls it inlined that its exit materialized, run in the// interpreter from now on.diff --git a/Libraries/LibJS/Rust/src/jit/translate.rs b/Libraries/LibJS/Rust/src/jit/translate.rsindex 494f71bef4e..b7d20db866c 100644--- a/Libraries/LibJS/Rust/src/jit/translate.rs+++ b/Libraries/LibJS/Rust/src/jit/translate.rs@@ -30,6 +30,7 @@ use super::code::{CompileState, EXIT_COUNT_BEFORE_DISCARD, InlinedFunction, JitCuse super::{DeferGc, executable_of, frame_of, frames_above};use crate::bytecode::executable::Executable;use crate::bytecode::instruction::{OpCode, instruction_length_from_bytes};+use crate::bytecode::instruction_at;use crate::bytecode::op;use crate::interpreter::vm::Vm;use crate::layout::cell::Gc;@@ -195,26 +196,21 @@ struct CallLinkage {/// The argument count, length and kind of the Call or CallConstruct instruction at the start of `bytes`, or of the call/// of a getter a GetById instruction or of a setter a PutById instruction makes.-fn call_instruction_shape(bytes: &[u8]) -> (u32, u32, bool) {- let opcode = bytes[0];+fn call_instruction_shape(executable: &Executable, pc: u32) -> (u32, u32, bool) {+ let opcode = executable.bytecode()[pc as usize];if opcode == OpCode::GetById as u8 {- // SAFETY: The bytes start with a GetById instruction.- let get = unsafe { &*bytes.as_ptr().cast::<op::GetById>() };+ let get = instruction_at::<op::GetById>(executable, pc);return (0, get.length(), false);}if opcode == OpCode::PutById as u8 {- // SAFETY: The bytes start with a PutById instruction.- let put = unsafe { &*bytes.as_ptr().cast::<op::PutById>() };+ let put = instruction_at::<op::PutById>(executable, pc);return (1, put.length(), false);}if opcode == OpCode::CallConstruct as u8 {- // SAFETY: The bytes start with a CallConstruct instruction.- let call = unsafe { &*bytes.as_ptr().cast::<op::CallConstruct>() };+ let call = instruction_at::<op::CallConstruct>(executable, pc);return (call.argument_count, call.length(), true);}- assert_eq!(opcode, OpCode::Call as u8);- // SAFETY: The bytes start with a Call instruction.- let call = unsafe { &*bytes.as_ptr().cast::<op::Call>() };+ let call = instruction_at::<op::Call>(executable, pc);(call.argument_count, call.length(), false)}@@ -226,7 +222,7 @@ fn call_linkage(executable: &Executable, frame_state: &FrameState) -> CallLinkagunreachable!("frames at calls resume after them");};let pc = frame_state.pc;- let (argument_count, length, is_construct) = call_instruction_shape(&executable.bytecode()[pc as usize..]);+ let (argument_count, length, is_construct) = call_instruction_shape(executable, pc);CallLinkage {passed_argument_count: frame_state.passed_argument_count.unwrap_or(argument_count),return_pc: pc + length,