decoder.js 49 KB

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