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.
@@ -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
+ }
@@ -13,6 +13,7 @@ import {
13
13
  toUint8Array,
14
14
  } from "../utils/encoding.js";
15
15
  import { derSignatureToRaw, rawSignatureToDer } from "../utils/ecdsaDer.js";
16
+ import { SECP256K1_CURVE } from "../utils/walletCurves.js";
16
17
  import {
17
18
  parseCronExpression,
18
19
  matchesCronExpression,
@@ -913,7 +914,7 @@ export class BrowserHost {
913
914
  );
914
915
  }
915
916
  return new Uint8Array(
916
- wasmWallet.curves.publicKeyFromPrivate(toUint8Array(privateKey)),
917
+ wasmWallet.curves.publicKeyFromPrivate(toUint8Array(privateKey), SECP256K1_CURVE),
917
918
  );
918
919
  },
919
920
  sign: (message, privateKey) => {