space-data-module-sdk 0.9.14 → 0.9.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -385,6 +385,38 @@ If a runtime cannot interoperate with the guest pthread contract directly,
385
385
  document that as a wrapper requirement instead of changing the guest artifact
386
386
  semantics.
387
387
 
388
+ ## WebAssembly SIMD (opt-in)
389
+
390
+ `compileModuleFromSource({ simd128: true })` compiles the module's own code and its `libraries` with
391
+ `-msimd128`: `__wasm_simd128__` is defined, clang vector types and `wasm_simd128.h` lower to `v128`
392
+ instructions, and the compiler may vectorize. It needs `threadModel` `"wasi-sequential"` or
393
+ `"emscripten-pthreads"` (the clang `wasm32-wasip1-threads` toolchain); the legacy `"single-thread"`
394
+ model refuses it. The generated manifest exports and invoke bridge keep their flags.
395
+
396
+ - A module that does not opt in compiles with exactly the flags it always did: its `module.wasm`
397
+ and guest-link object are byte-identical to SDK 0.9.14's.
398
+ - The artifact guard (`src/compiler/simdArtifactGuard.js`) holds the emitted wasm to the declaration:
399
+ an opted-in build must declare `simd128` in `target_features`; relaxed-SIMD is always refused (its
400
+ results are implementation-defined and would differ between the browser and WasmEdge); and an
401
+ artifact with a function body the scanner cannot decode is refused, because SIMD inside it would go
402
+ uncounted.
403
+ - SIMD without the option is NOT refused yet. A module built by its own clang driver with `-msimd128`
404
+ (a driver named by `SDN_WASI_CLANGXX`, as the modules `propagator/ffm` and `analysis/density-calibration`
405
+ do), or with a per-function `target("simd128")` attribute, still compiles. Its SIMD is recorded as if
406
+ the module had declared it (`result.simd128` with `undeclared: true`, `result.guestLink.simd128`,
407
+ `metadata.json`), and a warning (`result.warnings`, and the process warning `SDM_SIMD128_UNDECLARED`)
408
+ tells the module to pass `simd128: true`. Undeclared SIMD will become an error in a later release.
409
+ - The use is recorded: `result.simd128` (`requested`, `undeclared`, `declared`, `used`,
410
+ `instructionCount`, ...), `result.guestLink.simd128`, the guest-link bundle metadata and
411
+ `writeGuestLinkFiles`' `metadata.json` (`simd128: true`, only for a module that uses SIMD), and the
412
+ artifact's own `target_features` section. The plugin manifest FlatBuffer has no field for build
413
+ features and is unchanged.
414
+ - Runtimes: every current browser engine and WasmEdge 0.16.4 run fixed-width SIMD, interpreted and
415
+ AOT (`wasmedge compile`); no exception handling is involved.
416
+ - Proof: `node scripts/e2e/simd128-option.mjs` builds one kernel with and without the option on both
417
+ thread models, runs it in headless Chromium and native WasmEdge (and as WasmEdge AOT) with
418
+ byte-identical responses at 1, 2 and 4 threads, and checks the unchanged build is byte-identical.
419
+
388
420
  ## Browser + WasmEdge Isomorphism
389
421
 
390
422
  The supported isomorphic profile and browser edge shims are documented in
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "space-data-module-sdk",
3
- "version": "0.9.14",
3
+ "version": "0.9.15",
4
4
  "license": "Apache-2.0",
5
5
  "description": "Module SDK for building, validating, signing, and deploying WebAssembly modules on the Space Data Network.",
6
6
  "type": "module",
@@ -48,6 +48,11 @@ import {
48
48
  assertSequentialFlagsAbsent,
49
49
  PTHREAD_FINAL_LINK_FLAGS,
50
50
  } from "./pthreadArtifactGuard.js";
51
+ import {
52
+ SIMD128_COMPILE_FLAG,
53
+ SIMD128_UNDECLARED_WARNING_CODE,
54
+ assertSimdArtifact,
55
+ } from "./simdArtifactGuard.js";
51
56
  import { resolveWasiThreadsToolchain } from "./wasiThreadsToolchain.js";
52
57
  import { encodePluginManifest, toEmbeddedPluginManifest } from "../manifest/index.js";
53
58
  import {
@@ -399,6 +404,35 @@ function buildSourceCompilerArgs(options = {}) {
399
404
  return args;
400
405
  }
401
406
 
407
+ // WebAssembly SIMD is an OPT-IN of the module, never a default: a module that does
408
+ // not ask for it compiles with exactly the flags it always has. It is a flag of the
409
+ // sanctioned clang wasm32-wasip1-threads toolchain, so the legacy single-thread
410
+ // (Emscripten) model refuses it rather than ship a lane no guard or runtime proof
411
+ // covers. See simdArtifactGuard.js for what the emitted artifact is held to.
412
+ function resolveSimd128(value, threadModel) {
413
+ if (value === undefined || value === null || value === false) {
414
+ return false;
415
+ }
416
+ if (value !== true) {
417
+ throw new Error(`simd128 must be true or false, got "${String(value)}".`);
418
+ }
419
+ if (threadModel === ModuleThreadModel.SINGLE_THREAD) {
420
+ throw new Error(
421
+ `simd128 requires threadModel "${ModuleThreadModel.WASI_SEQUENTIAL}" or ` +
422
+ `"${ModuleThreadModel.EMSCRIPTEN_PTHREADS}": SIMD is built by the clang ` +
423
+ `wasm32-wasip1-threads toolchain, not the legacy Emscripten "${ModuleThreadModel.SINGLE_THREAD}" model.`,
424
+ );
425
+ }
426
+ return true;
427
+ }
428
+
429
+ // The flags that apply to the module's OWN code - its source and its `libraries` -
430
+ // and not to the SDK's generated manifest exports and invoke bridge, which are the
431
+ // same objects (and the same compile-cache entries) with or without SIMD.
432
+ function moduleCodeCompilerArgs(options = {}) {
433
+ return options.simd128 === true ? [SIMD128_COMPILE_FLAG] : [];
434
+ }
435
+
402
436
  function normalizeThreadModel(value) {
403
437
  if (value === undefined || value === null || value === "") {
404
438
  return null;
@@ -635,6 +669,7 @@ function createGuestLinkBundleEntries(guestLink) {
635
669
  ...(Array.isArray(guestLink.capabilities)
636
670
  ? { capabilities: [...guestLink.capabilities] }
637
671
  : {}),
672
+ ...(guestLink.simd128 === true ? { simd128: true } : {}),
638
673
  },
639
674
  description: "Guest-link metadata for monolithic flow linking.",
640
675
  },
@@ -762,6 +797,7 @@ function normalizeArgv(argv, workDir) {
762
797
  // that runs them.
763
798
  async function resolveToolchainProfile(kind, { language, sourceCompilerCommand, compileOptions, tempDir }) {
764
799
  const sourceCompilerArgs = buildSourceCompilerArgs(compileOptions);
800
+ const moduleCodeArgs = moduleCodeCompilerArgs(compileOptions);
765
801
  if (kind === "wasi") {
766
802
  const toolchain = resolveWasiThreadsToolchain();
767
803
  const isCpp = String(language ?? "").toLowerCase().startsWith("c++");
@@ -789,6 +825,7 @@ async function resolveToolchainProfile(kind, { language, sourceCompilerCommand,
789
825
  ...(libraryLanguage === "c++" ? ["-std=c++17"] : []),
790
826
  ...extra,
791
827
  ...sourceCompilerArgs,
828
+ ...moduleCodeArgs,
792
829
  "-o",
793
830
  objectPath,
794
831
  ]
@@ -802,6 +839,7 @@ async function resolveToolchainProfile(kind, { language, sourceCompilerCommand,
802
839
  ...(isCpp ? ["-std=c++17"] : []),
803
840
  ...extra,
804
841
  ...sourceCompilerArgs,
842
+ ...moduleCodeArgs,
805
843
  "-o",
806
844
  objectPath,
807
845
  ]
@@ -1315,10 +1353,12 @@ export async function compileModuleFromSource(options = {}) {
1315
1353
  manifest,
1316
1354
  threadModel: options.threadModel,
1317
1355
  });
1356
+ const simd128 = resolveSimd128(options.simd128, threadModel);
1318
1357
  const compileOptions = {
1319
1358
  ...options,
1320
1359
  noEntry: includeCommandMain !== true,
1321
1360
  threadModel,
1361
+ simd128,
1322
1362
  guestLinkCapabilities: resolveGuestLinkCapabilities(
1323
1363
  manifest,
1324
1364
  options.guestLinkCapabilities,
@@ -1394,6 +1434,30 @@ export async function compileModuleFromSource(options = {}) {
1394
1434
  });
1395
1435
  }
1396
1436
 
1437
+ // The SIMD guard holds the artifact to the build's declaration: never relaxed-SIMD,
1438
+ // every function body decodable, and simd128 in target_features when the module
1439
+ // opted in. SIMD without the opt-in is recorded as if declared, with a warning
1440
+ // (it becomes an error in a later release). See simdArtifactGuard.js.
1441
+ const { warning: simd128Warning, ...simd128Report } = assertSimdArtifact(wasmBytes, {
1442
+ optedIn: simd128,
1443
+ // A path only when the caller asked for one: otherwise the artifact is in a temp dir that is gone.
1444
+ source: options.outputPath != null ? resolvedOutputPath : `the module "${manifest.pluginId ?? "unnamed"}"`,
1445
+ });
1446
+ const buildWarnings = [];
1447
+ if (simd128Warning) {
1448
+ buildWarnings.push(simd128Warning);
1449
+ process.emitWarning(simd128Warning, {
1450
+ type: "DeprecationWarning",
1451
+ code: SIMD128_UNDECLARED_WARNING_CODE,
1452
+ });
1453
+ }
1454
+ // Present only for a module that uses SIMD (declared or not): any other module has
1455
+ // a guest-link record byte-identical to what it always had.
1456
+ const guestLink =
1457
+ result.guestLink && (simd128 || simd128Report.undeclared)
1458
+ ? { ...result.guestLink, simd128: true }
1459
+ : result.guestLink;
1460
+
1397
1461
  // Validate the compiled artifact
1398
1462
  const report = await validateArtifactWithStandards({
1399
1463
  manifest,
@@ -1418,10 +1482,12 @@ export async function compileModuleFromSource(options = {}) {
1418
1482
  options.outputPath != null || keepTempDir ? resolvedOutputPath : null,
1419
1483
  tempDir: keepTempDir ? tempDir : null,
1420
1484
  wasmBytes,
1421
- guestLink: result.guestLink,
1485
+ guestLink,
1422
1486
  compileCache: result.cache,
1423
1487
  manifestWarnings: warnings,
1488
+ warnings: buildWarnings,
1424
1489
  threadFeatures,
1490
+ simd128: simd128Report,
1425
1491
  report,
1426
1492
  };
1427
1493
  } finally {
@@ -2,7 +2,8 @@
2
2
  //
3
3
  // <dir>/module-link.o the prefixed guest-link object
4
4
  // <dir>/metadata.json format, language, threadModel, symbolPrefix, methodSymbols
5
- // (+ libraries, below)
5
+ // (+ libraries, below; + simd128: true when the module
6
+ // opted in to WebAssembly SIMD)
6
7
  // <dir>/libraries/<name>-<version>-<sha12>.o
7
8
  // each shared library object the module links
8
9
  // (compile option `libraries`), listed in
@@ -62,6 +63,7 @@ export async function writeGuestLinkFiles(compilation, dir, metadata = {}) {
62
63
  symbolPrefix: guestLink.symbolPrefix,
63
64
  methodSymbols: guestLink.methodSymbols,
64
65
  ...(libraryEntries.length > 0 ? { libraries: libraryEntries } : {}),
66
+ ...(guestLink.simd128 === true ? { simd128: true } : {}),
65
67
  ...metadata,
66
68
  };
67
69
  // The SDK's one canonical writer of this metadata (the guest-link bundle entry
@@ -6,6 +6,7 @@ export type {
6
6
  ModuleLibrarySource,
7
7
  ModuleThreadModelName,
8
8
  ProtectedArtifact,
9
+ Simd128Report,
9
10
  } from "../index.js";
10
11
 
11
12
  export {
@@ -35,3 +36,81 @@ export {
35
36
  loadSharedEmception,
36
37
  withSharedEmception,
37
38
  } from "./emception.js";
39
+
40
+ // --- Artifact guards (src/compiler/pthreadArtifactGuard.js, simdArtifactGuard.js) ---
41
+
42
+ type WasmBytes = Uint8Array | ArrayBuffer | ArrayBufferView;
43
+
44
+ /** One memory of a wasm module, imported or declared. */
45
+ export interface WasmMemoryLimits {
46
+ source: "import" | "declared";
47
+ /** Present for an imported memory. */
48
+ module?: string;
49
+ name?: string;
50
+ flags: number;
51
+ min: number;
52
+ max: number | null;
53
+ shared: boolean;
54
+ growable: boolean;
55
+ }
56
+
57
+ /** What analyzeWasmThreadFeatures reads off a compiled artifact. */
58
+ export interface WasmThreadFeatures {
59
+ hasSharedMemory: boolean;
60
+ sharedMemory: WasmMemoryLimits | null;
61
+ memories: WasmMemoryLimits[];
62
+ usesAtomics: boolean;
63
+ atomicInstructionCount: number;
64
+ /** The names in the target_features section; null when the module has none. */
65
+ declaredFeatures: string[] | null;
66
+ isGrowableSharedMemory: boolean;
67
+ hasWasiThreadSpawnImport: boolean;
68
+ hasWasiThreadStartExport: boolean;
69
+ emscriptenThreadHooks: string[];
70
+ isIsomorphicPthreads: boolean;
71
+ }
72
+
73
+ export function analyzeWasmThreadFeatures(wasmBytes: WasmBytes): WasmThreadFeatures;
74
+ /** Throws unless the artifact is a real wasi-threads shared-memory/atomics module. */
75
+ export function assertPthreadArtifact(wasmBytes: WasmBytes, options?: { source?: string }): WasmThreadFeatures;
76
+ /** Throws unless the artifact is a self-contained wasi-sequential module built for the sanctioned target. */
77
+ export function assertSequentialArtifact(
78
+ wasmBytes: WasmBytes,
79
+ options?: { source?: string; target?: string },
80
+ ): WasmThreadFeatures;
81
+ /** Throws when an assembled emscripten-pthreads final-link argument list lost a mandated flag. */
82
+ export function assertPthreadFlagsPresent(args: string[], context?: { threadModel?: string }): void;
83
+ /** Throws when an assembled wasi-sequential final-link argument list carries a thread-memory flag. */
84
+ export function assertSequentialFlagsAbsent(args: string[], context?: { threadModel?: string }): string[];
85
+ export const PTHREAD_FINAL_LINK_FLAGS: readonly string[];
86
+ export const SANCTIONED_WASI_TARGET: "wasm32-wasip1-threads";
87
+
88
+ /** What analyzeWasmSimdFeatures reads off a compiled artifact. */
89
+ export interface WasmSimdFeatures {
90
+ /** target_features lists simd128 as used; null when the module has no target_features section. */
91
+ declared: boolean | null;
92
+ /** target_features lists relaxed-simd as used; null when the module has no target_features section. */
93
+ declaredRelaxed: boolean | null;
94
+ /** The code section holds fixed-width SIMD instructions. */
95
+ used: boolean;
96
+ instructionCount: number;
97
+ /** SIMD instructions beyond the fixed-width set (relaxed-simd and later proposals). */
98
+ relaxedInstructionCount: number;
99
+ /** Function bodies the scanner could not decode; their instructions are not counted. */
100
+ undecodableFunctions: number;
101
+ }
102
+
103
+ export function analyzeWasmSimdFeatures(wasmBytes: WasmBytes): WasmSimdFeatures;
104
+ /**
105
+ * Hold an artifact's SIMD use to the build's declaration. Throws on relaxed-SIMD, on a function body
106
+ * the scanner cannot decode, and on an opted-in build whose artifact does not declare simd128. SIMD
107
+ * without the opt-in is returned as `undeclared` with a `warning`, not thrown (an error in a later release).
108
+ */
109
+ export function assertSimdArtifact(
110
+ wasmBytes: WasmBytes,
111
+ options?: { optedIn?: boolean; source?: string },
112
+ ): WasmSimdFeatures & { requested: boolean; undeclared: boolean; warning?: string };
113
+ /** The clang flag the `simd128` compile option adds to a module's own code. */
114
+ export const SIMD128_COMPILE_FLAG: "-msimd128";
115
+ /** The process warning code emitted for an artifact that carries SIMD its build did not declare. */
116
+ export const SIMD128_UNDECLARED_WARNING_CODE: "SDM_SIMD128_UNDECLARED";
@@ -17,6 +17,13 @@ export {
17
17
  PTHREAD_FINAL_LINK_FLAGS,
18
18
  } from "./pthreadArtifactGuard.js";
19
19
 
20
+ export {
21
+ analyzeWasmSimdFeatures,
22
+ assertSimdArtifact,
23
+ SIMD128_COMPILE_FLAG,
24
+ SIMD128_UNDECLARED_WARNING_CODE,
25
+ } from "./simdArtifactGuard.js";
26
+
20
27
  export { resolveWasiThreadsToolchain } from "./wasiThreadsToolchain.js";
21
28
  export { writeGuestLinkFiles } from "./guestLinkFiles.js";
22
29
 
@@ -7,9 +7,10 @@
7
7
 
8
8
  import {
9
9
  decodeUnsignedLeb128,
10
- listWasmCustomSections,
11
10
  parseWasmModuleSections,
12
11
  } from "../bundle/wasm.js";
12
+ import { scanWasmCode } from "./wasmCodeScan.js";
13
+ import { readDeclaredFeatures } from "./wasmTargetFeatures.js";
13
14
 
14
15
  // Mirrors ModuleThreadModel.EMSCRIPTEN_PTHREADS in compileModule.js. Kept as a
15
16
  // local literal to avoid an import cycle (compileModule imports this module).
@@ -139,291 +140,6 @@ export function assertPthreadFlagsPresent(args, context = {}) {
139
140
  }
140
141
  }
141
142
 
142
- const VALTYPE_BYTES = new Set([0x7f, 0x7e, 0x7d, 0x7c, 0x7b, 0x70, 0x6f]);
143
-
144
- /**
145
- * Skip a LEB128-encoded integer (signedness is irrelevant for skipping — only
146
- * the continuation bits matter). Bounds-checked.
147
- */
148
- function skipLeb(bytes, cursor, end) {
149
- let position = cursor;
150
- while (position < end) {
151
- const byte = bytes[position++];
152
- if ((byte & 0x80) === 0) {
153
- return position;
154
- }
155
- }
156
- throw new Error("LEB128 immediate ran past end of function body.");
157
- }
158
-
159
- /** Decode a LEB128 value AND return the next offset (bounds-checked). */
160
- function readLeb(bytes, cursor, end) {
161
- if (cursor >= end) {
162
- throw new Error("LEB128 immediate ran past end of function body.");
163
- }
164
- const info = decodeUnsignedLeb128(bytes, cursor);
165
- if (info.nextOffset > end) {
166
- throw new Error("LEB128 immediate ran past end of function body.");
167
- }
168
- return info;
169
- }
170
-
171
- function skipBlockType(bytes, cursor, end) {
172
- if (cursor >= end) {
173
- throw new Error("Block type ran past end of function body.");
174
- }
175
- const byte = bytes[cursor];
176
- // 0x40 (empty), single-byte value types, and single-byte type indices all
177
- // consume exactly one byte; only a multi-byte (continuation-bit) type index
178
- // needs a full LEB skip.
179
- if ((byte & 0x80) !== 0) {
180
- return skipLeb(bytes, cursor, end);
181
- }
182
- return cursor + 1;
183
- }
184
-
185
- function skipMemArg(bytes, cursor, end) {
186
- const alignInfo = readLeb(bytes, cursor, end);
187
- let position = alignInfo.nextOffset;
188
- // Multi-memory / memory64: align bit 6 flags a following memory index.
189
- if ((alignInfo.value & 0x40) !== 0) {
190
- position = skipLeb(bytes, position, end);
191
- }
192
- return skipLeb(bytes, position, end);
193
- }
194
-
195
- function skipVec(bytes, cursor, end, bytesPerElement) {
196
- const countInfo = readLeb(bytes, cursor, end);
197
- let position = countInfo.nextOffset;
198
- for (let i = 0; i < countInfo.value; i += 1) {
199
- if (bytesPerElement === "leb") {
200
- position = skipLeb(bytes, position, end);
201
- } else {
202
- position += bytesPerElement;
203
- }
204
- }
205
- if (position > end) {
206
- throw new Error("Vector immediate ran past end of function body.");
207
- }
208
- return position;
209
- }
210
-
211
- /**
212
- * Walk one function body and count genuine 0xFE-prefixed atomic instructions.
213
- * This is a real instruction decoder — NOT a byte scan — so `0xFE` bytes that
214
- * appear inside i32.const / LEB128 / memarg immediates are never miscounted.
215
- */
216
- function countAtomicsInFunctionBody(bytes, bodyStart, bodyEnd) {
217
- let cursor = bodyStart;
218
- // Local declarations: vec of (count, valtype).
219
- const localVecCount = readLeb(bytes, cursor, bodyEnd);
220
- cursor = localVecCount.nextOffset;
221
- for (let i = 0; i < localVecCount.value; i += 1) {
222
- cursor = skipLeb(bytes, cursor, bodyEnd); // count
223
- if (cursor >= bodyEnd) {
224
- throw new Error("Local declaration ran past end of function body.");
225
- }
226
- // valtype: usually one byte; concrete heap types are a LEB.
227
- if ((bytes[cursor] & 0x80) !== 0) {
228
- cursor = skipLeb(bytes, cursor, bodyEnd);
229
- } else {
230
- cursor += 1;
231
- }
232
- }
233
-
234
- let atomics = 0;
235
- while (cursor < bodyEnd) {
236
- const opcode = bytes[cursor++];
237
- switch (opcode) {
238
- // Control / parametric with no immediates.
239
- case 0x00: // unreachable
240
- case 0x01: // nop
241
- case 0x05: // else
242
- case 0x0b: // end
243
- case 0x0f: // return
244
- case 0x1a: // drop
245
- case 0x1b: // select
246
- break;
247
- case 0x02: // block
248
- case 0x03: // loop
249
- case 0x04: // if
250
- cursor = skipBlockType(bytes, cursor, bodyEnd);
251
- break;
252
- case 0x0c: // br
253
- case 0x0d: // br_if
254
- cursor = skipLeb(bytes, cursor, bodyEnd);
255
- break;
256
- case 0x0e: {
257
- // br_table: vec<labelidx> + default labelidx
258
- cursor = skipVec(bytes, cursor, bodyEnd, "leb");
259
- cursor = skipLeb(bytes, cursor, bodyEnd);
260
- break;
261
- }
262
- case 0x10: // call
263
- case 0x12: // return_call
264
- cursor = skipLeb(bytes, cursor, bodyEnd);
265
- break;
266
- case 0x11: // call_indirect
267
- case 0x13: // return_call_indirect
268
- cursor = skipLeb(bytes, cursor, bodyEnd); // typeidx
269
- cursor = skipLeb(bytes, cursor, bodyEnd); // tableidx
270
- break;
271
- case 0x1c: // select t*
272
- cursor = skipVec(bytes, cursor, bodyEnd, 1);
273
- break;
274
- case 0x20: // local.get
275
- case 0x21: // local.set
276
- case 0x22: // local.tee
277
- case 0x23: // global.get
278
- case 0x24: // global.set
279
- case 0x25: // table.get
280
- case 0x26: // table.set
281
- cursor = skipLeb(bytes, cursor, bodyEnd);
282
- break;
283
- case 0x3f: // memory.size
284
- case 0x40: // memory.grow
285
- cursor = skipLeb(bytes, cursor, bodyEnd); // memidx (reserved)
286
- break;
287
- case 0x41: // i32.const
288
- case 0x42: // i64.const
289
- cursor = skipLeb(bytes, cursor, bodyEnd);
290
- break;
291
- case 0x43: // f32.const
292
- cursor += 4;
293
- break;
294
- case 0x44: // f64.const
295
- cursor += 8;
296
- break;
297
- case 0xd0: // ref.null
298
- if (cursor < bodyEnd && (bytes[cursor] & 0x80) !== 0) {
299
- cursor = skipLeb(bytes, cursor, bodyEnd);
300
- } else {
301
- cursor += 1;
302
- }
303
- break;
304
- case 0xd1: // ref.is_null
305
- break;
306
- case 0xd2: // ref.func
307
- cursor = skipLeb(bytes, cursor, bodyEnd);
308
- break;
309
- case 0xfc: {
310
- // Bulk-memory / saturating-truncation / table ops.
311
- const sub = readLeb(bytes, cursor, bodyEnd);
312
- cursor = sub.nextOffset;
313
- switch (sub.value) {
314
- case 0: case 1: case 2: case 3:
315
- case 4: case 5: case 6: case 7:
316
- break; // trunc_sat: no immediates
317
- case 8: // memory.init dataidx memidx
318
- cursor = skipLeb(bytes, cursor, bodyEnd);
319
- cursor = skipLeb(bytes, cursor, bodyEnd);
320
- break;
321
- case 9: // data.drop
322
- cursor = skipLeb(bytes, cursor, bodyEnd);
323
- break;
324
- case 10: // memory.copy memidx memidx
325
- cursor = skipLeb(bytes, cursor, bodyEnd);
326
- cursor = skipLeb(bytes, cursor, bodyEnd);
327
- break;
328
- case 11: // memory.fill memidx
329
- cursor = skipLeb(bytes, cursor, bodyEnd);
330
- break;
331
- case 12: // table.init elemidx tableidx
332
- case 14: // table.copy tableidx tableidx
333
- cursor = skipLeb(bytes, cursor, bodyEnd);
334
- cursor = skipLeb(bytes, cursor, bodyEnd);
335
- break;
336
- case 13: // elem.drop
337
- case 15: // table.grow
338
- case 16: // table.size
339
- case 17: // table.fill
340
- cursor = skipLeb(bytes, cursor, bodyEnd);
341
- break;
342
- default:
343
- break;
344
- }
345
- break;
346
- }
347
- case 0xfd: {
348
- // SIMD (not emitted by our pthreads builds, but decode defensively).
349
- const sub = readLeb(bytes, cursor, bodyEnd);
350
- cursor = sub.nextOffset;
351
- const op = sub.value;
352
- if (op <= 0x0b) {
353
- cursor = skipMemArg(bytes, cursor, bodyEnd); // v128 load/store
354
- } else if (op === 0x0c || op === 0x0d) {
355
- cursor += 16; // v128.const / i8x16.shuffle
356
- } else if (op >= 0x15 && op <= 0x22) {
357
- cursor += 1; // extract/replace lane
358
- } else if (op >= 0x54 && op <= 0x5b) {
359
- cursor = skipMemArg(bytes, cursor, bodyEnd);
360
- cursor += 1; // load/store lane
361
- } else if (op === 0x5c || op === 0x5d) {
362
- cursor = skipMemArg(bytes, cursor, bodyEnd); // load32/64_zero
363
- }
364
- break;
365
- }
366
- case 0xfe: {
367
- // Atomics / threads.
368
- const sub = readLeb(bytes, cursor, bodyEnd);
369
- cursor = sub.nextOffset;
370
- atomics += 1;
371
- if (sub.value === 0x03) {
372
- cursor += 1; // atomic.fence: one reserved byte, no memarg
373
- } else {
374
- cursor = skipMemArg(bytes, cursor, bodyEnd);
375
- }
376
- break;
377
- }
378
- default:
379
- if (opcode >= 0x28 && opcode <= 0x3e) {
380
- // Memory load/store family (i32.load .. i64.store32): each carries a
381
- // memarg (align + offset). Skipping this is what prevents 0xFE bytes
382
- // inside memory-offset immediates from being miscounted as atomics.
383
- cursor = skipMemArg(bytes, cursor, bodyEnd);
384
- break;
385
- }
386
- // All remaining MVP numeric/comparison/conversion opcodes
387
- // (0x45..0xc4, sign-extension, etc.) take no immediates.
388
- break;
389
- }
390
- if (cursor > bodyEnd) {
391
- throw new Error("Instruction immediate ran past end of function body.");
392
- }
393
- }
394
- return atomics;
395
- }
396
-
397
- function countAtomicInstructions(parsed) {
398
- const codeSection = parsed.sections.find((section) => section.id === 10);
399
- if (!codeSection) {
400
- return 0;
401
- }
402
- const bytes = parsed.bytes;
403
- let total = 0;
404
- try {
405
- let cursor = codeSection.payloadStart;
406
- const funcCount = readLeb(bytes, cursor, codeSection.payloadEnd);
407
- cursor = funcCount.nextOffset;
408
- for (let i = 0; i < funcCount.value && cursor < codeSection.payloadEnd; i += 1) {
409
- const sizeInfo = readLeb(bytes, cursor, codeSection.payloadEnd);
410
- const bodyStart = sizeInfo.nextOffset;
411
- const bodyEnd = bodyStart + sizeInfo.value;
412
- if (bodyEnd > codeSection.payloadEnd) {
413
- break;
414
- }
415
- try {
416
- total += countAtomicsInFunctionBody(bytes, bodyStart, bodyEnd);
417
- } catch {
418
- // Best-effort per function: skip an undecodable body rather than crash.
419
- }
420
- cursor = bodyEnd;
421
- }
422
- } catch {
423
- // Truncated / malformed code section: return best-effort count.
424
- }
425
- return total;
426
- }
427
143
 
428
144
  function readLimits(bytes, cursor, end) {
429
145
  const flags = bytes[cursor];
@@ -598,40 +314,6 @@ function isEmscriptenThreadHook(entry) {
598
314
  );
599
315
  }
600
316
 
601
- function readDeclaredFeatures(wasmBytes) {
602
- let customSections;
603
- try {
604
- customSections = listWasmCustomSections(wasmBytes);
605
- } catch {
606
- return null;
607
- }
608
- const featureSection = customSections.find(
609
- (section) => section.name === "target_features",
610
- );
611
- if (!featureSection) {
612
- return null;
613
- }
614
- const bytes = featureSection.dataBytes;
615
- const features = [];
616
- try {
617
- let cursor = 0;
618
- const countInfo = decodeUnsignedLeb128(bytes, cursor);
619
- cursor = countInfo.nextOffset;
620
- for (let i = 0; i < countInfo.value; i += 1) {
621
- cursor += 1; // prefix ('+', '-', '=')
622
- const nameLen = decodeUnsignedLeb128(bytes, cursor);
623
- cursor = nameLen.nextOffset;
624
- features.push(
625
- textDecoder.decode(bytes.subarray(cursor, cursor + nameLen.value)),
626
- );
627
- cursor += nameLen.value;
628
- }
629
- } catch {
630
- return features.length > 0 ? features : null;
631
- }
632
- return features;
633
- }
634
-
635
317
  /**
636
318
  * Parse a compiled wasm artifact and report its threading features, including
637
319
  * the isomorphic wasi-threads host contract.
@@ -658,7 +340,7 @@ export function analyzeWasmThreadFeatures(wasmBytes) {
658
340
  ...collectDeclaredMemories(parsed),
659
341
  ];
660
342
  const sharedMemory = memories.find((memory) => memory.shared) ?? null;
661
- const atomicInstructionCount = countAtomicInstructions(parsed);
343
+ const atomicInstructionCount = scanWasmCode(parsed).atomic;
662
344
  const declaredFeatures = readDeclaredFeatures(parsed.bytes);
663
345
  const usesAtomics =
664
346
  atomicInstructionCount > 0 ||
@@ -0,0 +1,137 @@
1
+ // WebAssembly SIMD guardrail: the opt-in flag and the emitted-artifact validator.
2
+ //
3
+ // SIMD is OPT-IN per module: `compileModuleFromSource({ simd128: true })` compiles
4
+ // the module's own code (and its `libraries`) with -msimd128. The guard then holds
5
+ // the emitted artifact to that declaration:
6
+ //
7
+ // * a module that DID opt in must declare `simd128` in target_features (the flag
8
+ // reached the objects);
9
+ // * a module that did NOT opt in but whose artifact carries SIMD anyway (a
10
+ // per-function `__attribute__((target("simd128")))`, or a module built by its own
11
+ // clang driver with -msimd128) is NOT refused yet: the SIMD is recorded as if the
12
+ // module had declared it, and a warning tells the module to pass
13
+ // `simd128: true`. Undeclared SIMD will become an error in a later release;
14
+ // * relaxed-SIMD is refused either way. Its instructions are implementation-defined
15
+ // (whether an FMA fuses, which lane a select takes), so the same module would
16
+ // return different bytes in the browser and under WasmEdge. Fixed-width simd128
17
+ // is deterministic and is the only SIMD the SDK admits;
18
+ // * an artifact with a function body the scanner cannot decode is refused: SIMD
19
+ // inside that body would go uncounted, so its use cannot be ruled out.
20
+ //
21
+ // Both runtime lanes execute fixed-width SIMD: every current browser engine and
22
+ // WasmEdge 0.16.4 (interpreter and AOT). The analysis is recorded on the compile
23
+ // result and in the guest-link metadata so a build record says what the artifact
24
+ // needs.
25
+
26
+ import { parseWasmModuleSections } from "../bundle/wasm.js";
27
+ import { scanWasmCode } from "./wasmCodeScan.js";
28
+ import { readTargetFeatureEntries } from "./wasmTargetFeatures.js";
29
+
30
+ /** The clang flag the `simd128` compile option turns on for a module's own code. */
31
+ export const SIMD128_COMPILE_FLAG = "-msimd128";
32
+
33
+ /** The process warning code for an artifact that carries SIMD its build did not declare. */
34
+ export const SIMD128_UNDECLARED_WARNING_CODE = "SDM_SIMD128_UNDECLARED";
35
+
36
+ /**
37
+ * Parse a compiled wasm artifact and report how it uses SIMD.
38
+ *
39
+ * @param {Uint8Array|ArrayBuffer|ArrayBufferView} wasmBytes
40
+ * @returns {{
41
+ * declared: boolean|null,
42
+ * declaredRelaxed: boolean|null,
43
+ * used: boolean,
44
+ * instructionCount: number,
45
+ * relaxedInstructionCount: number,
46
+ * undecodableFunctions: number,
47
+ * }}
48
+ * declared / declaredRelaxed whether target_features lists simd128 /
49
+ * relaxed-simd as used; null when the module has no target_features section.
50
+ * instructionCount fixed-width SIMD instructions in the code section.
51
+ * relaxedInstructionCount SIMD instructions beyond the fixed-width set
52
+ * (relaxed-simd and later proposals).
53
+ * undecodableFunctions function bodies the scanner could not decode (their
54
+ * instructions are not counted).
55
+ */
56
+ export function analyzeWasmSimdFeatures(wasmBytes) {
57
+ const parsed = parseWasmModuleSections(wasmBytes);
58
+ const code = scanWasmCode(parsed);
59
+ const entries = readTargetFeatureEntries(parsed.bytes);
60
+ const declares = (name) =>
61
+ entries === null
62
+ ? null
63
+ : entries.some((entry) => entry.name === name && entry.prefix !== "-");
64
+ return {
65
+ declared: declares("simd128"),
66
+ declaredRelaxed: declares("relaxed-simd"),
67
+ used: code.simd > 0,
68
+ instructionCount: code.simd,
69
+ relaxedInstructionCount: code.relaxedSimd,
70
+ undecodableFunctions: code.undecodableFunctions,
71
+ };
72
+ }
73
+
74
+ /**
75
+ * Hold a compiled wasm artifact's SIMD use to the build's declaration (see the file
76
+ * header). Returns the analysis plus `requested` (the module opted in) and
77
+ * `undeclared` (SIMD without the opt-in; `warning` then says what to do) on success;
78
+ * throws a clear, actionable error otherwise.
79
+ *
80
+ * @param {Uint8Array|ArrayBuffer|ArrayBufferView} wasmBytes
81
+ * @param {{ optedIn?: boolean, source?: string }} [options]
82
+ */
83
+ export function assertSimdArtifact(wasmBytes, options = {}) {
84
+ const source = options.source ? String(options.source) : "emitted wasm";
85
+ const optedIn = options.optedIn === true;
86
+ let analysis;
87
+ try {
88
+ analysis = analyzeWasmSimdFeatures(wasmBytes);
89
+ } catch (error) {
90
+ throw new Error(
91
+ `simd128 artifact validation failed for ${source}: could not parse the ` +
92
+ `emitted wasm (${error instanceof Error ? error.message : String(error)}).`,
93
+ );
94
+ }
95
+
96
+ const failures = [];
97
+ if (analysis.relaxedInstructionCount > 0 || analysis.declaredRelaxed === true) {
98
+ failures.push(
99
+ "it uses relaxed-SIMD " +
100
+ `(${analysis.relaxedInstructionCount} instruction(s); target_features ` +
101
+ `${analysis.declaredRelaxed ? "declares" : "does not declare"} relaxed-simd) - ` +
102
+ "relaxed-SIMD results are implementation-defined, so the same module would return " +
103
+ "different bytes in the browser and under WasmEdge; only fixed-width simd128 is admitted",
104
+ );
105
+ }
106
+ if (analysis.undecodableFunctions > 0) {
107
+ failures.push(
108
+ `${analysis.undecodableFunctions} function body(ies) could not be decoded, so SIMD ` +
109
+ "inside them would go uncounted and the artifact's SIMD use cannot be ruled out",
110
+ );
111
+ }
112
+ if (optedIn && analysis.declared === false) {
113
+ failures.push(
114
+ `simd128 was requested (${SIMD128_COMPILE_FLAG}) but target_features does not ` +
115
+ "declare simd128 - the flag did not reach the module's objects",
116
+ );
117
+ }
118
+ if (failures.length > 0) {
119
+ throw new Error(
120
+ `simd128 artifact validation REJECTED ${source}: ${failures.join("; ")}. ` +
121
+ "This build must not ship.",
122
+ );
123
+ }
124
+
125
+ const undeclared = !optedIn && (analysis.instructionCount > 0 || analysis.declared === true);
126
+ const result = { requested: optedIn, undeclared, ...analysis };
127
+ if (undeclared) {
128
+ result.warning =
129
+ `${source} uses WebAssembly SIMD (${analysis.instructionCount} v128 instruction(s); ` +
130
+ `target_features ${analysis.declared ? "declares" : "does not declare"} simd128) but the build did ` +
131
+ "not declare it. Pass compileModuleFromSource({ simd128: true }) so the module declares that it " +
132
+ "needs SIMD (a module built by its own clang driver with -msimd128, or a per-function " +
133
+ 'target("simd128") attribute, is the usual cause). The SDK records the use as if declared ' +
134
+ "and does not refuse the artifact yet; undeclared SIMD will become an error in a later release.";
135
+ }
136
+ return result;
137
+ }
@@ -0,0 +1,413 @@
1
+ // Instruction scanner for the code section of a wasm module.
2
+ //
3
+ // This is a real instruction decoder - NOT a byte scan - so bytes that happen to
4
+ // equal a prefix opcode inside i32.const / LEB128 / memarg immediates are never
5
+ // miscounted. It answers "which instruction classes does this module's code
6
+ // contain"; what to DO about the answer (thread-model policy, SIMD policy) lives
7
+ // in the guards that import it, so the decoder has one reason to change: the
8
+ // wasm instruction encoding.
9
+ //
10
+ // A function body is decoded to its closing `end`: block depth is tracked, and a
11
+ // body whose last instruction does not close the function block exactly at the
12
+ // body's final byte was mis-decoded, so it is reported as undecodable instead of
13
+ // contributing a count. A caller that needs a proof (the SIMD guard) therefore
14
+ // sees `undecodableFunctions`, never a silent miss.
15
+
16
+ import { decodeUnsignedLeb128 } from "../bundle/wasm.js";
17
+
18
+ /**
19
+ * Skip a LEB128-encoded integer (signedness is irrelevant for skipping — only
20
+ * the continuation bits matter). Bounds-checked.
21
+ */
22
+ function skipLeb(bytes, cursor, end) {
23
+ let position = cursor;
24
+ while (position < end) {
25
+ const byte = bytes[position++];
26
+ if ((byte & 0x80) === 0) {
27
+ return position;
28
+ }
29
+ }
30
+ throw new Error("LEB128 immediate ran past end of function body.");
31
+ }
32
+
33
+ /** Decode a LEB128 value AND return the next offset (bounds-checked). */
34
+ function readLeb(bytes, cursor, end) {
35
+ if (cursor >= end) {
36
+ throw new Error("LEB128 immediate ran past end of function body.");
37
+ }
38
+ const info = decodeUnsignedLeb128(bytes, cursor);
39
+ if (info.nextOffset > end) {
40
+ throw new Error("LEB128 immediate ran past end of function body.");
41
+ }
42
+ return info;
43
+ }
44
+
45
+ function skipBlockType(bytes, cursor, end) {
46
+ if (cursor >= end) {
47
+ throw new Error("Block type ran past end of function body.");
48
+ }
49
+ const byte = bytes[cursor];
50
+ // 0x40 (empty), single-byte value types, and single-byte type indices all
51
+ // consume exactly one byte; only a multi-byte (continuation-bit) type index
52
+ // needs a full LEB skip.
53
+ if ((byte & 0x80) !== 0) {
54
+ return skipLeb(bytes, cursor, end);
55
+ }
56
+ return cursor + 1;
57
+ }
58
+
59
+ function skipMemArg(bytes, cursor, end) {
60
+ const alignInfo = readLeb(bytes, cursor, end);
61
+ let position = alignInfo.nextOffset;
62
+ // Multi-memory / memory64: align bit 6 flags a following memory index.
63
+ if ((alignInfo.value & 0x40) !== 0) {
64
+ position = skipLeb(bytes, position, end);
65
+ }
66
+ return skipLeb(bytes, position, end);
67
+ }
68
+
69
+ function skipVec(bytes, cursor, end, bytesPerElement) {
70
+ const countInfo = readLeb(bytes, cursor, end);
71
+ let position = countInfo.nextOffset;
72
+ for (let i = 0; i < countInfo.value; i += 1) {
73
+ if (bytesPerElement === "leb") {
74
+ position = skipLeb(bytes, position, end);
75
+ } else {
76
+ position += bytesPerElement;
77
+ }
78
+ }
79
+ if (position > end) {
80
+ throw new Error("Vector immediate ran past end of function body.");
81
+ }
82
+ return position;
83
+ }
84
+
85
+ // The fixed-width SIMD proposal occupies 0xFD sub-opcodes 0x00..0xFF. Every
86
+ // sub-opcode from 0x100 up belongs to a later proposal: relaxed-SIMD
87
+ // (0x100..0x113, results implementation-defined) and whatever follows it.
88
+ const FIXED_WIDTH_SIMD_LIMIT = 0x100;
89
+
90
+ /**
91
+ * Walk one function body to its closing `end` and count, by class, the
92
+ * instructions it holds. Throws when the body does not decode to exactly its
93
+ * own bytes.
94
+ *
95
+ * @returns {{ atomic: number, simd: number, relaxedSimd: number, exceptionHandling: number }}
96
+ * atomic 0xFE-prefixed threads instructions
97
+ * simd 0xFD-prefixed fixed-width SIMD instructions (sub-opcode < 0x100)
98
+ * relaxedSimd 0xFD-prefixed instructions at sub-opcode 0x100 and above
99
+ * exceptionHandling try / catch / throw / rethrow / delegate / try_table / throw_ref
100
+ */
101
+ function scanFunctionBody(bytes, bodyStart, bodyEnd) {
102
+ let cursor = bodyStart;
103
+ // Local declarations: vec of (count, valtype).
104
+ const localVecCount = readLeb(bytes, cursor, bodyEnd);
105
+ cursor = localVecCount.nextOffset;
106
+ for (let i = 0; i < localVecCount.value; i += 1) {
107
+ cursor = skipLeb(bytes, cursor, bodyEnd); // count
108
+ if (cursor >= bodyEnd) {
109
+ throw new Error("Local declaration ran past end of function body.");
110
+ }
111
+ // valtype: usually one byte; concrete heap types are a LEB.
112
+ if ((bytes[cursor] & 0x80) !== 0) {
113
+ cursor = skipLeb(bytes, cursor, bodyEnd);
114
+ } else {
115
+ cursor += 1;
116
+ }
117
+ }
118
+
119
+ const counts = { atomic: 0, simd: 0, relaxedSimd: 0, exceptionHandling: 0 };
120
+ // The function body is itself a block; its closing `end` brings depth to 0.
121
+ let depth = 1;
122
+ while (cursor < bodyEnd) {
123
+ if (depth === 0) {
124
+ throw new Error("Instructions follow the function's closing end.");
125
+ }
126
+ const opcode = bytes[cursor++];
127
+ switch (opcode) {
128
+ // Control / parametric with no immediates.
129
+ case 0x00: // unreachable
130
+ case 0x01: // nop
131
+ case 0x05: // else (stays inside the open if block)
132
+ case 0x0f: // return
133
+ case 0x1a: // drop
134
+ case 0x1b: // select
135
+ break;
136
+ case 0x0b: // end
137
+ depth -= 1;
138
+ break;
139
+ case 0x02: // block
140
+ case 0x03: // loop
141
+ case 0x04: // if
142
+ cursor = skipBlockType(bytes, cursor, bodyEnd);
143
+ depth += 1;
144
+ break;
145
+ case 0x06: // try (legacy exception handling)
146
+ counts.exceptionHandling += 1;
147
+ cursor = skipBlockType(bytes, cursor, bodyEnd);
148
+ depth += 1;
149
+ break;
150
+ case 0x07: // catch tagidx
151
+ case 0x08: // throw tagidx
152
+ case 0x09: // rethrow labelidx
153
+ counts.exceptionHandling += 1;
154
+ cursor = skipLeb(bytes, cursor, bodyEnd);
155
+ break;
156
+ case 0x0a: // throw_ref
157
+ case 0x19: // catch_all
158
+ counts.exceptionHandling += 1;
159
+ break;
160
+ case 0x18: // delegate labelidx: closes the try block like an end
161
+ counts.exceptionHandling += 1;
162
+ cursor = skipLeb(bytes, cursor, bodyEnd);
163
+ depth -= 1;
164
+ break;
165
+ case 0x1f: { // try_table blocktype vec(catch clause)
166
+ counts.exceptionHandling += 1;
167
+ cursor = skipBlockType(bytes, cursor, bodyEnd);
168
+ const clauses = readLeb(bytes, cursor, bodyEnd);
169
+ cursor = clauses.nextOffset;
170
+ for (let i = 0; i < clauses.value; i += 1) {
171
+ if (cursor >= bodyEnd) {
172
+ throw new Error("Catch clause ran past end of function body.");
173
+ }
174
+ const kind = bytes[cursor++];
175
+ if (kind === 0x00 || kind === 0x01) {
176
+ cursor = skipLeb(bytes, cursor, bodyEnd); // tagidx
177
+ } else if (kind !== 0x02 && kind !== 0x03) {
178
+ throw new Error(`Unknown catch clause kind 0x${kind.toString(16)}.`);
179
+ }
180
+ cursor = skipLeb(bytes, cursor, bodyEnd); // labelidx
181
+ }
182
+ depth += 1;
183
+ break;
184
+ }
185
+ case 0x0c: // br
186
+ case 0x0d: // br_if
187
+ cursor = skipLeb(bytes, cursor, bodyEnd);
188
+ break;
189
+ case 0x0e: {
190
+ // br_table: vec<labelidx> + default labelidx
191
+ cursor = skipVec(bytes, cursor, bodyEnd, "leb");
192
+ cursor = skipLeb(bytes, cursor, bodyEnd);
193
+ break;
194
+ }
195
+ case 0x10: // call
196
+ case 0x12: // return_call
197
+ case 0x14: // call_ref typeidx
198
+ case 0x15: // return_call_ref typeidx
199
+ cursor = skipLeb(bytes, cursor, bodyEnd);
200
+ break;
201
+ case 0x11: // call_indirect
202
+ case 0x13: // return_call_indirect
203
+ cursor = skipLeb(bytes, cursor, bodyEnd); // typeidx
204
+ cursor = skipLeb(bytes, cursor, bodyEnd); // tableidx
205
+ break;
206
+ case 0x1c: // select t*
207
+ cursor = skipVec(bytes, cursor, bodyEnd, 1);
208
+ break;
209
+ case 0x20: // local.get
210
+ case 0x21: // local.set
211
+ case 0x22: // local.tee
212
+ case 0x23: // global.get
213
+ case 0x24: // global.set
214
+ case 0x25: // table.get
215
+ case 0x26: // table.set
216
+ cursor = skipLeb(bytes, cursor, bodyEnd);
217
+ break;
218
+ case 0x3f: // memory.size
219
+ case 0x40: // memory.grow
220
+ cursor = skipLeb(bytes, cursor, bodyEnd); // memidx (reserved)
221
+ break;
222
+ case 0x41: // i32.const
223
+ case 0x42: // i64.const
224
+ cursor = skipLeb(bytes, cursor, bodyEnd);
225
+ break;
226
+ case 0x43: // f32.const
227
+ cursor += 4;
228
+ break;
229
+ case 0x44: // f64.const
230
+ cursor += 8;
231
+ break;
232
+ case 0xd0: // ref.null
233
+ if (cursor < bodyEnd && (bytes[cursor] & 0x80) !== 0) {
234
+ cursor = skipLeb(bytes, cursor, bodyEnd);
235
+ } else {
236
+ cursor += 1;
237
+ }
238
+ break;
239
+ case 0xd1: // ref.is_null
240
+ case 0xd3: // ref.eq
241
+ case 0xd4: // ref.as_non_null
242
+ break;
243
+ case 0xd2: // ref.func
244
+ case 0xd5: // br_on_null labelidx
245
+ case 0xd6: // br_on_non_null labelidx
246
+ cursor = skipLeb(bytes, cursor, bodyEnd);
247
+ break;
248
+ case 0xfc: {
249
+ // Bulk-memory / saturating-truncation / table ops.
250
+ const sub = readLeb(bytes, cursor, bodyEnd);
251
+ cursor = sub.nextOffset;
252
+ switch (sub.value) {
253
+ case 0: case 1: case 2: case 3:
254
+ case 4: case 5: case 6: case 7:
255
+ break; // trunc_sat: no immediates
256
+ case 8: // memory.init dataidx memidx
257
+ cursor = skipLeb(bytes, cursor, bodyEnd);
258
+ cursor = skipLeb(bytes, cursor, bodyEnd);
259
+ break;
260
+ case 9: // data.drop
261
+ cursor = skipLeb(bytes, cursor, bodyEnd);
262
+ break;
263
+ case 10: // memory.copy memidx memidx
264
+ cursor = skipLeb(bytes, cursor, bodyEnd);
265
+ cursor = skipLeb(bytes, cursor, bodyEnd);
266
+ break;
267
+ case 11: // memory.fill memidx
268
+ cursor = skipLeb(bytes, cursor, bodyEnd);
269
+ break;
270
+ case 12: // table.init elemidx tableidx
271
+ case 14: // table.copy tableidx tableidx
272
+ cursor = skipLeb(bytes, cursor, bodyEnd);
273
+ cursor = skipLeb(bytes, cursor, bodyEnd);
274
+ break;
275
+ case 13: // elem.drop
276
+ case 15: // table.grow
277
+ case 16: // table.size
278
+ case 17: // table.fill
279
+ cursor = skipLeb(bytes, cursor, bodyEnd);
280
+ break;
281
+ case 19: // i64.add128
282
+ case 20: // i64.sub128
283
+ case 21: // i64.mul_wide_s
284
+ case 22: // i64.mul_wide_u
285
+ break; // wide arithmetic: no immediates
286
+ default:
287
+ // An unknown sub-opcode's immediates cannot be skipped: the body is
288
+ // undecodable rather than guessed at (as an unknown opcode is, below).
289
+ throw new Error(`Unsupported 0xFC sub-opcode ${sub.value}.`);
290
+ }
291
+ break;
292
+ }
293
+ case 0xfd: {
294
+ // SIMD.
295
+ const sub = readLeb(bytes, cursor, bodyEnd);
296
+ cursor = sub.nextOffset;
297
+ const op = sub.value;
298
+ if (op >= FIXED_WIDTH_SIMD_LIMIT) {
299
+ counts.relaxedSimd += 1;
300
+ } else {
301
+ counts.simd += 1;
302
+ }
303
+ if (op <= 0x0b) {
304
+ cursor = skipMemArg(bytes, cursor, bodyEnd); // v128 load/store
305
+ } else if (op === 0x0c || op === 0x0d) {
306
+ cursor += 16; // v128.const / i8x16.shuffle
307
+ } else if (op >= 0x15 && op <= 0x22) {
308
+ cursor += 1; // extract/replace lane
309
+ } else if (op >= 0x54 && op <= 0x5b) {
310
+ cursor = skipMemArg(bytes, cursor, bodyEnd);
311
+ cursor += 1; // load/store lane
312
+ } else if (op === 0x5c || op === 0x5d) {
313
+ cursor = skipMemArg(bytes, cursor, bodyEnd); // load32/64_zero
314
+ }
315
+ break;
316
+ }
317
+ case 0xfe: {
318
+ // Atomics / threads.
319
+ const sub = readLeb(bytes, cursor, bodyEnd);
320
+ cursor = sub.nextOffset;
321
+ counts.atomic += 1;
322
+ if (sub.value === 0x03) {
323
+ cursor += 1; // atomic.fence: one reserved byte, no memarg
324
+ } else {
325
+ cursor = skipMemArg(bytes, cursor, bodyEnd);
326
+ }
327
+ break;
328
+ }
329
+ default:
330
+ if (opcode >= 0x28 && opcode <= 0x3e) {
331
+ // Memory load/store family (i32.load .. i64.store32): each carries a
332
+ // memarg (align + offset). Skipping this is what prevents 0xFE bytes
333
+ // inside memory-offset immediates from being miscounted as atomics.
334
+ cursor = skipMemArg(bytes, cursor, bodyEnd);
335
+ break;
336
+ }
337
+ if (opcode >= 0x45 && opcode <= 0xc4) {
338
+ // MVP numeric / comparison / conversion opcodes and the sign-extension
339
+ // operators take no immediates.
340
+ break;
341
+ }
342
+ // Reserved opcodes and prefixes this decoder does not know (the GC
343
+ // prefix 0xFB): their immediates cannot be skipped, so the body is
344
+ // undecodable rather than guessed at.
345
+ throw new Error(`Unsupported opcode 0x${opcode.toString(16)}.`);
346
+ }
347
+ if (cursor > bodyEnd) {
348
+ throw new Error("Instruction immediate ran past end of function body.");
349
+ }
350
+ }
351
+ if (depth !== 0) {
352
+ throw new Error("Function body does not close its block at its final byte.");
353
+ }
354
+ return counts;
355
+ }
356
+
357
+ /**
358
+ * Scan the code section of a parsed wasm module (parseWasmModuleSections).
359
+ *
360
+ * @returns {{
361
+ * atomic: number, simd: number, relaxedSimd: number, exceptionHandling: number,
362
+ * undecodableFunctions: number,
363
+ * }}
364
+ * Totals over every function that decodes; `undecodableFunctions` counts the
365
+ * bodies that did not (their instructions contribute nothing).
366
+ */
367
+ export function scanWasmCode(parsed) {
368
+ const totals = {
369
+ atomic: 0,
370
+ simd: 0,
371
+ relaxedSimd: 0,
372
+ exceptionHandling: 0,
373
+ undecodableFunctions: 0,
374
+ };
375
+ const codeSection = parsed.sections.find((section) => section.id === 10);
376
+ if (!codeSection) {
377
+ return totals;
378
+ }
379
+ const bytes = parsed.bytes;
380
+ try {
381
+ let cursor = codeSection.payloadStart;
382
+ const funcCount = readLeb(bytes, cursor, codeSection.payloadEnd);
383
+ cursor = funcCount.nextOffset;
384
+ for (let i = 0; i < funcCount.value; i += 1) {
385
+ if (cursor >= codeSection.payloadEnd) {
386
+ totals.undecodableFunctions += funcCount.value - i;
387
+ break;
388
+ }
389
+ const sizeInfo = readLeb(bytes, cursor, codeSection.payloadEnd);
390
+ const bodyStart = sizeInfo.nextOffset;
391
+ const bodyEnd = bodyStart + sizeInfo.value;
392
+ if (bodyEnd > codeSection.payloadEnd) {
393
+ totals.undecodableFunctions += funcCount.value - i;
394
+ break;
395
+ }
396
+ try {
397
+ const counts = scanFunctionBody(bytes, bodyStart, bodyEnd);
398
+ totals.atomic += counts.atomic;
399
+ totals.simd += counts.simd;
400
+ totals.relaxedSimd += counts.relaxedSimd;
401
+ totals.exceptionHandling += counts.exceptionHandling;
402
+ } catch {
403
+ // A body that does not decode is counted, not trusted and not fatal.
404
+ totals.undecodableFunctions += 1;
405
+ }
406
+ cursor = bodyEnd;
407
+ }
408
+ } catch {
409
+ // Truncated / malformed code section: report what decoded.
410
+ totals.undecodableFunctions += 1;
411
+ }
412
+ return totals;
413
+ }
@@ -0,0 +1,63 @@
1
+ // The `target_features` custom section of a wasm module (tool-conventions
2
+ // "Feature section"): the features its objects were built with, as the linker
3
+ // merged them. It is the artifact's own statement of what a runtime must
4
+ // support, independent of any instruction the code section happens to contain.
5
+
6
+ import { decodeUnsignedLeb128, listWasmCustomSections } from "../bundle/wasm.js";
7
+
8
+ const textDecoder = new TextDecoder();
9
+
10
+ /**
11
+ * Every entry of the target_features section.
12
+ *
13
+ * @param {Uint8Array} wasmBytes
14
+ * @returns {{ prefix: string, name: string }[]|null} `prefix` is "+" (used),
15
+ * "=" (used and required of every object) or "-" (disallowed); null when the
16
+ * module has no target_features section (or it cannot be read at all).
17
+ */
18
+ export function readTargetFeatureEntries(wasmBytes) {
19
+ let customSections;
20
+ try {
21
+ customSections = listWasmCustomSections(wasmBytes);
22
+ } catch {
23
+ return null;
24
+ }
25
+ const featureSection = customSections.find(
26
+ (section) => section.name === "target_features",
27
+ );
28
+ if (!featureSection) {
29
+ return null;
30
+ }
31
+ const bytes = featureSection.dataBytes;
32
+ const entries = [];
33
+ try {
34
+ let cursor = 0;
35
+ const countInfo = decodeUnsignedLeb128(bytes, cursor);
36
+ cursor = countInfo.nextOffset;
37
+ for (let i = 0; i < countInfo.value; i += 1) {
38
+ const prefix = String.fromCharCode(bytes[cursor]);
39
+ cursor += 1;
40
+ const nameLen = decodeUnsignedLeb128(bytes, cursor);
41
+ cursor = nameLen.nextOffset;
42
+ entries.push({
43
+ prefix,
44
+ name: textDecoder.decode(bytes.subarray(cursor, cursor + nameLen.value)),
45
+ });
46
+ cursor += nameLen.value;
47
+ }
48
+ } catch {
49
+ return entries.length > 0 ? entries : null;
50
+ }
51
+ return entries;
52
+ }
53
+
54
+ /**
55
+ * The names in the target_features section, whatever their prefix.
56
+ *
57
+ * @param {Uint8Array} wasmBytes
58
+ * @returns {string[]|null} null when there is no readable section.
59
+ */
60
+ export function readDeclaredFeatures(wasmBytes) {
61
+ const entries = readTargetFeatureEntries(wasmBytes);
62
+ return entries === null ? null : entries.map((entry) => entry.name);
63
+ }
package/src/index.d.ts CHANGED
@@ -993,12 +993,48 @@ export interface CompilationResult {
993
993
  tempDir: string | null;
994
994
  wasmBytes: Uint8Array;
995
995
  guestLink: GuestLinkArtifact | null;
996
+ /**
997
+ * How the emitted artifact uses WebAssembly SIMD, as the artifact guard read
998
+ * it. Always present: `requested: false, used: false` for a module that did
999
+ * not opt in with `simd128: true` and carries no SIMD.
1000
+ */
1001
+ simd128: Simd128Report;
1002
+ /**
1003
+ * Build warnings (not manifest warnings): today, the SIMD an artifact carries without
1004
+ * the build having passed `simd128: true`, with what to do about it. Empty otherwise.
1005
+ */
1006
+ warnings: string[];
996
1007
  /** Which compile steps the content cache answered. */
997
1008
  compileCache?: CompileCacheReport;
998
1009
  manifestWarnings: string[];
999
1010
  report: ComplianceReport;
1000
1011
  }
1001
1012
 
1013
+ export interface Simd128Report {
1014
+ /** The module opted in with `simd128: true` (compiled with -msimd128). */
1015
+ requested: boolean;
1016
+ /**
1017
+ * The artifact carries SIMD but the build did not pass `simd128: true` (a module built by its
1018
+ * own clang driver with -msimd128, or a per-function target("simd128") attribute). It is
1019
+ * recorded as if declared (`guestLink.simd128`), a warning is added to `CompilationResult.warnings`
1020
+ * and emitted as the process warning SDM_SIMD128_UNDECLARED, and the artifact is not refused
1021
+ * yet: undeclared SIMD will become an error in a later release.
1022
+ */
1023
+ undeclared: boolean;
1024
+ /** `simd128` is listed as used in the artifact's target_features section; null when it has none. */
1025
+ declared: boolean | null;
1026
+ /** `relaxed-simd` is listed in target_features; always false or null in an artifact that shipped. */
1027
+ declaredRelaxed: boolean | null;
1028
+ /** The code section holds fixed-width SIMD instructions. */
1029
+ used: boolean;
1030
+ /** Fixed-width SIMD (0xFD) instructions in the code section. */
1031
+ instructionCount: number;
1032
+ /** Relaxed-SIMD instructions; always 0 in an artifact that shipped (the guard refuses them). */
1033
+ relaxedInstructionCount: number;
1034
+ /** Function bodies the scanner could not decode; their instructions are not counted. */
1035
+ undecodableFunctions: number;
1036
+ }
1037
+
1002
1038
  export interface GuestLinkArtifact {
1003
1039
  format: "wasm-object";
1004
1040
  language: string;
@@ -1006,6 +1042,8 @@ export interface GuestLinkArtifact {
1006
1042
  methodSymbols: Record<string, string>;
1007
1043
  threadModel: ModuleThreadModelName;
1008
1044
  capabilities: string[];
1045
+ /** Present (true) only for a module that uses WebAssembly SIMD, declared with `simd128: true` or not. */
1046
+ simd128?: true;
1009
1047
  objectBytes: Uint8Array;
1010
1048
  /** Present when the compile linked `libraries`. */
1011
1049
  libraries?: GuestLinkLibrary[];
@@ -1076,6 +1114,20 @@ export function compileModuleFromSource(options: {
1076
1114
  * on failure. A failed compile always removes it.
1077
1115
  */
1078
1116
  keepTempDir?: boolean;
1117
+ /**
1118
+ * Opt in to WebAssembly SIMD: the module's own code and its `libraries` are
1119
+ * compiled with -msimd128 (so `__wasm_simd128__` is defined and the compiler may
1120
+ * vectorize), and the artifact guard records the use in `CompilationResult.simd128`
1121
+ * and the guest-link metadata. Default `false`: a module that does not opt in is
1122
+ * compiled with exactly the flags it always was. An artifact that carries SIMD
1123
+ * anyway (the module's own clang driver passes -msimd128, or a per-function
1124
+ * target("simd128") attribute) is recorded as if declared and warned about, not
1125
+ * refused yet; undeclared SIMD will become an error in a later release.
1126
+ * Relaxed-SIMD is always refused: its results are implementation-defined. Needs
1127
+ * `threadModel` "wasi-sequential" or "emscripten-pthreads" (the clang
1128
+ * wasm32-wasip1-threads toolchain).
1129
+ */
1130
+ simd128?: boolean;
1079
1131
  importedMemory?: boolean;
1080
1132
  sharedMemory?: boolean;
1081
1133
  initialMemoryBytes?: number;