From 38c109832794e3457cb1d0781f959941116fe421 Mon Sep 17 00:00:00 2001 From: Liam Murphy Date: Tue, 23 Jan 2024 10:30:19 +1100 Subject: [PATCH 1/3] Shrink JS-allocated strings down to the correct size before passing them to Rust Fixes #3801. I opted to solve it this way rather than just pass the capacity to Rust as well because it means the allocation isn't up to 3x bigger than it needs to be anymore. I also removed a TODO about fixing that. --- crates/cli-support/src/js/mod.rs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/crates/cli-support/src/js/mod.rs b/crates/cli-support/src/js/mod.rs index ee1c4790ff8..5a5ebfee527 100644 --- a/crates/cli-support/src/js/mod.rs +++ b/crates/cli-support/src/js/mod.rs @@ -1296,11 +1296,6 @@ impl<'a> Context<'a> { mem = mem, ); - // TODO: - // When converting a JS string to UTF-8, the maximum size is `arg.length * 3`, - // so we just allocate that. This wastes memory, so we should investigate - // looping over the string to calculate the precise size, or perhaps using - // `shrink_to_fit` on the Rust side. self.global(&format!( "function {name}(arg, malloc, realloc) {{ {debug} @@ -1314,6 +1309,7 @@ impl<'a> Context<'a> { const ret = encodeString(arg, view); {debug_end} offset += ret.written; + ptr = realloc(ptr, len, offset, 1) >>> 0; }} WASM_VECTOR_LEN = offset; From 3f59fe990ca211e9fe816f0cf9917dd7cbccdc91 Mon Sep 17 00:00:00 2001 From: Liam Murphy Date: Tue, 23 Jan 2024 10:54:37 +1100 Subject: [PATCH 2/3] Update reference tests --- crates/cli/tests/reference/string-arg.js | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/cli/tests/reference/string-arg.js b/crates/cli/tests/reference/string-arg.js index 8c006997f9d..7ce1a4db2f3 100644 --- a/crates/cli/tests/reference/string-arg.js +++ b/crates/cli/tests/reference/string-arg.js @@ -75,6 +75,7 @@ function passStringToWasm0(arg, malloc, realloc) { const ret = encodeString(arg, view); offset += ret.written; + ptr = realloc(ptr, len, offset, 1) >>> 0; } WASM_VECTOR_LEN = offset; From 170aba2994c504d563ae2ef75288ef1aba885a55 Mon Sep 17 00:00:00 2001 From: Liam Murphy Date: Wed, 24 Jan 2024 10:48:04 +1100 Subject: [PATCH 3/3] Add changelog entry --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 58546a4344e..095e3af8ecf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,11 @@ * Deprecate `wasm_bindgen_test_configure!`s `run_in_worker` in favor of `run_in_dedicated_worker`. [#3804](https://github.com/rustwasm/wasm-bindgen/pull/3804) +### Fixed + +* Fixed UB when freeing strings received from JS if not using the default allocator. + [#3808](https://github.com/rustwasm/wasm-bindgen/pull/3808) + ## [0.2.90](https://github.com/rustwasm/wasm-bindgen/compare/0.2.89...0.2.90) Released 2024-01-06