Skip to content

Truly independent web browser

LibJS: Keep what running code reads in one block of memory

Andreas Klinge8161ce0e4d1
diff --git a/Libraries/LibJS/Rust/src/bytecode/codegen/context.rs b/Libraries/LibJS/Rust/src/bytecode/codegen/context.rs
index 2d612424e50..02afb34b21a 100644
--- a/Libraries/LibJS/Rust/src/bytecode/codegen/context.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/codegen/context.rs
@@ -33,7 +33,6 @@ use crate::parser::EnclosingCode;
use crate::utf16::Utf16View;
use super::constants::ConstantTable;
-use super::emitter::AssembledBytecode;
use super::environment::BindingLocation;
use super::environment::EnclosingEnvironmentScope;
use super::environment::EnvironmentCoordinateScope;
@@ -457,11 +456,6 @@ impl<'t> Generator<'t> {
self.context.initialized_arguments[index] = true;
}
- /// Generates what is left of the bytecode, once all the code has been emitted.
- pub(super) fn assemble(&mut self) -> AssembledBytecode {
- self.finish_stream()
- }
-
pub(super) fn cache_counts(&self) -> ExecutableCacheCounts {
ExecutableCacheCounts {
property_lookup: self.next_property_lookup_cache,
diff --git a/Libraries/LibJS/Rust/src/bytecode/codegen/emitter.rs b/Libraries/LibJS/Rust/src/bytecode/codegen/emitter.rs
index ffbe77786cb..12892c78ffe 100644
--- a/Libraries/LibJS/Rust/src/bytecode/codegen/emitter.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/codegen/emitter.rs
@@ -10,13 +10,14 @@ use crate::bytecode::executable_data::ExceptionHandler;
use crate::bytecode::operand::Operand;
use crate::bytecode::operand::OperandType;
use crate::bytecode::source_map::SourceMapEntry;
+use crate::layout::buffer::BlockSlice;
use crate::u32_from_usize;
/// The result of assembling bytecode.
pub struct AssembledBytecode {
- pub bytecode: Vec<u8>,
- pub source_map: Vec<SourceMapEntry>,
- pub exception_handlers: Vec<ExceptionHandler>,
+ pub bytecode: BlockSlice<u8>,
+ pub source_map: BlockSlice<SourceMapEntry>,
+ pub exception_handlers: BlockSlice<ExceptionHandler>,
pub number_of_registers: u32,
/// One past the highest `Operand::argument` index referenced by any
/// instruction, or 0 if the bytecode never reads an argument.
diff --git a/Libraries/LibJS/Rust/src/bytecode/codegen/names.rs b/Libraries/LibJS/Rust/src/bytecode/codegen/names.rs
index 119fc3fcc5e..2f9361cdd42 100644
--- a/Libraries/LibJS/Rust/src/bytecode/codegen/names.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/codegen/names.rs
@@ -23,7 +23,10 @@ use crate::ast::SyntaxTree;
use crate::bytecode::operand::IdentifierTableIndex;
use crate::bytecode::operand::PropertyKeyTableIndex;
use crate::bytecode::operand::StringTableIndex;
+use crate::layout::buffer::BlockSlice;
use crate::parser::ScriptData;
+use crate::slice_block::SliceBlock;
+use crate::slice_block::SliceBlockBuilder;
use crate::u32_from_usize;
use crate::utf16::Utf16View;
@@ -407,22 +410,31 @@ impl NameTables {
self.script_names.fly_string(tree, name).clone()
}
+ /// How much of a block the tables that stay with the code take.
+ pub(super) fn room_for_tables(&self) -> usize {
+ SliceBlock::room_for::<Utf16FlyString>(self.identifiers.entries.len())
+ + SliceBlock::room_for::<Utf16FlyString>(self.strings.entries.len())
+ }
+
/// Hands out the tables, as an executable keeps them: identifiers, property keys and strings.
pub(super) fn take_tables(
&mut self,
tree: &SyntaxTree,
- ) -> (Vec<Utf16FlyString>, Vec<Utf16FlyString>, Vec<Utf16FlyString>) {
+ block: &mut SliceBlockBuilder,
+ ) -> (
+ BlockSlice<Utf16FlyString>,
+ Box<[Utf16FlyString]>,
+ BlockSlice<Utf16FlyString>,
+ ) {
let script_names = &mut self.script_names;
- let mut take = |table: &Table| -> Vec<Utf16FlyString> {
- let mut strings = Vec::with_capacity(table.entries.len());
- for entry in &table.entries {
- strings.push(match entry {
- TableEntry::Name(name) => script_names.fly_string(tree, *name).clone(),
- TableEntry::Text(text) => text.clone(),
- });
- }
- strings
+ let mut fly_string_of = |entry: &TableEntry| match entry {
+ TableEntry::Name(name) => script_names.fly_string(tree, *name).clone(),
+ TableEntry::Text(text) => text.clone(),
};
- (take(&self.identifiers), take(&self.property_keys), take(&self.strings))
+ (
+ block.slice(self.identifiers.entries.iter().map(&mut fly_string_of)),
+ self.property_keys.entries.iter().map(&mut fly_string_of).collect(),
+ block.slice(self.strings.entries.iter().map(&mut fly_string_of)),
+ )
}
}
diff --git a/Libraries/LibJS/Rust/src/bytecode/codegen/scope.rs b/Libraries/LibJS/Rust/src/bytecode/codegen/scope.rs
index b88f8aed406..d9e93770249 100644
--- a/Libraries/LibJS/Rust/src/bytecode/codegen/scope.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/codegen/scope.rs
@@ -37,6 +37,7 @@ use crate::parser::token::N_DOT_NEW_TARGET;
use crate::parser::token::N_DOT_SUPER;
use crate::parser::token::N_DOT_THIS;
use crate::parser::token::N_DOT_UNBOUND;
+use crate::slice_block::SliceBlock;
use crate::u32_from_usize;
use super::EnclosingEnvironmentScope;
@@ -1936,30 +1937,34 @@ impl Generator<'_> {
shared_function_data.push(pending);
}
- let assembled = self.assemble();
- let (identifier_table, property_key_table, string_table) = self.context.names.take_tables(tree);
+ self.seal_stream();
+ let scope = &self.context.scope;
+ let variable_name_count = scope.locals.len() + scope.parameters.len();
+ let other_tables_size = self.context.names.room_for_tables()
+ + SliceBlock::room_for::<ak::Utf16FlyString>(variable_name_count)
+ + SliceBlock::room_for::<LocalVariableMetadata>(scope.locals.len());
+ let (assembled, mut block) = self.finish_stream(other_tables_size);
+ let (identifier_table, property_key_table, string_table) = self.context.names.take_tables(tree, &mut block);
let context = &mut *self.context;
let constants: Box<[_]> = context.constants.values.drain(..).collect();
let scope = &context.scope;
- let local_variable_metadata = scope
- .locals
- .iter()
- .map(|local| LocalVariableMetadata {
- is_mutable: local.is_mutable,
- scope_range: local.block_range.map(|(start, end)| tree.range_between(start, end)),
- })
- .collect();
- let mut variable_names = Vec::with_capacity(scope.locals.len() + scope.parameters.len());
- for local in &scope.locals {
- variable_names.push(context.names.fly_string_of(tree, local.name));
- }
- for &(name, is_argument) in &scope.parameters {
- variable_names.push(if is_argument {
- context.names.fly_string_of(tree, name)
- } else {
- ak::Utf16FlyString::default()
- });
- }
+ let local_variable_metadata = block.slice(scope.locals.iter().map(|local| LocalVariableMetadata {
+ is_mutable: local.is_mutable,
+ scope_range: local.block_range.map(|(start, end)| tree.range_between(start, end)),
+ }));
+ let local_names = scope.locals.iter().map(|local| (local.name, true));
+ let variable_names = block.slice_of_length(
+ variable_name_count,
+ local_names
+ .chain(scope.parameters.iter().copied())
+ .map(|(name, has_name)| {
+ if has_name {
+ context.names.fly_string_of(tree, name)
+ } else {
+ ak::Utf16FlyString::default()
+ }
+ }),
+ );
let environment_binding_count = scope.environment_binding_count;
let function_environment_binding_count = scope
.function_environment_binding_count
@@ -1975,23 +1980,24 @@ impl Generator<'_> {
Box::default()
};
let executable = ExecutableData {
- bytecode: assembled.bytecode.into(),
- exception_handlers: assembled.exception_handlers.into(),
- source_map: assembled.source_map.into(),
+ bytecode: assembled.bytecode,
+ exception_handlers: assembled.exception_handlers,
+ source_map: assembled.source_map,
number_of_registers: assembled.number_of_registers,
number_of_arguments: assembled.number_of_arguments,
is_strict: self.strict,
cache_counts: self.cache_counts(),
- identifier_table: identifier_table.into(),
- string_table: string_table.into(),
- variable_names: variable_names.into(),
+ identifier_table,
+ string_table,
+ variable_names,
local_variable_metadata,
length_identifier: self.length_identifier,
- property_key_table: property_key_table.into(),
+ property_key_table,
constants,
shared_function_data: shared_function_data.into(),
class_blueprints: std::mem::take(&mut self.class_blueprints).into(),
position_source: Some(script.positions.clone()),
+ tables: block.finish(),
};
let this_from_environment = this_comes_from_environment(flags);
PrecompiledFunction {
diff --git a/Libraries/LibJS/Rust/src/bytecode/codegen/stream.rs b/Libraries/LibJS/Rust/src/bytecode/codegen/stream.rs
index 1043016954c..cf3b95b8ece 100644
--- a/Libraries/LibJS/Rust/src/bytecode/codegen/stream.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/codegen/stream.rs
@@ -34,6 +34,8 @@ use crate::bytecode::instruction::typed::TypedInstruction;
use crate::bytecode::operand::*;
use crate::bytecode::source_map::SourceMapEntry;
use crate::bytecode::source_map::SourceOffset;
+use crate::slice_block::SliceBlock;
+use crate::slice_block::SliceBlockBuilder;
use crate::u32_from_usize;
use libjs_abi::FunctionNamePrefix;
@@ -3594,9 +3596,8 @@ impl Generator<'_> {
});
}
- /// Assembles what was emitted: the operands that come after the registers get their place in the frame, and labels
- /// their offsets.
- pub(super) fn finish_stream(&mut self) -> AssembledBytecode {
+ /// Ends the code, so that nothing comes after this but assembling it.
+ pub(super) fn seal_stream(&mut self) {
if !self.is_stream_dead() {
let value = match self.context.stream.completion {
Some(completion) => completion,
@@ -3613,6 +3614,11 @@ impl Generator<'_> {
}
}
self.insert_body_head();
+ }
+
+ /// Assembles what was emitted into a new block, which has `other_tables_size` bytes left: the operands that come
+ /// after the registers get their place in the frame, and labels their offsets.
+ pub(super) fn finish_stream(&mut self, other_tables_size: usize) -> (AssembledBytecode, SliceBlockBuilder) {
let frame = FrameLayout {
register_count: self.context.stream.temporary_count.max(Register::RESERVED_COUNT),
local_count: self.context.scope.local_count(),
@@ -3622,7 +3628,7 @@ impl Generator<'_> {
let head = &stream.head;
let segment = &mut stream.current;
let head_size = u32_from_usize(head.bytes.len());
- let mut exception_handlers = Vec::with_capacity(stream.handler_changes.len());
+ let mut exception_handlers = Vec::new();
for (index, &(start, handler)) in stream.handler_changes.iter().enumerate() {
let end = stream
.handler_changes
@@ -3639,9 +3645,14 @@ impl Generator<'_> {
});
}
}
- let mut bytecode = Vec::with_capacity(head.bytes.len() + segment.bytes.len());
- bytecode.extend_from_slice(&head.bytes);
- bytecode.extend_from_slice(&segment.bytes);
+ let source_entry_count = head.source_entries.len() + segment.source_entries.len();
+ let mut block = SliceBlock::builder(
+ SliceBlock::room_for::<u8>(head.bytes.len() + segment.bytes.len())
+ + SliceBlock::room_for::<SourceMapEntry>(source_entry_count)
+ + SliceBlock::room_for::<ExceptionHandler>(exception_handlers.len())
+ + other_tables_size,
+ );
+ let mut bytecode = block.slice_from_parts(&head.bytes, &segment.bytes);
let head_positions = head.operand_positions.iter().map(|position| position.offset);
let positions = segment
.operand_positions
@@ -3666,20 +3677,23 @@ impl Generator<'_> {
.source_entries
.iter()
.map(|&(bytecode_offset, source_offset)| (bytecode_offset + head_size, source_offset));
- let source_map = head_entries
- .chain(entries)
- .map(|(bytecode_offset, source_offset)| SourceMapEntry {
- bytecode_offset,
- line: u32::MAX,
- column: source_offset.0,
- })
- .collect();
- AssembledBytecode {
+ let source_map = block.slice_of_length(
+ source_entry_count,
+ head_entries
+ .chain(entries)
+ .map(|(bytecode_offset, source_offset)| SourceMapEntry {
+ bytecode_offset,
+ line: u32::MAX,
+ column: source_offset.0,
+ }),
+ );
+ let assembled = AssembledBytecode {
bytecode,
source_map,
- exception_handlers,
+ exception_handlers: block.slice(exception_handlers.into_iter()),
number_of_registers: frame.register_count,
number_of_arguments: stream.number_of_arguments,
- }
+ };
+ (assembled, block)
}
}
diff --git a/Libraries/LibJS/Rust/src/bytecode/executable_data.rs b/Libraries/LibJS/Rust/src/bytecode/executable_data.rs
index b706ef2c7dd..539982daa50 100644
--- a/Libraries/LibJS/Rust/src/bytecode/executable_data.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/executable_data.rs
@@ -17,6 +17,8 @@ use super::source_map::SourceMapEntry;
use crate::ast::FunctionId;
use crate::compile::SharedFunctionDescription;
use crate::compile::utf16_string_memory_size;
+use crate::layout::buffer::BlockSlice;
+use crate::slice_block::SliceBlock;
/// Exception handler range (with byte offsets, post-linking).
#[derive(Debug, Clone)]
@@ -172,21 +174,21 @@ pub struct LocalVariableMetadata {
///
/// [`Executable`]: super::executable::Executable
pub struct ExecutableData {
- pub bytecode: Box<[u8]>,
+ pub bytecode: BlockSlice<u8>,
/// Sorted by start offset, and not overlapping.
- pub exception_handlers: Box<[ExceptionHandler]>,
+ pub exception_handlers: BlockSlice<ExceptionHandler>,
/// Sorted by bytecode offset: where in the source code the instructions from each offset on came from.
- pub source_map: Box<[SourceMapEntry]>,
+ pub source_map: BlockSlice<SourceMapEntry>,
pub number_of_registers: u32,
pub number_of_arguments: u32,
pub is_strict: bool,
pub cache_counts: ExecutableCacheCounts,
- pub identifier_table: Box<[ak::Utf16FlyString]>,
- pub string_table: Box<[ak::Utf16FlyString]>,
+ pub identifier_table: BlockSlice<ak::Utf16FlyString>,
+ pub string_table: BlockSlice<ak::Utf16FlyString>,
/// The names of the local variables, then the names of the arguments.
- pub variable_names: Box<[ak::Utf16FlyString]>,
+ pub variable_names: BlockSlice<ak::Utf16FlyString>,
/// One for each of the local variables.
- pub local_variable_metadata: Box<[LocalVariableMetadata]>,
+ pub local_variable_metadata: BlockSlice<LocalVariableMetadata>,
pub length_identifier: Option<PropertyKeyTableIndex>,
/// What linking reads, and nothing after it (see [`ExecutableData::release_link_inputs()`]).
pub property_key_table: Box<[ak::Utf16FlyString]>,
@@ -195,6 +197,8 @@ pub struct ExecutableData {
pub class_blueprints: Box<[PendingClassBlueprint]>,
/// What turns the source offsets of a source map that has them into lines and columns.
pub position_source: Option<Arc<crate::parser::SourcePositions>>,
+ /// The memory of everything above that running the code reads, which gets dropped before it.
+ pub tables: SliceBlock,
}
fn constant_memory_size(constant: &ConstantValue) -> usize {
@@ -205,6 +209,11 @@ fn constant_memory_size(constant: &ConstantValue) -> usize {
}
}
+// SAFETY: Code compiles away from the heap, so it cannot hold a cell. What it describes turns into cells only when an
+// Executable links it, and those stay with that Executable.
+#[cfg(not(test))]
+unsafe impl crate::gc::lint_markers::HoldsNoCells for ExecutableData {}
+
impl ExecutableData {
/// The entries of the source map, with the lines and columns that they stand for. Code that goes by offsets of the
/// source leaves working those out until something asks.
diff --git a/Libraries/LibJS/Rust/src/slice_block.rs b/Libraries/LibJS/Rust/src/slice_block.rs
index 8a43f373299..62318e07f89 100644
--- a/Libraries/LibJS/Rust/src/slice_block.rs
+++ b/Libraries/LibJS/Rust/src/slice_block.rs
@@ -100,26 +100,48 @@ pub struct SliceBlockBuilder {
impl SliceBlockBuilder {
/// Moves `elements` into the block. It has to have been made with room for them.
pub fn slice<T>(&mut self, elements: impl ExactSizeIterator<Item = T>) -> BlockSlice<T> {
- let length = elements.len();
+ self.slice_of_length(elements.len(), elements)
+ }
+
+ /// Moves the `length` elements that `elements` yields into the block.
+ pub fn slice_of_length<T>(&mut self, length: usize, elements: impl Iterator<Item = T>) -> BlockSlice<T> {
+ let data = self.claim::<T>(length);
+ let mut written = 0;
+ for element in elements.take(length) {
+ // SAFETY: There is room for `length` elements.
+ unsafe { data.add(written).write(element) };
+ written += 1;
+ }
+ assert_eq!(written, length, "an iterator yields as much as it says");
+ BlockSlice::from_data(data)
+ }
+
+ /// Copies two slices into the block, one after the other, as one.
+ pub fn slice_from_parts<T: Copy>(&mut self, first: &[T], second: &[T]) -> BlockSlice<T> {
+ let data = self.claim::<T>(first.len() + second.len());
+ // SAFETY: There is room for both, and nothing else knows of that memory.
+ unsafe {
+ core::ptr::copy_nonoverlapping(first.as_ptr(), data, first.len());
+ core::ptr::copy_nonoverlapping(second.as_ptr(), data.add(first.len()), second.len());
+ }
+ BlockSlice::from_data(data)
+ }
+
+ /// Room for `length` elements with their length in front of them, or null if that is none.
+ fn claim<T>(&mut self, length: usize) -> *mut T {
let room = SliceBlock::room_for::<T>(length);
assert!(room <= self.remaining, "a block has room for what goes in it");
if length == 0 {
- return BlockSlice::empty();
+ return core::ptr::null_mut();
}
- // SAFETY: There is room for the length and for `length` elements, aligned for both, since everything in a block
- // takes a multiple of the size of the length.
+ // SAFETY: There is room, aligned for the length and for the elements, since everything in a block takes a
+ // multiple of the size of the length.
unsafe {
self.free.cast::<usize>().write(length);
let data = self.free.add(THIN_SLICE_HEADER_SIZE).cast::<T>();
- let mut written = 0;
- for element in elements.take(length) {
- data.add(written).write(element);
- written += 1;
- }
- assert_eq!(written, length, "an iterator yields as much as it says");
self.free = self.free.add(room);
self.remaining -= room;
- BlockSlice::from_data(data)
+ data
}
}
@@ -129,6 +151,11 @@ impl SliceBlockBuilder {
}
}
+// SAFETY: A slice owns its elements, like a Box<[T]>.
+unsafe impl<T: Send> Send for BlockSlice<T> {}
+// SAFETY: As above.
+unsafe impl<T: Sync> Sync for BlockSlice<T> {}
+
impl<T> BlockSlice<T> {
pub fn as_slice(&self) -> &[T] {
if self.data.is_null() {