Skip to content

Truly independent web browser

LibWasm+LibWeb: Trace the values embedders hold by their types

Andreas Klinge339aca1d355
diff --git a/Libraries/LibWasm/Engine/src/capi.rs b/Libraries/LibWasm/Engine/src/capi.rs
index 89f85bdcbb3..05ceba725cb 100644
--- a/Libraries/LibWasm/Engine/src/capi.rs
+++ b/Libraries/LibWasm/Engine/src/capi.rs
@@ -13,7 +13,7 @@
use crate::module::{ImportDescription, Module};
use crate::runtime::entity::{Entity, Handle};
-use crate::runtime::heap::{GcInterface, Visitor};
+use crate::runtime::heap::{GcInterface, TRACE_NONE, Visitor};
use crate::runtime::{ExternValue, HostFunction, InstantiationError, Store, Trap, Value};
use crate::types::{AddressType, FuncType, GlobalType, HeapType, Limits, MemoryType, RefType, TableType, ValType};
use core::ffi::c_void;
@@ -112,7 +112,8 @@ pub enum WasmHeapKind {
None,
Exception,
NoException,
- /// A type the module defines; `type_index` is its index in the module.
+ /// A type the module defines; `type_index` is its index in the module, or its identity in the store for the types
+ /// of the store's functions and globals.
Concrete,
}
@@ -196,17 +197,19 @@ impl WasmValueType {
}
/// A value: i32 and f32 bits in the low 32 bits of `low`, v128 in `low` and `high`, references as their bits (zero
-/// for null).
+/// for null). `trace` says how the collector follows the value, as one of the TRACE_* kinds, which only a reference
+/// needs: a function reference points into its function's cell, while other references are the addresses of cells.
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct WasmValue {
pub kind: WasmValueKind,
+ pub trace: u8,
pub low: u64,
pub high: u64,
}
impl WasmValue {
- fn of(value: Value) -> Self {
+ fn of(value: Value, trace: u8) -> Self {
let (kind, low, high) = match value {
Value::I32(value) => (WasmValueKind::I32, u64::from(value as u32), 0),
Value::I64(value) => (WasmValueKind::I64, value as u64, 0),
@@ -215,7 +218,7 @@ impl WasmValue {
Value::V128(bits) => (WasmValueKind::V128, bits as u64, (bits >> 64) as u64),
Value::Ref(bits) => (WasmValueKind::Reference, bits, 0),
};
- Self { kind, low, high }
+ Self { kind, trace, low, high }
}
fn to_value(self) -> Value {
@@ -596,6 +599,8 @@ struct HostFunctionData {
user_data: *mut std::ffi::c_void,
/// The store the function belongs to, which its calls get.
store: *mut WasmStore,
+ /// The types of the arguments, which say how the collector follows them.
+ parameter_types: Vec<ValType>,
result_count: usize,
}
@@ -606,11 +611,20 @@ impl Drop for HostFunctionData {
}
impl HostFunction for HostFunctionData {
- fn call(&self, _: &mut Store, arguments: &[Value]) -> Result<Vec<Value>, Trap> {
- let arguments: Vec<WasmValue> = arguments.iter().map(|&value| WasmValue::of(value)).collect();
+ fn call(&self, store: &mut Store, arguments: &[Value]) -> Result<Vec<Value>, Trap> {
+ // NB: A host function's concrete types are identities of the store, which the store knows by the time the
+ // function is called, even its own. An embedder may still pass types of a module that the store does not
+ // have. Arguments of those types are not traced, which is safe while the call lasts, as the caller keeps
+ // them alive.
+ let arguments: Vec<WasmValue> = arguments
+ .iter()
+ .zip(&self.parameter_types)
+ .map(|(&value, &ty)| WasmValue::of(value, store.trace_of_known(ty).unwrap_or(TRACE_NONE)))
+ .collect();
let mut results = vec![
WasmValue {
kind: WasmValueKind::I32,
+ trace: TRACE_NONE,
low: 0,
high: 0,
};
@@ -691,6 +705,7 @@ pub unsafe extern "C" fn wasm_store_allocate_host_function(
release,
user_data,
store,
+ parameter_types: ty.params.clone(),
result_count: ty.results.len(),
});
store_of(store).allocate_host_function(ty, data).cell().cast()
@@ -920,10 +935,13 @@ pub unsafe extern "C" fn wasm_store_invoke(
.iter()
.map(|value| value.to_value())
.collect();
- match store_of(store).invoke(entity(function), &arguments) {
+ let store = store_of(store);
+ match store.invoke(entity(function), &arguments) {
Ok(values) => {
- for (index, value) in values.into_iter().take(result_count).enumerate() {
- unsafe { *results.add(index) = WasmValue::of(value) };
+ let types = &store.function(entity(function)).ty.results;
+ for (index, (value, &ty)) in values.into_iter().zip(types).take(result_count).enumerate() {
+ let trace = store.trace_of_known(ty).unwrap_or(TRACE_NONE);
+ unsafe { *results.add(index) = WasmValue::of(value, trace) };
}
WasmStatus::Ok
}
@@ -931,6 +949,18 @@ pub unsafe extern "C" fn wasm_store_invoke(
}
}
+/// Visits a value of a store with a LibGC visitor, which keeps the cell a reference refers to alive.
+///
+/// # Safety
+///
+/// `visitor` must be the LibGC visitor a cell's visit_edges was given, and `value` a value of a store.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_visitor_visit_value(visitor: *mut c_void, value: WasmValue) {
+ if value.kind == WasmValueKind::Reference {
+ Visitor::new(visitor).visit_value(value.low, value.trace);
+ }
+}
+
/// The reference to a function, as tables and reference values hold it.
///
/// # Safety
@@ -980,7 +1010,8 @@ pub unsafe extern "C" fn wasm_store_global_type(
/// `store` must be a live store with a global at `global`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn wasm_store_global_get(store: *mut WasmStore, global: *mut c_void) -> WasmValue {
- WasmValue::of(store_of(store).global(entity(global)).get())
+ let global = store_of(store).global(entity(global));
+ WasmValue::of(global.get(), global.trace)
}
// WASI.
diff --git a/Libraries/LibWasm/Engine/src/runtime/mod.rs b/Libraries/LibWasm/Engine/src/runtime/mod.rs
index d1cfacd4ecd..ed3a17b4982 100644
--- a/Libraries/LibWasm/Engine/src/runtime/mod.rs
+++ b/Libraries/LibWasm/Engine/src/runtime/mod.rs
@@ -1136,6 +1136,22 @@ impl Store {
unsafe { TagAddress::from_ptr(identity as *const TagInstance) }
}
+ /// How the collector follows a value of a type of this store, as one of the TRACE_* kinds of heap.rs.
+ pub fn trace_of(&self, ty: ValType) -> u8 {
+ gc::trace_of(ty, &self.types)
+ }
+
+ /// The same, or None for a concrete type that is not an identity of this store.
+ pub fn trace_of_known(&self, ty: ValType) -> Option<u8> {
+ if let ValType::Ref(reference) = ty
+ && let HeapType::Concrete(identity) = reference.heap
+ && self.types.get(identity as usize).is_none()
+ {
+ return None;
+ }
+ Some(self.trace_of(ty))
+ }
+
pub fn function_reference(&self, address: FunctionAddress) -> u64 {
address.as_ptr() as u64
}
diff --git a/Libraries/LibWasm/Runtime.cpp b/Libraries/LibWasm/Runtime.cpp
index 8418d9090ca..71958a2fd33 100644
--- a/Libraries/LibWasm/Runtime.cpp
+++ b/Libraries/LibWasm/Runtime.cpp
@@ -43,6 +43,7 @@ static_assert(offsetof(ValueType, nullable) == offsetof(FFI::WasmValueType, null
static_assert(offsetof(ValueType, type_index) == offsetof(FFI::WasmValueType, type_index));
static_assert(sizeof(Value) == sizeof(FFI::WasmValue));
static_assert(offsetof(Value, kind) == offsetof(FFI::WasmValue, kind));
+static_assert(offsetof(Value, trace) == offsetof(FFI::WasmValue, trace));
static_assert(offsetof(Value, low) == offsetof(FFI::WasmValue, low));
static_assert(offsetof(Value, high) == offsetof(FFI::WasmValue, high));
static_assert(sizeof(Limits) == sizeof(FFI::WasmLimits));
@@ -58,6 +59,12 @@ static_assert(offsetof(ExternType, limits) == offsetof(FFI::WasmExternType, limi
static_assert(offsetof(ExternType, value_type) == offsetof(FFI::WasmExternType, value_type));
static_assert(offsetof(ExternType, is_mutable) == offsetof(FFI::WasmExternType, mutable_));
+void Value::visit_edges(GC::Cell::Visitor& visitor) const
+{
+ // NB: LibGC's C interface passes its Cell::Visitor as the visitor.
+ FFI::wasm_visitor_visit_value(&visitor, bit_cast<FFI::WasmValue>(*this));
+}
+
static FFI::WasmValueType to_ffi(ValueType type) { return bit_cast<FFI::WasmValueType>(type); }
static FFI::WasmValue to_ffi(Value value) { return bit_cast<FFI::WasmValue>(value); }
static FFI::WasmLimits to_ffi(Limits limits) { return bit_cast<FFI::WasmLimits>(limits); }
@@ -189,7 +196,7 @@ struct HostFunctionData {
AK_ALLOC_WITH_KMALLOC;
Store& store;
- Store::HostFunction function;
+ GC::Ref<Store::HostFunction> function;
};
}
@@ -199,7 +206,7 @@ static FFI::WasmStatus call_host_function(void* user_data, FFI::WasmStore*, FFI:
auto& data = *static_cast<HostFunctionData*>(user_data);
ReadonlySpan<Value> argument_span { reinterpret_cast<Value const*>(arguments), argument_count };
Span<Value> result_span { reinterpret_cast<Value*>(results), result_count };
- auto result = data.function(data.store, argument_span, result_span);
+ auto result = (*data.function)(data.store, argument_span, result_span);
if (!result.is_error())
return FFI::WasmStatus::Ok;
*error = make_string(result.error().message);
@@ -210,7 +217,7 @@ static void visit_host_function(void* user_data, void* visitor)
{
// NB: LibGC's C interface passes its Cell::Visitor as the visitor.
auto& data = *static_cast<HostFunctionData*>(user_data);
- static_cast<GC::Cell::Visitor*>(visitor)->visit_possible_values(data.function.raw_capture_range());
+ static_cast<GC::Cell::Visitor*>(visitor)->visit(data.function);
}
static void release_host_function(void* user_data)
@@ -218,7 +225,7 @@ static void release_host_function(void* user_data)
delete static_cast<HostFunctionData*>(user_data);
}
-Entity Store::allocate_host_function(FunctionType const& type, HostFunction function)
+Entity Store::allocate_host_function(FunctionType const& type, GC::Ref<HostFunction> function)
{
Vector<FFI::WasmValueType> parameters;
Vector<FFI::WasmValueType> results;
@@ -226,7 +233,9 @@ Entity Store::allocate_host_function(FunctionType const& type, HostFunction func
parameters.append(to_ffi(parameter));
for (auto result : type.results)
results.append(to_ffi(result));
- auto* data = new HostFunctionData { *this, move(function) };
+ auto* data = new HostFunctionData { *this, function };
+ // NB: Allocating the function's cell can collect garbage, and only the cell visits the GC::Function once it exists.
+ auto function_root = GC::make_root(function);
return entity_from_ffi(FFI::wasm_store_allocate_host_function(m_store, parameters.data(), parameters.size(), results.data(), results.size(), call_host_function, visit_host_function, release_host_function, data));
}
@@ -328,9 +337,9 @@ ErrorOr<Values, Failure> Store::invoke(Entity function, ReadonlySpan<Value> argu
return results;
}
-u64 Store::function_reference(Entity function)
+Value Store::function_reference(Entity function)
{
- return FFI::wasm_store_function_reference(m_store, to_ffi(function));
+ return { ValueKind::Reference, ValueTrace::FunctionReference, FFI::wasm_store_function_reference(m_store, to_ffi(function)), 0 };
}
Entity Store::function_from_reference(u64 reference)
diff --git a/Libraries/LibWasm/Runtime.h b/Libraries/LibWasm/Runtime.h
index cb79ed78c8b..80f0895c330 100644
--- a/Libraries/LibWasm/Runtime.h
+++ b/Libraries/LibWasm/Runtime.h
@@ -16,9 +16,10 @@
#include <AK/Span.h>
#include <AK/StringView.h>
#include <AK/Vector.h>
-#include <LibGC/ConservativeVector.h>
#include <LibGC/Forward.h>
+#include <LibGC/Function.h>
#include <LibGC/Ptr.h>
+#include <LibGC/RootVector.h>
#include <LibWasm/Export.h>
namespace Wasm::FFI {
@@ -70,22 +71,32 @@ struct ValueType {
static constexpr ValueType reference(HeapKind heap, bool nullable = true) { return { ValueKind::Reference, heap, nullable, 0 }; }
};
+// How the garbage collector follows a value. A function reference points into its function's cell, while any other
+// reference is null, an i31, the address of a cell, or the address of a host value's cell with bit 1 set.
+enum class ValueTrace : u8 {
+ None,
+ Reference,
+ FunctionReference,
+};
+
// A value. i32 and f32 bits are zero-extended in `low`, a v128 is `low` and `high`, and a reference is its bits, which
// are zero for null.
-struct Value {
+struct WASM_API Value {
ValueKind kind { ValueKind::I32 };
+ ValueTrace trace { ValueTrace::None };
u64 low { 0 };
u64 high { 0 };
- static Value from_i32(i32 value) { return { ValueKind::I32, static_cast<u32>(value), 0 }; }
- static Value from_i64(i64 value) { return { ValueKind::I64, static_cast<u64>(value), 0 }; }
- static Value from_f32_bits(u32 bits) { return { ValueKind::F32, bits, 0 }; }
- static Value from_f64_bits(u64 bits) { return { ValueKind::F64, bits, 0 }; }
+ static Value from_i32(i32 value) { return { ValueKind::I32, ValueTrace::None, static_cast<u32>(value), 0 }; }
+ static Value from_i64(i64 value) { return { ValueKind::I64, ValueTrace::None, static_cast<u64>(value), 0 }; }
+ static Value from_f32_bits(u32 bits) { return { ValueKind::F32, ValueTrace::None, bits, 0 }; }
+ static Value from_f64_bits(u64 bits) { return { ValueKind::F64, ValueTrace::None, bits, 0 }; }
static Value from_f32(float value) { return from_f32_bits(bit_cast<u32>(value)); }
static Value from_f64(double value) { return from_f64_bits(bit_cast<u64>(value)); }
- static Value from_v128(u64 low, u64 high) { return { ValueKind::V128, low, high }; }
- static Value from_reference(u64 bits) { return { ValueKind::Reference, bits, 0 }; }
- static Value default_for(ValueType type) { return { type.kind, 0, 0 }; }
+ static Value from_v128(u64 low, u64 high) { return { ValueKind::V128, ValueTrace::None, low, high }; }
+ // A reference that is not a function reference, which only the store makes (see Store::function_reference()).
+ static Value from_reference(u64 bits) { return { ValueKind::Reference, ValueTrace::Reference, bits, 0 }; }
+ static Value default_for(ValueType type) { return { type.kind, ValueTrace::None, 0, 0 }; }
i32 to_i32() const { return static_cast<i32>(static_cast<u32>(low)); }
i64 to_i64() const { return static_cast<i64>(low); }
@@ -95,6 +106,8 @@ struct Value {
double to_f64() const { return bit_cast<double>(f64_bits()); }
u64 reference_bits() const { return low; }
bool is_null_reference() const { return low == 0; }
+
+ void visit_edges(GC::Cell::Visitor&) const;
};
enum class ExternKind : u8 {
@@ -135,6 +148,8 @@ struct ExternType {
};
struct FunctionType {
+ GC_HOLDS_NO_CELL_EDGES;
+
Vector<ValueType> parameters;
Vector<ValueType> results;
};
@@ -150,8 +165,8 @@ struct InstanceExport {
Extern value;
};
-// Values that may be references to cells, which the garbage collector finds while the vector lives.
-using Values = GC::ConservativeVector<Value, 8>;
+// Values that may be references to cells, which the garbage collector keeps alive while the vector lives.
+using Values = GC::RootVector<Value, 8>;
// A compiled module, which can be shared across threads and instantiated in any store.
class WASM_API Module : public AtomicRefCounted<Module> {
@@ -210,11 +225,11 @@ public:
explicit Store(GC::Heap&);
~Store();
- // A host function writes one result for each result of its type, or returns an error to trap or throw. Its
- // function visits the cells it captures, so it must not capture roots.
- using HostFunction = Function<ErrorOr<void, HostError>(Store&, ReadonlySpan<Value> arguments, Span<Value> results)>;
+ // A host function writes one result for each result of its type, or returns an error to trap or throw. The
+ // function it is made of lives as long as the function is in the store.
+ using HostFunction = GC::Function<ErrorOr<void, HostError>(Store&, ReadonlySpan<Value> arguments, Span<Value> results)>;
- Entity allocate_host_function(FunctionType const&, HostFunction);
+ Entity allocate_host_function(FunctionType const&, GC::Ref<HostFunction>);
Optional<Entity> allocate_memory(Limits);
Optional<Entity> allocate_table(ValueType element, Limits, u64 initial);
Entity allocate_global(ValueType, bool is_mutable, Value);
@@ -226,7 +241,8 @@ public:
FunctionType function_type(Entity function);
ErrorOr<Values, Failure> invoke(Entity function, ReadonlySpan<Value> arguments);
- u64 function_reference(Entity function);
+ // A reference to the function, which the garbage collector follows into the function's cell.
+ Value function_reference(Entity function);
// The function a non-null function reference refers to.
Entity function_from_reference(u64 reference);
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_assembly/exception.rs b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/exception.rs
index 1900c981c54..e6734eec7d7 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/web_assembly/exception.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/exception.rs
@@ -76,6 +76,7 @@ impl Exception {
// NB: The converted values may refer to new cells, which the cell of the values keeps alive until they are in
// the exception.
let wasm_payload = WasmValues::allocate(vm);
+ let payload_traces = WasmValues::traces_of(vm, &types);
// 7. For each value and resultType of payload and types, paired linearly,
for (index, &result_type) in types.iter().enumerate() {
@@ -88,14 +89,14 @@ impl Exception {
payload.get(index).expect("the payload has a value per type"),
result_type,
)?;
- wasm_payload.0.borrow_mut().push(value);
+ wasm_payload.push(value, payload_traces[index]);
}
// 8. Let (store, exceptionAddr) be exn_alloc(store, exceptionTag.[[Address]], wasmPayload).
// 9. Set the surrounding agent's associated store to store.
let exception = agent
.store()
- .allocate_exception_with_values(exception_tag.address(), &wasm_payload.0.borrow());
+ .allocate_exception_with_values(exception_tag.address(), &wasm_payload.values());
// NB: Using the Gc after the allocation keeps the payload where the conservative scan finds it until it is in
// the exception.
core::hint::black_box(wasm_payload);
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_assembly/exported_function.rs b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/exported_function.rs
index 7e498652130..642d3425f6d 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/web_assembly/exported_function.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/exported_function.rs
@@ -166,6 +166,7 @@ fn call_an_exported_function(vm: &Vm, function: &ExportedFunction) -> ThrowCompl
// 5. Let args be « ».
// NB: The converted arguments may refer to new cells, which the cell of the arguments keeps alive during the call.
let args = WasmValues::allocate(vm);
+ let arg_traces = WasmValues::traces_of(vm, parameters);
// 6. Let i be 0.
// 7. For each t of parameters,
@@ -176,7 +177,7 @@ fn call_an_exported_function(vm: &Vm, function: &ExportedFunction) -> ThrowCompl
// 3. Append ? ToWebAssemblyValue(arg, t) to args.
let arg = to_webassembly_value(vm, arg, t)?;
- args.0.borrow_mut().push(arg);
+ args.push(arg, arg_traces[i]);
// 4. Set i to i + 1.
}
@@ -186,7 +187,7 @@ fn call_an_exported_function(vm: &Vm, function: &ExportedFunction) -> ThrowCompl
// 8. Let (store, ret) be the result of func_invoke(store, funcaddr, args).
// 9. Set the surrounding agent's associated store to store.
- let result = Agent::the(vm).store().invoke(function.function.0, &args.0.borrow());
+ let result = Agent::the(vm).store().invoke(function.function.0, &args.values());
// NB: Using the Gc after the call keeps the arguments where the conservative scan finds them until it has returned.
core::hint::black_box(args);
@@ -195,7 +196,7 @@ fn call_an_exported_function(vm: &Vm, function: &ExportedFunction) -> ThrowCompl
// 11. If ret is of the form exception exnaddr, then
// NB: throw_of_trap() throws what an error or an exception throws.
match result {
- Ok(values) => *ret.0.borrow_mut() = values,
+ Ok(values) => ret.set(vm, values, results),
Err(trap) => return Err(throw_of_trap(vm, trap)),
}
@@ -207,7 +208,7 @@ fn call_an_exported_function(vm: &Vm, function: &ExportedFunction) -> ThrowCompl
// 2. For each r of ret,
// 1. Append ToJSValue(r) to values.
// 3. Return CreateArrayFromList(values).
- let result = results_to_js_value(vm, &ret.0.borrow(), results);
+ let result = results_to_js_value(vm, &ret.values(), results);
// NB: Using the Gc after the conversion keeps the results where the conservative scan finds them until it is done.
core::hint::black_box(ret);
result
@@ -328,6 +329,7 @@ fn run_a_host_function(
// NB: Converting subsequent results can collect garbage, so keep earlier reference results in a traced cell.
let converted = WasmValues::allocate(vm);
+ let result_traces = WasmValues::traces_of(vm, results);
// 9. Otherwise,
{
@@ -367,12 +369,12 @@ fn run_a_host_function(
values.get(index).expect("the list has a value per result"),
result_type,
)?;
- converted.0.borrow_mut().push(value);
+ converted.push(value, result_traces[index]);
}
// 7. Return wasmValues.
}
- Ok(converted.0.take())
+ Ok(converted.take())
}
/// https://webassembly.github.io/spec/js-api/#create-a-host-function
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_assembly/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/mod.rs
index 746c7f53e34..b9178a5f257 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/web_assembly/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/mod.rs
@@ -51,7 +51,7 @@ use libwasm_engine::Module as CoreModule;
use libwasm_engine::runtime::entity::{Entity, Handle};
use libwasm_engine::runtime::heap::{CellTypeInfo, GcInterface, GcLayout, PrimitiveStorageLayout};
use libwasm_engine::runtime::{InstantiationError, Store, TagAddress, Trap, Value as WasmValue};
-use libwasm_engine::types::FuncType;
+use libwasm_engine::types::{FuncType, ValType};
use crate::bindings::conversions::BufferSource;
use crate::bindings::interface::{Interface, Ref, Wrapped, implementation_if_wrapper};
@@ -152,10 +152,15 @@ unsafe impl Trace for CellReference {
}
}
-/// Values of the store, which may be references that keep cells alive where they are traced, as a conservative scan
-/// of the values would. They live in a cell of their own, which a Gc in a local keeps alive. As allocating the cell can
-/// collect garbage, it is allocated empty, before there are values for it to keep alive.
-pub(crate) struct WasmValues(pub(crate) RefCell<Vec<WasmValue>>);
+/// Values of the store, which may be references that keep cells alive where they are traced. Each is traced as the type
+/// it was made for says, which a function reference needs, as it points into its function's cell. They live in a cell of
+/// their own, which a Gc in a local keeps alive. As allocating the cell can collect garbage, it is allocated empty,
+/// before there are values for it to keep alive.
+pub(crate) struct WasmValues {
+ values: RefCell<Vec<WasmValue>>,
+ /// How the collector follows each value, as the store's trace_of() says.
+ traces: RefCell<Vec<u8>>,
+}
static WASM_VALUES_CLASS: EmbedderClass<WasmValues> = EmbedderClass::new("WasmValues");
@@ -165,24 +170,50 @@ impl EmbedderValue for WasmValues {
impl WasmValues {
pub(crate) fn allocate(vm: &Vm) -> Gc<EmbedderCell<WasmValues>> {
- WASM_VALUES_CLASS.allocate(vm, |_| WasmValues(RefCell::default()))
+ WASM_VALUES_CLASS.allocate(vm, |_| WasmValues {
+ values: RefCell::default(),
+ traces: RefCell::default(),
+ })
+ }
+
+ /// How the collector follows values of `types`, for push().
+ pub(crate) fn traces_of(vm: &Vm, types: &[ValType]) -> Vec<u8> {
+ let store = Agent::the(vm).store();
+ types.iter().map(|&ty| store.trace_of(ty)).collect()
+ }
+
+ /// Appends a value, which the collector follows as `trace` says.
+ pub(crate) fn push(&self, value: WasmValue, trace: u8) {
+ self.values.borrow_mut().push(value);
+ self.traces.borrow_mut().push(trace);
+ }
+
+ /// Replaces the values with ones of the types `types`.
+ pub(crate) fn set(&self, vm: &Vm, values: Vec<WasmValue>, types: &[ValType]) {
+ *self.traces.borrow_mut() = Self::traces_of(vm, types);
+ *self.values.borrow_mut() = values;
+ }
+
+ pub(crate) fn values(&self) -> core::cell::Ref<'_, Vec<WasmValue>> {
+ self.values.borrow()
+ }
+
+ pub(crate) fn take(&self) -> Vec<WasmValue> {
+ self.traces.take();
+ self.values.take()
}
}
-// SAFETY: Every cell the values refer to is at an address in their bits, which this visits as a possible value. Only
-// the edges of a cell may be visited so, which is why the values live in one.
+// SAFETY: Every reference among the values is traced as the type it was made for says.
unsafe impl Trace for WasmValues {
fn trace(&self, visitor: &mut Visitor) {
- for value in self.0.borrow().iter() {
- let (slots, count) = value.to_slots();
- // SAFETY: The visitor is live while it traces, and the slots are plain data.
- unsafe {
- gc_visitor_visit_possible_values(
- visitor.as_raw().cast(),
- slots.as_ptr().cast(),
- count * size_of::<u64>(),
- );
- };
+ let wasm_visitor = libwasm_engine::runtime::heap::Visitor::new(visitor.as_raw().cast());
+ let (values, traces) = (self.values.borrow(), self.traces.borrow());
+ debug_assert_eq!(values.len(), traces.len());
+ for (value, &trace) in values.iter().zip(traces.iter()) {
+ if let WasmValue::Ref(bits) = *value {
+ wasm_visitor.visit_value(bits, trace);
+ }
}
}
}
diff --git a/Tests/LibWasm/test-wasm.cpp b/Tests/LibWasm/test-wasm.cpp
index ab6547c9398..738c5268414 100644
--- a/Tests/LibWasm/test-wasm.cpp
+++ b/Tests/LibWasm/test-wasm.cpp
@@ -218,10 +218,10 @@ private:
return s_spec_test_namespace;
auto add_print = [](StringView name, Vector<ValueType> parameters) {
- auto address = keep(store().allocate_host_function({ move(parameters), {} }, [](auto&, auto, auto) -> ErrorOr<void, Wasm::Runtime::HostError> {
+ auto address = keep(store().allocate_host_function({ move(parameters), {} }, GC::create_function(GC::Heap::the(), [](Store&, ReadonlySpan<Value>, Span<Value>) -> ErrorOr<void, Wasm::Runtime::HostError> {
// Noop, this just needs to exist.
return {};
- }));
+ })));
s_spec_test_namespace.set({ "spectest", name }, { ExternKind::Function, address });
};
auto i32 = ValueType::scalar(ValueKind::I32);
@@ -547,7 +547,7 @@ JS_DEFINE_NATIVE_FUNCTION(WebAssemblyModule::wasm_invoke)
auto address = function_entity(TRY(vm.argument(0).to_double(vm)));
auto type = store().function_type(address);
- Vector<Value> arguments;
+ Values arguments;
if (type.parameters.size() + 1 > vm.argument_count())
return vm.throw_completion<JS::TypeError>(Utf16String::formatted("Expected {} arguments for call, but found {}", type.parameters.size() + 1, vm.argument_count()));
size_t index = 1;
@@ -595,7 +595,7 @@ JS_DEFINE_NATIVE_FUNCTION(WebAssemblyModule::wasm_invoke)
}
switch (parameter.heap) {
case HeapKind::Function:
- arguments.append(Value::from_reference(store().function_reference(function_entity(double_value))));
+ arguments.append(store().function_reference(function_entity(double_value)));
break;
case HeapKind::Extern:
case HeapKind::Any:
diff --git a/Utilities/wasm.cpp b/Utilities/wasm.cpp
index 64d9f5b0edd..eb1c5f3f799 100644
--- a/Utilities/wasm.cpp
+++ b/Utilities/wasm.cpp
@@ -6,6 +6,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <AK/AnyOf.h>
#include <AK/GenericLexer.h>
#include <AK/Hex.h>
#include <AK/JsonArray.h>
@@ -402,7 +403,8 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)
if (result_kind.has_value())
function_type.results.append(ValueType::scalar(*result_kind));
- auto host_function = store.allocate_host_function(function_type, [&vm, &realm, function, &store, &main_instance, function_type, name](Wasm::Runtime::Store&, ReadonlySpan<WasmValue> arguments, Span<WasmValue> results) mutable -> ErrorOr<void, HostError> {
+ auto host_function = store.allocate_host_function(function_type, GC::create_function(vm->heap(), GC::captures(realm, function, make_ref_counted<ReentryTarget>(store, main_instance), function_type, name), [](auto& realm, auto& function, auto& target, auto& function_type, auto& name, Wasm::Runtime::Store&, ReadonlySpan<WasmValue> arguments, Span<WasmValue> results) -> ErrorOr<void, HostError> {
+ auto& vm = realm.vm();
GC::RootVector<JS::Value> js_arguments;
for (size_t index = 0; index < arguments.size(); ++index) {
auto argument = arguments[index];
@@ -421,7 +423,7 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)
break;
case ValueKind::V128: {
u64 halves[2] = { argument.low, argument.high };
- js_arguments.append(JS::BigInt::create(*vm, Crypto::SignedBigInteger { Crypto::UnsignedBigInteger::import_data({ reinterpret_cast<u8 const*>(halves), sizeof(halves) }) }));
+ js_arguments.append(JS::BigInt::create(vm, Crypto::SignedBigInteger { Crypto::UnsignedBigInteger::import_data({ reinterpret_cast<u8 const*>(halves), sizeof(halves) }) }));
break;
}
case ValueKind::Reference:
@@ -431,9 +433,8 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)
// The function's `this` can call back into the main instance's exports.
auto reentry_this = JS::Object::create(realm, realm.intrinsics().object_prototype());
- auto reentry = make_ref_counted<ReentryTarget>(store, main_instance);
auto invoke = JS::NativeFunction::create(
- realm, GC::create_function(vm->heap(), GC::captures(reentry), [](NonnullRefPtr<ReentryTarget>& reentry, JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {
+ realm, GC::create_function(vm.heap(), GC::captures(target), [](NonnullRefPtr<ReentryTarget>& reentry, JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {
auto& store = reentry->store;
auto& main_instance = reentry->main_instance;
if (!main_instance)
@@ -487,9 +488,9 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)
1, "invoke"_utf16);
reentry_this->define_direct_property("invoke"_utf16, invoke, JS::default_attributes);
- auto result = JS::call(*vm, function, reentry_this, js_arguments.span());
+ auto result = JS::call(vm, function, reentry_this, js_arguments.span());
if (result.is_error()) {
- warnln("JS exception: {}", MUST(result.error_value().to_utf16_string(*vm)));
+ warnln("JS exception: {}", MUST(result.error_value().to_utf16_string(vm)));
return HostError { "JS exception" };
}
if (function_type.results.is_empty())
@@ -499,15 +500,15 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)
auto converted = [&]() -> JS::ThrowCompletionOr<WasmValue> {
switch (function_type.results.first().kind) {
case ValueKind::I32:
- return WasmValue::from_i32(static_cast<i32>(TRY(value.to_u32(*vm))));
+ return WasmValue::from_i32(static_cast<i32>(TRY(value.to_u32(vm))));
case ValueKind::I64:
- return WasmValue::from_i64(static_cast<i64>(TRY(value.to_bigint_uint64(*vm))));
+ return WasmValue::from_i64(static_cast<i64>(TRY(value.to_bigint_uint64(vm))));
case ValueKind::F32:
- return WasmValue::from_f32(static_cast<float>(TRY(value.to_double(*vm))));
+ return WasmValue::from_f32(static_cast<float>(TRY(value.to_double(vm))));
case ValueKind::F64:
- return WasmValue::from_f64(TRY(value.to_double(*vm)));
+ return WasmValue::from_f64(TRY(value.to_double(vm)));
case ValueKind::V128: {
- auto bigint = TRY(value.to_bigint(*vm));
+ auto bigint = TRY(value.to_bigint(vm));
u64 halves[2] = {};
(void)bigint->big_integer().unsigned_value().export_data({ reinterpret_cast<u8*>(halves), sizeof(halves) });
return WasmValue::from_v128(halves[0], halves[1]);
@@ -523,7 +524,7 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)
}
results[0] = converted.release_value();
return {};
- });
+ }));
js_exports.set({ module, function_name }, { ExternKind::Function, keep(host_function) });
return true;
},
@@ -647,7 +648,14 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)
auto type = module_to_link.function_type(import.type.type_index);
if (!type.has_value())
break;
- stub = store.allocate_host_function(*type, [name = ByteString(import.name), type = *type](auto&, ReadonlySpan<WasmValue> stub_arguments, Span<WasmValue>) -> ErrorOr<void, HostError> {
+ // NB: A host function's concrete types are identities of the store, which the types of a module
+ // that is not instantiated yet have none of.
+ auto names_a_concrete_type = [](ValueType value_type) { return value_type.kind == ValueKind::Reference && value_type.heap == Wasm::Runtime::HeapKind::Concrete; };
+ if (any_of(type->parameters, names_a_concrete_type) || any_of(type->results, names_a_concrete_type)) {
+ warnln("Cannot stub import {} of a type that names a type of its module", import.name);
+ break;
+ }
+ stub = store.allocate_host_function(*type, GC::create_function(vm->heap(), GC::captures(ByteString(import.name), *type), [](auto& name, auto& type, Wasm::Runtime::Store&, ReadonlySpan<WasmValue> stub_arguments, Span<WasmValue>) -> ErrorOr<void, HostError> {
StringBuilder builder;
for (size_t argument = 0; argument < stub_arguments.size(); ++argument) {
if (argument != 0)
@@ -656,7 +664,7 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)
}
dbgln("[wasm runtime] Stub function {} was called with the following arguments: {}", name, builder.string_view());
return {};
- });
+ }));
break;
}
case ExternKind::Table: