Files: e5f317ee074967d082a366e35035d77ef081fa84 / wasmContainer.js
9331 bytesRaw
1 | const {wasm2json, json2wasm} = require('wasm-json-toolkit') |
2 | const wasmMetering = require('wasm-metering') |
3 | const ReferanceMap = require('reference-map') |
4 | const Message = require('./message.js') |
5 | const customTypes = require('./customTypes.js') |
6 | const injectGlobals = require('./injectGlobals.js') |
7 | const typeCheckWrapper = require('./typeCheckWrapper.js') |
8 | const {FunctionRef, ModuleRef, DEFAULTS} = require('./systemObjects.js') |
9 | |
10 | const FUNC_INDEX_OFFSET = 1 |
11 | |
12 | const nativeTypes = new Set(['i32', 'i64', 'f32', 'f64']) |
13 | const LANGUAGE_TYPES = { |
14 | 0x0: 'actor', |
15 | 0x1: 'buf', |
16 | 0x02: 'elem', |
17 | 0x03: 'link', |
18 | 0x04: 'id', |
19 | 0x7f: 'i32', |
20 | 0x7e: 'i64', |
21 | 0x7d: 'f32', |
22 | 0x7c: 'f64', |
23 | 0x70: 'anyFunc', |
24 | 0x60: 'func', |
25 | 0x40: 'block_type' |
26 | } |
27 | |
28 | function generateWrapper (funcRef, container) { |
29 | let wrapper = typeCheckWrapper(funcRef.params) |
30 | const wasm = json2wasm(wrapper) |
31 | const mod = WebAssembly.Module(wasm) |
32 | const self = funcRef |
33 | wrapper = WebAssembly.Instance(mod, { |
34 | 'env': { |
35 | 'checkTypes': function () { |
36 | const args = [...arguments] |
37 | const checkedArgs = [] |
38 | while (args.length) { |
39 | const type = LANGUAGE_TYPES[args.shift()] |
40 | let arg = args.shift() |
41 | if (!nativeTypes.has(type)) { |
42 | arg = container.refs.get(arg, type) |
43 | } |
44 | checkedArgs.push(arg) |
45 | } |
46 | const message = new Message({ |
47 | funcRef: self, |
48 | funcArguments: checkedArgs |
49 | }) |
50 | container.actor.send(message) |
51 | } |
52 | } |
53 | }) |
54 | wrapper.exports.check.object = funcRef |
55 | return wrapper |
56 | } |
57 | |
58 | module.exports = class WasmContainer { |
59 | constructor (actor) { |
60 | this.actor = actor |
61 | this.refs = new ReferanceMap() |
62 | } |
63 | |
64 | static async onCreation (wasm, id, tree) { |
65 | const cachedb = tree.dag._dag |
66 | if (!WebAssembly.validate(wasm)) { |
67 | throw new Error('invalid wasm binary') |
68 | } |
69 | let moduleJSON = wasm2json(wasm) |
70 | const json = customTypes.mergeTypeSections(moduleJSON) |
71 | moduleJSON = wasmMetering.meterJSON(moduleJSON, { |
72 | meterType: 'i32' |
73 | }) |
74 | |
75 | // initialize the globals |
76 | let numOfGlobals = json.globals.length |
77 | if (numOfGlobals) { |
78 | moduleJSON = injectGlobals(moduleJSON, json.globals) |
79 | } |
80 | // recompile the wasm |
81 | wasm = json2wasm(moduleJSON) |
82 | await Promise.all([ |
83 | new Promise((resolve, reject) => { |
84 | cachedb.put(id.id.toString() + 'meta', JSON.stringify(json), resolve) |
85 | }), |
86 | new Promise((resolve, reject) => { |
87 | cachedb.put(id.id.toString() + 'code', wasm.toString('hex'), resolve) |
88 | }) |
89 | ]) |
90 | return ModuleRef.fromMetaJSON(json, id) |
91 | } |
92 | |
93 | getInterface (funcRef) { |
94 | const self = this |
95 | return { |
96 | func: { |
97 | externalize: index => { |
98 | const func = this.instance.exports.table.get(index) |
99 | const object = func.object |
100 | if (object) { |
101 | // externalize a pervously internalized function |
102 | return self.refs.add(object) |
103 | } else { |
104 | const params = self.json.types[self.json.indexes[func.name - FUNC_INDEX_OFFSET]].params |
105 | const ref = new FunctionRef(true, func.tableIndex, params, self.actor.id) |
106 | return self.refs.add(ref, 'func') |
107 | } |
108 | }, |
109 | internalize: (ref, index) => { |
110 | const funcRef = self.refs.get(ref, 'func') |
111 | const wrapper = generateWrapper(funcRef, self) |
112 | this.instance.exports.table.set(index, wrapper.exports.check) |
113 | }, |
114 | catch: (ref, catchRef) => { |
115 | const {funcRef} = self.refs.get(ref, FunctionRef) |
116 | const {funcRef: catchFunc} = self.refs.get(ref, FunctionRef) |
117 | funcRef.catch = catchFunc |
118 | }, |
119 | getGasAmount: (funcRef) => {}, |
120 | setGasAmount: (funcRef) => {} |
121 | }, |
122 | link: { |
123 | wrap: ref => { |
124 | const obj = this.refs.get(ref) |
125 | const link = {'/': obj} |
126 | return this.refs.add(link, 'link') |
127 | }, |
128 | unwrap: async (ref, cb) => { |
129 | const obj = this.refs.get(ref, 'link') |
130 | const promise = this.actor.tree.dataStore.get(obj) |
131 | await this._opsQueue.push(promise) |
132 | // todo |
133 | } |
134 | }, |
135 | module: { |
136 | new: code => {}, |
137 | exports: (modRef, offset, length) => { |
138 | const mod = this.refs.get(modRef, 'mod') |
139 | let name = this.getMemory(offset, length) |
140 | name = Buffer.from(name).toString() |
141 | const funcRef = mod.getFuncRef(name) |
142 | return this.refs.add(funcRef, 'func') |
143 | }, |
144 | self: () => { |
145 | return this.refs.add(this.modSelf, 'mod') |
146 | } |
147 | }, |
148 | memory: { |
149 | externalize: (index, length) => { |
150 | const buf = Buffer.from(this.getMemory(index, length)) |
151 | return this.refs.add(buf, 'buf') |
152 | }, |
153 | internalize: (dataRef, srcOffset, sinkOffset, length) => { |
154 | let buf = this.refs.get(dataRef, 'buf') |
155 | buf = buf.subarray(srcOffset, length) |
156 | const mem = this.getMemory(sinkOffset, buf.length) |
157 | mem.set(buf) |
158 | }, |
159 | length (dataRef) { |
160 | let buf = this.refs.get(dataRef, 'buf') |
161 | return buf.length |
162 | } |
163 | }, |
164 | table: { |
165 | externalize: (index, length) => { |
166 | const mem = Buffer.from(this.getMemory(index, length * 4)) |
167 | const objects = [] |
168 | while (length--) { |
169 | const ref = mem.readUInt32LE(length * 4) |
170 | const obj = this.refs.get(ref) |
171 | objects.unshift(obj) |
172 | } |
173 | return this.refs.add(objects, 'elem') |
174 | }, |
175 | internalize: (elemRef, srcOffset, sinkOffset, length) => { |
176 | let table = this.refs.get(elemRef, 'elem') |
177 | const buf = table.slice(srcOffset, srcOffset + length).map(obj => this.refs.add(obj)) |
178 | const mem = new Uint32Array(this.instance.exports.memory.buffer, sinkOffset, length) |
179 | mem.set(buf) |
180 | } |
181 | }, |
182 | metering: { |
183 | usegas: amount => { |
184 | funcRef.gas -= amount |
185 | if (funcRef.gas < 0) { |
186 | throw new Error('out of gas! :(') |
187 | } |
188 | } |
189 | } |
190 | } |
191 | } |
192 | |
193 | async onMessage (message) { |
194 | const funcRef = message.funcRef |
195 | // console.log(funcRef) |
196 | const intef = this.getInterface(funcRef) |
197 | this.instance = WebAssembly.Instance(this.mod, intef) |
198 | // map table indexes |
199 | const table = this.instance.exports.table |
200 | if (table) { |
201 | let length = table.length |
202 | while (length--) { |
203 | const func = table.get(length) |
204 | if (func) { |
205 | func.tableIndex = length |
206 | } |
207 | } |
208 | } |
209 | // import references |
210 | const args = message.funcArguments.map((arg, index) => { |
211 | const type = funcRef.params[index] |
212 | if (nativeTypes.has(type)) { |
213 | return arg |
214 | } else { |
215 | return this.refs.add(arg, type) |
216 | } |
217 | }) |
218 | |
219 | // setup globals |
220 | let numOfGlobals = this.json.globals.length |
221 | if (numOfGlobals) { |
222 | const refs = [] |
223 | while (numOfGlobals--) { |
224 | const obj = this.actor.storage[numOfGlobals] || DEFAULTS[this.json.globals[numOfGlobals].type] |
225 | refs.push(this.refs.add(obj, this.json.globals[numOfGlobals].type)) |
226 | } |
227 | this.instance.exports.setter_globals(...refs) |
228 | } |
229 | |
230 | // call entrypoint function |
231 | if (funcRef.private) { |
232 | this.instance.exports.table.get(funcRef.identifier)(...args) |
233 | } else { |
234 | this.instance.exports[funcRef.identifier](...args) |
235 | } |
236 | await this.onDone() |
237 | |
238 | // store globals |
239 | numOfGlobals = this.json.globals.length |
240 | if (numOfGlobals) { |
241 | this.actor.storage = [] |
242 | this.instance.exports.getter_globals() |
243 | const mem = new Uint32Array(this.instance.exports.memory.buffer, 0, numOfGlobals) |
244 | while (numOfGlobals--) { |
245 | const ref = mem[numOfGlobals] |
246 | this.actor.storage.push(this.refs.get(ref, this.json.globals[numOfGlobals].type)) |
247 | } |
248 | } |
249 | |
250 | this.refs.clear() |
251 | } |
252 | |
253 | /** |
254 | * returns a promise that resolves when the wasm instance is done running |
255 | * @returns {Promise} |
256 | */ |
257 | async onDone () { |
258 | let prevOps |
259 | while (prevOps !== this._opsQueue) { |
260 | prevOps = this._opsQueue |
261 | await prevOps |
262 | } |
263 | } |
264 | |
265 | /** |
266 | * Pushed an async operation to the a promise queue that |
267 | * @returns {Promise} the returned promise resolves in the order the intail |
268 | * operation was pushed to the queue |
269 | */ |
270 | pushOpsQueue (promise) { |
271 | this._opsQueue = Promise.all([this._opsQueue, promise]) |
272 | return this._opsQueue |
273 | } |
274 | |
275 | async onStartup () { |
276 | let [json, wasm] = await Promise.all([ |
277 | new Promise((resolve, reject) => { |
278 | this.actor.cachedb.get(this.actor.id.id.toString() + 'meta', (err, json) => { |
279 | if (err) { |
280 | reject(err) |
281 | } else { |
282 | resolve(json) |
283 | } |
284 | }) |
285 | }), |
286 | new Promise((resolve, reject) => { |
287 | this.actor.cachedb.get(this.actor.id.id.toString() + 'code', (err, wasm) => { |
288 | if (err) { |
289 | reject(err) |
290 | } else { |
291 | resolve(wasm) |
292 | } |
293 | }) |
294 | }) |
295 | ]) |
296 | wasm = Buffer.from(wasm, 'hex') |
297 | json = JSON.parse(json) |
298 | this.mod = WebAssembly.Module(wasm) |
299 | this.json = json |
300 | this.modSelf = ModuleRef.fromMetaJSON(json, this.actor.id) |
301 | } |
302 | |
303 | getMemory (offset, length) { |
304 | return new Uint8Array(this.instance.exports.memory.buffer, offset, length) |
305 | } |
306 | |
307 | static get typeId () { |
308 | return 9 |
309 | } |
310 | } |
311 |
Built with git-ssb-web