You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1775 lines
53 KiB

4 years ago
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.decode = decode;
  6. var _helperApiError = require("@webassemblyjs/helper-api-error");
  7. var ieee754 = _interopRequireWildcard(require("@webassemblyjs/ieee754"));
  8. var utf8 = _interopRequireWildcard(require("@webassemblyjs/utf8"));
  9. var t = _interopRequireWildcard(require("@webassemblyjs/ast"));
  10. var _leb = require("@webassemblyjs/leb128");
  11. var _helperWasmBytecode = _interopRequireDefault(require("@webassemblyjs/helper-wasm-bytecode"));
  12. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  13. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
  14. function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
  15. function toHex(n) {
  16. return "0x" + Number(n).toString(16);
  17. }
  18. function byteArrayEq(l, r) {
  19. if (l.length !== r.length) {
  20. return false;
  21. }
  22. for (var i = 0; i < l.length; i++) {
  23. if (l[i] !== r[i]) {
  24. return false;
  25. }
  26. }
  27. return true;
  28. }
  29. function decode(ab, opts) {
  30. var buf = new Uint8Array(ab);
  31. var getUniqueName = t.getUniqueNameGenerator();
  32. var offset = 0;
  33. function getPosition() {
  34. return {
  35. line: -1,
  36. column: offset
  37. };
  38. }
  39. function dump(b, msg) {
  40. if (opts.dump === false) return;
  41. var pad = "\t\t\t\t\t\t\t\t\t\t";
  42. var str = "";
  43. if (b.length < 5) {
  44. str = b.map(toHex).join(" ");
  45. } else {
  46. str = "...";
  47. }
  48. console.log(toHex(offset) + ":\t", str, pad, ";", msg);
  49. }
  50. function dumpSep(msg) {
  51. if (opts.dump === false) return;
  52. console.log(";", msg);
  53. }
  54. /**
  55. * TODO(sven): we can atually use a same structure
  56. * we are adding incrementally new features
  57. */
  58. var state = {
  59. elementsInFuncSection: [],
  60. elementsInExportSection: [],
  61. elementsInCodeSection: [],
  62. /**
  63. * Decode memory from:
  64. * - Memory section
  65. */
  66. memoriesInModule: [],
  67. /**
  68. * Decoded types from:
  69. * - Type section
  70. */
  71. typesInModule: [],
  72. /**
  73. * Decoded functions from:
  74. * - Function section
  75. * - Import section
  76. */
  77. functionsInModule: [],
  78. /**
  79. * Decoded tables from:
  80. * - Table section
  81. */
  82. tablesInModule: [],
  83. /**
  84. * Decoded globals from:
  85. * - Global section
  86. */
  87. globalsInModule: []
  88. };
  89. function isEOF() {
  90. return offset >= buf.length;
  91. }
  92. function eatBytes(n) {
  93. offset = offset + n;
  94. }
  95. function readBytesAtOffset(_offset, numberOfBytes) {
  96. var arr = [];
  97. for (var i = 0; i < numberOfBytes; i++) {
  98. arr.push(buf[_offset + i]);
  99. }
  100. return arr;
  101. }
  102. function readBytes(numberOfBytes) {
  103. return readBytesAtOffset(offset, numberOfBytes);
  104. }
  105. function readF64() {
  106. var bytes = readBytes(ieee754.NUMBER_OF_BYTE_F64);
  107. var value = ieee754.decodeF64(bytes);
  108. if (Math.sign(value) * value === Infinity) {
  109. return {
  110. value: Math.sign(value),
  111. inf: true,
  112. nextIndex: ieee754.NUMBER_OF_BYTE_F64
  113. };
  114. }
  115. if (isNaN(value)) {
  116. var sign = bytes[bytes.length - 1] >> 7 ? -1 : 1;
  117. var mantissa = 0;
  118. for (var i = 0; i < bytes.length - 2; ++i) {
  119. mantissa += bytes[i] * Math.pow(256, i);
  120. }
  121. mantissa += bytes[bytes.length - 2] % 16 * Math.pow(256, bytes.length - 2);
  122. return {
  123. value: sign * mantissa,
  124. nan: true,
  125. nextIndex: ieee754.NUMBER_OF_BYTE_F64
  126. };
  127. }
  128. return {
  129. value: value,
  130. nextIndex: ieee754.NUMBER_OF_BYTE_F64
  131. };
  132. }
  133. function readF32() {
  134. var bytes = readBytes(ieee754.NUMBER_OF_BYTE_F32);
  135. var value = ieee754.decodeF32(bytes);
  136. if (Math.sign(value) * value === Infinity) {
  137. return {
  138. value: Math.sign(value),
  139. inf: true,
  140. nextIndex: ieee754.NUMBER_OF_BYTE_F32
  141. };
  142. }
  143. if (isNaN(value)) {
  144. var sign = bytes[bytes.length - 1] >> 7 ? -1 : 1;
  145. var mantissa = 0;
  146. for (var i = 0; i < bytes.length - 2; ++i) {
  147. mantissa += bytes[i] * Math.pow(256, i);
  148. }
  149. mantissa += bytes[bytes.length - 2] % 128 * Math.pow(256, bytes.length - 2);
  150. return {
  151. value: sign * mantissa,
  152. nan: true,
  153. nextIndex: ieee754.NUMBER_OF_BYTE_F32
  154. };
  155. }
  156. return {
  157. value: value,
  158. nextIndex: ieee754.NUMBER_OF_BYTE_F32
  159. };
  160. }
  161. function readUTF8String() {
  162. var lenu32 = readU32(); // Don't eat any bytes. Instead, peek ahead of the current offset using
  163. // readBytesAtOffset below. This keeps readUTF8String neutral with respect
  164. // to the current offset, just like the other readX functions.
  165. var strlen = lenu32.value;
  166. dump([strlen], "string length");
  167. var bytes = readBytesAtOffset(offset + lenu32.nextIndex, strlen);
  168. var value = utf8.decode(bytes);
  169. return {
  170. value: value,
  171. nextIndex: strlen + lenu32.nextIndex
  172. };
  173. }
  174. /**
  175. * Decode an unsigned 32bits integer
  176. *
  177. * The length will be handled by the leb librairy, we pass the max number of
  178. * byte.
  179. */
  180. function readU32() {
  181. var bytes = readBytes(_leb.MAX_NUMBER_OF_BYTE_U32);
  182. var buffer = Buffer.from(bytes);
  183. return (0, _leb.decodeUInt32)(buffer);
  184. }
  185. function readVaruint32() {
  186. // where 32 bits = max 4 bytes
  187. var bytes = readBytes(4);
  188. var buffer = Buffer.from(bytes);
  189. return (0, _leb.decodeUInt32)(buffer);
  190. }
  191. function readVaruint7() {
  192. // where 7 bits = max 1 bytes
  193. var bytes = readBytes(1);
  194. var buffer = Buffer.from(bytes);
  195. return (0, _leb.decodeUInt32)(buffer);
  196. }
  197. /**
  198. * Decode a signed 32bits interger
  199. */
  200. function read32() {
  201. var bytes = readBytes(_leb.MAX_NUMBER_OF_BYTE_U32);
  202. var buffer = Buffer.from(bytes);
  203. return (0, _leb.decodeInt32)(buffer);
  204. }
  205. /**
  206. * Decode a signed 64bits integer
  207. */
  208. function read64() {
  209. var bytes = readBytes(_leb.MAX_NUMBER_OF_BYTE_U64);
  210. var buffer = Buffer.from(bytes);
  211. return (0, _leb.decodeInt64)(buffer);
  212. }
  213. function readU64() {
  214. var bytes = readBytes(_leb.MAX_NUMBER_OF_BYTE_U64);
  215. var buffer = Buffer.from(bytes);
  216. return (0, _leb.decodeUInt64)(buffer);
  217. }
  218. function readByte() {
  219. return readBytes(1)[0];
  220. }
  221. function parseModuleHeader() {
  222. if (isEOF() === true || offset + 4 > buf.length) {
  223. throw new Error("unexpected end");
  224. }
  225. var header = readBytes(4);
  226. if (byteArrayEq(_helperWasmBytecode.default.magicModuleHeader, header) === false) {
  227. throw new _helperApiError.CompileError("magic header not detected");
  228. }
  229. dump(header, "wasm magic header");
  230. eatBytes(4);
  231. }
  232. function parseVersion() {
  233. if (isEOF() === true || offset + 4 > buf.length) {
  234. throw new Error("unexpected end");
  235. }
  236. var version = readBytes(4);
  237. if (byteArrayEq(_helperWasmBytecode.default.moduleVersion, version) === false) {
  238. throw new _helperApiError.CompileError("unknown binary version");
  239. }
  240. dump(version, "wasm version");
  241. eatBytes(4);
  242. }
  243. function parseVec(cast) {
  244. var u32 = readU32();
  245. var length = u32.value;
  246. eatBytes(u32.nextIndex);
  247. dump([length], "number");
  248. if (length === 0) {
  249. return [];
  250. }
  251. var elements = [];
  252. for (var i = 0; i < length; i++) {
  253. var byte = readByte();
  254. eatBytes(1);
  255. var value = cast(byte);
  256. dump([byte], value);
  257. if (typeof value === "undefined") {
  258. throw new _helperApiError.CompileError("Internal failure: parseVec could not cast the value");
  259. }
  260. elements.push(value);
  261. }
  262. return elements;
  263. } // Type section
  264. // https://webassembly.github.io/spec/binary/modules.html#binary-typesec
  265. function parseTypeSection(numberOfTypes) {
  266. var typeInstructionNodes = [];
  267. dump([numberOfTypes], "num types");
  268. for (var i = 0; i < numberOfTypes; i++) {
  269. var _startLoc = getPosition();
  270. dumpSep("type " + i);
  271. var type = readByte();
  272. eatBytes(1);
  273. if (type == _helperWasmBytecode.default.types.func) {
  274. dump([type], "func");
  275. var paramValtypes = parseVec(function (b) {
  276. return _helperWasmBytecode.default.valtypes[b];
  277. });
  278. var params = paramValtypes.map(function (v) {
  279. return t.funcParam(
  280. /*valtype*/
  281. v);
  282. });
  283. var result = parseVec(function (b) {
  284. return _helperWasmBytecode.default.valtypes[b];
  285. });
  286. typeInstructionNodes.push(function () {
  287. var endLoc = getPosition();
  288. return t.withLoc(t.typeInstruction(undefined, t.signature(params, result)), endLoc, _startLoc);
  289. }());
  290. state.typesInModule.push({
  291. params: params,
  292. result: result
  293. });
  294. } else {
  295. throw new Error("Unsupported type: " + toHex(type));
  296. }
  297. }
  298. return typeInstructionNodes;
  299. } // Import section
  300. // https://webassembly.github.io/spec/binary/modules.html#binary-importsec
  301. function parseImportSection(numberOfImports) {
  302. var imports = [];
  303. for (var i = 0; i < numberOfImports; i++) {
  304. dumpSep("import header " + i);
  305. var _startLoc2 = getPosition();
  306. /**
  307. * Module name
  308. */
  309. var moduleName = readUTF8String();
  310. eatBytes(moduleName.nextIndex);
  311. dump([], "module name (".concat(moduleName.value, ")"));
  312. /**
  313. * Name
  314. */
  315. var name = readUTF8String();
  316. eatBytes(name.nextIndex);
  317. dump([], "name (".concat(name.value, ")"));
  318. /**
  319. * Import descr
  320. */
  321. var descrTypeByte = readByte();
  322. eatBytes(1);
  323. var descrType = _helperWasmBytecode.default.importTypes[descrTypeByte];
  324. dump([descrTypeByte], "import kind");
  325. if (typeof descrType === "undefined") {
  326. throw new _helperApiError.CompileError("Unknown import description type: " + toHex(descrTypeByte));
  327. }
  328. var importDescr = void 0;
  329. if (descrType === "func") {
  330. var indexU32 = readU32();
  331. var typeindex = indexU32.value;
  332. eatBytes(indexU32.nextIndex);
  333. dump([typeindex], "type index");
  334. var signature = state.typesInModule[typeindex];
  335. if (typeof signature === "undefined") {
  336. throw new _helperApiError.CompileError("function signature not found (".concat(typeindex, ")"));
  337. }
  338. var id = getUniqueName("func");
  339. importDescr = t.funcImportDescr(id, t.signature(signature.params, signature.result));
  340. state.functionsInModule.push({
  341. id: t.identifier(name.value),
  342. signature: signature,
  343. isExternal: true
  344. });
  345. } else if (descrType === "global") {
  346. importDescr = parseGlobalType();
  347. var globalNode = t.global(importDescr, []);
  348. state.globalsInModule.push(globalNode);
  349. } else if (descrType === "table") {
  350. importDescr = parseTableType(i);
  351. } else if (descrType === "mem") {
  352. var memoryNode = parseMemoryType(0);
  353. state.memoriesInModule.push(memoryNode);
  354. importDescr = memoryNode;
  355. } else {
  356. throw new _helperApiError.CompileError("Unsupported import of type: " + descrType);
  357. }
  358. imports.push(function () {
  359. var endLoc = getPosition();
  360. return t.withLoc(t.moduleImport(moduleName.value, name.value, importDescr), endLoc, _startLoc2);
  361. }());
  362. }
  363. return imports;
  364. } // Function section
  365. // https://webassembly.github.io/spec/binary/modules.html#function-section
  366. function parseFuncSection(numberOfFunctions) {
  367. dump([numberOfFunctions], "num funcs");
  368. for (var i = 0; i < numberOfFunctions; i++) {
  369. var indexU32 = readU32();
  370. var typeindex = indexU32.value;
  371. eatBytes(indexU32.nextIndex);
  372. dump([typeindex], "type index");
  373. var signature = state.typesInModule[typeindex];
  374. if (typeof signature === "undefined") {
  375. throw new _helperApiError.CompileError("function signature not found (".concat(typeindex, ")"));
  376. } // preserve anonymous, a name might be resolved later
  377. var id = t.withRaw(t.identifier(getUniqueName("func")), "");
  378. state.functionsInModule.push({
  379. id: id,
  380. signature: signature,
  381. isExternal: false
  382. });
  383. }
  384. } // Export section
  385. // https://webassembly.github.io/spec/binary/modules.html#export-section
  386. function parseExportSection(numberOfExport) {
  387. dump([numberOfExport], "num exports"); // Parse vector of exports
  388. for (var i = 0; i < numberOfExport; i++) {
  389. var _startLoc3 = getPosition();
  390. /**
  391. * Name
  392. */
  393. var name = readUTF8String();
  394. eatBytes(name.nextIndex);
  395. dump([], "export name (".concat(name.value, ")"));
  396. /**
  397. * exportdescr
  398. */
  399. var typeIndex = readByte();
  400. eatBytes(1);
  401. dump([typeIndex], "export kind");
  402. var indexu32 = readU32();
  403. var index = indexu32.value;
  404. eatBytes(indexu32.nextIndex);
  405. dump([index], "export index");
  406. var id = void 0,
  407. signature = void 0;
  408. if (_helperWasmBytecode.default.exportTypes[typeIndex] === "Func") {
  409. var func = state.functionsInModule[index];
  410. if (typeof func === "undefined") {
  411. throw new _helperApiError.CompileError("unknown function (".concat(index, ")"));
  412. }
  413. id = t.numberLiteralFromRaw(index, String(index));
  414. signature = func.signature;
  415. } else if (_helperWasmBytecode.default.exportTypes[typeIndex] === "Table") {
  416. var table = state.tablesInModule[index];
  417. if (typeof table === "undefined") {
  418. throw new _helperApiError.CompileError("unknown table ".concat(index));
  419. }
  420. id = t.numberLiteralFromRaw(index, String(index));
  421. signature = null;
  422. } else if (_helperWasmBytecode.default.exportTypes[typeIndex] === "Mem") {
  423. var memNode = state.memoriesInModule[index];
  424. if (typeof memNode === "undefined") {
  425. throw new _helperApiError.CompileError("unknown memory ".concat(index));
  426. }
  427. id = t.numberLiteralFromRaw(index, String(index));
  428. signature = null;
  429. } else if (_helperWasmBytecode.default.exportTypes[typeIndex] === "Global") {
  430. var global = state.globalsInModule[index];
  431. if (typeof global === "undefined") {
  432. throw new _helperApiError.CompileError("unknown global ".concat(index));
  433. }
  434. id = t.numberLiteralFromRaw(index, String(index));
  435. signature = null;
  436. } else {
  437. console.warn("Unsupported export type: " + toHex(typeIndex));
  438. return;
  439. }
  440. var endLoc = getPosition();
  441. state.elementsInExportSection.push({
  442. name: name.value,
  443. type: _helperWasmBytecode.default.exportTypes[typeIndex],
  444. signature: signature,
  445. id: id,
  446. index: index,
  447. endLoc: endLoc,
  448. startLoc: _startLoc3
  449. });
  450. }
  451. } // Code section
  452. // https://webassembly.github.io/spec/binary/modules.html#code-section
  453. function parseCodeSection(numberOfFuncs) {
  454. dump([numberOfFuncs], "number functions"); // Parse vector of function
  455. for (var i = 0; i < numberOfFuncs; i++) {
  456. var _startLoc4 = getPosition();
  457. dumpSep("function body " + i); // the u32 size of the function code in bytes
  458. // Ignore it for now
  459. var bodySizeU32 = readU32();
  460. eatBytes(bodySizeU32.nextIndex);
  461. dump([bodySizeU32.value], "function body size");
  462. var code = [];
  463. /**
  464. * Parse locals
  465. */
  466. var funcLocalNumU32 = readU32();
  467. var funcLocalNum = funcLocalNumU32.value;
  468. eatBytes(funcLocalNumU32.nextIndex);
  469. dump([funcLocalNum], "num locals");
  470. var locals = [];
  471. for (var _i = 0; _i < funcLocalNum; _i++) {
  472. var _startLoc5 = getPosition();
  473. var localCountU32 = readU32();
  474. var localCount = localCountU32.value;
  475. eatBytes(localCountU32.nextIndex);
  476. dump([localCount], "num local");
  477. var valtypeByte = readByte();
  478. eatBytes(1);
  479. var type = _helperWasmBytecode.default.valtypes[valtypeByte];
  480. var args = [];
  481. for (var _i2 = 0; _i2 < localCount; _i2++) {
  482. args.push(t.valtypeLiteral(type));
  483. }
  484. var localNode = function () {
  485. var endLoc = getPosition();
  486. return t.withLoc(t.instruction("local", args), endLoc, _startLoc5);
  487. }();
  488. locals.push(localNode);
  489. dump([valtypeByte], type);
  490. if (typeof type === "undefined") {
  491. throw new _helperApiError.CompileError("Unexpected valtype: " + toHex(valtypeByte));
  492. }
  493. }
  494. code.push.apply(code, locals); // Decode instructions until the end
  495. parseInstructionBlock(code);
  496. var endLoc = getPosition();
  497. state.elementsInCodeSection.push({
  498. code: code,
  499. locals: locals,
  500. endLoc: endLoc,
  501. startLoc: _startLoc4,
  502. bodySize: bodySizeU32.value
  503. });
  504. }
  505. }
  506. function parseInstructionBlock(code) {
  507. while (true) {
  508. var _startLoc6 = getPosition();
  509. var instructionAlreadyCreated = false;
  510. var instructionByte = readByte();
  511. eatBytes(1);
  512. if (instructionByte === 0xfe) {
  513. throw new _helperApiError.CompileError("Atomic instructions are not implemented");
  514. }
  515. var instruction = _helperWasmBytecode.default.symbolsByByte[instructionByte];
  516. if (typeof instruction === "undefined") {
  517. throw new _helperApiError.CompileError("Unexpected instruction: " + toHex(instructionByte));
  518. }
  519. if (typeof instruction.object === "string") {
  520. dump([instructionByte], "".concat(instruction.object, ".").concat(instruction.name));
  521. } else {
  522. dump([instructionByte], instruction.name);
  523. }
  524. /**
  525. * End of the function
  526. */
  527. if (instruction.name === "end") {
  528. var node = function () {
  529. var endLoc = getPosition();
  530. return t.withLoc(t.instruction(instruction.name), endLoc, _startLoc6);
  531. }();
  532. code.push(node);
  533. break;
  534. }
  535. var args = [];
  536. if (instruction.name === "loop") {
  537. var _startLoc7 = getPosition();
  538. var blocktypeByte = readByte();
  539. eatBytes(1);
  540. var blocktype = _helperWasmBytecode.default.blockTypes[blocktypeByte];
  541. dump([blocktypeByte], "blocktype");
  542. if (typeof blocktype === "undefined") {
  543. throw new _helperApiError.CompileError("Unexpected blocktype: " + toHex(blocktypeByte));
  544. }
  545. var instr = [];
  546. parseInstructionBlock(instr); // preserve anonymous
  547. var label = t.withRaw(t.identifier(getUniqueName("loop")), "");
  548. var loopNode = function () {
  549. var endLoc = getPosition();
  550. return t.withLoc(t.loopInstruction(label, blocktype, instr), endLoc, _startLoc7);
  551. }();
  552. code.push(loopNode);
  553. instructionAlreadyCreated = true;
  554. } else if (instruction.name === "if") {
  555. var _startLoc8 = getPosition();
  556. var _blocktypeByte = readByte();
  557. eatBytes(1);
  558. var _blocktype = _helperWasmBytecode.default.blockTypes[_blocktypeByte];
  559. dump([_blocktypeByte], "blocktype");
  560. if (typeof _blocktype === "undefined") {
  561. throw new _helperApiError.CompileError("Unexpected blocktype: " + toHex(_blocktypeByte));
  562. }
  563. var testIndex = t.withRaw(t.identifier(getUniqueName("if")), "");
  564. var ifBody = [];
  565. parseInstructionBlock(ifBody); // Defaults to no alternate
  566. var elseIndex = 0;
  567. for (elseIndex = 0; elseIndex < ifBody.length; ++elseIndex) {
  568. var _instr = ifBody[elseIndex];
  569. if (_instr.type === "Instr" && _instr.id === "else") {
  570. break;
  571. }
  572. }
  573. var consequentInstr = ifBody.slice(0, elseIndex);
  574. var alternate = ifBody.slice(elseIndex + 1); // wast sugar
  575. var testInstrs = [];
  576. var ifNode = function () {
  577. var endLoc = getPosition();
  578. return t.withLoc(t.ifInstruction(testIndex, testInstrs, _blocktype, consequentInstr, alternate), endLoc, _startLoc8);
  579. }();
  580. code.push(ifNode);
  581. instructionAlreadyCreated = true;
  582. } else if (instruction.name === "block") {
  583. var _startLoc9 = getPosition();
  584. var _blocktypeByte2 = readByte();
  585. eatBytes(1);
  586. var _blocktype2 = _helperWasmBytecode.default.blockTypes[_blocktypeByte2];
  587. dump([_blocktypeByte2], "blocktype");
  588. if (typeof _blocktype2 === "undefined") {
  589. throw new _helperApiError.CompileError("Unexpected blocktype: " + toHex(_blocktypeByte2));
  590. }
  591. var _instr2 = [];
  592. parseInstructionBlock(_instr2); // preserve anonymous
  593. var _label = t.withRaw(t.identifier(getUniqueName("block")), "");
  594. var blockNode = function () {
  595. var endLoc = getPosition();
  596. return t.withLoc(t.blockInstruction(_label, _instr2, _blocktype2), endLoc, _startLoc9);
  597. }();
  598. code.push(blockNode);
  599. instructionAlreadyCreated = true;
  600. } else if (instruction.name === "call") {
  601. var indexu32 = readU32();
  602. var index = indexu32.value;
  603. eatBytes(indexu32.nextIndex);
  604. dump([index], "index");
  605. var callNode = function () {
  606. var endLoc = getPosition();
  607. return t.withLoc(t.callInstruction(t.indexLiteral(index)), endLoc, _startLoc6);
  608. }();
  609. code.push(callNode);
  610. instructionAlreadyCreated = true;
  611. } else if (instruction.name === "call_indirect") {
  612. var _startLoc10 = getPosition();
  613. var indexU32 = readU32();
  614. var typeindex = indexU32.value;
  615. eatBytes(indexU32.nextIndex);
  616. dump([typeindex], "type index");
  617. var signature = state.typesInModule[typeindex];
  618. if (typeof signature === "undefined") {
  619. throw new _helperApiError.CompileError("call_indirect signature not found (".concat(typeindex, ")"));
  620. }
  621. var _callNode = t.callIndirectInstruction(t.signature(signature.params, signature.result), []);
  622. var flagU32 = readU32();
  623. var flag = flagU32.value; // 0x00 - reserved byte
  624. eatBytes(flagU32.nextIndex);
  625. if (flag !== 0) {
  626. throw new _helperApiError.CompileError("zero flag expected");
  627. }
  628. code.push(function () {
  629. var endLoc = getPosition();
  630. return t.withLoc(_callNode, endLoc, _startLoc10);
  631. }());
  632. instructionAlreadyCreated = true;
  633. } else if (instruction.name === "br_table") {
  634. var indicesu32 = readU32();
  635. var indices = indicesu32.value;
  636. eatBytes(indicesu32.nextIndex);
  637. dump([indices], "num indices");
  638. for (var i = 0; i <= indices; i++) {
  639. var _indexu = readU32();
  640. var _index = _indexu.value;
  641. eatBytes(_indexu.nextIndex);
  642. dump([_index], "index");
  643. args.push(t.numberLiteralFromRaw(_indexu.value.toString(), "u32"));
  644. }
  645. } else if (instructionByte >= 0x28 && instructionByte <= 0x40) {
  646. /**
  647. * Memory instructions
  648. */
  649. if (instruction.name === "grow_memory" || instruction.name === "current_memory") {
  650. var _indexU = readU32();
  651. var _index2 = _indexU.value;
  652. eatBytes(_indexU.nextIndex);
  653. if (_index2 !== 0) {
  654. throw new Error("zero flag expected");
  655. }
  656. dump([_index2], "index");
  657. } else {
  658. var aligun32 = readU32();
  659. var align = aligun32.value;
  660. eatBytes(aligun32.nextIndex);
  661. dump([align], "align");
  662. var offsetu32 = readU32();
  663. var _offset2 = offsetu32.value;
  664. eatBytes(offsetu32.nextIndex);
  665. dump([_offset2], "offset");
  666. }
  667. } else if (instructionByte >= 0x41 && instructionByte <= 0x44) {
  668. /**
  669. * Numeric instructions
  670. */
  671. if (instruction.object === "i32") {
  672. var value32 = read32();
  673. var value = value32.value;
  674. eatBytes(value32.nextIndex);
  675. dump([value], "i32 value");
  676. args.push(t.numberLiteralFromRaw(value));
  677. }
  678. if (instruction.object === "u32") {
  679. var valueu32 = readU32();
  680. var _value = valueu32.value;
  681. eatBytes(valueu32.nextIndex);
  682. dump([_value], "u32 value");
  683. args.push(t.numberLiteralFromRaw(_value));
  684. }
  685. if (instruction.object === "i64") {
  686. var value64 = read64();
  687. var _value2 = value64.value;
  688. eatBytes(value64.nextIndex);
  689. dump([Number(_value2.toString())], "i64 value");
  690. var high = _value2.high,
  691. low = _value2.low;
  692. var _node = {
  693. type: "LongNumberLiteral",
  694. value: {
  695. high: high,
  696. low: low
  697. }
  698. };
  699. args.push(_node);
  700. }
  701. if (instruction.object === "u64") {
  702. var valueu64 = readU64();
  703. var _value3 = valueu64.value;
  704. eatBytes(valueu64.nextIndex);
  705. dump([Number(_value3.toString())], "u64 value");
  706. var _high = _value3.high,
  707. _low = _value3.low;
  708. var _node2 = {
  709. type: "LongNumberLiteral",
  710. value: {
  711. high: _high,
  712. low: _low
  713. }
  714. };
  715. args.push(_node2);
  716. }
  717. if (instruction.object === "f32") {
  718. var valuef32 = readF32();
  719. var _value4 = valuef32.value;
  720. eatBytes(valuef32.nextIndex);
  721. dump([_value4], "f32 value");
  722. args.push( // $FlowIgnore
  723. t.floatLiteral(_value4, valuef32.nan, valuef32.inf, String(_value4)));
  724. }
  725. if (instruction.object === "f64") {
  726. var valuef64 = readF64();
  727. var _value5 = valuef64.value;
  728. eatBytes(valuef64.nextIndex);
  729. dump([_value5], "f64 value");
  730. args.push( // $FlowIgnore
  731. t.floatLiteral(_value5, valuef64.nan, valuef64.inf, String(_value5)));
  732. }
  733. } else {
  734. for (var _i3 = 0; _i3 < instruction.numberOfArgs; _i3++) {
  735. var u32 = readU32();
  736. eatBytes(u32.nextIndex);
  737. dump([u32.value], "argument " + _i3);
  738. args.push(t.numberLiteralFromRaw(u32.value));
  739. }
  740. }
  741. if (instructionAlreadyCreated === false) {
  742. if (typeof instruction.object === "string") {
  743. var _node3 = function () {
  744. var endLoc = getPosition();
  745. return t.withLoc(t.objectInstruction(instruction.name, instruction.object, args), endLoc, _startLoc6);
  746. }();
  747. code.push(_node3);
  748. } else {
  749. var _node4 = function () {
  750. var endLoc = getPosition();
  751. return t.withLoc(t.instruction(instruction.name, args), endLoc, _startLoc6);
  752. }();
  753. code.push(_node4);
  754. }
  755. }
  756. }
  757. } // https://webassembly.github.io/spec/core/binary/types.html#limits
  758. function parseLimits() {
  759. var limitType = readByte();
  760. eatBytes(1);
  761. dump([limitType], "limit type");
  762. var min, max;
  763. if (limitType === 0x01 || limitType === 0x03 // shared limits
  764. ) {
  765. var u32min = readU32();
  766. min = parseInt(u32min.value);
  767. eatBytes(u32min.nextIndex);
  768. dump([min], "min");
  769. var u32max = readU32();
  770. max = parseInt(u32max.value);
  771. eatBytes(u32max.nextIndex);
  772. dump([max], "max");
  773. }
  774. if (limitType === 0x00) {
  775. var _u32min = readU32();
  776. min = parseInt(_u32min.value);
  777. eatBytes(_u32min.nextIndex);
  778. dump([min], "min");
  779. }
  780. return t.limit(min, max);
  781. } // https://webassembly.github.io/spec/core/binary/types.html#binary-tabletype
  782. function parseTableType(index) {
  783. var name = t.withRaw(t.identifier(getUniqueName("table")), String(index));
  784. var elementTypeByte = readByte();
  785. eatBytes(1);
  786. dump([elementTypeByte], "element type");
  787. var elementType = _helperWasmBytecode.default.tableTypes[elementTypeByte];
  788. if (typeof elementType === "undefined") {
  789. throw new _helperApiError.CompileError("Unknown element type in table: " + toHex(elementType));
  790. }
  791. var limits = parseLimits();
  792. return t.table(elementType, limits, name);
  793. } // https://webassembly.github.io/spec/binary/types.html#global-types
  794. function parseGlobalType() {
  795. var valtypeByte = readByte();
  796. eatBytes(1);
  797. var type = _helperWasmBytecode.default.valtypes[valtypeByte];
  798. dump([valtypeByte], type);
  799. if (typeof type === "undefined") {
  800. throw new _helperApiError.CompileError("Unknown valtype: " + toHex(valtypeByte));
  801. }
  802. var globalTypeByte = readByte();
  803. eatBytes(1);
  804. var globalType = _helperWasmBytecode.default.globalTypes[globalTypeByte];
  805. dump([globalTypeByte], "global type (".concat(globalType, ")"));
  806. if (typeof globalType === "undefined") {
  807. throw new _helperApiError.CompileError("Invalid mutability: " + toHex(globalTypeByte));
  808. }
  809. return t.globalType(type, globalType);
  810. } // function parseNameModule() {
  811. // const lenu32 = readVaruint32();
  812. // eatBytes(lenu32.nextIndex);
  813. // console.log("len", lenu32);
  814. // const strlen = lenu32.value;
  815. // dump([strlen], "string length");
  816. // const bytes = readBytes(strlen);
  817. // eatBytes(strlen);
  818. // const value = utf8.decode(bytes);
  819. // return [t.moduleNameMetadata(value)];
  820. // }
  821. // this section contains an array of function names and indices
  822. function parseNameSectionFunctions() {
  823. var functionNames = [];
  824. var numberOfFunctionsu32 = readU32();
  825. var numbeOfFunctions = numberOfFunctionsu32.value;
  826. eatBytes(numberOfFunctionsu32.nextIndex);
  827. for (var i = 0; i < numbeOfFunctions; i++) {
  828. var indexu32 = readU32();
  829. var index = indexu32.value;
  830. eatBytes(indexu32.nextIndex);
  831. var name = readUTF8String();
  832. eatBytes(name.nextIndex);
  833. functionNames.push(t.functionNameMetadata(name.value, index));
  834. }
  835. return functionNames;
  836. }
  837. function parseNameSectionLocals() {
  838. var localNames = [];
  839. var numbeOfFunctionsu32 = readU32();
  840. var numbeOfFunctions = numbeOfFunctionsu32.value;
  841. eatBytes(numbeOfFunctionsu32.nextIndex);
  842. for (var i = 0; i < numbeOfFunctions; i++) {
  843. var functionIndexu32 = readU32();
  844. var functionIndex = functionIndexu32.value;
  845. eatBytes(functionIndexu32.nextIndex);
  846. var numLocalsu32 = readU32();
  847. var numLocals = numLocalsu32.value;
  848. eatBytes(numLocalsu32.nextIndex);
  849. for (var _i4 = 0; _i4 < numLocals; _i4++) {
  850. var localIndexu32 = readU32();
  851. var localIndex = localIndexu32.value;
  852. eatBytes(localIndexu32.nextIndex);
  853. var name = readUTF8String();
  854. eatBytes(name.nextIndex);
  855. localNames.push(t.localNameMetadata(name.value, localIndex, functionIndex));
  856. }
  857. }
  858. return localNames;
  859. } // this is a custom section used for name resolution
  860. // https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#name-section
  861. function parseNameSection(remainingBytes) {
  862. var nameMetadata = [];
  863. var initialOffset = offset;
  864. while (offset - initialOffset < remainingBytes) {
  865. // name_type
  866. var sectionTypeByte = readVaruint7();
  867. eatBytes(sectionTypeByte.nextIndex); // name_payload_len
  868. var subSectionSizeInBytesu32 = readVaruint32();
  869. eatBytes(subSectionSizeInBytesu32.nextIndex);
  870. switch (sectionTypeByte.value) {
  871. // case 0: {
  872. // TODO(sven): re-enable that
  873. // Current status: it seems that when we decode the module's name
  874. // no name_payload_len is used.
  875. //
  876. // See https://github.com/WebAssembly/design/blob/master/BinaryEncoding.md#name-section
  877. //
  878. // nameMetadata.push(...parseNameModule());
  879. // break;
  880. // }
  881. case 1:
  882. {
  883. nameMetadata.push.apply(nameMetadata, _toConsumableArray(parseNameSectionFunctions()));
  884. break;
  885. }
  886. case 2:
  887. {
  888. nameMetadata.push.apply(nameMetadata, _toConsumableArray(parseNameSectionLocals()));
  889. break;
  890. }
  891. default:
  892. {
  893. // skip unknown subsection
  894. eatBytes(subSectionSizeInBytesu32.value);
  895. }
  896. }
  897. }
  898. return nameMetadata;
  899. } // this is a custom setion used for information about the producers
  900. // https://github.com/WebAssembly/tool-conventions/blob/master/ProducersSection.md
  901. function parseProducersSection() {
  902. var metadata = t.producersSectionMetadata([]); // field_count
  903. var sectionTypeByte = readVaruint32();
  904. eatBytes(sectionTypeByte.nextIndex);
  905. dump([sectionTypeByte.value], "num of producers");
  906. var fields = {
  907. language: [],
  908. "processed-by": [],
  909. sdk: []
  910. }; // fields
  911. for (var fieldI = 0; fieldI < sectionTypeByte.value; fieldI++) {
  912. // field_name
  913. var fieldName = readUTF8String();
  914. eatBytes(fieldName.nextIndex); // field_value_count
  915. var valueCount = readVaruint32();
  916. eatBytes(valueCount.nextIndex); // field_values
  917. for (var producerI = 0; producerI < valueCount.value; producerI++) {
  918. var producerName = readUTF8String();
  919. eatBytes(producerName.nextIndex);
  920. var producerVersion = readUTF8String();
  921. eatBytes(producerVersion.nextIndex);
  922. fields[fieldName.value].push(t.producerMetadataVersionedName(producerName.value, producerVersion.value));
  923. }
  924. metadata.producers.push(fields[fieldName.value]);
  925. }
  926. return metadata;
  927. }
  928. function parseGlobalSection(numberOfGlobals) {
  929. var globals = [];
  930. dump([numberOfGlobals], "num globals");
  931. for (var i = 0; i < numberOfGlobals; i++) {
  932. var _startLoc11 = getPosition();
  933. var globalType = parseGlobalType();
  934. /**
  935. * Global expressions
  936. */
  937. var init = [];
  938. parseInstructionBlock(init);
  939. var node = function () {
  940. var endLoc = getPosition();
  941. return t.withLoc(t.global(globalType, init), endLoc, _startLoc11);
  942. }();
  943. globals.push(node);
  944. state.globalsInModule.push(node);
  945. }
  946. return globals;
  947. }
  948. function parseElemSection(numberOfElements) {
  949. var elems = [];
  950. dump([numberOfElements], "num elements");
  951. for (var i = 0; i < numberOfElements; i++) {
  952. var _startLoc12 = getPosition();
  953. var tableindexu32 = readU32();
  954. var tableindex = tableindexu32.value;
  955. eatBytes(tableindexu32.nextIndex);
  956. dump([tableindex], "table index");
  957. /**
  958. * Parse instructions
  959. */
  960. var instr = [];
  961. parseInstructionBlock(instr);
  962. /**
  963. * Parse ( vector function index ) *
  964. */
  965. var indicesu32 = readU32();
  966. var indices = indicesu32.value;
  967. eatBytes(indicesu32.nextIndex);
  968. dump([indices], "num indices");
  969. var indexValues = [];
  970. for (var _i5 = 0; _i5 < indices; _i5++) {
  971. var indexu32 = readU32();
  972. var index = indexu32.value;
  973. eatBytes(indexu32.nextIndex);
  974. dump([index], "index");
  975. indexValues.push(t.indexLiteral(index));
  976. }
  977. var elemNode = function () {
  978. var endLoc = getPosition();
  979. return t.withLoc(t.elem(t.indexLiteral(tableindex), instr, indexValues), endLoc, _startLoc12);
  980. }();
  981. elems.push(elemNode);
  982. }
  983. return elems;
  984. } // https://webassembly.github.io/spec/core/binary/types.html#memory-types
  985. function parseMemoryType(i) {
  986. var limits = parseLimits();
  987. return t.memory(limits, t.indexLiteral(i));
  988. } // https://webassembly.github.io/spec/binary/modules.html#table-section
  989. function parseTableSection(numberOfElements) {
  990. var tables = [];
  991. dump([numberOfElements], "num elements");
  992. for (var i = 0; i < numberOfElements; i++) {
  993. var tablesNode = parseTableType(i);
  994. state.tablesInModule.push(tablesNode);
  995. tables.push(tablesNode);
  996. }
  997. return tables;
  998. } // https://webassembly.github.io/spec/binary/modules.html#memory-section
  999. function parseMemorySection(numberOfElements) {
  1000. var memories = [];
  1001. dump([numberOfElements], "num elements");
  1002. for (var i = 0; i < numberOfElements; i++) {
  1003. var memoryNode = parseMemoryType(i);
  1004. state.memoriesInModule.push(memoryNode);
  1005. memories.push(memoryNode);
  1006. }
  1007. return memories;
  1008. } // https://webassembly.github.io/spec/binary/modules.html#binary-startsec
  1009. function parseStartSection() {
  1010. var startLoc = getPosition();
  1011. var u32 = readU32();
  1012. var startFuncIndex = u32.value;
  1013. eatBytes(u32.nextIndex);
  1014. dump([startFuncIndex], "index");
  1015. return function () {
  1016. var endLoc = getPosition();
  1017. return t.withLoc(t.start(t.indexLiteral(startFuncIndex)), endLoc, startLoc);
  1018. }();
  1019. } // https://webassembly.github.io/spec/binary/modules.html#data-section
  1020. function parseDataSection(numberOfElements) {
  1021. var dataEntries = [];
  1022. dump([numberOfElements], "num elements");
  1023. for (var i = 0; i < numberOfElements; i++) {
  1024. var memoryIndexu32 = readU32();
  1025. var memoryIndex = memoryIndexu32.value;
  1026. eatBytes(memoryIndexu32.nextIndex);
  1027. dump([memoryIndex], "memory index");
  1028. var instrs = [];
  1029. parseInstructionBlock(instrs);
  1030. var hasExtraInstrs = instrs.filter(function (i) {
  1031. return i.id !== "end";
  1032. }).length !== 1;
  1033. if (hasExtraInstrs) {
  1034. throw new _helperApiError.CompileError("data section offset must be a single instruction");
  1035. }
  1036. var bytes = parseVec(function (b) {
  1037. return b;
  1038. });
  1039. dump([], "init");
  1040. dataEntries.push(t.data(t.memIndexLiteral(memoryIndex), instrs[0], t.byteArray(bytes)));
  1041. }
  1042. return dataEntries;
  1043. } // https://webassembly.github.io/spec/binary/modules.html#binary-section
  1044. function parseSection(sectionIndex) {
  1045. var sectionId = readByte();
  1046. eatBytes(1);
  1047. if (sectionId >= sectionIndex || sectionIndex === _helperWasmBytecode.default.sections.custom) {
  1048. sectionIndex = sectionId + 1;
  1049. } else {
  1050. if (sectionId !== _helperWasmBytecode.default.sections.custom) throw new _helperApiError.CompileError("Unexpected section: " + toHex(sectionId));
  1051. }
  1052. var nextSectionIndex = sectionIndex;
  1053. var startOffset = offset;
  1054. var startLoc = getPosition();
  1055. var u32 = readU32();
  1056. var sectionSizeInBytes = u32.value;
  1057. eatBytes(u32.nextIndex);
  1058. var sectionSizeInBytesNode = function () {
  1059. var endLoc = getPosition();
  1060. return t.withLoc(t.numberLiteralFromRaw(sectionSizeInBytes), endLoc, startLoc);
  1061. }();
  1062. switch (sectionId) {
  1063. case _helperWasmBytecode.default.sections.type:
  1064. {
  1065. dumpSep("section Type");
  1066. dump([sectionId], "section code");
  1067. dump([sectionSizeInBytes], "section size");
  1068. var _startLoc13 = getPosition();
  1069. var _u = readU32();
  1070. var numberOfTypes = _u.value;
  1071. eatBytes(_u.nextIndex);
  1072. var _metadata = t.sectionMetadata("type", startOffset, sectionSizeInBytesNode, function () {
  1073. var endLoc = getPosition();
  1074. return t.withLoc(t.numberLiteralFromRaw(numberOfTypes), endLoc, _startLoc13);
  1075. }());
  1076. var _nodes = parseTypeSection(numberOfTypes);
  1077. return {
  1078. nodes: _nodes,
  1079. metadata: _metadata,
  1080. nextSectionIndex: nextSectionIndex
  1081. };
  1082. }
  1083. case _helperWasmBytecode.default.sections.table:
  1084. {
  1085. dumpSep("section Table");
  1086. dump([sectionId], "section code");
  1087. dump([sectionSizeInBytes], "section size");
  1088. var _startLoc14 = getPosition();
  1089. var _u2 = readU32();
  1090. var numberOfTable = _u2.value;
  1091. eatBytes(_u2.nextIndex);
  1092. dump([numberOfTable], "num tables");
  1093. var _metadata2 = t.sectionMetadata("table", startOffset, sectionSizeInBytesNode, function () {
  1094. var endLoc = getPosition();
  1095. return t.withLoc(t.numberLiteralFromRaw(numberOfTable), endLoc, _startLoc14);
  1096. }());
  1097. var _nodes2 = parseTableSection(numberOfTable);
  1098. return {
  1099. nodes: _nodes2,
  1100. metadata: _metadata2,
  1101. nextSectionIndex: nextSectionIndex
  1102. };
  1103. }
  1104. case _helperWasmBytecode.default.sections.import:
  1105. {
  1106. dumpSep("section Import");
  1107. dump([sectionId], "section code");
  1108. dump([sectionSizeInBytes], "section size");
  1109. var _startLoc15 = getPosition();
  1110. var numberOfImportsu32 = readU32();
  1111. var numberOfImports = numberOfImportsu32.value;
  1112. eatBytes(numberOfImportsu32.nextIndex);
  1113. dump([numberOfImports], "number of imports");
  1114. var _metadata3 = t.sectionMetadata("import", startOffset, sectionSizeInBytesNode, function () {
  1115. var endLoc = getPosition();
  1116. return t.withLoc(t.numberLiteralFromRaw(numberOfImports), endLoc, _startLoc15);
  1117. }());
  1118. var _nodes3 = parseImportSection(numberOfImports);
  1119. return {
  1120. nodes: _nodes3,
  1121. metadata: _metadata3,
  1122. nextSectionIndex: nextSectionIndex
  1123. };
  1124. }
  1125. case _helperWasmBytecode.default.sections.func:
  1126. {
  1127. dumpSep("section Function");
  1128. dump([sectionId], "section code");
  1129. dump([sectionSizeInBytes], "section size");
  1130. var _startLoc16 = getPosition();
  1131. var numberOfFunctionsu32 = readU32();
  1132. var numberOfFunctions = numberOfFunctionsu32.value;
  1133. eatBytes(numberOfFunctionsu32.nextIndex);
  1134. var _metadata4 = t.sectionMetadata("func", startOffset, sectionSizeInBytesNode, function () {
  1135. var endLoc = getPosition();
  1136. return t.withLoc(t.numberLiteralFromRaw(numberOfFunctions), endLoc, _startLoc16);
  1137. }());
  1138. parseFuncSection(numberOfFunctions);
  1139. var _nodes4 = [];
  1140. return {
  1141. nodes: _nodes4,
  1142. metadata: _metadata4,
  1143. nextSectionIndex: nextSectionIndex
  1144. };
  1145. }
  1146. case _helperWasmBytecode.default.sections.export:
  1147. {
  1148. dumpSep("section Export");
  1149. dump([sectionId], "section code");
  1150. dump([sectionSizeInBytes], "section size");
  1151. var _startLoc17 = getPosition();
  1152. var _u3 = readU32();
  1153. var numberOfExport = _u3.value;
  1154. eatBytes(_u3.nextIndex);
  1155. var _metadata5 = t.sectionMetadata("export", startOffset, sectionSizeInBytesNode, function () {
  1156. var endLoc = getPosition();
  1157. return t.withLoc(t.numberLiteralFromRaw(numberOfExport), endLoc, _startLoc17);
  1158. }());
  1159. parseExportSection(numberOfExport);
  1160. var _nodes5 = [];
  1161. return {
  1162. nodes: _nodes5,
  1163. metadata: _metadata5,
  1164. nextSectionIndex: nextSectionIndex
  1165. };
  1166. }
  1167. case _helperWasmBytecode.default.sections.code:
  1168. {
  1169. dumpSep("section Code");
  1170. dump([sectionId], "section code");
  1171. dump([sectionSizeInBytes], "section size");
  1172. var _startLoc18 = getPosition();
  1173. var _u4 = readU32();
  1174. var numberOfFuncs = _u4.value;
  1175. eatBytes(_u4.nextIndex);
  1176. var _metadata6 = t.sectionMetadata("code", startOffset, sectionSizeInBytesNode, function () {
  1177. var endLoc = getPosition();
  1178. return t.withLoc(t.numberLiteralFromRaw(numberOfFuncs), endLoc, _startLoc18);
  1179. }());
  1180. if (opts.ignoreCodeSection === true) {
  1181. var remainingBytes = sectionSizeInBytes - _u4.nextIndex;
  1182. eatBytes(remainingBytes); // eat the entire section
  1183. } else {
  1184. parseCodeSection(numberOfFuncs);
  1185. }
  1186. var _nodes6 = [];
  1187. return {
  1188. nodes: _nodes6,
  1189. metadata: _metadata6,
  1190. nextSectionIndex: nextSectionIndex
  1191. };
  1192. }
  1193. case _helperWasmBytecode.default.sections.start:
  1194. {
  1195. dumpSep("section Start");
  1196. dump([sectionId], "section code");
  1197. dump([sectionSizeInBytes], "section size");
  1198. var _metadata7 = t.sectionMetadata("start", startOffset, sectionSizeInBytesNode);
  1199. var _nodes7 = [parseStartSection()];
  1200. return {
  1201. nodes: _nodes7,
  1202. metadata: _metadata7,
  1203. nextSectionIndex: nextSectionIndex
  1204. };
  1205. }
  1206. case _helperWasmBytecode.default.sections.element:
  1207. {
  1208. dumpSep("section Element");
  1209. dump([sectionId], "section code");
  1210. dump([sectionSizeInBytes], "section size");
  1211. var _startLoc19 = getPosition();
  1212. var numberOfElementsu32 = readU32();
  1213. var numberOfElements = numberOfElementsu32.value;
  1214. eatBytes(numberOfElementsu32.nextIndex);
  1215. var _metadata8 = t.sectionMetadata("element", startOffset, sectionSizeInBytesNode, function () {
  1216. var endLoc = getPosition();
  1217. return t.withLoc(t.numberLiteralFromRaw(numberOfElements), endLoc, _startLoc19);
  1218. }());
  1219. var _nodes8 = parseElemSection(numberOfElements);
  1220. return {
  1221. nodes: _nodes8,
  1222. metadata: _metadata8,
  1223. nextSectionIndex: nextSectionIndex
  1224. };
  1225. }
  1226. case _helperWasmBytecode.default.sections.global:
  1227. {
  1228. dumpSep("section Global");
  1229. dump([sectionId], "section code");
  1230. dump([sectionSizeInBytes], "section size");
  1231. var _startLoc20 = getPosition();
  1232. var numberOfGlobalsu32 = readU32();
  1233. var numberOfGlobals = numberOfGlobalsu32.value;
  1234. eatBytes(numberOfGlobalsu32.nextIndex);
  1235. var _metadata9 = t.sectionMetadata("global", startOffset, sectionSizeInBytesNode, function () {
  1236. var endLoc = getPosition();
  1237. return t.withLoc(t.numberLiteralFromRaw(numberOfGlobals), endLoc, _startLoc20);
  1238. }());
  1239. var _nodes9 = parseGlobalSection(numberOfGlobals);
  1240. return {
  1241. nodes: _nodes9,
  1242. metadata: _metadata9,
  1243. nextSectionIndex: nextSectionIndex
  1244. };
  1245. }
  1246. case _helperWasmBytecode.default.sections.memory:
  1247. {
  1248. dumpSep("section Memory");
  1249. dump([sectionId], "section code");
  1250. dump([sectionSizeInBytes], "section size");
  1251. var _startLoc21 = getPosition();
  1252. var _numberOfElementsu = readU32();
  1253. var _numberOfElements = _numberOfElementsu.value;
  1254. eatBytes(_numberOfElementsu.nextIndex);
  1255. var _metadata10 = t.sectionMetadata("memory", startOffset, sectionSizeInBytesNode, function () {
  1256. var endLoc = getPosition();
  1257. return t.withLoc(t.numberLiteralFromRaw(_numberOfElements), endLoc, _startLoc21);
  1258. }());
  1259. var _nodes10 = parseMemorySection(_numberOfElements);
  1260. return {
  1261. nodes: _nodes10,
  1262. metadata: _metadata10,
  1263. nextSectionIndex: nextSectionIndex
  1264. };
  1265. }
  1266. case _helperWasmBytecode.default.sections.data:
  1267. {
  1268. dumpSep("section Data");
  1269. dump([sectionId], "section code");
  1270. dump([sectionSizeInBytes], "section size");
  1271. var _metadata11 = t.sectionMetadata("data", startOffset, sectionSizeInBytesNode);
  1272. var _startLoc22 = getPosition();
  1273. var _numberOfElementsu2 = readU32();
  1274. var _numberOfElements2 = _numberOfElementsu2.value;
  1275. eatBytes(_numberOfElementsu2.nextIndex);
  1276. _metadata11.vectorOfSize = function () {
  1277. var endLoc = getPosition();
  1278. return t.withLoc(t.numberLiteralFromRaw(_numberOfElements2), endLoc, _startLoc22);
  1279. }();
  1280. if (opts.ignoreDataSection === true) {
  1281. var _remainingBytes = sectionSizeInBytes - _numberOfElementsu2.nextIndex;
  1282. eatBytes(_remainingBytes); // eat the entire section
  1283. dumpSep("ignore data (" + sectionSizeInBytes + " bytes)");
  1284. return {
  1285. nodes: [],
  1286. metadata: _metadata11,
  1287. nextSectionIndex: nextSectionIndex
  1288. };
  1289. } else {
  1290. var _nodes11 = parseDataSection(_numberOfElements2);
  1291. return {
  1292. nodes: _nodes11,
  1293. metadata: _metadata11,
  1294. nextSectionIndex: nextSectionIndex
  1295. };
  1296. }
  1297. }
  1298. case _helperWasmBytecode.default.sections.custom:
  1299. {
  1300. dumpSep("section Custom");
  1301. dump([sectionId], "section code");
  1302. dump([sectionSizeInBytes], "section size");
  1303. var _metadata12 = [t.sectionMetadata("custom", startOffset, sectionSizeInBytesNode)];
  1304. var sectionName = readUTF8String();
  1305. eatBytes(sectionName.nextIndex);
  1306. dump([], "section name (".concat(sectionName.value, ")"));
  1307. var _remainingBytes2 = sectionSizeInBytes - sectionName.nextIndex;
  1308. if (sectionName.value === "name") {
  1309. var initialOffset = offset;
  1310. try {
  1311. _metadata12.push.apply(_metadata12, _toConsumableArray(parseNameSection(_remainingBytes2)));
  1312. } catch (e) {
  1313. console.warn("Failed to decode custom \"name\" section @".concat(offset, "; ignoring (").concat(e.message, ")."));
  1314. eatBytes(offset - (initialOffset + _remainingBytes2));
  1315. }
  1316. } else if (sectionName.value === "producers") {
  1317. var _initialOffset = offset;
  1318. try {
  1319. _metadata12.push(parseProducersSection());
  1320. } catch (e) {
  1321. console.warn("Failed to decode custom \"producers\" section @".concat(offset, "; ignoring (").concat(e.message, ")."));
  1322. eatBytes(offset - (_initialOffset + _remainingBytes2));
  1323. }
  1324. } else {
  1325. // We don't parse the custom section
  1326. eatBytes(_remainingBytes2);
  1327. dumpSep("ignore custom " + JSON.stringify(sectionName.value) + " section (" + _remainingBytes2 + " bytes)");
  1328. }
  1329. return {
  1330. nodes: [],
  1331. metadata: _metadata12,
  1332. nextSectionIndex: nextSectionIndex
  1333. };
  1334. }
  1335. }
  1336. throw new _helperApiError.CompileError("Unexpected section: " + toHex(sectionId));
  1337. }
  1338. parseModuleHeader();
  1339. parseVersion();
  1340. var moduleFields = [];
  1341. var sectionIndex = 0;
  1342. var moduleMetadata = {
  1343. sections: [],
  1344. functionNames: [],
  1345. localNames: [],
  1346. producers: []
  1347. };
  1348. /**
  1349. * All the generate declaration are going to be stored in our state
  1350. */
  1351. while (offset < buf.length) {
  1352. var _parseSection = parseSection(sectionIndex),
  1353. _nodes12 = _parseSection.nodes,
  1354. _metadata13 = _parseSection.metadata,
  1355. nextSectionIndex = _parseSection.nextSectionIndex;
  1356. moduleFields.push.apply(moduleFields, _toConsumableArray(_nodes12));
  1357. var metadataArray = Array.isArray(_metadata13) ? _metadata13 : [_metadata13];
  1358. metadataArray.forEach(function (metadataItem) {
  1359. if (metadataItem.type === "FunctionNameMetadata") {
  1360. moduleMetadata.functionNames.push(metadataItem);
  1361. } else if (metadataItem.type === "LocalNameMetadata") {
  1362. moduleMetadata.localNames.push(metadataItem);
  1363. } else if (metadataItem.type === "ProducersSectionMetadata") {
  1364. moduleMetadata.producers.push(metadataItem);
  1365. } else {
  1366. moduleMetadata.sections.push(metadataItem);
  1367. }
  1368. }); // Ignore custom section
  1369. if (nextSectionIndex) {
  1370. sectionIndex = nextSectionIndex;
  1371. }
  1372. }
  1373. /**
  1374. * Transform the state into AST nodes
  1375. */
  1376. var funcIndex = 0;
  1377. state.functionsInModule.forEach(function (func) {
  1378. var params = func.signature.params;
  1379. var result = func.signature.result;
  1380. var body = []; // External functions doesn't provide any code, can skip it here
  1381. if (func.isExternal === true) {
  1382. return;
  1383. }
  1384. var decodedElementInCodeSection = state.elementsInCodeSection[funcIndex];
  1385. if (opts.ignoreCodeSection === false) {
  1386. if (typeof decodedElementInCodeSection === "undefined") {
  1387. throw new _helperApiError.CompileError("func " + toHex(funcIndex) + " code not found");
  1388. }
  1389. body = decodedElementInCodeSection.code;
  1390. }
  1391. funcIndex++;
  1392. var funcNode = t.func(func.id, t.signature(params, result), body);
  1393. if (func.isExternal === true) {
  1394. funcNode.isExternal = func.isExternal;
  1395. } // Add function position in the binary if possible
  1396. if (opts.ignoreCodeSection === false) {
  1397. var _startLoc23 = decodedElementInCodeSection.startLoc,
  1398. endLoc = decodedElementInCodeSection.endLoc,
  1399. bodySize = decodedElementInCodeSection.bodySize;
  1400. funcNode = t.withLoc(funcNode, endLoc, _startLoc23);
  1401. funcNode.metadata = {
  1402. bodySize: bodySize
  1403. };
  1404. }
  1405. moduleFields.push(funcNode);
  1406. });
  1407. state.elementsInExportSection.forEach(function (moduleExport) {
  1408. /**
  1409. * If the export has no id, we won't be able to call it from the outside
  1410. * so we can omit it
  1411. */
  1412. if (moduleExport.id != null) {
  1413. moduleFields.push(t.withLoc(t.moduleExport(moduleExport.name, t.moduleExportDescr(moduleExport.type, moduleExport.id)), moduleExport.endLoc, moduleExport.startLoc));
  1414. }
  1415. });
  1416. dumpSep("end of program");
  1417. var module = t.module(null, moduleFields, t.moduleMetadata(moduleMetadata.sections, moduleMetadata.functionNames, moduleMetadata.localNames, moduleMetadata.producers));
  1418. return t.program([module]);
  1419. }