Skip to content

Commit

Permalink
Shrink JS-allocated strings down to the correct size before passing t…
Browse files Browse the repository at this point in the history
…hem to Rust (#3808)

* 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.

* Update reference tests

* Add changelog entry
  • Loading branch information
Liamolucko committed Jan 25, 2024
1 parent 034fb35 commit acef364
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 5 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,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
Expand Down
6 changes: 1 addition & 5 deletions crates/cli-support/src/js/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand All @@ -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;
Expand Down
1 change: 1 addition & 0 deletions crates/cli/tests/reference/string-arg.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit acef364

Please sign in to comment.