decoder.js 53 KB

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