WebAssemblyParser.js 5.8 KB

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