Skip to content

Commit

Permalink
Made sure downcast_from_ptr() correctly consumes the Trap wrapper class
Browse files Browse the repository at this point in the history
  • Loading branch information
Michael-F-Bryan committed Sep 11, 2023
1 parent b144015 commit 203e72e
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 32 deletions.
30 changes: 22 additions & 8 deletions lib/api/src/js/trap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ impl Trap {

#[wasm_bindgen]
impl Trap {
/// A marker method to indicate that an object is an instance of the `Trap`
/// class.
pub fn __wbg_wasmer_trap() {}
}

Expand Down Expand Up @@ -108,17 +110,29 @@ fn downcast_from_ptr(value: &JsValue) -> Option<Trap> {
let class = prototype.constructor();
let key = JsValue::from_str("__wbg_wasmer_trap");

let _marker_func: js_sys::Function = Reflect::get(&class, &key)
let marker_func: Option<js_sys::Function> = Reflect::get(&class, &key)
.and_then(|v: JsValue| v.dyn_into())
.ok()?;
.ok();

// Note: this assumes the wrapper class generated by #[wasm_bindgen] will
// always store the pointer in a field called "__wbg_ptr". This is valid
// as of wasm-bindgen version 0.2.87
let key = JsValue::from_str("__wbg_ptr");
let ptr = Reflect::get(value, &key).ok().and_then(|v| v.as_f64())?;
if marker_func.is_none() {
// We couldn't find the marker, so it's something else.
return None;
}

// Safety: The marker function exists, therefore it's safe to cast back to a trap.
// Note: this assumes the wrapper class generated by #[wasm_bindgen] will
// always have a `__destroy_into_raw()` method which consumes the `Trap`
// wrapper and returns a pointer.
//
// This is valid as of wasm-bindgen version 0.2.87
let key = JsValue::from_str("__destroy_into_raw");
let ptr = Reflect::get(value, &key)
.ok()
.and_then(|v| v.dyn_into::<js_sys::Function>().ok())
.and_then(|destroy_into_raw| destroy_into_raw.call0(value).ok())
.and_then(|ret| ret.as_f64())?;

// Safety: The marker function exists, therefore it's safe to convert back
// to a Trap.
unsafe {
Some(<Trap as wasm_bindgen::convert::FromWasmAbi>::from_abi(
ptr as u32,
Expand Down
24 changes: 0 additions & 24 deletions lib/wasi-web/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 203e72e

Please sign in to comment.