LibWeb: Keep Wasm-imported functions alive

The user is not required to keep the object alive, this commit makes it
so the lifetime of these functions is extended to match the Wasm module
it is imported into.
Fixes the crash in #907.
This commit is contained in:
Ali Mohammad Pur 2024-07-31 12:34:55 +02:00 committed by Andreas Kling
parent 1eced20521
commit 1fa528b19f
Notes: github-actions[bot] 2024-08-01 09:42:26 +00:00
2 changed files with 5 additions and 0 deletions

View file

@ -45,6 +45,7 @@ void visit_edges(JS::Object& object, JS::Cell::Visitor& visitor)
if (auto maybe_cache = Detail::s_caches.get(global_object); maybe_cache.has_value()) {
auto& cache = maybe_cache.release_value();
visitor.visit(cache.function_instances());
visitor.visit(cache.imported_objects());
}
}
@ -186,6 +187,7 @@ JS::ThrowCompletionOr<NonnullOwnPtr<Wasm::ModuleInstance>> instantiate_module(JS
if (!import_.is_function())
return {};
auto& function = import_.as_function();
cache.add_imported_object(function);
// FIXME: If this is a function created by create_native_function(),
// just extract its address and resolve to that.
Wasm::HostFunction host_function {

View file

@ -41,15 +41,18 @@ class WebAssemblyCache {
public:
void add_compiled_module(NonnullRefPtr<CompiledWebAssemblyModule> module) { m_compiled_modules.append(module); }
void add_function_instance(Wasm::FunctionAddress address, JS::GCPtr<JS::NativeFunction> function) { m_function_instances.set(address, function); }
void add_imported_object(JS::GCPtr<JS::Object> object) { m_imported_objects.set(object); }
Optional<JS::GCPtr<JS::NativeFunction>> get_function_instance(Wasm::FunctionAddress address) { return m_function_instances.get(address); }
HashMap<Wasm::FunctionAddress, JS::GCPtr<JS::NativeFunction>> function_instances() const { return m_function_instances; }
HashTable<JS::GCPtr<JS::Object>> imported_objects() const { return m_imported_objects; }
Wasm::AbstractMachine& abstract_machine() { return m_abstract_machine; }
private:
HashMap<Wasm::FunctionAddress, JS::GCPtr<JS::NativeFunction>> m_function_instances;
Vector<NonnullRefPtr<CompiledWebAssemblyModule>> m_compiled_modules;
HashTable<JS::GCPtr<JS::Object>> m_imported_objects;
Wasm::AbstractMachine m_abstract_machine;
};