-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
Copy pathruntime_functions.js
220 lines (195 loc) · 5.73 KB
/
runtime_functions.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
/**
* @license
* Copyright 2020 The Emscripten Authors
* SPDX-License-Identifier: MIT
*/
// This gives correct answers for everything less than 2^{14} = 16384
// I hope nobody is contemplating functions with 16384 arguments...
function uleb128Encode(n) {
#if ASSERTIONS
assert(n < 16384);
#endif
if (n < 128) {
return [n];
}
return [(n % 128) | 128, n >> 7];
}
// Converts a signature like 'vii' into a description of the wasm types, like
// { parameters: ['i32', 'i32'], results: [] }.
function sigToWasmTypes(sig) {
var typeNames = {
'i': 'i32',
'j': 'i64',
'f': 'f32',
'd': 'f64',
#if MEMORY64
'p': 'i64',
#else
'p': 'i32',
#endif
};
var type = {
parameters: [],
results: sig[0] == 'v' ? [] : [typeNames[sig[0]]]
};
for (var i = 1; i < sig.length; ++i) {
#if ASSERTIONS
assert(sig[i] in typeNames, 'invalid signature char: ' + sig[i]);
#endif
type.parameters.push(typeNames[sig[i]]);
}
return type;
}
// Wraps a JS function as a wasm function with a given signature.
function convertJsFunctionToWasm(func, sig) {
#if WASM2JS
return func;
#else // WASM2JS
// If the type reflection proposal is available, use the new
// "WebAssembly.Function" constructor.
// Otherwise, construct a minimal wasm module importing the JS function and
// re-exporting it.
if (typeof WebAssembly.Function == "function") {
return new WebAssembly.Function(sigToWasmTypes(sig), func);
}
// The module is static, with the exception of the type section, which is
// generated based on the signature passed in.
var typeSection = [
0x01, // count: 1
0x60, // form: func
];
var sigRet = sig.slice(0, 1);
var sigParam = sig.slice(1);
var typeCodes = {
'i': 0x7f, // i32
#if MEMORY64
'p': 0x7e, // i64
#else
'p': 0x7f, // i32
#endif
'j': 0x7e, // i64
'f': 0x7d, // f32
'd': 0x7c, // f64
};
// Parameters, length + signatures
typeSection = typeSection.concat(uleb128Encode(sigParam.length));
for (var i = 0; i < sigParam.length; ++i) {
#if ASSERTIONS
assert(sigParam[i] in typeCodes, 'invalid signature char: ' + sigParam[i]);
#endif
typeSection.push(typeCodes[sigParam[i]]);
}
// Return values, length + signatures
// With no multi-return in MVP, either 0 (void) or 1 (anything else)
if (sigRet == 'v') {
typeSection.push(0x00);
} else {
typeSection = typeSection.concat([0x01, typeCodes[sigRet]]);
}
// Write the section code and overall length of the type section into the
// section header
typeSection = [0x01 /* Type section code */].concat(
uleb128Encode(typeSection.length),
typeSection
);
// Rest of the module is static
var bytes = new Uint8Array([
0x00, 0x61, 0x73, 0x6d, // magic ("\0asm")
0x01, 0x00, 0x00, 0x00, // version: 1
].concat(typeSection, [
0x02, 0x07, // import section
// (import "e" "f" (func 0 (type 0)))
0x01, 0x01, 0x65, 0x01, 0x66, 0x00, 0x00,
0x07, 0x05, // export section
// (export "f" (func 0 (type 0)))
0x01, 0x01, 0x66, 0x00, 0x00,
]));
// We can compile this wasm module synchronously because it is very small.
// This accepts an import (at "e.f"), that it reroutes to an export (at "f")
var module = new WebAssembly.Module(bytes);
var instance = new WebAssembly.Instance(module, {
'e': {
'f': func
}
});
var wrappedFunc = instance.exports['f'];
return wrappedFunc;
#endif // WASM2JS
}
var freeTableIndexes = [];
// Weak map of functions in the table to their indexes, created on first use.
var functionsInTableMap;
function getEmptyTableSlot() {
// Reuse a free index if there is one, otherwise grow.
if (freeTableIndexes.length) {
return freeTableIndexes.pop();
}
// Grow the table
try {
wasmTable.grow(1);
} catch (err) {
if (!(err instanceof RangeError)) {
throw err;
}
throw 'Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.';
}
return wasmTable.length - 1;
}
function updateTableMap(offset, count) {
for (var i = offset; i < offset + count; i++) {
var item = getWasmTableEntry(i);
// Ignore null values.
if (item) {
functionsInTableMap.set(item, i);
}
}
}
/**
* Add a function to the table.
* 'sig' parameter is required if the function being added is a JS function.
* @param {string=} sig
*/
function addFunction(func, sig) {
#if ASSERTIONS
assert(typeof func != 'undefined');
#endif // ASSERTIONS
// Check if the function is already in the table, to ensure each function
// gets a unique index. First, create the map if this is the first use.
if (!functionsInTableMap) {
functionsInTableMap = new WeakMap();
updateTableMap(0, wasmTable.length);
}
if (functionsInTableMap.has(func)) {
return functionsInTableMap.get(func);
}
// It's not in the table, add it now.
#if ASSERTIONS >= 2
// Make sure functionsInTableMap is actually up to date, that is, that this
// function is not actually in the wasm Table despite not being tracked in
// functionsInTableMap.
for (var i = 0; i < wasmTable.length; i++) {
assert(getWasmTableEntry(i) != func, 'function in Table but not functionsInTableMap');
}
#endif
var ret = getEmptyTableSlot();
// Set the new value.
try {
// Attempting to call this with JS function will cause of table.set() to fail
setWasmTableEntry(ret, func);
} catch (err) {
if (!(err instanceof TypeError)) {
throw err;
}
#if ASSERTIONS
assert(typeof sig != 'undefined', 'Missing signature argument to addFunction: ' + func);
#endif
var wrapped = convertJsFunctionToWasm(func, sig);
setWasmTableEntry(ret, wrapped);
}
functionsInTableMap.set(func, ret);
return ret;
}
function removeFunction(index) {
functionsInTableMap.delete(getWasmTableEntry(index));
freeTableIndexes.push(index);
}