decoder.js 52 KB

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