decoder.js 60 KB

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