Skip to content

Commit 450c923

Browse files
committed
Add the anyref_heap_live_count function
This is useful for debugging and writing tests that assert various operations do not leak `JsValue`s.
1 parent f4c5532 commit 450c923

File tree

5 files changed

+132
-0
lines changed

5 files changed

+132
-0
lines changed

crates/cli-support/src/js/mod.rs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -636,6 +636,37 @@ impl<'a> Context<'a> {
636636
))
637637
})?;
638638

639+
self.bind("__wbindgen_anyref_heap_live_count", &|me| {
640+
if me.config.anyref {
641+
// Eventually we should add support to the anyref-xform to
642+
// re-write calls to the imported
643+
// `__wbindgen_anyref_heap_live_count` function into calls to
644+
// the exported `__wbindgen_anyref_heap_live_count_impl`
645+
// function, and to un-export that function.
646+
//
647+
// But for now, we just bounce wasm -> js -> wasm because it is
648+
// easy.
649+
Ok("function() {{ return wasm.__wbindgen_anyref_heap_live_count_impl(); }}".into())
650+
} else {
651+
me.expose_global_heap();
652+
Ok(format!(
653+
"
654+
function() {{
655+
let free_count = 0;
656+
let next = heap_next;
657+
while (next < heap.length) {{
658+
free_count += 1;
659+
next = heap[next];
660+
}}
661+
return heap.length - free_count - {} - {};
662+
}}
663+
",
664+
INITIAL_HEAP_OFFSET,
665+
INITIAL_HEAP_VALUES.len(),
666+
))
667+
}
668+
})?;
669+
639670
self.bind("__wbindgen_debug_string", &|me| {
640671
me.expose_pass_string_to_wasm()?;
641672
me.expose_uint32_memory();

src/anyref.rs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,20 @@ impl Slab {
107107
None => internal_error("slot out of bounds"),
108108
}
109109
}
110+
111+
fn live_count(&self) -> u32 {
112+
let mut free_count = 0;
113+
let mut next = self.head;
114+
while next < self.data.len() {
115+
debug_assert!((free_count as usize) < self.data.len());
116+
free_count += 1;
117+
match self.data.get(next) {
118+
Some(n) => next = *n,
119+
None => internal_error("slot out of bounds"),
120+
};
121+
}
122+
self.data.len() as u32 - free_count - super::JSIDX_RESERVED
123+
}
110124
}
111125

112126
fn internal_error(msg: &str) -> ! {
@@ -205,6 +219,20 @@ pub unsafe extern fn __wbindgen_drop_anyref_slice(ptr: *mut JsValue, len: usize)
205219
}
206220
}
207221

222+
// Implementation of `__wbindgen_anyref_heap_live_count` for when we are using
223+
// `anyref` instead of the JS `heap`.
224+
#[no_mangle]
225+
pub unsafe extern "C" fn __wbindgen_anyref_heap_live_count_impl() -> u32 {
226+
tl::HEAP_SLAB
227+
.try_with(|slot| {
228+
let slab = slot.replace(Slab::new());
229+
let count = slab.live_count();
230+
slot.replace(slab);
231+
count
232+
})
233+
.unwrap_or_else(|_| internal_error("tls access failure"))
234+
}
235+
208236
// see comment in module above this in `link_mem_intrinsics`
209237
#[inline(never)]
210238
pub fn link_intrinsics() {

src/lib.rs

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -494,6 +494,8 @@ externs! {
494494
fn __wbindgen_number_new(f: f64) -> u32;
495495
fn __wbindgen_symbol_new(ptr: *const u8, len: usize) -> u32;
496496

497+
fn __wbindgen_anyref_heap_live_count() -> u32;
498+
497499
fn __wbindgen_is_null(idx: u32) -> u32;
498500
fn __wbindgen_is_undefined(idx: u32) -> u32;
499501
fn __wbindgen_is_symbol(idx: u32) -> u32;
@@ -655,6 +657,56 @@ pub fn throw_val(s: JsValue) -> ! {
655657
}
656658
}
657659

660+
/// Get the count of live `anyref`s / `JsValue`s in `wasm-bindgen`'s heap.
661+
///
662+
/// ## Usage
663+
///
664+
/// This is intended for debugging and writing tests.
665+
///
666+
/// To write a test that asserts against unnecessarily keeping `anref`s /
667+
/// `JsValue`s alive:
668+
///
669+
/// * get an initial live count,
670+
///
671+
/// * perform some series of operations or function calls that should clean up
672+
/// after themselves, and should not keep holding onto `anyref`s / `JsValue`s
673+
/// after completion,
674+
///
675+
/// * get the final live count,
676+
///
677+
/// * and assert that the initial and final counts are the same.
678+
///
679+
/// ## What is Counted
680+
///
681+
/// Note that this only counts the *owned* `anyref`s / `JsValue`s that end up in
682+
/// `wasm-bindgen`'s heap. It does not count borrowed `anyref`s / `JsValue`s
683+
/// that are on its stack.
684+
///
685+
/// For example, these `JsValue`s are accounted for:
686+
///
687+
/// ```ignore
688+
/// #[wasm_bindgen]
689+
/// pub fn my_function(this_is_counted: JsValue) {
690+
/// let also_counted = JsValue::from_str("hi");
691+
/// assert!(wasm_bindgen::anyref_heap_live_count() >= 2);
692+
/// }
693+
/// ```
694+
///
695+
/// While this borrowed `JsValue` ends up on the stack, not the heap, and
696+
/// therefore is not accounted for:
697+
///
698+
/// ```ignore
699+
/// #[wasm_bindgen]
700+
/// pub fn my_other_function(this_is_not_counted: &JsValue) {
701+
/// // ...
702+
/// }
703+
/// ```
704+
pub fn anyref_heap_live_count() -> u32 {
705+
unsafe {
706+
__wbindgen_anyref_heap_live_count()
707+
}
708+
}
709+
658710
/// An extension trait for `Option<T>` and `Result<T, E>` for unwraping the `T`
659711
/// value, or throwing a JS error if it is not available.
660712
///
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
use wasm_bindgen::prelude::*;
2+
use wasm_bindgen_test::*;
3+
4+
// This test is in the headless suite so that we can test the `anyref` table
5+
// implementation of `anyref_heap_live_count` (as opposed to the JS `heap`
6+
// implementation) in Firefox.
7+
#[wasm_bindgen_test]
8+
fn test_anyref_heap_live_count() {
9+
let initial = wasm_bindgen::anyref_heap_live_count();
10+
11+
let after_alloc = {
12+
let _vals: Vec<_> = (0..10).map(JsValue::from).collect();
13+
wasm_bindgen::anyref_heap_live_count()
14+
};
15+
16+
let after_dealloc = wasm_bindgen::anyref_heap_live_count();
17+
18+
assert_eq!(initial, after_dealloc);
19+
assert_eq!(initial + 10, after_alloc);
20+
}

tests/headless/main.rs

100644100755
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,3 +49,4 @@ pub fn import_export_same_name() {
4949

5050
pub mod snippets;
5151
pub mod modules;
52+
pub mod anyref_heap_live_count;

0 commit comments

Comments
 (0)