decoder.js 53 KB

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