Skip to content

Commit 6d906d0

Browse files
committed
fix: improved wasm transformations
1 parent eeb2fd0 commit 6d906d0

5 files changed

Lines changed: 223 additions & 153 deletions

File tree

‎lib/WebAssemblyGenerator.js‎

Lines changed: 135 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,11 @@ const { RawSource } = require("webpack-sources");
88

99
const { edit, add } = require("@webassemblyjs/wasm-edit");
1010
const { decode } = require("@webassemblyjs/wasm-parser");
11-
// const { print } = require("@webassemblyjs/wast-printer");
1211
const t = require("@webassemblyjs/ast");
1312

1413
// FIXME(sven): remove this once we're ready to merge
1514
function debug(...msg) {
16-
if (false) console.log(...msg);
15+
// console.log(...msg);
1716
}
1817

1918
function compose(...fns) {
@@ -22,124 +21,194 @@ function compose(...fns) {
2221
}, value => value);
2322
}
2423

25-
/**
26-
* Utility functions
27-
*/
24+
// Utility functions
2825
const isGlobalImport = moduleImport => moduleImport.descr.type === "GlobalType";
26+
const initFuncId = t.identifier("__init__");
2927

3028
/**
31-
* Export the start function and removes the start instruction
29+
* Removes the start instruction
30+
*
31+
* @param {ArrayBuffer} state - unused state
32+
* @returns {ArrayBuffer} bin'
3233
*/
33-
function rewriteStartFunc(bin) {
34-
debug("rewriteStartFunc");
34+
const removeStartFunc = state => bin => {
35+
debug("removeStartFunc");
36+
37+
return edit(bin, {
38+
Start(path) {
39+
path.remove();
40+
}
41+
});
42+
};
3543

44+
function getStartFuncIndex(ast) {
3645
let startAtFuncIndex;
3746

38-
bin = edit(bin, {
47+
t.traverse(ast, {
3948
Start(path) {
4049
startAtFuncIndex = path.node.index;
41-
42-
path.remove();
4350
}
4451
});
4552

46-
// No start func, abort here
47-
if (startAtFuncIndex === undefined) {
48-
return bin;
49-
}
53+
return startAtFuncIndex;
54+
}
5055

51-
debug("found start at func index", startAtFuncIndex.value);
56+
function getImportedGlobals(ast) {
57+
const importedGlobals = [];
5258

53-
bin = add(bin, [t.moduleExport("start", "Func", startAtFuncIndex)]);
59+
t.traverse(ast, {
60+
ModuleImport({ node }) {
61+
if (isGlobalImport(node) === true) {
62+
importedGlobals.push(node);
63+
}
64+
}
65+
});
5466

55-
return bin;
67+
return importedGlobals;
5668
}
5769

5870
/**
59-
* Remove the ModuleImport for globals but keep the global declaration
71+
* Rewrite the import globals:
72+
* - removes the ModuleImport instruction
73+
* - injects at the same offset a mutable global of the same time
74+
*
75+
* Since the imported globals are before the other global declarations, our
76+
* indices will be preserved.
6077
*
61-
* @param {ArrayBuffer} bin
78+
* Note that globals will become mutable.
79+
*
80+
* FIXME(sven): issue in webassemblyjs/wasm-edit, when we update a path
81+
* we need to make sure that the change is visible to everyone. Currently
82+
* removing an import doesn't update the location of the following imports (which
83+
* have been shifted). The work arround is to reparse the binary each time.
84+
*
85+
* @param {ArrayBuffer} bin - the input wasm binary
6286
* @returns {ArrayBuffer} bin'
6387
*/
64-
function removeImportedGlobals(bin) {
65-
const newGlobals = [];
88+
const rewriteImportedGlobals = ({ importedGlobals }) => bin => {
89+
debug("rewriteImportedGlobals");
90+
91+
const globalImportCount = importedGlobals.length;
6692

67-
bin = edit(bin, {
68-
ModuleImport(path) {
69-
if (isGlobalImport(path.node) === true) {
70-
debug("remove import", path.node.module, path.node.name);
93+
// Work arround the bug discribed above
94+
for (let i = 0, nbr = globalImportCount; i < nbr; i++) {
95+
let removedThisOne = false;
96+
let newGlobal;
7197

72-
const globalType = path.node.descr;
98+
bin = edit(bin, {
99+
ModuleImport(path) {
100+
if (removedThisOne === true) {
101+
return;
102+
}
73103

74-
globalType.mutability = "var";
104+
if (isGlobalImport(path.node) === true) {
105+
const globalType = path.node.descr;
75106

76-
newGlobals.push(
77-
t.global(globalType, [
107+
globalType.mutability = "var";
108+
109+
newGlobal = t.global(globalType, [
78110
t.objectInstruction("const", "i32", [t.numberLiteral(0)])
79-
])
80-
);
111+
]);
112+
113+
debug("remove import", path.node.module, path.node.name);
114+
path.remove();
81115

82-
path.remove();
116+
removedThisOne = true;
117+
}
83118
}
84-
}
85-
});
119+
});
86120

87-
return add(bin, newGlobals);
88-
}
121+
bin = add(bin, [newGlobal]);
122+
}
123+
124+
return bin;
125+
};
89126

90127
/**
91-
* Add our init function.
128+
* Add an init function.
129+
*
130+
* The init function fills the globals given input arguments.
92131
*
93-
* @param {ArrayBuffer} bin
132+
* @param {ArrayBuffer} bin - the input wasm binary
94133
* @returns {ArrayBuffer} bin'
95134
*/
96-
function addInitFunction(bin) {
97-
// get next func index
98-
const ast = decode(bin, {
99-
ignoreDataSection: true
135+
const addInitFunction = ({
136+
startAtFuncIndex,
137+
importedGlobals,
138+
funcSectionMetadata
139+
}) => bin => {
140+
debug("addInitFunction");
141+
142+
const nextTypeIndex = funcSectionMetadata.vectorOfSize;
143+
144+
const funcParams = importedGlobals.map(importedGlobal => {
145+
// used for debugging
146+
const id = t.identifier(`${importedGlobal.module}.${importedGlobal.name}`);
147+
148+
return t.funcParam(importedGlobal.descr.valtype, id);
100149
});
101150

102-
const section = t.getSectionMetadata(ast, "func");
103-
const nextTypeIndex = section.vectorOfSize;
104-
105-
const func = t.func(
106-
null,
107-
[t.funcParam("i32")],
108-
[],
109-
[
110-
t.instruction("get_local", [t.indexLiteral(0)]),
111-
t.instruction("set_global", [t.indexLiteral(0)])
112-
]
113-
);
151+
const funcBody = importedGlobals.reduce((acc, importedGlobal, index) => {
152+
const args = [t.indexLiteral(index)];
153+
const body = [
154+
t.instruction("get_local", args),
155+
t.instruction("set_global", args)
156+
];
157+
158+
return [...acc, ...body];
159+
}, []);
160+
161+
if (typeof startAtFuncIndex !== "undefined") {
162+
debug("call start func", startAtFuncIndex.value);
163+
164+
funcBody.push(t.callInstruction(startAtFuncIndex));
165+
}
166+
167+
const funcResults = [];
168+
169+
const func = t.func(initFuncId, funcParams, funcResults, funcBody);
114170

115171
const functype = t.typeInstructionFunc(func.params, func.result);
116172
const funcindex = t.indexInFuncSection(t.indexLiteral(nextTypeIndex));
117173

118174
const moduleExport = t.moduleExport(
119-
"__init__",
175+
initFuncId.value,
120176
"Func",
121-
t.indexLiteral(nextTypeIndex + 1)
177+
t.indexLiteral(nextTypeIndex)
122178
);
123179

124180
return add(bin, [func, moduleExport, funcindex, functype]);
125-
}
126-
127-
const transform = compose(
128-
removeImportedGlobals,
129-
addInitFunction
130-
131-
// rewriteStartFunc
132-
);
181+
};
133182

134183
class WebAssemblyGenerator {
135184
generate(module) {
136185
const bin = module.originalSource().source();
137186

187+
const ast = decode(bin, {
188+
ignoreDataSection: true
189+
});
190+
191+
const importedGlobals = getImportedGlobals(ast);
192+
const funcSectionMetadata = t.getSectionMetadata(ast, "func");
193+
const startAtFuncIndex = getStartFuncIndex(ast);
194+
195+
const transform = compose(
196+
removeStartFunc(),
197+
198+
rewriteImportedGlobals({ importedGlobals }),
199+
200+
addInitFunction({
201+
importedGlobals,
202+
funcSectionMetadata,
203+
startAtFuncIndex
204+
})
205+
);
206+
138207
debug("__________________________________________________________");
139208
const newBin = transform(bin);
140209
debug("__________________________________________________________");
141210

142-
// console.log(print(decode(newBin)));
211+
// console.log(require("@webassemblyjs/wast-printer").print(decode(newBin)));
143212

144213
return new RawSource(newBin);
145214
}

‎lib/wasm/WasmModuleTemplatePlugin.js‎

Lines changed: 23 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,27 @@
77
const RawSource = require("webpack-sources").RawSource;
88
const WebAssemblyImportDependency = require("../dependencies/WebAssemblyImportDependency");
99

10+
function generateInitParams(module) {
11+
const list = [];
12+
13+
for (const dep of module.dependencies) {
14+
if (dep instanceof WebAssemblyImportDependency) {
15+
if (dep.description.type === "GlobalType") {
16+
const exportName = dep.name;
17+
const usedName = dep.module && dep.module.isUsed(exportName);
18+
19+
list.push(
20+
`__webpack_require__(${JSON.stringify(
21+
dep.module.id
22+
)})[${JSON.stringify(usedName)}]`
23+
);
24+
}
25+
}
26+
}
27+
28+
return list;
29+
}
30+
1031
class WasmModuleTemplatePlugin {
1132
apply(moduleTemplate) {
1233
moduleTemplate.hooks.content.tap(
@@ -40,27 +61,9 @@ class WasmModuleTemplatePlugin {
4061
return `${module.moduleArgument}.exports = instance.exports;`;
4162
}
4263
};
43-
function generateInitParams(module) {
44-
const list = [];
45-
46-
for (const dep of module.dependencies) {
47-
if (dep instanceof WebAssemblyImportDependency) {
48-
if (dep.description.type === "GlobalType") {
49-
const exportName = dep.name;
50-
const usedName = dep.module && dep.module.isUsed(exportName);
51-
52-
list.push(
53-
`__webpack_require__(${JSON.stringify(
54-
dep.module.id
55-
)})[${JSON.stringify(usedName)}]`
56-
);
57-
}
58-
}
59-
}
60-
61-
return list;
62-
}
6364

65+
// FIXME(sven): assert that the exports exists in the modules
66+
// otherwise it will default to i32 0
6467
const initParams = generateInitParams(module).join(",");
6568
const source = new RawSource(
6669
[

‎lib/web/FetchCompileWasmMainTemplatePlugin.js‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,7 @@ class FetchCompileWasmMainTemplatePlugin {
2828
const webassemblyModuleFilename =
2929
mainTemplate.outputOptions.webassemblyModuleFilename;
3030

31-
/**
32-
* Get all wasm modules
33-
*/
31+
// Get all wasm modules
3432
function getAllWasmModules() {
3533
const wasmModules = chunk.getAllAsyncChunks();
3634
const array = [];
@@ -104,7 +102,7 @@ class FetchCompileWasmMainTemplatePlugin {
104102
}
105103

106104
return (
107-
JSON.stringify(module.id) + ": {" + importsCode.join(",") + "\n}"
105+
JSON.stringify(module.id) + ": {" + importsCode.join(",") + "\n},"
108106
);
109107
}
110108

‎package.json‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@
55
"description": "Packs CommonJs/AMD modules for the browser. Allows to split your codebase into multiple bundles, which can be loaded on demand. Support loaders to preprocess files, i.e. json, jsx, es7, css, less, ... and your custom stuff.",
66
"license": "MIT",
77
"dependencies": {
8-
"@webassemblyjs/ast": "1.1.2-y.7",
9-
"@webassemblyjs/wasm-edit": "1.1.2-y.7",
10-
"@webassemblyjs/wasm-parser": "1.1.2-y.7",
8+
"@webassemblyjs/ast": "1.1.2-y.8",
9+
"@webassemblyjs/wasm-edit": "1.1.2-y.8",
10+
"@webassemblyjs/wasm-parser": "1.1.2-y.8",
1111
"@webassemblyjs/wast-printer": "^1.1.2-y.0",
1212
"acorn": "^5.0.0",
1313
"acorn-dynamic-import": "^3.0.0",

0 commit comments

Comments
 (0)