Truly independent web browser
LibJS+LibWeb: Keep a digest of script text in the compiled script cache
Andreas Klingb1ade9cc28d9
diff --git a/Libraries/LibJS/Rust/src/embedding/source_code.rs b/Libraries/LibJS/Rust/src/embedding/source_code.rsindex 7d5ccba34c9..170bde9bdee 100644--- a/Libraries/LibJS/Rust/src/embedding/source_code.rs+++ b/Libraries/LibJS/Rust/src/embedding/source_code.rs@@ -64,6 +64,23 @@ pub unsafe extern "C" fn js_source_code_create(Rc::into_raw(SourceCode::create(filename, code)).cast()}+/// SourceCode::create_sharing_code(filename, other): new source code with the code of `other`, whose one reference the+/// caller owns and gives up with js_source_code_release(). Adopts the filename, which the caller gives up with+/// AK::Utf16String::into_raw(). Only the VM's thread may call this.+///+/// # Safety+///+/// `filename` must be a raw AK::Utf16String whose reference the caller gives up, and `other` must be live source code.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn js_source_code_create_sharing_code(+ filename: JSOwnedUtf16String,+ other: *const JSSourceCode,+) -> *const JSSourceCode {+ // SAFETY: The caller transfers the reference to the filename and passes live source code.+ let (filename, other) = unsafe { (owned_utf16_string_from_abi(filename), source_code_from_abi(other)) };+ Rc::into_raw(SourceCode::create_sharing_code(filename, other)).cast()+}+/// Adds a reference to the source code, which the caller gives up with js_source_code_release(). Only the VM's thread/// may call this.///@@ -177,6 +194,22 @@ pub unsafe extern "C" fn js_weak_source_code_is_alive(weak: *const JSWeakSourceCunsafe { &*weak.cast::<std::rc::Weak<SourceCode>>() }.strong_count() > 0}+/// The source code of the weak reference with one more reference, which the caller gives up with+/// js_source_code_release(), or null if nothing holds it anymore. Only the VM's thread may call this.+///+/// # Safety+///+/// `weak` must be a weak reference that js_source_code_downgrade() handed out and that was not destroyed.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn js_weak_source_code_upgrade(weak: *const JSWeakSourceCode) -> *const JSSourceCode {+ assert!(!weak.is_null(), "the embedder passes a weak reference");+ // SAFETY: The caller passes a live weak reference, which is a boxed Weak<SourceCode>.+ unsafe { &*weak.cast::<std::rc::Weak<SourceCode>>() }+ .upgrade()+ .map_or(core::ptr::null(), Rc::into_raw)+ .cast()+}+/// Destroys a weak reference that js_source_code_downgrade() handed out. Null does nothing. Only the VM's thread may/// call this.///diff --git a/Libraries/LibJS/Rust/src/source_code.rs b/Libraries/LibJS/Rust/src/source_code.rsindex 0cf91b70f11..72d78ba4582 100644--- a/Libraries/LibJS/Rust/src/source_code.rs+++ b/Libraries/LibJS/Rust/src/source_code.rs@@ -28,6 +28,14 @@ impl SourceCode {})}+ /// Source code under `filename` that shares the code of `other`, parked or not.+ pub fn create_sharing_code(filename: Utf16String, other: &SourceCode) -> Rc<SourceCode> {+ Rc::new(Self {+ filename,+ code: Arc::clone(&other.code),+ })+ }+pub fn filename(&self) -> &Utf16String {&self.filename}diff --git a/Libraries/LibJS/SourceCode.cpp b/Libraries/LibJS/SourceCode.cppindex a6902210445..65c5c13325d 100644--- a/Libraries/LibJS/SourceCode.cpp+++ b/Libraries/LibJS/SourceCode.cpp@@ -26,6 +26,11 @@ NonnullRefPtr<SourceCode const> SourceCode::create(Utf16String filename, Utf16Streturn adopt_source_code_from_abi(js_source_code_create(owned_utf16_string_to_abi(move(filename)), owned_utf16_string_to_abi(move(code))));}+NonnullRefPtr<SourceCode const> SourceCode::create_sharing_code(Utf16String filename, SourceCode const& other)+{+ return adopt_source_code_from_abi(js_source_code_create_sharing_code(owned_utf16_string_to_abi(move(filename)), source_code_to_abi(other)));+}+Utf16String const& SourceCode::filename() const{return string_in_place_from_abi(js_source_code_filename_address(source_code_to_abi(*this)));@@ -85,4 +90,14 @@ bool WeakSourceCode::is_alive() constreturn m_weak && js_weak_source_code_is_alive(weak_source_code_to_abi(m_weak));}+RefPtr<SourceCode const> WeakSourceCode::strong_ref() const+{+ if (!m_weak)+ return nullptr;+ auto const* source_code = js_weak_source_code_upgrade(weak_source_code_to_abi(m_weak));+ if (!source_code)+ return nullptr;+ return adopt_source_code_from_abi(source_code);+}+}diff --git a/Libraries/LibJS/SourceCode.h b/Libraries/LibJS/SourceCode.hindex dcda92872d3..b36ddd9ea37 100644--- a/Libraries/LibJS/SourceCode.h+++ b/Libraries/LibJS/SourceCode.h@@ -36,6 +36,8 @@ public:GC_HOLDS_NO_CELL_EDGES;static NonnullRefPtr<SourceCode const> create(Utf16String filename, Utf16String code);+ // Source code under another filename that shares the code of the given source code, parked or not.+ static NonnullRefPtr<SourceCode const> create_sharing_code(Utf16String filename, SourceCode const&);Utf16String const& filename() const;// NB: The runtime may hold the code compressed, so this is a string of its own, not a reference to one.@@ -60,6 +62,7 @@ public:~WeakSourceCode();bool is_alive() const;+ RefPtr<SourceCode const> strong_ref() const;private:FFI::WeakSourceCode* m_weak { nullptr };diff --git a/Libraries/LibWeb/HTML/Scripting/CompiledScriptCache.cpp b/Libraries/LibWeb/HTML/Scripting/CompiledScriptCache.cppindex e7f3c756720..2bc220e8998 100644--- a/Libraries/LibWeb/HTML/Scripting/CompiledScriptCache.cpp+++ b/Libraries/LibWeb/HTML/Scripting/CompiledScriptCache.cpp@@ -6,33 +6,63 @@#include <AK/NeverDestroyed.h>#include <AK/NumericLimits.h>+#include <LibCrypto/Hash/Hash.h>#include <LibWeb/HTML/Scripting/CompiledScriptCache.h>namespace Web::HTML {static constexpr size_t compiled_script_cache_size_limit = 16 * MiB;+CompiledScriptFingerprint CompiledScriptFingerprint::of(Utf16String const& source_text)+{+ // NB: The storage width is part of what is hashed, so the same text in another width only misses the cache.+ auto view = source_text.utf16_view();+ u8 is_wide = view.has_latin1_storage() ? 0 : 1;+ Crypto::Hash::Hasher hasher { Crypto::Hash::HashKind::SHA256 };+ hasher.update(ReadonlyBytes { &is_wide, sizeof(is_wide) });+ if (is_wide) {+ auto units = view.utf16_span();+ hasher.update(ReadonlyBytes { reinterpret_cast<u8 const*>(units.data()), units.size() * sizeof(char16_t) });+ } else {+ hasher.update(view.latin1_span());+ }+ auto digest = hasher.finish();++ CompiledScriptFingerprint fingerprint;+ VERIFY(digest.size == fingerprint.sha256_digest.size());+ digest.bytes().copy_to(fingerprint.sha256_digest);+ fingerprint.length_in_code_units = source_text.length_in_code_units();+ return fingerprint;+}+CompiledScriptCache& CompiledScriptCache::the(){static thread_local NeverDestroyed<CompiledScriptCache> cache;return *cache;}-Optional<CompiledScriptCache::Hit> CompiledScriptCache::find(CompiledScriptCacheKey const& key, Utf16String const& source_text)+Optional<CompiledScriptCache::Hit> CompiledScriptCache::find(CompiledScriptCacheKey const& key, CompiledScriptFingerprint const& fingerprint){auto entry = m_entries.get(key);- if (!entry.has_value() || entry->source_text != source_text)+ if (!entry.has_value() || entry->fingerprint != fingerprint)return {};entry->touch_serial = ++m_next_touch_serial;- Hit hit { entry->program.clone(), entry->source_text };+ Hit hit { entry->program.clone(), nullptr };+ // NB: Loads of one script share one text, which LibJS parks for all of them at once.+ for (auto const& linked : entry->linked_source_codes) {+ if (auto source_code = linked.strong_ref()) {+ hit.source_code_to_share = move(source_code);+ break;+ }+ }// NB: Entries grow as their functions compile, which no store sees.evict_until_within_limit(key);return hit;}-void CompiledScriptCache::store(CompiledScriptCacheKey key, Utf16String source_text, JS::CompiledProgram const& program)+void CompiledScriptCache::store(CompiledScriptCacheKey key, CompiledScriptFingerprint const& fingerprint, JS::CompiledProgram const& program){if (auto entry = m_entries.take(key); entry.has_value())release(*entry);@@ -40,7 +70,7 @@ void CompiledScriptCache::store(CompiledScriptCacheKey key, Utf16String source_t// NB: However large the program is, it costs nothing while a document runs it, which the one that stores it is about// to, and goes once none does.program.set_retains_compiled_functions(true);- m_entries.set(key, Entry { move(source_text), program.clone(), ++m_next_touch_serial, {} });+ m_entries.set(key, Entry { fingerprint, program.clone(), ++m_next_touch_serial, {} });evict_until_within_limit(key);}diff --git a/Libraries/LibWeb/HTML/Scripting/CompiledScriptCache.h b/Libraries/LibWeb/HTML/Scripting/CompiledScriptCache.hindex 6312209e205..2e04117e909 100644--- a/Libraries/LibWeb/HTML/Scripting/CompiledScriptCache.h+++ b/Libraries/LibWeb/HTML/Scripting/CompiledScriptCache.h@@ -6,6 +6,7 @@#pragma once+#include <AK/Array.h>#include <AK/HashMap.h>#include <AK/Optional.h>#include <AK/String.h>@@ -18,6 +19,16 @@namespace Web::HTML {+// What tells the source text of an entry apart from other text, without keeping the text.+struct WEB_API CompiledScriptFingerprint {+ static CompiledScriptFingerprint of(Utf16String const& source_text);++ Array<u8, 32> sha256_digest {};+ size_t length_in_code_units { 0 };++ bool operator==(CompiledScriptFingerprint const&) const = default;+};+// What a compiled script is stored under. The filename, base URL and muted errors of a script belong to one load of it// and are not part of its compiled code.struct CompiledScriptCacheKey {@@ -32,6 +43,7 @@ struct CompiledScriptCacheKey {// The compiled scripts of this agent, which a script that loads again links into its own realm instead of being// parsed and compiled again. Entries are found after a fetch completed, by the decoded source text the fetch came up// with, so they answer nothing that the checks of a fetch decide, and can not stand in for different source text.+// Entries hold a SHA-256 digest of the text and not the text itself, so that the text goes once LibJS parks it.//// The size limit is for the programs that only the cache keeps alive. A program that a live document runs stays in// memory with or without its entry, so it counts for nothing until no document runs it anymore, and an entry that the@@ -40,15 +52,16 @@ class WEB_API CompiledScriptCache {public:struct Hit {JS::CompiledProgram program;- Utf16String source_text;+ // A live source code that the program was linked into, whose code a new load shares, if there is one.+ RefPtr<JS::SourceCode const> source_code_to_share;};static CompiledScriptCache& the();- Optional<Hit> find(CompiledScriptCacheKey const&, Utf16String const& source_text);+ Optional<Hit> find(CompiledScriptCacheKey const&, CompiledScriptFingerprint const&);// From here on, the program keeps the functions that get compiled for it. Replaces what the key held before.- void store(CompiledScriptCacheKey, Utf16String source_text, JS::CompiledProgram const&);+ void store(CompiledScriptCacheKey, CompiledScriptFingerprint const&, JS::CompiledProgram const&);// The program of the key is linked into a record of the source code, which keeps the entry from counting against// the limit for as long as anything holds the source code.@@ -60,7 +73,7 @@ public:private:struct Entry {- Utf16String source_text;+ CompiledScriptFingerprint fingerprint;JS::CompiledProgram program;u64 touch_serial { 0 };// The source code of the records that the program was linked into.diff --git a/Libraries/LibWeb/HTML/Scripting/Fetching.cpp b/Libraries/LibWeb/HTML/Scripting/Fetching.cppindex b9c814b2496..0c8157e3995 100644--- a/Libraries/LibWeb/HTML/Scripting/Fetching.cpp+++ b/Libraries/LibWeb/HTML/Scripting/Fetching.cpp@@ -103,8 +103,10 @@ static void compile_off_thread(EnvironmentSettingsObject& settings_object, Utf16// The script runs in a task of the settings object's global, so never beside a rendering update in flight that holds// back the tasks of its document, and the microtasks it queues (e.g. promise reactions from react_to_promise during// module linking) are drained after it.- auto run_callback = [settings_object = GC::make_root(settings_object), on_compiled = GC::make_root(on_compiled), source_filename = move(source_filename), cache_key](OffThreadCompiledProgram result, Utf16String source_text) mutable {- auto source_code = JS::SourceCode::create(move(source_filename), move(source_text));+ auto run_callback = [settings_object = GC::make_root(settings_object), on_compiled = GC::make_root(on_compiled), source_filename = move(source_filename), cache_key](OffThreadCompiledProgram result, Utf16String source_text, RefPtr<JS::SourceCode const> source_code_to_share) mutable {+ auto source_code = source_code_to_share+ ? JS::SourceCode::create_sharing_code(move(source_filename), *source_code_to_share)+ : JS::SourceCode::create(move(source_filename), move(source_text));// NB: The record that the task creates holds the source code, and so does every function of it.if (cache_key.has_value() && result.compiled)CompiledScriptCache::the().note_linked(*cache_key, *source_code);@@ -113,9 +115,10 @@ static void compile_off_thread(EnvironmentSettingsObject& settings_object, Utf16}));};- if (cache_key.has_value()) {- if (auto hit = CompiledScriptCache::the().find(*cache_key, source_text); hit.has_value()) {- run_callback(OffThreadCompiledProgram { .compiled = move(hit->program) }, move(hit->source_text));+ // NB: Text that the cache has no entry for is fingerprinted on the thread pool, beside its compilation.+ if (cache_key.has_value() && CompiledScriptCache::the().contains(*cache_key)) {+ if (auto hit = CompiledScriptCache::the().find(*cache_key, CompiledScriptFingerprint::of(source_text)); hit.has_value()) {+ run_callback(OffThreadCompiledProgram { .compiled = move(hit->program) }, move(source_text), move(hit->source_code_to_share));return;}}@@ -123,28 +126,33 @@ static void compile_off_thread(EnvironmentSettingsObject& settings_object, Utf16struct OffThreadCompilation {OffThreadCompiledProgram result;Utf16String source_text;+ Optional<CompiledScriptFingerprint> fingerprint;};- auto compile = [source_text = move(source_text), type, line_number_offset]() mutable {+ auto compile = [source_text = move(source_text), type, line_number_offset, wants_fingerprint = cache_key.has_value()]() mutable {OffThreadCompiledProgram result { .parsed = JS::ParsedProgram::parse(source_text, type, line_number_offset) };if (result.parsed && !result.parsed.has_errors())result.compiled = JS::CompiledProgram::compile(move(result.parsed));- return OffThreadCompilation { .result = move(result), .source_text = move(source_text) };+ Optional<CompiledScriptFingerprint> fingerprint;+ if (wants_fingerprint && result.compiled)+ fingerprint = CompiledScriptFingerprint::of(source_text);+ return OffThreadCompilation { .result = move(result), .source_text = move(source_text), .fingerprint = move(fingerprint) };};Platform::run_on_thread_pool<OffThreadCompilation>(move(compile),[cache_key = move(cache_key), run_callback = move(run_callback)](OffThreadCompilation compilation) mutable {auto result = move(compilation.result);+ RefPtr<JS::SourceCode const> source_code_to_share;if (cache_key.has_value() && result.compiled) {// NB: Another load of the script may have stored it while this one compiled.- if (auto hit = CompiledScriptCache::the().find(*cache_key, compilation.source_text); hit.has_value()) {+ if (auto hit = CompiledScriptCache::the().find(*cache_key, *compilation.fingerprint); hit.has_value()) {result.compiled = move(hit->program);- compilation.source_text = move(hit->source_text);+ source_code_to_share = move(hit->source_code_to_share);} else {- CompiledScriptCache::the().store(cache_key.release_value(), compilation.source_text, result.compiled);+ CompiledScriptCache::the().store(cache_key.release_value(), *compilation.fingerprint, result.compiled);}}- run_callback(move(result), move(compilation.source_text));+ run_callback(move(result), move(compilation.source_text), move(source_code_to_share));});}