Skip to content

Truly independent web browser

LibWasm: Check the kinds of values from the host against types

Andreas Klingdd7141a41024
diff --git a/Libraries/LibWasm/Engine/src/runtime/mod.rs b/Libraries/LibWasm/Engine/src/runtime/mod.rs
index 235afef4a65..c9c5269db07 100644
--- a/Libraries/LibWasm/Engine/src/runtime/mod.rs
+++ b/Libraries/LibWasm/Engine/src/runtime/mod.rs
@@ -80,6 +80,22 @@ impl Value {
}
}
+ /// Whether the value can be one of type `ty`: one of its kind, and not null where `ty` is not nullable.
+ ///
+ /// NB: The heap type of a reference is the embedder's to check, which knows what the reference is. Its bits do
+ /// not say which hierarchy it is of: an externref keeps the bits of the anyref it externalizes.
+ pub fn matches(self, ty: ValType) -> bool {
+ match (self, ty) {
+ (Self::I32(_), ValType::I32)
+ | (Self::I64(_), ValType::I64)
+ | (Self::F32(_), ValType::F32)
+ | (Self::F64(_), ValType::F64)
+ | (Self::V128(_), ValType::V128) => true,
+ (Self::Ref(bits), ValType::Ref(ty)) => bits != 0 || ty.nullable,
+ _ => false,
+ }
+ }
+
/// The value's slots in memory order (a v128's low half first), and how many of the two it takes.
pub fn to_slots(self) -> ([u64; 2], usize) {
match self {
@@ -109,6 +125,11 @@ impl Value {
}
}
+/// Whether `values` can be values of `types`, one of each.
+fn values_match(values: &[Value], types: &[ValType]) -> bool {
+ values.len() == types.len() && values.iter().zip(types).all(|(value, &ty)| value.matches(ty))
+}
+
/// Declares `Trap`, with a variant for each trap that has a `TRAP_*` code and a message of its own, besides traps of
/// the host and uncaught exceptions.
macro_rules! traps {
@@ -1115,6 +1136,10 @@ impl Store {
pub fn invoke(&mut self, address: FunctionAddress, arguments: &[Value]) -> Result<Vec<Value>, Trap> {
let function = self.function(address);
+ // NB: Code reads the arguments as the function's type says they are, and host functions index them by it.
+ if !values_match(arguments, &function.ty.params) {
+ return Err(Trap::Host("the arguments do not match the function's type".to_string()));
+ }
if let FunctionKind::Host(_) = function.kind {
return self.call_host(address, arguments);
}
@@ -1123,10 +1148,6 @@ impl Store {
for argument in arguments.iter().rev() {
argument.push_slots(&mut argument_slots);
}
- // NB: The interpreter reads the function's parameter slots from the arguments, so they must have that many.
- if arguments.len() != function.ty.params.len() || argument_slots.len() != function.header.param_slots as usize {
- return Err(Trap::Host("the arguments do not match the function's type".to_string()));
- }
let mut result_slots = vec![0u64; function.header.result_slots as usize];
self.invoke_slots(address, &argument_slots, &mut result_slots)?;
// The results are laid out as the operand stack holds them, the first one in the highest slots.
@@ -1183,7 +1204,14 @@ impl Store {
unreachable!("only host functions are called through call_host")
};
let callback = callback.clone();
- callback.call(self, arguments)
+ let values = callback.call(self, arguments)?;
+ // NB: Code reads the results as the function's type says they are, and they must fit where they go.
+ if !values_match(&values, &self.function(address).ty.results) {
+ return Err(Trap::Host(
+ "a host function returned results that do not match its type".to_string(),
+ ));
+ }
+ Ok(values)
}
/// Calls the host function at `address` with the arguments in `arguments`, its parameter slots in operand stack
@@ -1209,15 +1237,7 @@ impl Store {
slot -= ty.slot_count() as usize;
values.push(Value::from_slots(ty, &slots[slot..]));
}
- let (result_count, result_slots) = (function.ty.results.len(), function.header.result_slots as usize);
let values = self.call_host(address, &values)?;
- // NB: Results that do not match the function's type would not fit where they go.
- let slot_count: usize = values.iter().map(|value| value.to_slots().1).sum();
- if values.len() != result_count || slot_count != result_slots {
- return Err(Trap::Host(
- "a host function returned results that do not match its type".to_string(),
- ));
- }
let mut next = results;
for value in values.iter().rev() {
let (value, count) = value.to_slots();
diff --git a/Libraries/LibWasm/Engine/tests/execution.rs b/Libraries/LibWasm/Engine/tests/execution.rs
index 7e778ee28de..b7368de758d 100644
--- a/Libraries/LibWasm/Engine/tests/execution.rs
+++ b/Libraries/LibWasm/Engine/tests/execution.rs
@@ -229,6 +229,54 @@ fn catches_exceptions_from_webassembly_and_host_functions() {
assert_eq!(store.exception(exception).payload, &[5]);
}
+#[test]
+fn checks_values_from_the_host_against_function_types() {
+ use libwasm_engine::types::{FuncType, HeapType, RefType, ValType};
+ let mut store = Store::new();
+ let any = ValType::Ref(RefType {
+ nullable: true,
+ heap: HeapType::Any,
+ });
+ let reference = store.allocate_host_function(
+ FuncType {
+ params: vec![],
+ results: vec![any],
+ },
+ std::rc::Rc::new(|_: &mut Store, _: &[Value]| Ok(vec![Value::I64(0x4141)])),
+ );
+ let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/host_values.wasm");
+ let module = libwasm_engine::compile(&std::fs::read(path).unwrap()).unwrap();
+ let instance = store
+ .instantiate(Arc::new(module), &[ExternValue::Function(reference)])
+ .unwrap();
+ let is_host_trap = |result: Result<Vec<Value>, Trap>| matches!(result, Err(Trap::Host(_)));
+ let traps =
+ |store: &mut Store, name: &str, arguments: &[Value]| is_host_trap(call(store, instance, name, arguments));
+
+ assert_eq!(
+ call(&mut store, instance, "is_null", &[Value::Ref(0)]),
+ Ok(vec![Value::I32(1)])
+ );
+ assert!(traps(&mut store, "is_null", &[Value::I64(0x4141)]));
+ assert!(traps(&mut store, "take_non_null", &[Value::Ref(0)]));
+ assert!(traps(&mut store, "host_is_null", &[]));
+ assert!(is_host_trap(store.invoke(reference, &[])));
+
+ let takes_an_argument = store.allocate_host_function(
+ FuncType {
+ params: vec![ValType::I32],
+ results: vec![],
+ },
+ std::rc::Rc::new(|_: &mut Store, arguments: &[Value]| {
+ assert_eq!(arguments.len(), 1);
+ Ok(vec![])
+ }),
+ );
+ assert!(is_host_trap(store.invoke(takes_an_argument, &[])));
+ assert!(is_host_trap(store.invoke(takes_an_argument, &[Value::I64(1)])));
+ assert_eq!(store.invoke(takes_an_argument, &[Value::I32(1)]), Ok(vec![]));
+}
+
#[test]
fn waits_on_shared_memory() {
let mut store = Store::new();
diff --git a/Libraries/LibWasm/Engine/tests/fixtures/host_values.wasm b/Libraries/LibWasm/Engine/tests/fixtures/host_values.wasm
new file mode 100644
index 00000000000..087fc213dec
Binary files /dev/null and b/Libraries/LibWasm/Engine/tests/fixtures/host_values.wasm differ
diff --git a/Libraries/LibWasm/Engine/tests/fixtures/host_values.wat b/Libraries/LibWasm/Engine/tests/fixtures/host_values.wat
new file mode 100644
index 00000000000..106ec120d38
--- /dev/null
+++ b/Libraries/LibWasm/Engine/tests/fixtures/host_values.wat
@@ -0,0 +1,9 @@
+;; Functions that take values from the host as arguments and results.
+(module
+ (import "env" "reference" (func $reference (result anyref)))
+ (func (export "is_null") (param externref) (result i32)
+ (ref.is_null (local.get 0)))
+ (func (export "take_non_null") (param (ref extern)) (result i32)
+ (i32.const 1))
+ (func (export "host_is_null") (result i32)
+ (ref.is_null (call $reference))))