Skip to content

Commit 5fee19d

Browse files
authored
Merge pull request webpack#7487 from webpack/bugfix/no-wasm-import-mangle
allow to disable wasm import mangle
2 parents e2fe200 + 8e3be48 commit 5fee19d

10 files changed

+239
-139
lines changed

lib/WebpackOptionsApply.js

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,9 @@ class WebpackOptionsApply extends OptionsApply {
8787
FetchCompileWasmTemplatePlugin = require("./web/FetchCompileWasmTemplatePlugin");
8888
NodeSourcePlugin = require("./node/NodeSourcePlugin");
8989
new JsonpTemplatePlugin().apply(compiler);
90-
new FetchCompileWasmTemplatePlugin().apply(compiler);
90+
new FetchCompileWasmTemplatePlugin({
91+
mangleImports: options.optimization.mangleWasmImports
92+
}).apply(compiler);
9193
new FunctionModulePlugin().apply(compiler);
9294
new NodeSourcePlugin(options.node).apply(compiler);
9395
new LoaderTargetPlugin(options.target).apply(compiler);
@@ -97,7 +99,9 @@ class WebpackOptionsApply extends OptionsApply {
9799
FetchCompileWasmTemplatePlugin = require("./web/FetchCompileWasmTemplatePlugin");
98100
NodeSourcePlugin = require("./node/NodeSourcePlugin");
99101
new WebWorkerTemplatePlugin().apply(compiler);
100-
new FetchCompileWasmTemplatePlugin().apply(compiler);
102+
new FetchCompileWasmTemplatePlugin({
103+
mangleImports: options.optimization.mangleWasmImports
104+
}).apply(compiler);
101105
new FunctionModulePlugin().apply(compiler);
102106
new NodeSourcePlugin(options.node).apply(compiler);
103107
new LoaderTargetPlugin(options.target).apply(compiler);
@@ -111,7 +115,9 @@ class WebpackOptionsApply extends OptionsApply {
111115
new NodeTemplatePlugin({
112116
asyncChunkLoading: options.target === "async-node"
113117
}).apply(compiler);
114-
new ReadFileCompileWasmTemplatePlugin().apply(compiler);
118+
new ReadFileCompileWasmTemplatePlugin({
119+
mangleImports: options.optimization.mangleWasmImports
120+
}).apply(compiler);
115121
new FunctionModulePlugin().apply(compiler);
116122
new NodeTargetPlugin().apply(compiler);
117123
new LoaderTargetPlugin("node").apply(compiler);
@@ -274,7 +280,9 @@ class WebpackOptionsApply extends OptionsApply {
274280

275281
new JavascriptModulesPlugin().apply(compiler);
276282
new JsonModulesPlugin().apply(compiler);
277-
new WebAssemblyModulesPlugin().apply(compiler);
283+
new WebAssemblyModulesPlugin({
284+
mangleImports: options.optimization.mangleWasmImports
285+
}).apply(compiler);
278286

279287
new EntryOptionPlugin().apply(compiler);
280288
compiler.hooks.entryOption.call(options.context, options.entry);

lib/WebpackOptionsDefaulter.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -257,6 +257,7 @@ class WebpackOptionsDefaulter extends OptionsDefaulter {
257257
this.set("optimization.checkWasmTypes", "make", options =>
258258
isProductionLikeMode(options)
259259
);
260+
this.set("optimization.mangleWasmImports", false);
260261
this.set(
261262
"optimization.namedModules",
262263
"make",

lib/node/ReadFileCompileWasmTemplatePlugin.js

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,10 @@ const Template = require("../Template");
88
const WasmMainTemplatePlugin = require("../wasm/WasmMainTemplatePlugin");
99

1010
class ReadFileCompileWasmTemplatePlugin {
11+
constructor(options) {
12+
this.options = options || {};
13+
}
14+
1115
apply(compiler) {
1216
compiler.hooks.thisCompilation.tap(
1317
"ReadFileCompileWasmTemplatePlugin",
@@ -40,8 +44,13 @@ class ReadFileCompileWasmTemplatePlugin {
4044
]);
4145

4246
const plugin = new WasmMainTemplatePlugin(
43-
generateLoadBinaryCode,
44-
false
47+
Object.assign(
48+
{
49+
generateLoadBinaryCode,
50+
supportsStreaming: false
51+
},
52+
this.options
53+
)
4554
);
4655
plugin.apply(compilation.mainTemplate);
4756
}

lib/wasm/WasmMainTemplatePlugin.js

Lines changed: 83 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,16 @@ function getAllWasmModules(chunk) {
2727
/**
2828
* generates the import object function for a module
2929
* @param {Module} module the module
30+
* @param {boolean} mangle mangle imports
3031
* @returns {string} source code
3132
*/
32-
function generateImportObject(module) {
33+
function generateImportObject(module, mangle) {
3334
const waitForInstances = new Map();
3435
const properties = [];
35-
const usedWasmDependencies = WebAssemblyUtils.getUsedDependencies(module);
36+
const usedWasmDependencies = WebAssemblyUtils.getUsedDependencies(
37+
module,
38+
mangle
39+
);
3640
for (const usedDep of usedWasmDependencies) {
3741
const dep = usedDep.dependency;
3842
const importedModule = dep.module;
@@ -41,15 +45,17 @@ function generateImportObject(module) {
4145
const description = dep.description;
4246
const direct = dep.onlyDirectImport;
4347

44-
const propertyName = usedDep.name;
48+
const module = usedDep.module;
49+
const name = usedDep.name;
4550

4651
if (direct) {
4752
const instanceVar = `m${waitForInstances.size}`;
4853
waitForInstances.set(instanceVar, importedModule.id);
49-
properties.push(
50-
`${JSON.stringify(propertyName)}: ${instanceVar}` +
51-
`[${JSON.stringify(usedName)}]`
52-
);
54+
properties.push({
55+
module,
56+
name,
57+
value: `${instanceVar}[${JSON.stringify(usedName)}]`
58+
});
5359
} else {
5460
const params = description.signature.params.map(
5561
(param, k) => "p" + k + param.valtype
@@ -58,20 +64,55 @@ function generateImportObject(module) {
5864
const mod = `installedModules[${JSON.stringify(importedModule.id)}]`;
5965
const func = `${mod}.exports[${JSON.stringify(usedName)}]`;
6066

61-
properties.push(
62-
Template.asString([
63-
`${JSON.stringify(propertyName)}: ` +
64-
(importedModule.type.startsWith("webassembly")
65-
? `${mod} ? ${func} : `
66-
: "") +
67-
`function(${params}) {`,
67+
properties.push({
68+
module,
69+
name,
70+
value: Template.asString([
71+
(importedModule.type.startsWith("webassembly")
72+
? `${mod} ? ${func} : `
73+
: "") + `function(${params}) {`,
6874
Template.indent([`return ${func}(${params});`]),
6975
"}"
7076
])
71-
);
77+
});
7278
}
7379
}
7480

81+
let importObject;
82+
if (mangle) {
83+
importObject = [
84+
"return {",
85+
Template.indent([
86+
properties.map(p => `${JSON.stringify(p.name)}: ${p.value}`).join(",\n")
87+
]),
88+
"};"
89+
];
90+
} else {
91+
const propertiesByModule = new Map();
92+
for (const p of properties) {
93+
let list = propertiesByModule.get(p.module);
94+
if (list === undefined) {
95+
propertiesByModule.set(p.module, (list = []));
96+
}
97+
list.push(p);
98+
}
99+
importObject = [
100+
"return {",
101+
Template.indent([
102+
Array.from(propertiesByModule, ([module, list]) => {
103+
return Template.asString([
104+
`${JSON.stringify(module)}: {`,
105+
Template.indent([
106+
list.map(p => `${JSON.stringify(p.name)}: ${p.value}`).join(",\n")
107+
]),
108+
"}"
109+
]);
110+
}).join(",\n")
111+
]),
112+
"};"
113+
];
114+
}
115+
75116
if (waitForInstances.size === 1) {
76117
const moduleId = Array.from(waitForInstances.values())[0];
77118
const promise = `installedWasmModules[${JSON.stringify(moduleId)}]`;
@@ -80,11 +121,7 @@ function generateImportObject(module) {
80121
`${JSON.stringify(module.id)}: function() {`,
81122
Template.indent([
82123
`return promiseResolve().then(function() { return ${promise}; }).then(function(${variable}) {`,
83-
Template.indent([
84-
"return {",
85-
Template.indent([properties.join(",\n")]),
86-
"};"
87-
]),
124+
Template.indent(importObject),
88125
"});"
89126
]),
90127
"},"
@@ -102,41 +139,35 @@ function generateImportObject(module) {
102139
`${JSON.stringify(module.id)}: function() {`,
103140
Template.indent([
104141
`return promiseResolve().then(function() { return Promise.all([${promises}]); }).then(function(array) {`,
105-
Template.indent([
106-
`var ${variables};`,
107-
"return {",
108-
Template.indent([properties.join(",\n")]),
109-
"};"
110-
]),
142+
Template.indent([`var ${variables};`, ...importObject]),
111143
"});"
112144
]),
113145
"},"
114146
]);
115147
} else {
116148
return Template.asString([
117149
`${JSON.stringify(module.id)}: function() {`,
118-
Template.indent([
119-
"return {",
120-
Template.indent([properties.join(",\n")]),
121-
"};"
122-
]),
150+
Template.indent(importObject),
123151
"},"
124152
]);
125153
}
126154
}
127155

128156
class WasmMainTemplatePlugin {
129-
constructor(generateLoadBinaryCode, supportsStreaming) {
157+
constructor({ generateLoadBinaryCode, supportsStreaming, mangleImports }) {
130158
this.generateLoadBinaryCode = generateLoadBinaryCode;
131159
this.supportsStreaming = supportsStreaming;
160+
this.mangleImports = mangleImports;
132161
}
133162
apply(mainTemplate) {
134163
mainTemplate.hooks.localVars.tap(
135164
"WasmMainTemplatePlugin",
136165
(source, chunk) => {
137166
const wasmModules = getAllWasmModules(chunk);
138167
if (wasmModules.length === 0) return source;
139-
const importObjects = wasmModules.map(generateImportObject);
168+
const importObjects = wasmModules.map(module => {
169+
return generateImportObject(module, this.mangleImports);
170+
});
140171
return Template.asString([
141172
source,
142173
"",
@@ -192,6 +223,12 @@ class WasmMainTemplatePlugin {
192223
}
193224
}
194225
);
226+
const createImportObject = content =>
227+
this.mangleImports
228+
? `{ ${JSON.stringify(
229+
WebAssemblyUtils.MANGLED_MODULE
230+
)}: ${content} }`
231+
: content;
195232
return Template.asString([
196233
source,
197234
"",
@@ -219,15 +256,17 @@ class WasmMainTemplatePlugin {
219256
Template.indent([
220257
"promise = Promise.all([WebAssembly.compileStreaming(req), importObject]).then(function(items) {",
221258
Template.indent([
222-
"return WebAssembly.instantiate(items[0], " +
223-
`{ ${WebAssemblyUtils.MANGLED_MODULE}: items[1] });`
259+
`return WebAssembly.instantiate(items[0], ${createImportObject(
260+
"items[1]"
261+
)});`
224262
]),
225263
"});"
226264
]),
227265
"} else if(typeof WebAssembly.instantiateStreaming === 'function') {",
228266
Template.indent([
229-
"promise = WebAssembly.instantiateStreaming(req, " +
230-
`{ ${WebAssemblyUtils.MANGLED_MODULE}: importObject });`
267+
`promise = WebAssembly.instantiateStreaming(req, ${createImportObject(
268+
"importObject"
269+
)});`
231270
])
232271
])
233272
: Template.asString([
@@ -241,8 +280,9 @@ class WasmMainTemplatePlugin {
241280
]),
242281
"]).then(function(items) {",
243282
Template.indent([
244-
"return WebAssembly.instantiate(items[0], " +
245-
`{ ${WebAssemblyUtils.MANGLED_MODULE}: items[1] });`
283+
`return WebAssembly.instantiate(items[0], ${createImportObject(
284+
"items[1]"
285+
)});`
246286
]),
247287
"});"
248288
])
@@ -252,8 +292,9 @@ class WasmMainTemplatePlugin {
252292
"var bytesPromise = req.then(function(x) { return x.arrayBuffer(); });",
253293
"promise = bytesPromise.then(function(bytes) {",
254294
Template.indent([
255-
"return WebAssembly.instantiate(bytes, " +
256-
`{ ${WebAssemblyUtils.MANGLED_MODULE}: importObject });`
295+
`return WebAssembly.instantiate(bytes, ${createImportObject(
296+
"importObject"
297+
)});`
257298
]),
258299
"});"
259300
]),
@@ -290,6 +331,7 @@ class WasmMainTemplatePlugin {
290331
hash.update("WasmMainTemplatePlugin");
291332
hash.update("1");
292333
hash.update(`${mainTemplate.outputOptions.webassemblyModuleFilename}`);
334+
hash.update(`${this.mangleImports}`);
293335
});
294336
mainTemplate.hooks.hashForChunk.tap(
295337
"WasmMainTemplatePlugin",

lib/wasm/WebAssemblyGenerator.js

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -294,7 +294,7 @@ const rewriteImports = ({ ast, usedDependencyMap }) => bin => {
294294
);
295295

296296
if (typeof result !== "undefined") {
297-
path.node.module = WebAssemblyUtils.MANGLED_MODULE;
297+
path.node.module = result.module;
298298
path.node.name = result.name;
299299
}
300300
}
@@ -374,12 +374,13 @@ const addInitFunction = ({
374374
/**
375375
* Extract mangle mappings from module
376376
* @param {Module} module current module
377+
* @param {boolean} mangle mangle imports
377378
* @returns {Map<string, UsedWasmDependency>} mappings to mangled names
378379
*/
379-
const getUsedDependencyMap = module => {
380+
const getUsedDependencyMap = (module, mangle) => {
380381
/** @type {Map<string, UsedWasmDependency>} */
381382
const map = new Map();
382-
for (const usedDep of WebAssemblyUtils.getUsedDependencies(module)) {
383+
for (const usedDep of WebAssemblyUtils.getUsedDependencies(module, mangle)) {
383384
const dep = usedDep.dependency;
384385
const request = dep.request;
385386
const exportName = dep.name;
@@ -389,6 +390,11 @@ const getUsedDependencyMap = module => {
389390
};
390391

391392
class WebAssemblyGenerator extends Generator {
393+
constructor(options) {
394+
super();
395+
this.options = options;
396+
}
397+
392398
generate(module) {
393399
let bin = module.originalSource().source();
394400
bin = preprocess(bin);
@@ -411,7 +417,10 @@ class WebAssemblyGenerator extends Generator {
411417
const nextFuncIndex = getNextFuncIndex(ast, countImportedFunc);
412418
const nextTypeIndex = getNextTypeIndex(ast);
413419

414-
const usedDependencyMap = getUsedDependencyMap(module);
420+
const usedDependencyMap = getUsedDependencyMap(
421+
module,
422+
this.options.mangleImports
423+
);
415424
const externalExports = new Set(
416425
module.dependencies
417426
.filter(d => d instanceof WebAssemblyExportImportedDependency)

lib/wasm/WebAssemblyModulesPlugin.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,10 @@ const WebAssemblyImportDependency = require("../dependencies/WebAssemblyImportDe
1212
const WebAssemblyExportImportedDependency = require("../dependencies/WebAssemblyExportImportedDependency");
1313

1414
class WebAssemblyModulesPlugin {
15+
constructor(options) {
16+
this.options = options;
17+
}
18+
1519
apply(compiler) {
1620
compiler.hooks.compilation.tap(
1721
"WebAssemblyModulesPlugin",
@@ -37,7 +41,7 @@ class WebAssemblyModulesPlugin {
3741
.tap("WebAssemblyModulesPlugin", () => {
3842
return Generator.byType({
3943
javascript: new WebAssemblyJavascriptGenerator(),
40-
webassembly: new WebAssemblyGenerator()
44+
webassembly: new WebAssemblyGenerator(this.options)
4145
});
4246
});
4347

0 commit comments

Comments
 (0)