Skip to content

Commit

Permalink
Fix inheritance of polyfilled WebAssembly.Module
Browse files Browse the repository at this point in the history
The polyfilled WebAssembly.Module instance was not inheriting from the
polyfilled constructor's prototype when it's created by WebAssembly.compile
or WebAssembly.compileStreaming.
  • Loading branch information
kateinoigakukun committed Dec 3, 2024
1 parent 4e100e4 commit f8cbaa8
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
12 changes: 11 additions & 1 deletion polyfill.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,11 +60,19 @@ export function polyfill(WebAssembly) {
module[polyfilledImportsSymbol] = parseImports(sourceBytes);
}

// Modify the module's prototype chain to make the following inheritance
// test pass:
// * `module instanceof WebAssembly.Module === true`
// * `module instanceof newWebAssembly.Module === true`
const prependInheritance = (module) => {
Object.setPrototypeOf(module, newModule.prototype);
}

// Hook the Module constructor to store the source bytes.
const newModule = newWebAssembly.Module = function (bytes) {
const module = new WebAssembly.Module(bytes);
assignImports(module, bytes);
Object.setPrototypeOf(module, newModule.prototype);
prependInheritance(module);
return module;
}
Object.setPrototypeOf(newModule.prototype, WebAssembly.Module.prototype);
Expand All @@ -73,6 +81,7 @@ export function polyfill(WebAssembly) {
newWebAssembly.compile = async (source) => {
const module = await WebAssembly.compile(source);
assignImports(module, source);
prependInheritance(module);
return module;
};

Expand All @@ -83,6 +92,7 @@ export function polyfill(WebAssembly) {
const clone = response.clone();
const module = await WebAssembly.compileStreaming(response);
assignImports(module, new Uint8Array(await clone.arrayBuffer()));
prependInheritance(module);
return module;
};
}
Expand Down
12 changes: 12 additions & 0 deletions test/check.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,18 @@ async function checkPolyfill() {
} else {
module = getModule.fn();
}

if (module instanceof WebAssembly.Module === false) {
process.stdout.write("\x1b[31mF\x1b[0m\n");
console.error(`Expected module to be instance of the original WebAssembly.Module, but got something wrong by ${getModule.name}`);
return false;
}
if (module instanceof polyfilledWebAssembly.Module === false) {
process.stdout.write("\x1b[31mF\x1b[0m\n");
console.error(`Expected module to be instance of the polyfilled WebAssembly.Module, but got something wrong by ${getModule.name}`);
return false;
}

imports = polyfilledWebAssembly.Module.imports(module);
} catch (e) {
process.stdout.write("\x1b[31mF\x1b[0m\n");
Expand Down

0 comments on commit f8cbaa8

Please sign in to comment.