Truly independent web browser
LibJS: Let a compiled program be kept and linked more than once
Andreas Kling3ffc2af00c47
diff --git a/Libraries/LibJS/Rust/src/ast.rs b/Libraries/LibJS/Rust/src/ast.rsindex 9d7b94a1eee..5c92f27e26a 100644--- a/Libraries/LibJS/Rust/src/ast.rs+++ b/Libraries/LibJS/Rust/src/ast.rs@@ -285,6 +285,14 @@ pub(crate) struct NameTable {}impl NameTable {+ pub(crate) fn memory_size(&self) -> usize {+ self.spans.capacity() * size_of::<NameSpan>()+ + self.ascii_text.capacity()+ + self.utf16_text.capacity() * size_of::<u16>()+ + self.utf8_text.capacity()+ + self.utf8_spans.capacity() * size_of::<(u32, u32)>()+ }+pub(crate) fn push(&mut self, text: &[u8]) {let is_ascii = text.is_ascii();let start = if is_ascii {diff --git a/Libraries/LibJS/Rust/src/bytecode/executable_data.rs b/Libraries/LibJS/Rust/src/bytecode/executable_data.rsindex a1be1b852ad..b706ef2c7dd 100644--- a/Libraries/LibJS/Rust/src/bytecode/executable_data.rs+++ b/Libraries/LibJS/Rust/src/bytecode/executable_data.rs@@ -16,6 +16,7 @@ use super::operand::PropertyKeyTableIndex;use super::source_map::SourceMapEntry;use crate::ast::FunctionId;use crate::compile::SharedFunctionDescription;+use crate::compile::utf16_string_memory_size;/// Exception handler range (with byte offsets, post-linking).#[derive(Debug, Clone)]@@ -76,6 +77,21 @@ pub struct PrecompiledFunction {pub metadata: FunctionSfdMetadata,}+impl PrecompiledFunction {+ /// The bytes of this function's code, without the functions kept for its payloads.+ pub fn memory_size(&self) -> usize {+ size_of::<Self>() + size_of_val(&*self.metadata.parameter_names) + self.executable.memory_size()+ }++ /// This function again, sharing its code.+ pub fn shared_copy(&self) -> Self {+ Self {+ executable: self.executable.clone(),+ metadata: self.metadata.clone(),+ }+ }+}+#[derive(Clone, Copy)]pub enum PendingLiteralValueKind {None,@@ -108,6 +124,20 @@ pub struct PendingClassBlueprint {pub elements: Vec<PendingClassElement>,}+impl PendingClassBlueprint {+ pub fn memory_size(&self) -> usize {+ let string_size = |string: &Option<Utf16String>| string.as_ref().map_or(0, utf16_string_memory_size);+ size_of::<Self>()+ + string_size(&self.name)+ + self.elements.capacity() * size_of::<PendingClassElement>()+ + self+ .elements+ .iter()+ .map(|element| string_size(&element.private_identifier) + string_size(&element.literal_value_string))+ .sum::<usize>()+ }+}+/// How many inline cache and feedback slots of each kind the bytecode indexes into.#[derive(Clone, Copy)]pub struct ExecutableCacheCounts {@@ -167,6 +197,14 @@ pub struct ExecutableData {pub position_source: Option<Arc<crate::parser::SourcePositions>>,}+fn constant_memory_size(constant: &ConstantValue) -> usize {+ match constant {+ ConstantValue::String(string) => utf16_string_memory_size(string),+ ConstantValue::BigInt(literal) => literal.capacity(),+ _ => 0,+ }+}+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.@@ -191,6 +229,32 @@ impl ExecutableData {})}+ /// The bytes of this code and of what it holds for the functions and classes it declares. A name in one of the tables+ /// counts as its slot in the table, since the text of a name is shared by everything that uses it.+ pub fn memory_size(&self) -> usize {+ size_of::<Self>()+ + size_of_val(&*self.bytecode)+ + size_of_val(&*self.exception_handlers)+ + size_of_val(&*self.source_map)+ + size_of_val(&*self.identifier_table)+ + size_of_val(&*self.string_table)+ + size_of_val(&*self.variable_names)+ + size_of_val(&*self.local_variable_metadata)+ + size_of_val(&*self.property_key_table)+ + size_of_val(&*self.constants)+ + self.constants.iter().map(constant_memory_size).sum::<usize>()+ + self+ .shared_function_data+ .iter()+ .map(PendingSharedFunctionData::memory_size)+ .sum::<usize>()+ + self+ .class_blueprints+ .iter()+ .map(PendingClassBlueprint::memory_size)+ .sum::<usize>()+ }+/// Frees what only linking reads, for an executable that is the last to hold this code, so that code nothing can/// link again costs no more than what running it reads.pub fn release_link_inputs(&mut self) {diff --git a/Libraries/LibJS/Rust/src/compile.rs b/Libraries/LibJS/Rust/src/compile.rsindex 81e1b7aad7b..7c402b02fba 100644--- a/Libraries/LibJS/Rust/src/compile.rs+++ b/Libraries/LibJS/Rust/src/compile.rs@@ -161,13 +161,20 @@ pub fn parse(source: &ak::Utf16String, program_type: ProgramType, initial_line_n/// A script or module compiled to bytecode, with what its record needs from its code. The syntax tree is gone by now, so/// a compiled program holds no more of its source than the functions that have yet to compile need.+///+/// A clone shares everything with the original, and both can be finished into records of any number of realms.+#[derive(Clone)]pub struct CompiledProgram {program_type: ProgramType,has_top_level_await: bool,executable: Arc<ExecutableData>,declarations: CompiledProgramDeclarations,+ script: Arc<ScriptData>,+ /// The bytes of the top-level code and of the declarations, which do not change.+ top_level_size: usize,}+#[derive(Clone)]enum CompiledProgramDeclarations {Script(Arc<ScriptDeclarations>),Module(Arc<ModuleDeclarations>),@@ -278,11 +285,18 @@ pub fn compile_parsed_program_off_thread(parsed: ParsedProgram) -> CompiledProgrtree.script.index.prepare_for_reparsing();+ let declarations_size = match &declarations {+ CompiledProgramDeclarations::Script(declarations) => declarations.memory_size(),+ CompiledProgramDeclarations::Module(declarations) => declarations.memory_size(),+ };+CompiledProgram {program_type: parsed.program_type,has_top_level_await: parsed.has_top_level_await,+ top_level_size: executable.memory_size() + declarations_size,executable,declarations,+ script: tree.script.clone(),}}@@ -295,6 +309,18 @@ impl CompiledProgram {self.has_top_level_await}+ /// Whether the code that functions of this program compile to stays with the program from now on, so that the+ /// next record of it finds them compiled. It is memory that nothing but such a record has a use for.+ pub fn set_retains_compiled_functions(&self, retains_compiled_functions: bool) {+ self.script.set_retains_compiled_functions(retains_compiled_functions);+ }++ /// The bytes that the program holds on to right now: its source and the tables of its functions, its top-level+ /// code, and the code of its functions that compiled while it retained them.+ pub fn memory_size(&self) -> usize {+ self.top_level_size + self.script.memory_size()+ }+/// Finishes a script into what [`compile_script()`] returns.////// # Panics@@ -572,6 +598,18 @@ fn for_each_bound_name_in_pattern(pattern: &ast::BindingPattern, f: &mut dyn FnM// Eval// =============================================================================+/// The bytes of the storage of `string`.+pub(crate) fn utf16_string_memory_size(string: &Utf16String) -> usize {+ match string.as_units() {+ ak::Utf16StringUnits::Ascii(units) | ak::Utf16StringUnits::Latin1(units) => units.len(),+ ak::Utf16StringUnits::Utf16(units) => size_of_val(units),+ }+}++fn utf16_strings_memory_size(strings: &[Utf16String]) -> usize {+ size_of_val(strings) + strings.iter().map(utf16_string_memory_size).sum::<usize>()+}+/// How the code an eval runs relates to the code that calls it, as PerformEval works it out.#[derive(Clone, Copy, Default)]pub struct EvalContext {@@ -674,6 +712,43 @@ pub struct ModuleDeclarations {pub requested_modules: Vec<ast::ModuleRequest>,}+impl ModuleDeclarations {+ fn memory_size(&self) -> usize {+ let optional_string_size = |string: &Option<Utf16String>| string.as_ref().map_or(0, utf16_string_memory_size);+ let entries = [+ &self.local_export_entries,+ &self.indirect_export_entries,+ &self.star_export_entries,+ ];+ let export_entries_size = entries.iter().flat_map(|entries| entries.iter()).map(|entry| {+ size_of::<ModuleExportEntry>()+ + optional_string_size(&entry.export_name)+ + optional_string_size(&entry.local_or_import_name)+ });+ let import_entries_size = self.import_entries.iter().map(|entry| {+ size_of::<ModuleImportEntry>()+ + optional_string_size(&entry.import_name)+ + utf16_string_memory_size(&entry.local_name)+ });+ let functions_size = self.functions_to_initialize.iter().map(|function| {+ size_of::<ModuleFunctionToInitialize>()+ + function.description.memory_size()+ + utf16_string_memory_size(&function.name)+ });+ let lexical_bindings_size = self+ .lexical_bindings+ .iter()+ .map(|binding| size_of::<ModuleLexicalBinding>() + utf16_string_memory_size(&binding.name));+ size_of::<Self>()+ + utf16_strings_memory_size(&self.var_names)+ + size_of_val(&*self.requested_modules)+ + export_entries_size.sum::<usize>()+ + import_entries_size.sum::<usize>()+ + functions_size.sum::<usize>()+ + lexical_bindings_size.sum::<usize>()+ }+}+/// Collects what ParseModule records from a module's top-level scope.pub fn collect_module_declarations(tree: &Arc<SyntaxTree>) -> ModuleDeclarations {use ast::ExportEntryKind;@@ -1082,6 +1157,14 @@ pub struct SharedFunctionDescription {pub payload: Arc<FunctionPayload>,}+impl SharedFunctionDescription {+ /// The bytes of this description and of its payload. What the payload shares with the functions around it counts+ /// for those.+ pub(crate) fn memory_size(&self) -> usize {+ size_of::<Self>() + size_of::<FunctionPayload>()+ }+}+/// Describes a function of `tree`, whose code does not have to be in the tree.pub fn describe_shared_function(tree: &SyntaxTree,@@ -1193,6 +1276,20 @@ impl PendingSharedFunctionData {}}+ /// The bytes of what is kept for this function, including the code it was precompiled to.+ pub fn memory_size(&self) -> usize {+ size_of::<Self>() - size_of::<SharedFunctionDescription>()+ + self.description.memory_size()+ + self+ .class_field_initializer_name+ .as_ref()+ .map_or(0, |(name, _)| utf16_string_memory_size(name))+ + self+ .precompiled_function+ .as_ref()+ .map_or(0, |precompiled| precompiled.memory_size())+ }+/// The environment that the function closes over.pub fn enclosing_environment_scope(&self) -> Option<Arc<bytecode::codegen::EnclosingEnvironmentScope>> {self.description.payload.enclosing_environment_scope.clone()@@ -1267,6 +1364,27 @@ pub struct EvalDeclarations {pub private_names: Vec<Utf16String>,}+impl ScriptDeclarations {+ fn memory_size(&self) -> usize {+ let functions_size = self.functions_to_initialize.iter().map(|function| {+ size_of::<FunctionToInitialize>() - size_of::<PendingSharedFunctionData>()+ + function.shared_function_data.memory_size()+ + utf16_string_memory_size(&function.name)+ });+ let lexical_bindings_size = self+ .lexical_bindings+ .iter()+ .map(|binding| size_of::<LexicalBinding>() + utf16_string_memory_size(&binding.name));+ size_of::<Self>()+ + utf16_strings_memory_size(&self.lexical_names)+ + utf16_strings_memory_size(&self.var_names)+ + utf16_strings_memory_size(&self.var_scoped_names)+ + utf16_strings_memory_size(&self.annex_b_candidate_names)+ + functions_size.sum::<usize>()+ + lexical_bindings_size.sum::<usize>()+ }+}+/// Collect what GlobalDeclarationInstantiation needs from a script's top-level scope.pub fn collect_script_declarations(tree: &Arc<SyntaxTree>) -> ScriptDeclarations {use ast::DeclarationKind;diff --git a/Libraries/LibJS/Rust/src/embedding/compile.rs b/Libraries/LibJS/Rust/src/embedding/compile.rsindex 5e2015e8837..1d23ef772ea 100644--- a/Libraries/LibJS/Rust/src/embedding/compile.rs+++ b/Libraries/LibJS/Rust/src/embedding/compile.rs@@ -178,6 +178,45 @@ pub unsafe fn compiled_program_from_abi<'a>(compiled: *const JSCompiledProgram)unsafe { &*compiled.cast::<CompiledProgram>() }}+/// CompiledProgram::clone(): another reference to the same compiled program, which the caller owns. Any thread may call+/// this.+///+/// # Safety+///+/// `compiled` must be a live compiled program.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn js_compile_compiled_program_clone(+ compiled: *const JSCompiledProgram,+) -> *mut JSCompiledProgram {+ // SAFETY: The caller passes a live compiled program.+ compiled_program_into_abi(unsafe { compiled_program_from_abi(compiled) }.clone())+}++/// CompiledProgram::memory_size(). Any thread may call this.+///+/// # Safety+///+/// `compiled` must be a live compiled program.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn js_compile_compiled_program_memory_size(compiled: *const JSCompiledProgram) -> usize {+ // SAFETY: The caller passes a live compiled program.+ unsafe { compiled_program_from_abi(compiled) }.memory_size()+}++/// CompiledProgram::set_retains_compiled_functions(). Any thread may call this.+///+/// # Safety+///+/// `compiled` must be a live compiled program.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn js_compile_compiled_program_set_retains_compiled_functions(+ compiled: *const JSCompiledProgram,+ retains_compiled_functions: bool,+) {+ // SAFETY: The caller passes a live compiled program.+ unsafe { compiled_program_from_abi(compiled) }.set_retains_compiled_functions(retains_compiled_functions);+}+/// Destroys a compiled program that the caller owns and that will not run, freeing what the frontend compiled for it./// Null does nothing. Any thread may call this.///diff --git a/Libraries/LibJS/Rust/src/parser/columns.rs b/Libraries/LibJS/Rust/src/parser/columns.rsindex 1cb7e22149a..682e1442dab 100644--- a/Libraries/LibJS/Rust/src/parser/columns.rs+++ b/Libraries/LibJS/Rust/src/parser/columns.rs@@ -351,6 +351,24 @@ impl FunctionIndex {(start, end)}+ pub fn memory_size(&self) -> usize {+ let u32_columns = [+ &self.start,+ &self.params_start,+ &self.end,+ &self.flags,+ &self.length,+ &self.parameter_count,+ &self.name,+ &self.capture_start,+ &self.capture_count,+ &self.capture_names,+ ];+ let sorted_rows = self.rows_by_params_start.get().map_or(0, Vec::capacity);+ (u32_columns.iter().map(|column| column.capacity()).sum::<usize>() + sorted_rows) * size_of::<u32>()+ + self.ctx.capacity() * size_of::<u16>()+ }+/// Gives back what parsing set aside for rows that it did not need, now that the index is all that stays.pub fn shrink_to_fit(&mut self) {self.start.shrink_to_fit();diff --git a/Libraries/LibJS/Rust/src/parser/mod.rs b/Libraries/LibJS/Rust/src/parser/mod.rsindex 43aabcff1c5..754484a32cf 100644--- a/Libraries/LibJS/Rust/src/parser/mod.rs+++ b/Libraries/LibJS/Rust/src/parser/mod.rs@@ -35,6 +35,7 @@ use base::Parser;use columns::Ast;use columns::FunctionIndex;use columns::function_flag;+use core::sync::atomic::AtomicBool;use core::sync::atomic::AtomicUsize;use core::sync::atomic::Ordering;use intern::Interner;@@ -78,6 +79,11 @@ pub struct ScriptData {global_names_used_in_with: Vec<u32>,/// Filled in when the first function gets parsed again, for the ones after it.reparse_context: Mutex<Option<ReparseContext>>,+ /// Whether the code that gets compiled for the functions of this source is worth keeping, because the program may+ /// get linked again.+ retains_compiled_functions: AtomicBool,+ /// The bytes of the code kept so far, for [`ScriptData::memory_size()`].+ retained_code_size: AtomicUsize,}/// The memory of the tree of a function that a compile job is done with, for the next one on the thread.@@ -175,6 +181,22 @@ pub(crate) fn vm_stack_limit_of_this_thread() -> Option<usize> {}impl ScriptData {+ pub(crate) fn set_retains_compiled_functions(&self, retains_compiled_functions: bool) {+ self.retains_compiled_functions+ .store(retains_compiled_functions, Ordering::Relaxed);+ }++ /// The bytes of this source and of the tables that compile jobs read, and of the code kept for its functions so far.+ pub(crate) fn memory_size(&self) -> usize {+ size_of::<Self>()+ + crate::compile::utf16_string_memory_size(&self.positions.source)+ + self.index.memory_size()+ + self.names.memory_size()+ + self.positions.lines.memory_size()+ + self.global_names_used_in_with.capacity() * size_of::<u32>()+ + self.retained_code_size.load(Ordering::Relaxed)+ }+/// The rows of the top level for a sweep, which the parse of the source left here for its one compile.pub(crate) fn take_top_level_rows(self: &Arc<Self>) -> Result<(SyntaxTree, u32), OutOfStack> {let rows = self.top_level_rows.lock().expect("nothing panics with the rows").take();@@ -349,6 +371,10 @@ pub(crate) struct LineTable {}impl LineTable {+ fn memory_size(&self) -> usize {+ (self.line_starts.capacity() + self.low_surrogates.capacity()) * size_of::<u32>()+ }+fn new<U: Unit>(source: &[U], initial_line_number: u32) -> Self {let mut line_starts = vec![0];let mut low_surrogates = Vec::new();@@ -616,6 +642,8 @@ pub fn parse_to_tree(source: &ak::Utf16String, options: &ParseOptions) -> Resultdefault_constructor_parameter_name,global_names_used_in_with,reparse_context: Mutex::new(None),+ retains_compiled_functions: AtomicBool::new(false),+ retained_code_size: AtomicUsize::new(0),});let mut tree = SyntaxTree {script,diff --git a/Libraries/LibJS/ScriptCompilation.cpp b/Libraries/LibJS/ScriptCompilation.cppindex d2dcdd1e485..d1bd076b926 100644--- a/Libraries/LibJS/ScriptCompilation.cpp+++ b/Libraries/LibJS/ScriptCompilation.cpp@@ -151,6 +151,21 @@ CompiledProgram CompiledProgram::compile(ParsedProgram parsed)return CompiledProgram { compiled_program_from_abi(js_compile_parsed_program(program)) };}+CompiledProgram CompiledProgram::clone() const+{+ return CompiledProgram { compiled_program_from_abi(js_compile_compiled_program_clone(compiled_program_to_abi(m_program))) };+}++void CompiledProgram::set_retains_compiled_functions(bool retains_compiled_functions) const+{+ js_compile_compiled_program_set_retains_compiled_functions(compiled_program_to_abi(m_program), retains_compiled_functions);+}++size_t CompiledProgram::memory_size() const+{+ return js_compile_compiled_program_memory_size(compiled_program_to_abi(m_program));+}+Result<GC::Ref<Script>, Vector<ParserError>> create_script(ParsedProgram parsed, NonnullRefPtr<SourceCode const> source_code, Realm& realm, StringView filename, GC::Ptr<GC::Cell> host_defined){ParserErrorCollector errors;diff --git a/Libraries/LibJS/ScriptCompilation.h b/Libraries/LibJS/ScriptCompilation.hindex 2720cf97df0..30b27893585 100644--- a/Libraries/LibJS/ScriptCompilation.h+++ b/Libraries/LibJS/ScriptCompilation.h@@ -120,6 +120,17 @@ public:explicit operator bool() const { return m_program; }+ // Another reference to the same program, which can be turned into a record of its own, in any realm. They all share+ // the program's code, and each record gets the caches and the functions that depend on its realm.+ CompiledProgram clone() const;++ // Whether the code that the program's functions compile to stays with the program from now on, so that the next+ // record finds them compiled. Otherwise, it goes away with the function that compiled it.+ void set_retains_compiled_functions(bool) const;++ // The bytes that the program holds on to right now, which grows as functions compile while it retains them.+ size_t memory_size() const;+private:friend JS_API Result<GC::Ref<Script>, Vector<ParserError>> create_script(CompiledProgram, NonnullRefPtr<SourceCode const>, Realm&, StringView filename, GC::Ptr<GC::Cell>);friend JS_API Result<GC::Ref<SourceTextModule>, Vector<ParserError>> create_module(CompiledProgram, NonnullRefPtr<SourceCode const>, Realm&, StringView filename, GC::Ptr<GC::Cell>);