-
Notifications
You must be signed in to change notification settings - Fork 0
/
wasm-compiler.js
359 lines (303 loc) · 13 KB
/
wasm-compiler.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
let { getWasmMemoryExports, getWasmFunctionExports, getWasmImports, getTypedArrayCtorFromMemoryObj } = require("./wasm-to-sourcemap");
let g = Function('return this')();
module.exports.CompileWasmFunctions = "GetSyncFunctions";
function isEmpty(obj) {
for(var key in obj) return false;
return true;
}
function leb128Parse(index, buffer) {
let bytes = [];
while (index < buffer.length) {
let byte = buffer[index++];
bytes.push(byte);
if (!(byte & 0x80)) {
break;
}
}
let value = Number.parseInt(bytes.reverse().map(x => x.toString(2).padStart(8, "0").slice(1)).join(""), 2);
return {
value,
bytes,
};
}
function getSections(file) {
let sections = [];
// Insert a section for the magic number and version identifier
sections.push({
sectionId: -1,
offset: 0,
contents: file.slice(0, 8)
});
let i = 8;
while (i < file.length) {
let sectionId = file[i];
i++;
let { value, bytes } = leb128Parse(i, file);
let num = value;
i += bytes.length;
let baseOffsetStart = i;
let contents = file.slice(i, i + num);
sections.push({
sectionId,
offset: baseOffsetStart,
contents
});
i += num;
}
return sections;
}
/** Maps function index (in wasm file) to function name.
* @return {{ [fncIndex: number]: string }} */
function getExportNames(sections) {
sections = sections.filter(x => x.sectionId === 7);
let exportedFunctions = Object.create(null);
for(let exportSection of sections) {
let curIndex = 0;
let curBuffer = exportSection.contents;
function parseLeb128(signed = false) {
let obj = leb128Parse(curIndex, curBuffer);
curIndex += obj.bytes.length;
if(signed) {
let negativePoint = 1 << (7 * obj.bytes.length - 1);
if(obj.value >= negativePoint) {
obj.value = obj.value - 2 * negativePoint;
}
}
return obj.value;
}
let functionCount = parseLeb128();
while (curIndex < curBuffer.length) {
let nameLength = parseLeb128();
let nameBytes = curBuffer.slice(curIndex, curIndex + nameLength);
curIndex += nameLength;
let name = Array.from(nameBytes).map(x => String.fromCharCode(x)).join("");
let exportType = parseLeb128();
let exportValue = parseLeb128();
if (exportType === 0) {
exportedFunctions[exportValue] = name;
}
}
}
return exportedFunctions;
}
g.wasmCompilerCompileCache = g.wasmCompilerCompileCache || Object.create(null);
module.exports.compile = function compile(webAssembly, compilationCacheKey, functionsForImports = Object.create(null)) {
if (compilationCacheKey) {
if (compilationCacheKey in g.wasmCompilerCompileCache) {
return g.wasmCompilerCompileCache[compilationCacheKey];
}
}
let initializeWarningTimeout = 10 * 1000;
const MemoryBufferAddress = Symbol("MemoryBufferAddress");
const WasmFncObj = Symbol("WasmFncObj");
// An object where we put all the exports, once they are loaded
let exportsObj = Object.create(null);
// Some basic error handling, so at least string throws (such as throw "x too big"; ) can work.
function getLastError() {
if("SHIM__lastErrorString" in exportsObj) {
if (exportsObj.SHIM__lastErrorString[0]) {
let length = exportsObj.SHIM__lastErrorString[0];
return new TextDecoder().decode(exportsObj.SHIM__lastErrorString.slice(1, length + 1));
}
}
return `A call from wasm to the javascript wrapping function "SHIM__lastErrorString" was made, but the wasm file has no SHIM__lastErrorString export (an array containing the error), so this is invalid.`;
}
function SHIM__throwCurrentError() {
let error = new Error(getLastError());
// Remove our junk from the stack
if (error.stack) {
let stack = error.stack.split("\n");
stack.splice(1, 3);
error.stack = stack.join("\n");
}
if (!g["TEST_THROWS"]) {
console.error(error);
debugger;
}
throw error;
}
/*
let arrayObj = new Float64Array(baseExports.memory.buffer, offset, count);
*/
let importList = getWasmImports(webAssembly);
let dynamicFunctionsForImport;
let dynamicFunctionsForImportResolve;
let dynamicFunctionsResolved = false;
if(importList.length === 0) {
dynamicFunctionsForImport = Promise.resolve(Object.create(null));
dynamicFunctionsForImportResolve = function () {};
dynamicFunctionsResolved = true;
} else {
dynamicFunctionsForImport = new Promise(resolve => {
dynamicFunctionsForImportResolve = function(functions) {
if(dynamicFunctionsResolved) {
return;
}
dynamicFunctionsResolved = true;
resolve(functions);
}
});
}
let memoryBufferLookup = Object.create(null);
let memoryExports = getWasmMemoryExports(webAssembly);
for(let exportName in memoryExports) {
let memoryObj = memoryExports[exportName];
let { size, address } = memoryObj;
// Warning is given after compilation finishes
if(size < 0) continue;
exportsObj[exportName] = new Uint8Array(size);
let TypedArrayCtor = getTypedArrayCtorFromMemoryObj(memoryObj);
if(TypedArrayCtor) {
exportsObj[exportName] = new TypedArrayCtor(exportsObj[exportName].buffer, exportsObj[exportName].byteOffset, Math.round(size / memoryObj.byteWidth));
}
exportsObj[exportName][MemoryBufferAddress] = address;
memoryBufferLookup[address] = exportsObj[exportName];
}
let functionExports = getWasmFunctionExports(webAssembly);
for(let fncExport of functionExports) {
if(fncExport.warning) continue;
exportsObj[fncExport.demangledName] = async function() {
if(!dynamicFunctionsResolved) {
setTimeout(() => {
if(!dynamicFunctionsResolved) {
console.warn(`Failed to call GetSyncFunctions within a timeout of calling function ${fncExport.name}. The function call won't resolve until GetSyncFunctions is called.`);
}
}, initializeWarningTimeout);
}
let loadedExports = await exportsPromise;
return loadedExports[fncExport](...arguments);
};
exportsObj[fncExport.demangledName][WasmFncObj] = fncExport;
}
let elemIdLookup = Object.create(null);
for(let fncExport of functionExports) {
if(fncExport.warning) continue;
if("elemId" in fncExport) {
elemIdLookup[fncExport.elemId] = fncExport;
}
}
let moduleObjPromise = dynamicFunctionsForImport.then(dynamicFunctions => {
return WebAssembly.instantiate(webAssembly, {
env: {
SHIM__throwCurrentError,
... functionsForImports,
... dynamicFunctions
},
});
});
let exportsLoaded = false;
// Once the module loads, update exportsObj to have the actual correct functions, and typed arrays.
let exportsPromise = moduleObjPromise.then((moduleObj) => {
let baseExports = moduleObj.instance.exports;
//exportsObj["memory"] = Buffer.from(baseExports.memory.buffer);
for(let exportName in memoryExports) {
let memoryObj = memoryExports[exportName];
let { size, address } = memoryObj;
if(size < 0) {
console.warn(`Invalid size, ${size}, for ${exportName}, ignoring export.`);
continue;
}
let buffer = new Uint8Array(baseExports.memory.buffer, address, size);
let source = exportsObj[exportName];
buffer.set(new Uint8Array(source.buffer, source.byteOffset));
exportsObj[exportName] = buffer;
let TypedArrayCtor = getTypedArrayCtorFromMemoryObj(memoryObj);
if(TypedArrayCtor) {
exportsObj[exportName] = new TypedArrayCtor(exportsObj[exportName].buffer, exportsObj[exportName].byteOffset, Math.round(size / memoryObj.byteWidth));
}
exportsObj[exportName][MemoryBufferAddress] = address;
memoryBufferLookup[address] = exportsObj[exportName];
}
if(isEmpty(functionExports)) {
for(let name in baseExports) {
let fnc = baseExports[name];
if(typeof fnc === "function") {
exportsObj[name] = fnc;
}
}
} else {
for(let fncExport of functionExports) {
if(fncExport.warning) continue;
// TODO: If fncExport.javascriptTypeNames has any types which are pointers? Then wrap it, so that we check all of the arguments
// and convert any Buffers that our from this module to pass the correct memory offsets.
let fnc = baseExports[fncExport.name];
exportsObj[fncExport.demangledName] = fnc;
let needsShim = fncExport.javascriptTypeNames.some(x => x.type.pointer || x.type.subFunction) || fncExport.returnType.pointer || fncExport.returnType.subFunction;
if(needsShim) {
exportsObj[fncExport.demangledName] = function() {
let args = Array.from(arguments);
args = args.map(arg => {
if(arg && typeof arg === "object") {
if(MemoryBufferAddress in arg) {
return arg[MemoryBufferAddress];
}
}
if(typeof arg === "function") {
if(WasmFncObj in arg) {
let fncObj = arg[WasmFncObj];
if("elemId" in fncObj) {
return fncObj.elemId;
}
}
console.warn(`Passed unknown javascript function to wasm function. You may only pass functions from a wasm module back to the same module.`, arg);
}
return arg;
});
let result = fnc(...args);
if(fncExport.returnType.pointer) {
if(result in memoryBufferLookup) {
return memoryBufferLookup[result];
} else {
console.warn(`Returned address from pointer function which does not correspond to an exported memory address. Just returneding the address by itself`, fncExport);
}
}
if(fncExport.returnType.subFunction) {
let elemId = result;
if(elemId in elemIdLookup) {
return exportsObj[elemIdLookup[elemId].demangledName];
} else {
console.warn(`Returned element id (from a function that returns a function) that doesn't correspond to any element ids we know.`, fncExport, elemId, elemIdLookup);
}
}
return result;
};
}
exportsObj[fncExport.demangledName][WasmFncObj] = fncExport;
}
}
exportsLoaded = true;
return exportsObj;
}, e => {
console.error(e);
});
exportsObj.GetSyncFunctions = function GetSyncFunctions(functions) {
if(exportsLoaded) {
return exportsObj;
}
dynamicFunctionsForImportResolve(functions);
return exportsPromise;
};
exportsObj.CompileNewWasm = function (functions) {
return compile(webAssembly).GetSyncFunctions(functions);
};
exportsObj.UtilGetBufferFromAddress = function(address) {
return memoryBufferLookup[address];
};
exportsObj.UtilGetAddressFromBuffer = function(buffer) {
return buffer[MemoryBufferAddress];
};
exportsObj.UtilGetFncFromArg = function(arg) {
return elemIdLookup[arg];
};
exportsObj.UtilGetArgFromFnc = function(wasmFnc) {
let fncObj = wasmFnc[WasmFncObj];
if(!fncObj) return undefined;
return exportsObj[fncObj.name];
};
if (compilationCacheKey) {
if (!(compilationCacheKey in g.wasmCompilerCompileCache)) {
g.wasmCompilerCompileCache[compilationCacheKey] = exportsObj;
}
}
return exportsObj;
}