decoder.js 47 KB

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