Skip to content

Commit f903cd3

Browse files
committed
mangle exports of wasm modules
mangle webpack init function store WebAssembly.Instance.exports directly connect wasm modules directly when already cached
1 parent c92eabd commit f903cd3

4 files changed

Lines changed: 61 additions & 40 deletions

File tree

‎lib/MainTemplate.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ const Template = require("./Template");
4646
// __webpack_require__.r = define compatibility on export
4747
// __webpack_require__.n = compatibility get default export
4848
// __webpack_require__.h = the webpack hash
49-
// __webpack_require__.w = an object containing all installed WebAssembly.Modules keys by module id
49+
// __webpack_require__.w = an object containing all installed WebAssembly.Instance export objects keyed by module id
5050
// __webpack_require__.oe = the uncaught error handler for the webpack runtime
5151
// __webpack_require__.nc = the script nonce
5252

‎lib/wasm/WasmMainTemplatePlugin.js‎

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -67,22 +67,25 @@ function generateImportObject(module) {
6767
`installedWasmModules[${JSON.stringify(data.module.id)}]`
6868
);
6969
properties.push(
70-
`${JSON.stringify(data.exportName)}: ${instanceVar}.exports` +
71-
`[${JSON.stringify(data.exportName)}]`
70+
`${JSON.stringify(data.exportName)}: ${instanceVar}` +
71+
`[${JSON.stringify(data.usedName)}]`
7272
);
7373
} else {
7474
const params = data.description.signature.params.map(
7575
(param, k) => "p" + k + param.valtype
7676
);
7777

78-
const result = `__webpack_require__(${JSON.stringify(
79-
data.module.id
80-
)})[${JSON.stringify(data.usedName)}](${params})`;
78+
const mod = `installedModules[${JSON.stringify(data.module.id)}]`;
79+
const func = `${mod}.exports[${JSON.stringify(data.usedName)}]`;
8180

8281
properties.push(
8382
Template.asString([
84-
`${JSON.stringify(data.exportName)}: function(${params}) {`,
85-
Template.indent([`return ${result};`]),
83+
`${JSON.stringify(data.exportName)}: ` +
84+
(data.module.type.startsWith("webassembly")
85+
? `${mod} ? ${func} : `
86+
: "") +
87+
`function(${params}) {`,
88+
Template.indent([`return ${func}(${params});`]),
8689
"}"
8790
])
8891
);
@@ -257,7 +260,7 @@ class WasmMainTemplatePlugin {
257260
Template.indent([
258261
`return ${
259262
mainTemplate.requireFn
260-
}.w[wasmModuleId] = res.instance || res;`
263+
}.w[wasmModuleId] = (res.instance || res).exports;`
261264
]),
262265
"}));"
263266
]),
@@ -275,7 +278,7 @@ class WasmMainTemplatePlugin {
275278
return Template.asString([
276279
source,
277280
"",
278-
"// object with all WebAssembly.instance",
281+
"// object with all WebAssembly.instance exports",
279282
`${mainTemplate.requireFn}.w = {};`
280283
]);
281284
}

‎lib/wasm/WebAssemblyGenerator.js‎

Lines changed: 38 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,15 @@
55
"use strict";
66

77
const Generator = require("../Generator");
8+
const Template = require("../Template");
89
const { RawSource } = require("webpack-sources");
910

1011
const { editWithAST, addWithAST } = require("@webassemblyjs/wasm-edit");
1112
const { decode } = require("@webassemblyjs/wasm-parser");
1213
const t = require("@webassemblyjs/ast");
1314

1415
function compose(...fns) {
15-
return fns.reverse().reduce((prevFn, nextFn) => {
16+
return fns.reduce((prevFn, nextFn) => {
1617
return value => nextFn(prevFn(value));
1718
}, value => value);
1819
}
@@ -31,8 +32,6 @@ const isGlobalImport = n => n.descr.type === "GlobalType";
3132
*/
3233
const isFuncImport = n => n.descr.type === "FuncImportDescr";
3334

34-
const initFuncId = t.identifier("__webpack_init__");
35-
3635
// TODO replace with @callback
3736
/**
3837
* @typedef {(ArrayBuffer) => ArrayBuffer} ArrayBufferTransform
@@ -181,13 +180,36 @@ const rewriteImportedGlobals = state => bin => {
181180
return addWithAST(state.ast, bin, newGlobals);
182181
};
183182

183+
/**
184+
* Rewrite the export names
185+
* @param {Object} state state
186+
* @param {Object} state.ast Module's ast
187+
* @param {Object} state.module Module
188+
* @returns {ArrayBufferTransform} transform
189+
*/
190+
const rewriteExportNames = ({ ast, module }) => bin => {
191+
return editWithAST(ast, bin, {
192+
ModuleExport(path) {
193+
const usedName = module.isUsed(path.node.name);
194+
if (usedName) {
195+
path.node.name = usedName;
196+
// TODO remove this when fixed in @webassemblyjs
197+
path.node.descr.id = t.numberLiteral(+path.node.descr.id.raw);
198+
} else {
199+
path.remove();
200+
}
201+
}
202+
});
203+
};
204+
184205
/**
185206
* Add an init function.
186207
*
187208
* The init function fills the globals given input arguments.
188209
*
189210
* @param {Object} state transformation state
190211
* @param {Object} state.ast - Module's ast
212+
* @param {t.Identifier} state.initFuncId identifier of the init function
191213
* @param {t.IndexLiteral} state.startAtFuncIndex index of the start function
192214
* @param {t.ModuleImport[]} state.importedGlobals list of imported globals
193215
* @param {t.IndexLiteral} state.nextFuncIndex index of the next function
@@ -196,6 +218,7 @@ const rewriteImportedGlobals = state => bin => {
196218
*/
197219
const addInitFunction = ({
198220
ast,
221+
initFuncId,
199222
startAtFuncIndex,
200223
importedGlobals,
201224
nextFuncIndex,
@@ -246,6 +269,12 @@ class WebAssemblyGenerator extends Generator {
246269
generate(module) {
247270
const bin = module.originalSource().source();
248271

272+
const initFuncId = t.identifier(
273+
Array.isArray(module.usedExports)
274+
? Template.numberToIdentifer(module.usedExports.length)
275+
: "__webpack_init__"
276+
);
277+
249278
const ast = decode(bin, {
250279
ignoreDataSection: true,
251280
ignoreCodeSection: true
@@ -258,12 +287,18 @@ class WebAssemblyGenerator extends Generator {
258287
const nextTypeIndex = getNextTypeIndex(ast);
259288

260289
const transform = compose(
290+
rewriteExportNames({
291+
ast,
292+
module
293+
}),
294+
261295
removeStartFunc({ ast }),
262296

263297
rewriteImportedGlobals({ ast }),
264298

265299
addInitFunction({
266300
ast,
301+
initFuncId,
267302
importedGlobals,
268303
startAtFuncIndex,
269304
nextFuncIndex,

‎lib/wasm/WebAssemblyJavascriptGenerator.js‎

Lines changed: 10 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -39,29 +39,9 @@ function generateInitParams(module) {
3939

4040
class WebAssemblyJavascriptGenerator extends Generator {
4141
generate(module, dependencyTemplates, runtimeTemplate) {
42-
const generateExports = () => {
43-
if (
44-
Array.isArray(module.buildMeta.providedExports) &&
45-
Array.isArray(module.usedExports)
46-
) {
47-
// generate mangled exports
48-
return Template.asString(
49-
module.buildMeta.providedExports.map(exp => {
50-
const usedName = module.isUsed(exp);
51-
if (usedName) {
52-
return `${module.exportsArgument}[${JSON.stringify(
53-
usedName
54-
)}] = instance.exports[${JSON.stringify(exp)}];`;
55-
} else {
56-
return `// unused ${JSON.stringify(exp)} export`;
57-
}
58-
})
59-
);
60-
} else {
61-
// generate simple export
62-
return `${module.moduleArgument}.exports = instance.exports;`;
63-
}
64-
};
42+
const initIdentifer = Array.isArray(module.usedExports)
43+
? Template.numberToIdentifer(module.usedExports.length)
44+
: "__webpack_init__";
6545

6646
const generateImports = () => {
6747
const modules = new Map();
@@ -87,17 +67,20 @@ class WebAssemblyJavascriptGenerator extends Generator {
8767
[
8868
'"use strict";',
8969
"// Instantiate WebAssembly module",
90-
"var instance = __webpack_require__.w[module.i];",
70+
"var wasmExports = __webpack_require__.w[module.i];",
9171

9272
// this must be before import for circular dependencies
9373
"// export exports from WebAssembly module",
94-
generateExports(),
95-
74+
Array.isArray(module.usedExports)
75+
? `${module.moduleArgument}.exports = wasmExports;`
76+
: "for(var name in wasmExports) " +
77+
`if(name != ${JSON.stringify(initIdentifer)}) ` +
78+
`${module.exportsArgument}[name] = wasmExports[name];`,
9679
"// exec imports from WebAssembly module (for esm order)",
9780
generateImports(),
9881

9982
"// exec wasm module",
100-
`instance.exports.__webpack_init__(${initParams})`
83+
`wasmExports[${JSON.stringify(initIdentifer)}](${initParams})`
10184
].join("\n")
10285
);
10386
return source;

0 commit comments

Comments
 (0)