WebAssemblyParser.js 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const t = require("@webassemblyjs/ast");
  7. const { moduleContextFromModuleAST } = require("@webassemblyjs/ast");
  8. const { decode } = require("@webassemblyjs/wasm-parser");
  9. const Parser = require("../Parser");
  10. const StaticExportsDependency = require("../dependencies/StaticExportsDependency");
  11. const WebAssemblyExportImportedDependency = require("../dependencies/WebAssemblyExportImportedDependency");
  12. const WebAssemblyImportDependency = require("../dependencies/WebAssemblyImportDependency");
  13. /** @typedef {import("@webassemblyjs/ast").ModuleImport} ModuleImport */
  14. /** @typedef {import("@webassemblyjs/ast").NumberLiteral} NumberLiteral */
  15. /** @typedef {import("../Module")} Module */
  16. /** @typedef {import("../Module").BuildInfo} BuildInfo */
  17. /** @typedef {import("../Module").BuildMeta} BuildMeta */
  18. /** @typedef {import("../Parser").ParserState} ParserState */
  19. /** @typedef {import("../Parser").PreparsedAst} PreparsedAst */
  20. const JS_COMPAT_TYPES = new Set(["i32", "i64", "f32", "f64", "externref"]);
  21. /**
  22. * @param {t.Signature} signature the func signature
  23. * @returns {null | string} the type incompatible with js types
  24. */
  25. const getJsIncompatibleType = signature => {
  26. for (const param of signature.params) {
  27. if (!JS_COMPAT_TYPES.has(param.valtype)) {
  28. return `${param.valtype} as parameter`;
  29. }
  30. }
  31. for (const type of signature.results) {
  32. if (!JS_COMPAT_TYPES.has(type)) return `${type} as result`;
  33. }
  34. return null;
  35. };
  36. /**
  37. * TODO why are there two different Signature types?
  38. * @param {t.FuncSignature} signature the func signature
  39. * @returns {null | string} the type incompatible with js types
  40. */
  41. const getJsIncompatibleTypeOfFuncSignature = signature => {
  42. for (const param of signature.args) {
  43. if (!JS_COMPAT_TYPES.has(param)) {
  44. return `${param} as parameter`;
  45. }
  46. }
  47. for (const type of signature.result) {
  48. if (!JS_COMPAT_TYPES.has(type)) return `${type} as result`;
  49. }
  50. return null;
  51. };
  52. const decoderOpts = {
  53. ignoreCodeSection: true,
  54. ignoreDataSection: true,
  55. // this will avoid having to lookup with identifiers in the ModuleContext
  56. ignoreCustomNameSection: true
  57. };
  58. class WebAssemblyParser extends Parser {
  59. /**
  60. * @param {{}=} options parser options
  61. */
  62. constructor(options) {
  63. super();
  64. this.hooks = Object.freeze({});
  65. this.options = options;
  66. }
  67. /**
  68. * @param {string | Buffer | PreparsedAst} source the source to parse
  69. * @param {ParserState} state the parser state
  70. * @returns {ParserState} the parser state
  71. */
  72. parse(source, state) {
  73. if (!Buffer.isBuffer(source)) {
  74. throw new Error("WebAssemblyParser input must be a Buffer");
  75. }
  76. // flag it as ESM
  77. /** @type {BuildInfo} */
  78. (state.module.buildInfo).strict = true;
  79. /** @type {BuildMeta} */
  80. (state.module.buildMeta).exportsType = "namespace";
  81. // parse it
  82. const program = decode(source, decoderOpts);
  83. const module = program.body[0];
  84. const moduleContext = moduleContextFromModuleAST(module);
  85. // extract imports and exports
  86. /** @type {string[]} */
  87. const exports = [];
  88. const buildMeta = /** @type {BuildMeta} */ (state.module.buildMeta);
  89. /** @type {Record<string, string> | undefined} */
  90. let jsIncompatibleExports = (buildMeta.jsIncompatibleExports = undefined);
  91. /** @type {(ModuleImport | null)[]} */
  92. const importedGlobals = [];
  93. t.traverse(module, {
  94. ModuleExport({ node }) {
  95. const descriptor = node.descr;
  96. if (descriptor.exportType === "Func") {
  97. const funcIdx = descriptor.id.value;
  98. /** @type {t.FuncSignature} */
  99. const funcSignature = moduleContext.getFunction(funcIdx);
  100. const incompatibleType =
  101. getJsIncompatibleTypeOfFuncSignature(funcSignature);
  102. if (incompatibleType) {
  103. if (jsIncompatibleExports === undefined) {
  104. jsIncompatibleExports =
  105. /** @type {BuildMeta} */
  106. (state.module.buildMeta).jsIncompatibleExports = {};
  107. }
  108. jsIncompatibleExports[node.name] = incompatibleType;
  109. }
  110. }
  111. exports.push(node.name);
  112. if (node.descr && node.descr.exportType === "Global") {
  113. const refNode =
  114. importedGlobals[/** @type {NumberLiteral} */ (node.descr.id).value];
  115. if (refNode) {
  116. const dep = new WebAssemblyExportImportedDependency(
  117. node.name,
  118. refNode.module,
  119. refNode.name,
  120. /** @type {string} */
  121. (refNode.descr.valtype)
  122. );
  123. state.module.addDependency(dep);
  124. }
  125. }
  126. },
  127. Global({ node }) {
  128. const init = node.init[0];
  129. let importNode = null;
  130. if (init.id === "get_global") {
  131. const globalIdx = init.args[0].value;
  132. if (globalIdx < importedGlobals.length) {
  133. importNode = importedGlobals[globalIdx];
  134. }
  135. }
  136. importedGlobals.push(importNode);
  137. },
  138. ModuleImport({ node }) {
  139. /** @type {false | string} */
  140. let onlyDirectImport = false;
  141. if (t.isMemory(node.descr) === true) {
  142. onlyDirectImport = "Memory";
  143. } else if (t.isTable(node.descr) === true) {
  144. onlyDirectImport = "Table";
  145. } else if (t.isFuncImportDescr(node.descr) === true) {
  146. const incompatibleType = getJsIncompatibleType(
  147. /** @type {t.Signature} */
  148. (node.descr.signature)
  149. );
  150. if (incompatibleType) {
  151. onlyDirectImport = `Non-JS-compatible Func Signature (${incompatibleType})`;
  152. }
  153. } else if (t.isGlobalType(node.descr) === true) {
  154. const type = /** @type {string} */ (node.descr.valtype);
  155. if (!JS_COMPAT_TYPES.has(type)) {
  156. onlyDirectImport = `Non-JS-compatible Global Type (${type})`;
  157. }
  158. }
  159. const dep = new WebAssemblyImportDependency(
  160. node.module,
  161. node.name,
  162. node.descr,
  163. onlyDirectImport
  164. );
  165. state.module.addDependency(dep);
  166. if (t.isGlobalType(node.descr)) {
  167. importedGlobals.push(node);
  168. }
  169. }
  170. });
  171. state.module.addDependency(new StaticExportsDependency(exports, false));
  172. return state;
  173. }
  174. }
  175. module.exports = WebAssemblyParser;