Skip to content

Truly independent web browser

19.9 KB
Raw Blame
/*
 * Copyright (c) 2026-present, the Ladybird developers.
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

//! Decoder for assembled bytecode.
//!
//! The `OpCode` and `Instruction` enums, the per-opcode field decoder and the
//! operand / jump target visitors are generated by build.rs from
//! interpreter.flap. The input is the exact byte stream the interpreter
//! executes: operands are flat slot indices, labels are absolute byte offsets.

use ak::Zone;
use ak::ZoneVec;

include!(concat!(env!("OUT_DIR"), "/decoder_generated.rs"));

/// A frame slot, as a flat index into the interpreter's
/// `[registers | locals | constants | arguments]` value array.
///
/// See `FrameLayout` for how to classify an index.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Operand(u32);

impl Operand {
    /// The encoding of an absent `Optional<Operand>`.
    pub const INVALID: u32 = 0xFFFF_FFFF;

    /// The raw operand that an operand byte of the bytecode stands for, `INVALID` for an absent one.
    pub fn raw_from_byte(byte: u8) -> u32 {
        if byte == u8::MAX {
            Self::INVALID
        } else {
            u32::from(byte)
        }
    }

    pub fn from_raw(raw: u32) -> Self {
        Self(raw)
    }

    pub fn optional_from_raw(raw: u32) -> Option<Self> {
        if raw == Self::INVALID { None } else { Some(Self(raw)) }
    }

    /// The flat slot index, as the bytecode encodes it.
    pub fn raw(self) -> u32 {
        self.0
    }
}

/// Whether an instruction reads an operand, writes it, or both.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OperandRole {
    In,
    Out,
    InOut,
}

impl OperandRole {
    pub fn is_read(self) -> bool {
        matches!(self, OperandRole::In | OperandRole::InOut)
    }

    pub fn is_written(self) -> bool {
        matches!(self, OperandRole::Out | OperandRole::InOut)
    }
}

/// A bytecode offset (absolute, from the start of the executable's bytecode).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Label(pub u32);

/// Index into the executable's identifier table.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct IdentifierTableIndex(pub u32);

impl IdentifierTableIndex {
    pub const INVALID: u32 = 0xFFFF_FFFF;

    pub fn optional_from_raw(raw: u32) -> Option<Self> {
        if raw == Self::INVALID { None } else { Some(Self(raw)) }
    }
}

/// Index into the executable's property key table.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PropertyKeyTableIndex(pub u32);

/// Index into the executable's string table.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StringTableIndex(pub u32);

impl StringTableIndex {
    pub const INVALID: u32 = 0xFFFF_FFFF;

    pub fn optional_from_raw(raw: u32) -> Option<Self> {
        if raw == Self::INVALID { None } else { Some(Self(raw)) }
    }
}

/// Environment coordinate used by the binding instructions.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EnvironmentCoordinate {
    pub hops: u32,
    pub index: u32,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DecodeErrorKind {
    UnknownOpcode,
    TruncatedInstruction,
    InvalidLength,
}

/// Why the instruction at `pc` could not be decoded.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DecodeError {
    pub pc: u32,
    pub kind: DecodeErrorKind,
}

/// How a slow path that takes an instruction's `Op` record receives its
/// operands, following Flap's `SlowPathLayout`. The record (`Op::Values`) has
/// one value per scalar operand field, in field order, followed by the values
/// of the operand array.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SlowPathAbi {
    /// `AsmSlowPathResult f(VM*, u32 pc, Op const*, Value input...)`: the
    /// inputs are passed by value and the single output, if any, comes back as
    /// the second return word.
    Scalar,
    /// `i64 f(VM*, u32 pc, Op const*, Op::Values& outputs, Value input...)`:
    /// inputs (and input/outputs) by value, outputs written to the record.
    ScalarInputs,
    /// `i64 f(VM*, u32 pc, Op const*, Op::Values& values)`: everything in the
    /// record, including the operand array.
    Record,
}

/// One scalar operand field of an instruction, as seen by its slow path.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SlowPathField {
    /// Byte offset of the operand within the instruction.
    pub instruction_offset: u32,
    pub role: OperandRole,
    /// Whether the operand is an `Optional<Operand>`; absent ones read as the empty value.
    pub optional: bool,
}

/// The operand array of an instruction, as seen by its slow path.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SlowPathArray {
    /// Byte offset of the first operand of the array within the instruction.
    pub instruction_offset: u32,
    /// Byte offset of the one-byte element count within the instruction.
    pub count_offset: u32,
    pub optional: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SlowPathLayout {
    pub abi: SlowPathAbi,
    pub fields: &'static [SlowPathField],
    pub array: Option<SlowPathArray>,
}

/// The interpreter feedback slots one instruction records into, one index
/// space per feedback kind (see `Libraries/LibJS/Rust/src/layout/feedback.rs`).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct FeedbackSlots {
    pub arith: Option<u16>,
    pub value: Option<u16>,
    pub call: Option<u16>,
    pub keyed: Option<u16>,
    /// The property lookup cache whose site's value feedback the instruction records.
    pub cache_value: Option<u16>,
}

/// One decoded instruction and where it lives in the bytecode.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DecodedInstruction<'a> {
    /// Byte offset of the instruction.
    pub pc: u32,
    /// Encoded length in bytes; the next instruction starts at `pc + length`.
    pub length: u32,
    pub instruction: Instruction<'a>,
}

impl OpCode {
    /// Whether an instruction of this opcode costs nothing in inlined code:
    /// entering the frame, moves between slots (which SSA values rename),
    /// and jumps.
    pub fn is_free_when_inlined(self) -> bool {
        matches!(
            self,
            OpCode::Enter | OpCode::EnterCoercingThis | OpCode::Mov | OpCode::Jump
        )
    }
}

/// How many of a callee's instructions cost something in inlined code,
/// which decides whether it is small enough to always inline.
pub fn inlining_size(instructions: &[DecodedInstruction]) -> usize {
    instructions
        .iter()
        .filter(|decoded| !decoded.instruction.opcode().is_free_when_inlined())
        .count()
}

impl Instruction<'_> {
    /// The property lookup cache whose entries compiled code speculates on
    /// for this instruction, as shape checks that exit with
    /// `ExitKind::BadShape`.
    pub fn speculated_property_lookup_cache(&self) -> Option<u32> {
        match *self {
            Instruction::GetById { cache, .. }
            | Instruction::PutById { cache, .. }
            | Instruction::GetLength { cache, .. }
            | Instruction::GetByValue { cache, .. }
            | Instruction::PutByValue { cache, .. } => Some(cache),
            _ => None,
        }
    }
}

impl DecodedInstruction<'_> {
    pub fn next_pc(&self) -> u32 {
        self.pc + self.length
    }
}

#[cfg(test)]
fn narrow_index(index: u32) -> u16 {
    if index == u32::MAX {
        return u16::MAX;
    }
    u16::try_from(index).expect("bytecode indices fit in 16 bits")
}

/// See `WIDE_NAME_INDEX_MARK` of the bytecode generator.
const WIDE_NAME_INDEX_MARK: u16 = 0xff00;
const NO_NAME_INDEX: u16 = u16::MAX;

#[cfg(test)]
fn is_wide_name_index(index: u32) -> bool {
    index != u32::MAX && index >= u32::from(WIDE_NAME_INDEX_MARK)
}

#[cfg(test)]
fn name_index_field(index: u32, distance: usize) -> u16 {
    if index == u32::MAX {
        return NO_NAME_INDEX;
    }
    if !is_wide_name_index(index) {
        return index as u16;
    }
    WIDE_NAME_INDEX_MARK + u16::try_from(distance).unwrap()
}

fn read_optional_name_index(bytes: &[u8], at: usize) -> Option<u32> {
    match read_u16(bytes, at) {
        NO_NAME_INDEX => None,
        raw if raw >= WIDE_NAME_INDEX_MARK => Some(read_u32(bytes, at - usize::from(raw - WIDE_NAME_INDEX_MARK))),
        raw => Some(u32::from(raw)),
    }
}

fn read_name_index(bytes: &[u8], at: usize) -> u32 {
    read_optional_name_index(bytes, at).expect("the field holds a name table index")
}

fn read_u16(bytes: &[u8], at: usize) -> u16 {
    u16::from_ne_bytes(bytes[at..at + 2].try_into().unwrap())
}

fn read_u32(bytes: &[u8], at: usize) -> u32 {
    u32::from_ne_bytes(bytes[at..at + 4].try_into().unwrap())
}

fn read_u64(bytes: &[u8], at: usize) -> u64 {
    u64::from_ne_bytes(bytes[at..at + 8].try_into().unwrap())
}

/// The opcode and the encoded length of the instruction starting at byte offset `pc`, after a check that the whole
/// instruction lies within `bytes`.
fn opcode_and_length(bytes: &[u8], pc: u32) -> Result<(u8, usize), DecodeError> {
    let error = |kind| DecodeError { pc, kind };
    let at = pc as usize;
    if at >= bytes.len() {
        return Err(error(DecodeErrorKind::TruncatedInstruction));
    }
    let opcode = bytes[at];
    let length = instruction_length_from_bytes(opcode, bytes, at).map_err(error)?;
    if length == 0 || at + length > bytes.len() {
        return Err(error(DecodeErrorKind::TruncatedInstruction));
    }
    if u32::try_from(length).is_err() {
        return Err(error(DecodeErrorKind::InvalidLength));
    }
    Ok((opcode, length))
}

/// Decodes the instruction starting at byte offset `pc`. Its array, if it has one, is in `zone`.
pub fn decode_instruction<'a>(bytes: &[u8], pc: u32, zone: &'a Zone) -> Result<DecodedInstruction<'a>, DecodeError> {
    let error = |kind| DecodeError { pc, kind };
    let (opcode, length) = opcode_and_length(bytes, pc)?;
    let instruction = match decode_fields(opcode, bytes, pc as usize, length, zone).map_err(error)? {
        // NB: The rest of the compiler has no reason to care how far up the frame a move reaches.
        Instruction::MovWide { dst_slot, src_slot } => Instruction::Mov {
            dst: Operand::from_raw(dst_slot),
            src: Operand::from_raw(src_slot),
        },
        instruction => instruction,
    };
    Ok(DecodedInstruction {
        pc,
        length: length as u32,
        instruction,
    })
}

/// The feedback slots of the instruction starting at byte offset `pc`, or `None` if it cannot be decoded.
pub fn feedback_slots_at(bytes: &[u8], pc: u32) -> Option<FeedbackSlots> {
    let (opcode, _) = opcode_and_length(bytes, pc).ok()?;
    Some(feedback_slots_from_bytes(opcode, bytes, pc as usize))
}

/// Decodes a whole instruction stream into `zone`.
pub fn decode_all<'a>(bytes: &[u8], zone: &'a Zone) -> Result<&'a [DecodedInstruction<'a>], DecodeError> {
    let end = u32::try_from(bytes.len()).map_err(|_| DecodeError {
        pc: 0,
        kind: DecodeErrorKind::InvalidLength,
    })?;
    // NB: The list gets its size before the first instruction is decoded, so the arrays that the zone gives out
    //     after it never make it move.
    let mut count = 0;
    let mut pc = 0;
    while pc < end {
        let (_, length) = opcode_and_length(bytes, pc)?;
        pc += length as u32;
        count += 1;
    }
    let mut instructions = ZoneVec::with_capacity_in(count, zone);
    let mut pc = 0;
    while pc < end {
        let instruction = decode_instruction(bytes, pc, zone)?;
        pc = instruction.next_pc();
        instructions.push(instruction);
    }
    Ok(instructions.into_slice())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn operand(index: u32) -> Operand {
        Operand::from_raw(index)
    }

    fn operands_with_roles(instruction: &Instruction) -> Vec<(u32, OperandRole)> {
        let mut operands = Vec::new();
        instruction.for_each_operand(|operand, role| operands.push((operand.raw(), role)));
        operands
    }

    fn jump_targets(instruction: &Instruction) -> Vec<u32> {
        let mut targets = Vec::new();
        instruction.for_each_jump_target(|label| targets.push(label.0));
        targets
    }

    #[test]
    fn decodes_hand_assembled_mov() {
        let mut bytes = vec![OpCode::Mov as u8];
        bytes.push(7); // dst
        bytes.push(12); // src

        let decoded = decode_instruction(&bytes, 0, crate::test_zone()).unwrap();
        assert_eq!(decoded.pc, 0);
        assert_eq!(decoded.length, 3);
        assert_eq!(
            decoded.instruction,
            Instruction::Mov {
                dst: operand(7),
                src: operand(12)
            }
        );
        assert_eq!(decoded.instruction.opcode(), OpCode::Mov);
        assert_eq!(
            operands_with_roles(&decoded.instruction),
            [(7, OperandRole::Out), (12, OperandRole::In)]
        );
        assert!(!decoded.instruction.is_terminator());
        assert!(OpCode::Mov.can_fall_through());
    }

    #[test]
    fn decodes_hand_assembled_jump_if() {
        let mut bytes = vec![0; 16];
        let mut jump = vec![OpCode::JumpIf as u8];
        jump.push(5); // condition
        jump.extend(32u32.to_ne_bytes()); // true_target
        jump.extend(48u32.to_ne_bytes()); // false_target
        bytes.extend(jump);

        let decoded = decode_instruction(&bytes, 16, crate::test_zone()).unwrap();
        assert_eq!(decoded.pc, 16);
        assert_eq!(decoded.length, 10);
        assert_eq!(decoded.next_pc(), 26);
        assert_eq!(
            decoded.instruction,
            Instruction::JumpIf {
                condition: operand(5),
                true_target: Label(32),
                false_target: Label(48)
            }
        );
        assert_eq!(jump_targets(&decoded.instruction), [32, 48]);
        assert_eq!(operands_with_roles(&decoded.instruction), [(5, OperandRole::In)]);
        assert!(decoded.instruction.is_terminator());
        assert!(OpCode::JumpIf.is_terminator());
        assert!(!OpCode::JumpIf.can_fall_through());
        assert!(OpCode::JumpTrue.is_terminator());
        assert!(OpCode::JumpTrue.can_fall_through());
        assert!(!OpCode::Return.can_fall_through());
    }

    #[test]
    fn decodes_variable_length_call() {
        let call = Instruction::Call {
            call_feedback: 0,
            dst: operand(5),
            callee: operand(6),
            this_value: operand(7),
            argument_count: 3,
            arguments: crate::test_zone().alloc_slice_copy(&[operand(8), operand(20), operand(21)]),
        };
        let mut bytes = Vec::new();
        call.encode(&mut bytes);

        let decoded = decode_instruction(&bytes, 0, crate::test_zone()).unwrap();
        assert_eq!(decoded.length as usize, bytes.len());
        assert_eq!(decoded.length as usize, call.encoded_size());
        assert_eq!(decoded.instruction, call);
        assert_eq!(
            operands_with_roles(&decoded.instruction),
            [
                (5, OperandRole::Out),
                (6, OperandRole::In),
                (7, OperandRole::In),
                (8, OperandRole::In),
                (20, OperandRole::In),
                (21, OperandRole::In),
            ]
        );
        assert!(!decoded.instruction.is_terminator());
    }

    #[test]
    fn round_trips_a_stream_of_instructions() {
        let instructions = [
            Instruction::Enter,
            Instruction::NewPrimitiveArray {
                dst: operand(5),
                element_count: 2,
                elements: crate::test_zone().alloc_slice_copy(&[0x7ff8_0000_0000_0001, 42]),
            },
            Instruction::NewClass {
                element_keys_are_in_array: false,
                dst: operand(6),
                super_class: None,
                proto_parent: None,
                class_environment: operand(7),
                class_blueprint_index: 1,
                lhs_name: Some(IdentifierTableIndex(4)),
                computed_name: None,
                element_keys_count: 3,
                element_keys: crate::test_zone().alloc_slice_copy(&[Some(operand(8)), None, Some(operand(9))]),
            },
            Instruction::GetBinding {
                value_feedback: 0,
                dst: operand(5),
                identifier: IdentifierTableIndex(3),
                cache: EnvironmentCoordinate { hops: 1, index: 2 },
            },
            Instruction::CreateArguments {
                dst: None,
                kind: 1,
                is_immutable: true,
                creates_parameter_bindings: false,
            },
            Instruction::AddRhsInt32 {
                arith_feedback: 0,
                dst: operand(5),
                lhs: operand(6),
                rhs: -5,
            },
            Instruction::Mov {
                dst: operand(5),
                src: operand(6),
            },
            Instruction::PostfixIncrement {
                arith_feedback: 0,
                dst: operand(5),
                src: operand(6),
            },
            Instruction::Yield {
                continuation_label: Some(Label(0)),
                value: operand(5),
            },
            Instruction::Yield {
                continuation_label: None,
                value: operand(5),
            },
        ];
        let mut bytes = Vec::new();
        for instruction in &instructions {
            instruction.encode(&mut bytes);
        }

        let decoded = decode_all(&bytes, crate::test_zone()).unwrap();
        assert_eq!(decoded.len(), instructions.len());
        let mut pc = 0;
        for (decoded, instruction) in decoded.iter().zip(&instructions) {
            assert_eq!(&decoded.instruction, instruction);
            assert_eq!(decoded.pc, pc);
            pc += u32::try_from(instruction.encoded_size()).unwrap();
        }

        assert_eq!(
            operands_with_roles(&decoded[2].instruction),
            [
                (6, OperandRole::Out),
                (7, OperandRole::In),
                (8, OperandRole::In),
                (9, OperandRole::In)
            ]
        );
        assert!(operands_with_roles(&decoded[4].instruction).is_empty());
        assert_eq!(
            operands_with_roles(&decoded[6].instruction),
            [(5, OperandRole::Out), (6, OperandRole::In)]
        );
        assert_eq!(
            operands_with_roles(&decoded[7].instruction),
            [(5, OperandRole::Out), (6, OperandRole::InOut)]
        );
        assert_eq!(jump_targets(&decoded[8].instruction), [0]);
        assert!(jump_targets(&decoded[9].instruction).is_empty());
        assert!(decoded[9].instruction.is_terminator());
    }

    #[test]
    fn rejects_malformed_instructions() {
        let error = |bytes: &[u8]| decode_instruction(bytes, 0, crate::test_zone()).unwrap_err().kind;

        assert_eq!(error(&[]), DecodeErrorKind::TruncatedInstruction);
        assert_eq!(error(&[u8::MAX, 0]), DecodeErrorKind::UnknownOpcode);

        let mut mov = Vec::new();
        Instruction::Mov {
            dst: operand(5),
            src: operand(6),
        }
        .encode(&mut mov);
        assert_eq!(error(&mov[..2]), DecodeErrorKind::TruncatedInstruction);

        let mut call = Vec::new();
        Instruction::Call {
            call_feedback: 0,
            dst: operand(5),
            callee: operand(6),
            this_value: operand(7),
            argument_count: 1,
            arguments: crate::test_zone().alloc_slice_copy(&[operand(8)]),
        }
        .encode(&mut call);
        // Call's layout: header, call feedback slot, dst, callee, this_value, argument_count at 6.
        let mut too_many_arguments = call.clone();
        too_many_arguments[6] = 100;
        assert_eq!(error(&too_many_arguments), DecodeErrorKind::TruncatedInstruction);
        assert_eq!(error(&call[..call.len() - 1]), DecodeErrorKind::TruncatedInstruction);

        let mut stream = mov.clone();
        stream.extend(&mov[..2]);
        assert_eq!(
            decode_all(&stream, crate::test_zone()).unwrap_err(),
            DecodeError {
                pc: 3,
                kind: DecodeErrorKind::TruncatedInstruction
            }
        );
    }
}