space-data-module-sdk 0.9.14 → 0.9.16

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.16",
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",
@@ -129,7 +129,7 @@
129
129
  "flatbuffers": "^25.9.23",
130
130
  "flatc-wasm": "^26.1.32",
131
131
  "flatsql": "^2.0.0",
132
- "hd-wallet-wasm": "2.1.0",
132
+ "hd-wallet-wasm": "2.2.2",
133
133
  "sdn-emception": "1.0.0",
134
134
  "spacedatastandards.org": "1.261.0"
135
135
  },
@@ -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 ||