Skip to content

[wasm2js] Escape module names in generated JavaScript output#8377

Open
sumleo wants to merge 1 commit intoWebAssembly:mainfrom
sumleo:fix-wasm2js-string-escaping
Open

[wasm2js] Escape module names in generated JavaScript output#8377
sumleo wants to merge 1 commit intoWebAssembly:mainfrom
sumleo:fix-wasm2js-string-escaping

Conversation

@sumleo
Copy link
Contributor

@sumleo sumleo commented Feb 25, 2026

Summary

WebAssembly module and base names are arbitrary UTF-8 strings per the spec, and may contain JavaScript string metacharacters such as quotes, backslashes, and newlines. The wasm2js code generator was inserting these names directly into JavaScript string literals without escaping, which could produce syntactically invalid or exploitable JavaScript output.

This PR adds an escapeJSString() helper that escapes backslashes, single/double quotes, newlines, carriage returns, and the Unicode line/paragraph separators (U+2028, U+2029), and applies it at all three affected output points in src/wasm2js.h:

  1. emitPreES6 — ES6 import ... from '...' clause (single-quote string context). A module name containing ' would break out of the string literal.
  2. emitPostES6 — Object literal keys written as "..." for imported functions, memories, and tables. A module name containing " would break out.
  3. initActiveSegmentsimports['module']['base'] subscript expressions. Both module and base names are interpolated into single-quote strings without escaping.

Test plan

  • Full wasm2js test suite passes (python3 check.py --binaryen-bin ./build/bin wasm2js)
  • Clean build with no new warnings
  • Verified all three injection points are covered by reviewing every use of import->module and import->base in wasm2js.h

WebAssembly module and base names are arbitrary UTF-8 strings per the
spec, and may contain JavaScript string metacharacters such as quotes,
backslashes, and newlines. The wasm2js code generator was inserting
these names directly into JavaScript string literals without escaping,
which could produce syntactically invalid or exploitable JavaScript
output.

Add an escapeJSString() helper that escapes backslashes, single and
double quotes, newlines, carriage returns, and the Unicode line/paragraph
separators (U+2028, U+2029). Apply it at all three injection points:

1. emitPreES6: ES6 import 'from' clause (single-quote context)
2. emitPostES6: object literal keys (double-quote context) for
   imported functions, memories, and tables
3. initActiveSegments: imports['module']['base'] subscript access
   (single-quote context) for both module and base names
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant