2 * Copyright (C) 2016 Apple Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 import * as assert from 'assert.js';
27 import * as BuildWebAssembly from 'Builder_WebAssemblyBinary.js';
28 import * as WASM from 'WASM.js';
30 const _toJavaScriptName = name => {
31 const camelCase = name.replace(/([^a-z0-9].)/g, c => c[1].toUpperCase());
32 const CamelCase = camelCase.charAt(0).toUpperCase() + camelCase.slice(1);
36 const _isValidValue = (value, type) => {
38 case "i32": return ((value & 0xFFFFFFFF) >>> 0) === value;
39 case "i64": throw new Error(`Unimplemented: value check for ${type}`); // FIXME https://bugs.webkit.org/show_bug.cgi?id=163420 64-bit values
40 case "f32": return typeof(value) === "number" && isFinite(value);
41 case "f64": return typeof(value) === "number" && isFinite(value);
42 default: throw new Error(`Implementation problem: unknown type ${type}`);
45 const _unknownSectionId = 0;
47 const _normalizeFunctionSignature = (params, ret) => {
48 assert.isArray(params);
49 for (const p of params)
50 assert.truthy(WASM.isValidValueType(p), `Type parameter ${p} needs a valid value type`);
51 if (typeof(ret) === "undefined")
53 assert.isNotArray(ret, `Multiple return values not supported by WebAssembly yet`);
54 assert.truthy(WASM.isValidBlockType(ret), `Type return ${ret} must be valid block type`);
58 const _maybeRegisterType = (builder, type) => {
59 const typeSection = builder._getSection("Type");
60 if (typeof(type) === "number") {
61 // Type numbers already refer to the type section, no need to register them.
62 if (builder._checked) {
63 assert.isNotUndef(typeSection, `Can not use type ${type} if a type section is not present`);
64 assert.isNotUndef(typeSection.data[type], `Type ${type} does not exist in type section`);
68 assert.hasObjectProperty(type, "params", `Expected type to be a number or object with 'params' and optionally 'ret' fields`);
69 const [params, ret] = _normalizeFunctionSignature(type.params, type.ret);
70 assert.isNotUndef(typeSection, `Can not add type if a type section is not present`);
71 // Try reusing an equivalent type from the type section.
73 for (let i = 0; i !== typeSection.data.length; ++i) {
74 const t = typeSection.data[i];
75 if (t.ret === ret && params.length === t.params.length) {
76 for (let j = 0; j !== t.params.length; ++j) {
77 if (params[j] !== t.params[j])
84 if (typeof(type) !== "number") {
85 // Couldn't reuse a pre-existing type, register this type in the type section.
86 typeSection.data.push({ params: params, ret: ret });
87 type = typeSection.data.length - 1;
92 const _importFunctionContinuation = (builder, section, nextBuilder) => {
93 return (module, field, type) => {
94 assert.isString(module, `Import function module should be a string, got "${module}"`);
95 assert.isString(field, `Import function field should be a string, got "${field}"`);
96 const typeSection = builder._getSection("Type");
97 type = _maybeRegisterType(builder, type);
98 section.data.push({ field: field, type: type, kind: "Function", module: module });
99 // Imports also count in the function index space. Map them as objects to avoid clashing with Code functions' names.
100 builder._registerFunctionToIndexSpace({ module: module, field: field });
105 const _exportFunctionContinuation = (builder, section, nextBuilder) => {
106 return (field, index, type) => {
107 assert.isString(field, `Export function field should be a string, got "${field}"`);
108 const typeSection = builder._getSection("Type");
109 if (typeof(type) !== "undefined") {
110 // Exports can leave the type unspecified, letting the Code builder patch them up later.
111 type = _maybeRegisterType(builder, type);
113 // We can't check much about "index" here because the Code section succeeds the Export section. More work is done at Code().End() time.
114 switch (typeof(index)) {
115 case "string": break; // Assume it's a function name which will be revealed in the Code section.
116 case "number": break; // Assume it's a number in the "function index space".
118 // Re-exporting an import.
119 assert.hasObjectProperty(index, "module", `Re-exporting "${field}" from an import`);
120 assert.hasObjectProperty(index, "field", `Re-exporting "${field}" from an import`);
123 // Assume it's the same as the field (i.e. it's not being renamed).
126 default: throw new Error(`Export section's index must be a string or a number, got ${index}`);
128 const correspondingImport = builder._getFunctionFromIndexSpace(index);
129 const importSection = builder._getSection("Import");
130 if (typeof(index) === "object") {
131 // Re-exporting an import using its module+field name.
132 assert.isNotUndef(correspondingImport, `Re-exporting "${field}" couldn't find import from module "${index.module}" field "${index.field}"`);
133 index = correspondingImport;
134 if (typeof(type) === "undefined")
135 type = importSection.data[index].type;
136 if (builder._checked)
137 assert.eq(type, importSection.data[index].type, `Re-exporting import "${importSection.data[index].field}" as "${field}" has mismatching type`);
138 } else if (typeof(correspondingImport) !== "undefined") {
139 // Re-exporting an import using its index.
141 for (const i of importSection.data) {
142 if (i.module === correspondingImport.module && i.field === correspondingImport.field) {
147 if (typeof(type) === "undefined")
148 type = exportedImport.type;
149 if (builder._checked)
150 assert.eq(type, exportedImport.type, `Re-exporting import "${exportedImport.field}" as "${field}" has mismatching type`);
152 section.data.push({ field: field, type: type, kind: "Function", index: index });
157 const _checkStackArgs = (op, param) => {
158 for (let expect of param) {
159 if (WASM.isValidType(expect)) {
160 // FIXME implement stack checks for arguments. https://bugs.webkit.org/show_bug.cgi?id=163421
162 // Handle our own meta-types.
164 case "addr": break; // FIXME implement addr. https://bugs.webkit.org/show_bug.cgi?id=163421
165 case "any": break; // FIXME implement any. https://bugs.webkit.org/show_bug.cgi?id=163421
166 case "bool": break; // FIXME implement bool. https://bugs.webkit.org/show_bug.cgi?id=163421
167 case "call": break; // FIXME implement call stack argument checks based on function signature. https://bugs.webkit.org/show_bug.cgi?id=163421
168 case "global": break; // FIXME implement global. https://bugs.webkit.org/show_bug.cgi?id=163421
169 case "local": break; // FIXME implement local. https://bugs.webkit.org/show_bug.cgi?id=163421
170 case "prev": break; // FIXME implement prev, checking for whetever the previous value was. https://bugs.webkit.org/show_bug.cgi?id=163421
171 case "size": break; // FIXME implement size. https://bugs.webkit.org/show_bug.cgi?id=163421
172 default: throw new Error(`Implementation problem: unhandled meta-type "${expect}" on "${op}"`);
178 const _checkStackReturn = (op, ret) => {
179 for (let expect of ret) {
180 if (WASM.isValidType(expect)) {
181 // FIXME implement stack checks for return. https://bugs.webkit.org/show_bug.cgi?id=163421
183 // Handle our own meta-types.
185 case "bool": break; // FIXME implement bool. https://bugs.webkit.org/show_bug.cgi?id=163421
186 case "call": break; // FIXME implement call stack return check based on function signature. https://bugs.webkit.org/show_bug.cgi?id=163421
187 case "control": break; // FIXME implement control. https://bugs.webkit.org/show_bug.cgi?id=163421
188 case "global": break; // FIXME implement global. https://bugs.webkit.org/show_bug.cgi?id=163421
189 case "local": break; // FIXME implement local. https://bugs.webkit.org/show_bug.cgi?id=163421
190 case "prev": break; // FIXME implement prev, checking for whetever the parameter type was. https://bugs.webkit.org/show_bug.cgi?id=163421
191 case "size": break; // FIXME implement size. https://bugs.webkit.org/show_bug.cgi?id=163421
192 default: throw new Error(`Implementation problem: unhandled meta-type "${expect}" on "${op}"`);
198 const _checkImms = (op, imms, expectedImms, ret) => {
199 const minExpectedImms = expectedImms.filter(i => i.type.slice(-1) !== '*').length;
200 if (minExpectedImms !== expectedImms.length)
201 assert.ge(imms.length, minExpectedImms, `"${op}" expects at least ${minExpectedImms} immediate${minExpectedImms !== 1 ? 's' : ''}, got ${imms.length}`);
203 assert.eq(imms.length, minExpectedImms, `"${op}" expects exactly ${minExpectedImms} immediate${minExpectedImms !== 1 ? 's' : ''}, got ${imms.length}`);
204 for (let idx = 0; idx !== expectedImms.length; ++idx) {
205 const got = imms[idx];
206 const expect = expectedImms[idx];
207 switch (expect.name) {
208 case "function_index":
209 assert.truthy(_isValidValue(got, "i32"), `Invalid value on ${op}: got "${got}", expected i32`);
210 // FIXME check function indices. https://bugs.webkit.org/show_bug.cgi?id=163421
212 case "local_index": break; // improve checking https://bugs.webkit.org/show_bug.cgi?id=163421
213 case "global_index": break; // improve checking https://bugs.webkit.org/show_bug.cgi?id=163421
214 case "type_index": break; // improve checking https://bugs.webkit.org/show_bug.cgi?id=163421
216 assert.truthy(_isValidValue(got, ret[0]), `Invalid value on ${op}: got "${got}", expected ${ret[0]}`);
218 case "flags": break; // improve checking https://bugs.webkit.org/show_bug.cgi?id=163421
219 case "offset": break; // improve checking https://bugs.webkit.org/show_bug.cgi?id=163421
221 case "default_target": break; // improve checking https://bugs.webkit.org/show_bug.cgi?id=163421
222 case "relative_depth": break; // improve checking https://bugs.webkit.org/show_bug.cgi?id=163421
224 assert.truthy(WASM.isValidBlockType(imms[idx]), `Invalid block type on ${op}: "${imms[idx]}"`);
226 case "target_count": break; // improve checking https://bugs.webkit.org/show_bug.cgi?id=163421
227 case "target_table": break; // improve checking https://bugs.webkit.org/show_bug.cgi?id=163421
228 default: throw new Error(`Implementation problem: unhandled immediate "${expect.name}" on "${op}"`);
233 const _createFunctionBuilder = (func, builder, previousBuilder) => {
234 let functionBuilder = {};
235 for (const op in WASM.description.opcode) {
236 const name = _toJavaScriptName(op);
237 const value = WASM.description.opcode[op].value;
238 const ret = WASM.description.opcode[op]["return"];
239 const param = WASM.description.opcode[op].parameter;
240 const imm = WASM.description.opcode[op].immediate;
242 const checkStackArgs = builder._checked ? _checkStackArgs : () => {};
243 const checkStackReturn = builder._checked ? _checkStackReturn : () => {};
244 const checkImms = builder._checked ? _checkImms : () => {};
246 functionBuilder[name] = (...args) => {
250 nextBuilder = functionBuilder;
253 nextBuilder = previousBuilder;
258 nextBuilder = _createFunctionBuilder(func, builder, functionBuilder);
262 // Passing a function as the argument is a way to nest blocks lexically.
263 const continuation = args[args.length - 1];
264 const hasContinuation = typeof(continuation) === "function";
265 const imms = hasContinuation ? args.slice(0, -1) : args; // FIXME: allow passing in stack values, as-if code were a stack machine. Just check for a builder to this function, and drop. https://bugs.webkit.org/show_bug.cgi?id=163422
266 checkImms(op, imms, imm, ret);
267 checkStackArgs(op, param);
268 checkStackReturn(op, ret);
269 const stackArgs = []; // FIXME https://bugs.webkit.org/show_bug.cgi?id=162706
270 func.code.push({ name: op, value: value, arguments: stackArgs, immediates: imms });
272 return continuation(nextBuilder).End();
276 return functionBuilder;
279 const _createFunction = (section, builder, previousBuilder) => {
280 return (...args) => {
281 const nameOffset = (typeof(args[0]) === "string") >>> 0;
282 const functionName = nameOffset ? args[0] : undefined;
283 let signature = args[0 + nameOffset];
284 const locals = args[1 + nameOffset] === undefined ? [] : args[1 + nameOffset];
285 for (const local of locals)
286 assert.truthy(WASM.isValidValueType(local), `Type of local: ${local} needs to be a valid value type`);
288 if (typeof(signature) === "undefined")
289 signature = { params: [] };
290 assert.hasObjectProperty(signature, "params", `Expect function signature to be an object with a "params" field, got "${signature}"`);
291 const [params, ret] = _normalizeFunctionSignature(signature.params, signature.ret);
292 signature = { params: params, ret: ret };
295 type: _maybeRegisterType(builder, signature),
296 signature: signature,
297 locals: params.concat(locals), // Parameters are the first locals.
298 parameterCount: params.length,
302 const functionSection = builder._getSection("Function");
304 functionSection.data.push(func.type);
306 section.data.push(func);
307 builder._registerFunctionToIndexSpace(functionName);
309 return _createFunctionBuilder(func, builder, previousBuilder);
313 export default class Builder {
315 this.setChecked(true);
317 for (const p of WASM.description.preamble)
318 preamble[p.name] = p.value;
319 this.setPreamble(preamble);
321 this._functionIndexSpace = {};
322 this._functionIndexSpaceCount = 0;
323 this._registerSectionBuilders();
325 setChecked(checked) {
326 this._checked = checked;
330 this._preamble = Object.assign(this._preamble || {}, p);
333 _registerFunctionToIndexSpace(name) {
334 if (typeof(name) === "undefined") {
335 // Registering a nameless function still adds it to the function index space. Register it as something that can't normally be registered.
338 // Collisions are fine: we'll simply count the function and forget the previous one.
339 this._functionIndexSpace[name] = this._functionIndexSpaceCount++;
340 // Map it both ways, the number space is distinct from the name space.
341 this._functionIndexSpace[this._functionIndexSpace[name]] = name;
343 _getFunctionFromIndexSpace(name) {
344 return this._functionIndexSpace[name];
346 _registerSectionBuilders() {
347 for (const section in WASM.description.section) {
350 this[section] = function() {
351 const s = this._addSection(section);
352 const builder = this;
353 const typeBuilder = {
355 Func: (params, ret) => {
356 [params, ret] = _normalizeFunctionSignature(params, ret);
357 s.data.push({ params: params, ret: ret });
366 this[section] = function() {
367 const s = this._addSection(section);
368 const importBuilder = {
370 Table: () => { throw new Error(`Unimplemented: import table`); },
371 Memory: () => { throw new Error(`Unimplemented: import memory`); },
372 Global: () => { throw new Error(`Unimplemented: import global`); },
374 importBuilder.Function = _importFunctionContinuation(this, s, importBuilder);
375 return importBuilder;
380 this[section] = function() {
381 const s = this._addSection(section);
382 const exportBuilder = {
384 // FIXME: add ability to add this with whatever.
386 return exportBuilder;
391 // FIXME Implement table https://bugs.webkit.org/show_bug.cgi?id=164135
392 this[section] = () => { throw new Error(`Unimplemented: section type "${section}"`); };
396 this[section] = function() {
397 const s = this._addSection(section);
398 const exportBuilder = {
400 InitialMaxPages: (initial, max) => {
401 s.data.push({ initial, max });
402 return exportBuilder;
405 return exportBuilder;
410 // FIXME implement global https://bugs.webkit.org/show_bug.cgi?id=164133
411 this[section] = () => { throw new Error(`Unimplemented: section type "${section}"`); };
415 this[section] = function() {
416 const s = this._addSection(section);
417 const exportBuilder = {
419 Table: () => { throw new Error(`Unimplemented: export table`); },
420 Memory: () => { throw new Error(`Unimplemented: export memory`); },
421 Global: () => { throw new Error(`Unimplemented: export global`); },
423 exportBuilder.Function = _exportFunctionContinuation(this, s, exportBuilder);
424 return exportBuilder;
429 // FIXME implement start https://bugs.webkit.org/show_bug.cgi?id=161709
430 this[section] = () => { throw new Error(`Unimplemented: section type "${section}"`); };
434 // FIXME implement element https://bugs.webkit.org/show_bug.cgi?id=161709
435 this[section] = () => { throw new Error(`Unimplemented: section type "${section}"`); };
439 this[section] = function() {
440 const s = this._addSection(section);
441 const builder = this;
442 const codeBuilder = {
444 // We now have enough information to remap the export section's "type" and "index" according to the Code section we're currently ending.
445 const typeSection = builder._getSection("Type");
446 const importSection = builder._getSection("Import");
447 const exportSection = builder._getSection("Export");
448 const codeSection = s;
450 for (const e of exportSection.data) {
451 switch (typeof(e.index)) {
452 default: throw new Error(`Unexpected export index "${e.index}"`);
454 const index = builder._getFunctionFromIndexSpace(e.index);
455 assert.isNumber(index, `Export section contains undefined function "${e.index}"`);
459 const index = builder._getFunctionFromIndexSpace(e.index);
460 if (builder._checked)
461 assert.isNotUndef(index, `Export "${e.field}" does not correspond to a defined value in the function index space`);
464 throw new Error(`Unimplemented: Function().End() with undefined export index`); // FIXME
466 if (typeof(e.type) === "undefined") {
467 // This must be a function export from the Code section (re-exports were handled earlier).
468 const functionIndexSpaceOffset = importSection ? importSection.data.length : 0;
469 const functionIndex = e.index - functionIndexSpaceOffset;
470 e.type = codeSection.data[functionIndex].type;
478 codeBuilder.Function = _createFunction(s, builder, codeBuilder);
484 // FIXME implement data https://bugs.webkit.org/show_bug.cgi?id=161709
485 this[section] = () => { throw new Error(`Unimplemented: section type "${section}"`); };
489 this[section] = () => { throw new Error(`Unknown section type "${section}"`); };
494 this.Unknown = function(name) {
495 const s = this._addSection(name);
496 const builder = this;
497 const unknownBuilder = {
500 assert.eq(b & 0xFF, b, `Unknown section expected byte, got: "${b}"`);
502 return unknownBuilder;
505 return unknownBuilder;
508 _addSection(nameOrNumber, extraObject) {
509 const name = typeof(nameOrNumber) === "string" ? nameOrNumber : "";
510 const number = typeof(nameOrNumber) === "number" ? nameOrNumber : (WASM.description.section[name] ? WASM.description.section[name].value : _unknownSectionId);
513 for (const s of this._sections)
514 assert.falsy(s.name === name && s.id === number, `Cannot have two sections with the same name "${name}" and ID ${number}`);
516 if ((number !== _unknownSectionId) && (this._sections.length !== 0)) {
517 for (let i = this._sections.length - 1; i >= 0; --i) {
518 if (this._sections[i].id === _unknownSectionId)
520 assert.le(this._sections[i].id, number, `Bad section ordering: "${this._sections[i].name}" cannot precede "${name}"`);
525 const s = Object.assign({ name: name, id: number, data: [] }, extraObject || {});
526 this._sections.push(s);
529 _getSection(nameOrNumber) {
530 switch (typeof(nameOrNumber)) {
531 default: throw new Error(`Implementation problem: can not get section "${nameOrNumber}"`);
533 for (const s of this._sections)
534 if (s.name === nameOrNumber)
538 for (const s of this._sections)
539 if (s.id === nameOrNumber)
545 // FIXME Add more optimizations. https://bugs.webkit.org/show_bug.cgi?id=163424
550 preamble: this._preamble,
551 section: this._sections
553 return JSON.stringify(obj);
556 "use asm"; // For speed.
557 // FIXME Create an asm.js equivalent string which can be eval'd. https://bugs.webkit.org/show_bug.cgi?id=163425
558 throw new Error("asm.js not implemented yet");
560 WebAssembly() { return BuildWebAssembly.Binary(this._preamble, this._sections); }