decoder.js 53 KB

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