decoder.js 47 KB

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