decoder.js 56 KB

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