Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

decoder.js 51KB

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