10
0

decoder.js 57 KB

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