@gmitch215/folio 0.0.0-stage → 1.0.0

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/dist/bake.js ADDED
@@ -0,0 +1,701 @@
1
+ import { memoryImports } from "./memory.js";
2
+ import { pageBytes } from "./pages.js";
3
+ /** The image cannot be baked into this module. */
4
+ export class ImageMismatchError extends Error {
5
+ /** The reason, for a caller that handles one mismatch differently from another. */
6
+ code;
7
+ constructor(code, detail) {
8
+ super(`image does not fit the module (${code}): ${detail}`);
9
+ this.name = 'ImageMismatchError';
10
+ this.code = code;
11
+ }
12
+ }
13
+ /** Bytes are not an encoded image, or an image object is inconsistent. */
14
+ export class ImageFormatError extends Error {
15
+ /** The reason the bytes were rejected. */
16
+ code;
17
+ constructor(code, detail) {
18
+ super(`invalid memory image (${code}): ${detail}`);
19
+ this.name = 'ImageFormatError';
20
+ this.code = code;
21
+ }
22
+ }
23
+ /** Default cap on one data segment (64 MiB); it bounds the string and heap copy made per segment. */
24
+ export const maxSegmentBytes = 64 * 1024 * 1024;
25
+ const zeroPage = new Uint8Array(pageBytes);
26
+ const hexDigest = /^[0-9a-f]{64}$/;
27
+ const maxContextBytes = 4096;
28
+ const contextBytes = (context) => new TextEncoder().encode(context);
29
+ /** Lowercase sha256 hex of module bytes, the form `MemoryImage.module` holds. */
30
+ export async function moduleDigest(bytes) {
31
+ const hash = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes));
32
+ return Array.from(hash, (byte) => byte.toString(16).padStart(2, '0')).join('');
33
+ }
34
+ /** Memory size to create for an image, and how many of its pages the image carries. */
35
+ export function imagePages(image) {
36
+ return { memoryPages: image.byteLength / pageBytes, deltaPages: image.pages.length };
37
+ }
38
+ function viewOf(source) {
39
+ if (source instanceof WebAssembly.Memory)
40
+ return new Uint8Array(source.buffer);
41
+ return source instanceof Uint8Array ? source : new Uint8Array(source);
42
+ }
43
+ /** Index of the first byte where two pages differ, or -1. */
44
+ function firstDifference(a, aStart, b, bStart) {
45
+ const aAt = a.byteOffset + aStart;
46
+ const bAt = b.byteOffset + bStart;
47
+ if (!((aAt | bAt) & 3)) {
48
+ const x = new Uint32Array(a.buffer, aAt, pageBytes / 4);
49
+ const y = new Uint32Array(b.buffer, bAt, pageBytes / 4);
50
+ for (let i = 0; i < x.length; i++) {
51
+ if (x[i] === y[i])
52
+ continue;
53
+ for (let k = i * 4;; k++)
54
+ if (a[aStart + k] !== b[bStart + k])
55
+ return k;
56
+ }
57
+ return -1;
58
+ }
59
+ for (let i = 0; i < pageBytes; i++)
60
+ if (a[aStart + i] !== b[bStart + i])
61
+ return i;
62
+ return -1;
63
+ }
64
+ function assertImage(image) {
65
+ const bad = (detail) => new ImageFormatError('invalid', detail);
66
+ if (!Number.isInteger(image.byteLength) || image.byteLength < 0 || image.byteLength % pageBytes)
67
+ throw bad(`byteLength ${image.byteLength} is not a multiple of ${pageBytes}`);
68
+ const total = image.byteLength / pageBytes;
69
+ let last = -1;
70
+ for (const page of image.pages) {
71
+ if (!Number.isInteger(page) || page <= last || page >= total)
72
+ throw bad(`page ${page} is out of order or beyond ${total} pages`);
73
+ last = page;
74
+ }
75
+ if (image.data.length !== image.pages.length * pageBytes)
76
+ throw bad(`data holds ${image.data.length} bytes for ${image.pages.length} pages`);
77
+ if (image.module !== undefined && !hexDigest.test(image.module))
78
+ throw bad('module is not 64 lowercase hex characters');
79
+ if (image.context !== undefined) {
80
+ const size = contextBytes(image.context).length;
81
+ if (size === 0 || size > maxContextBytes)
82
+ throw bad(`context is ${size} bytes, it must hold 1 to ${maxContextBytes}`);
83
+ }
84
+ }
85
+ /**
86
+ * Compares a booted memory with a fresh instance of the same module, page by page. A fresh memory
87
+ * shorter than the booted one counts as zero past its end; a longer one is refused. A page the boot
88
+ * zeroed that the module's own data had set is a delta page and ships as zeros.
89
+ */
90
+ export function captureImage(booted, fresh, options = {}) {
91
+ const after = viewOf(booted);
92
+ const before = viewOf(fresh);
93
+ if (after.length % pageBytes || before.length % pageBytes)
94
+ throw new RangeError('memory sizes must be multiples of 65,536 bytes');
95
+ if (before.length > after.length)
96
+ throw new RangeError('the fresh memory is larger than the booted memory');
97
+ const pages = [];
98
+ for (let page = 0; page < after.length / pageBytes; page++) {
99
+ const start = page * pageBytes;
100
+ const same = start < before.length
101
+ ? firstDifference(after, start, before, start)
102
+ : firstDifference(after, start, zeroPage, 0);
103
+ if (same >= 0)
104
+ pages.push(page);
105
+ }
106
+ const data = new Uint8Array(pages.length * pageBytes);
107
+ pages.forEach((page, i) => data.set(after.subarray(page * pageBytes, (page + 1) * pageBytes), i * pageBytes));
108
+ const image = { byteLength: after.length, pages, data };
109
+ if (options.module !== undefined) {
110
+ if (!hexDigest.test(options.module))
111
+ throw new TypeError('module must be 64 lowercase hex characters');
112
+ image.module = options.module;
113
+ }
114
+ if (options.context !== undefined) {
115
+ const size = contextBytes(options.context).length;
116
+ if (size === 0 || size > maxContextBytes)
117
+ throw new TypeError(`context must hold 1 to ${maxContextBytes} UTF-8 bytes`);
118
+ image.context = options.context;
119
+ }
120
+ if (options.globals) {
121
+ const changed = {};
122
+ for (const [key, value] of Object.entries(options.globals.booted)) {
123
+ const initial = options.globals.fresh[Number(key)];
124
+ if (initial === undefined)
125
+ throw new TypeError(`no fresh value for global ${key}`);
126
+ if (!Object.is(value, initial))
127
+ changed[Number(key)] = value;
128
+ }
129
+ if (Object.keys(changed).length)
130
+ image.globals = changed;
131
+ }
132
+ if (options.table) {
133
+ const slots = [];
134
+ const { booted: now, fresh: then } = options.table;
135
+ for (let slot = 0; slot < Math.max(now.length, then.length); slot++) {
136
+ const a = slot < now.length ? now.get(slot) : null;
137
+ const b = slot < then.length ? then.get(slot) : null;
138
+ if ((a?.name ?? null) !== (b?.name ?? null))
139
+ slots.push(slot);
140
+ }
141
+ if (slots.length)
142
+ image.tableSlots = slots;
143
+ }
144
+ return image;
145
+ }
146
+ /**
147
+ * Copies the image pages into a live memory, which must hold a fresh instance's contents; the
148
+ * memory grows to the image size first. Globals and table slots are not restored, so an image that
149
+ * records changed ones is refused with `ImageMismatchError` code `global` or `table` unless
150
+ * `memoryOnly` is set; `bakeModule` is the route that writes changed globals into the module.
151
+ *
152
+ * `expect` names the module and context digests of the site doing the replay. Each one given must
153
+ * equal the image's own, so an image that carries none is refused too; `ImageMismatchError` has
154
+ * code `digest` or `context`, and nothing is written to the memory.
155
+ */
156
+ export function applyImage(memory, image, expect = {}) {
157
+ assertImage(image);
158
+ for (const [field, code] of [
159
+ ['module', 'digest'],
160
+ ['context', 'context']
161
+ ]) {
162
+ const wanted = expect[field];
163
+ if (wanted !== undefined && image[field] !== wanted)
164
+ throw new ImageMismatchError(code, `replay expects ${field} ${wanted}, image has ${image[field] ?? 'none'}`);
165
+ }
166
+ if (!expect.memoryOnly) {
167
+ const globals = Object.keys(image.globals ?? {}).length;
168
+ if (globals)
169
+ throw new ImageMismatchError('global', `the image records ${globals} changed global(s) that applyImage cannot set; use bakeModule or pass memoryOnly`);
170
+ const slots = image.tableSlots?.length ?? 0;
171
+ if (slots)
172
+ throw new ImageMismatchError('table', `the image records ${slots} changed table slot(s) that applyImage cannot set; use bakeModule or pass memoryOnly`);
173
+ }
174
+ const needed = image.byteLength / pageBytes;
175
+ const have = memory.buffer.byteLength / pageBytes;
176
+ if (have < needed)
177
+ memory.grow(needed - have);
178
+ const target = new Uint8Array(memory.buffer);
179
+ image.pages.forEach((page, i) => target.set(image.data.subarray(i * pageBytes, (i + 1) * pageBytes), page * pageBytes));
180
+ }
181
+ const magic = [0x46, 0x49, 0x4d, 0x47];
182
+ const version = 1;
183
+ const hasDigest = 1;
184
+ const hasGlobals = 2;
185
+ const hasTable = 4;
186
+ const hasContext = 8;
187
+ /**
188
+ * Serializes an image, little endian: magic `FIMG`, u32 version (1), u32 flags (1 digest, 2
189
+ * globals, 4 table slots, 8 context), u32 memory pages, u32 delta pages, then in this order the 32
190
+ * digest bytes, the context (u32 byte count, then UTF-8), the globals (u32 count, then per entry
191
+ * u32 index, u8 kind 0 for a number as f64 or 1 for a bigint as i64, 8 value bytes), the table
192
+ * slots (u32 count, u32 each), the u32 page indexes and the page bytes.
193
+ */
194
+ export function encodeImage(image) {
195
+ assertImage(image);
196
+ const globals = Object.entries(image.globals ?? {});
197
+ const slots = image.tableSlots ?? [];
198
+ const context = image.context === undefined ? undefined : contextBytes(image.context);
199
+ const flags = (image.module ? hasDigest : 0) |
200
+ (context ? hasContext : 0) |
201
+ (globals.length ? hasGlobals : 0) |
202
+ (slots.length ? hasTable : 0);
203
+ const head = 20 +
204
+ (image.module ? 32 : 0) +
205
+ (context ? 4 + context.length : 0) +
206
+ (globals.length ? 4 + globals.length * 13 : 0) +
207
+ (slots.length ? 4 + slots.length * 4 : 0) +
208
+ image.pages.length * 4;
209
+ const out = new Uint8Array(head + image.data.length);
210
+ const view = new DataView(out.buffer);
211
+ out.set(magic);
212
+ view.setUint32(4, version, true);
213
+ view.setUint32(8, flags, true);
214
+ view.setUint32(12, image.byteLength / pageBytes, true);
215
+ view.setUint32(16, image.pages.length, true);
216
+ let at = 20;
217
+ if (image.module) {
218
+ for (let i = 0; i < 32; i++)
219
+ out[at + i] = parseInt(image.module.slice(i * 2, i * 2 + 2), 16);
220
+ at += 32;
221
+ }
222
+ if (context) {
223
+ view.setUint32(at, context.length, true);
224
+ out.set(context, at + 4);
225
+ at += 4 + context.length;
226
+ }
227
+ if (globals.length) {
228
+ view.setUint32(at, globals.length, true);
229
+ at += 4;
230
+ for (const [key, value] of globals) {
231
+ view.setUint32(at, Number(key), true);
232
+ if (typeof value === 'bigint') {
233
+ view.setUint8(at + 4, 1);
234
+ view.setBigInt64(at + 5, value, true);
235
+ }
236
+ else {
237
+ view.setUint8(at + 4, 0);
238
+ view.setFloat64(at + 5, value, true);
239
+ }
240
+ at += 13;
241
+ }
242
+ }
243
+ if (slots.length) {
244
+ view.setUint32(at, slots.length, true);
245
+ at += 4;
246
+ for (const slot of slots) {
247
+ view.setUint32(at, slot, true);
248
+ at += 4;
249
+ }
250
+ }
251
+ for (const page of image.pages) {
252
+ view.setUint32(at, page, true);
253
+ at += 4;
254
+ }
255
+ out.set(image.data, at);
256
+ return out;
257
+ }
258
+ /** Parses `encodeImage` output; `data` is a view into `bytes`, not a copy. */
259
+ export function decodeImage(bytes) {
260
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.length);
261
+ let at = 0;
262
+ const need = (count) => {
263
+ if (at + count > bytes.length)
264
+ throw new ImageFormatError('truncated', `needs ${at + count} bytes, has ${bytes.length}`);
265
+ };
266
+ need(20);
267
+ if (!magic.every((value, i) => bytes[i] === value))
268
+ throw new ImageFormatError('magic', 'the bytes do not start with FIMG');
269
+ const found = view.getUint32(4, true);
270
+ if (found !== version)
271
+ throw new ImageFormatError('version', `version ${found}, this reader knows ${version}`);
272
+ const flags = view.getUint32(8, true);
273
+ if (flags & ~15)
274
+ throw new ImageFormatError('invalid', `unknown flags ${flags}`);
275
+ const memoryPages = view.getUint32(12, true);
276
+ const count = view.getUint32(16, true);
277
+ at = 20;
278
+ const image = { byteLength: memoryPages * pageBytes, pages: [], data: bytes };
279
+ if (flags & hasDigest) {
280
+ need(32);
281
+ image.module = Array.from(bytes.subarray(at, at + 32), (b) => b.toString(16).padStart(2, '0')).join('');
282
+ at += 32;
283
+ }
284
+ if (flags & hasContext) {
285
+ need(4);
286
+ const size = view.getUint32(at, true);
287
+ at += 4;
288
+ need(size);
289
+ try {
290
+ image.context = new TextDecoder('utf-8', { fatal: true }).decode(bytes.subarray(at, at + size));
291
+ }
292
+ catch {
293
+ throw new ImageFormatError('invalid', 'context is not UTF-8');
294
+ }
295
+ at += size;
296
+ }
297
+ if (flags & hasGlobals) {
298
+ need(4);
299
+ const total = view.getUint32(at, true);
300
+ at += 4;
301
+ need(total * 13);
302
+ image.globals = {};
303
+ for (let i = 0; i < total; i++, at += 13) {
304
+ const kind = view.getUint8(at + 4);
305
+ if (kind > 1)
306
+ throw new ImageFormatError('invalid', `unknown global kind ${kind}`);
307
+ image.globals[view.getUint32(at, true)] =
308
+ kind === 1 ? view.getBigInt64(at + 5, true) : view.getFloat64(at + 5, true);
309
+ }
310
+ }
311
+ if (flags & hasTable) {
312
+ need(4);
313
+ const total = view.getUint32(at, true);
314
+ at += 4;
315
+ need(total * 4);
316
+ image.tableSlots = Array.from({ length: total }, (_, i) => view.getUint32(at + i * 4, true));
317
+ at += total * 4;
318
+ }
319
+ need(count * 4);
320
+ image.pages = Array.from({ length: count }, (_, i) => view.getUint32(at + i * 4, true));
321
+ at += count * 4;
322
+ const length = count * pageBytes;
323
+ need(length);
324
+ if (at + length !== bytes.length)
325
+ throw new ImageFormatError('invalid', `${bytes.length - at - length} trailing bytes`);
326
+ image.data = bytes.subarray(at, at + length);
327
+ assertImage(image);
328
+ return image;
329
+ }
330
+ const truncatedModule = () => new RangeError('truncated wasm module');
331
+ function byte(c) {
332
+ if (c.at >= c.bytes.length)
333
+ throw truncatedModule();
334
+ return c.bytes[c.at++];
335
+ }
336
+ function uleb(c, limit) {
337
+ let value = 0;
338
+ for (let shift = 0; shift < limit * 7; shift += 7) {
339
+ const part = byte(c);
340
+ value += (part & 127) * 2 ** shift;
341
+ if (!(part & 128)) {
342
+ if (!Number.isSafeInteger(value))
343
+ throw new RangeError('wasm integer beyond 2^53');
344
+ return value;
345
+ }
346
+ }
347
+ throw new RangeError('invalid wasm integer');
348
+ }
349
+ const u32 = (c) => uleb(c, 5);
350
+ const u64 = (c) => uleb(c, 10);
351
+ function s64(c) {
352
+ let value = 0n;
353
+ for (let shift = 0n; shift < 70n; shift += 7n) {
354
+ const part = byte(c);
355
+ value |= BigInt(part & 127) << shift;
356
+ if (!(part & 128)) {
357
+ if (shift < 56n && part & 64)
358
+ value -= 1n << (shift + 7n);
359
+ if (value < 0n || value > BigInt(Number.MAX_SAFE_INTEGER))
360
+ throw new RangeError('unsupported data segment offset');
361
+ return Number(value);
362
+ }
363
+ }
364
+ throw new RangeError('invalid wasm integer');
365
+ }
366
+ function leb(value) {
367
+ const out = [];
368
+ do {
369
+ const part = value % 128;
370
+ value = Math.floor(value / 128);
371
+ out.push(value ? part | 128 : part);
372
+ } while (value);
373
+ return out;
374
+ }
375
+ function s32(c) {
376
+ let value = 0;
377
+ for (let shift = 0; shift < 35; shift += 7) {
378
+ const part = byte(c);
379
+ value |= (part & 127) << shift;
380
+ if (!(part & 128))
381
+ return shift < 25 && part & 64 ? value | (-1 << (shift + 7)) : value;
382
+ }
383
+ throw new RangeError('invalid wasm integer');
384
+ }
385
+ function name(c) {
386
+ const length = u32(c);
387
+ if (c.at + length > c.bytes.length)
388
+ throw truncatedModule();
389
+ const value = new TextDecoder().decode(c.bytes.subarray(c.at, c.at + length));
390
+ c.at += length;
391
+ return value;
392
+ }
393
+ /** Calls `visit` with a section's id, a cursor at its body, its end and its start; stops on `false`. */
394
+ function eachSection(bytes, visit) {
395
+ const header = [0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00];
396
+ if (bytes.length < 8 || !header.every((value, i) => bytes[i] === value))
397
+ throw new RangeError('not a wasm module');
398
+ const c = { bytes, at: 8 };
399
+ while (c.at < bytes.length) {
400
+ const start = c.at;
401
+ const id = byte(c);
402
+ const length = u32(c);
403
+ const end = c.at + length;
404
+ if (end > bytes.length)
405
+ throw truncatedModule();
406
+ if (visit(id, c, end, start) === false)
407
+ return;
408
+ c.at = end;
409
+ }
410
+ }
411
+ /**
412
+ * Reads memory 0 from the import and memory sections, without binaryen. `raise(pages)` returns the
413
+ * bytes with a defined memory's initial pages raised to `pages` (the same bytes if it is already
414
+ * large enough or imported); only the memory section is rewritten, so data segments, names and
415
+ * every other section stay as they are.
416
+ */
417
+ function findMemory(bytes) {
418
+ const imported = memoryImports(bytes)[0];
419
+ if (imported) {
420
+ const { initial, maximum, shared, memory64 } = imported;
421
+ const memory = { imported: true, initial, maximum, shared, memory64 };
422
+ return { memory, raise: () => bytes };
423
+ }
424
+ let found;
425
+ eachSection(bytes, (id, c, end, start) => {
426
+ if (id !== 5)
427
+ return;
428
+ const body = c.at;
429
+ if (u32(c) === 0)
430
+ return false;
431
+ const flags = u32(c);
432
+ if (flags & ~7)
433
+ throw new RangeError(`unsupported memory flags ${flags}`);
434
+ const limit = flags & 4 ? u64 : u32;
435
+ const from = c.at;
436
+ const initial = limit(c);
437
+ const to = c.at;
438
+ const maximum = flags & 1 ? limit(c) : undefined;
439
+ const memory = {
440
+ imported: false,
441
+ initial,
442
+ maximum,
443
+ shared: Boolean(flags & 2),
444
+ memory64: Boolean(flags & 4)
445
+ };
446
+ const raise = (pages) => {
447
+ if (pages <= initial)
448
+ return bytes;
449
+ const inner = [
450
+ ...bytes.subarray(body, from),
451
+ ...leb(pages),
452
+ ...bytes.subarray(to, end)
453
+ ];
454
+ return Uint8Array.from([
455
+ ...bytes.subarray(0, start),
456
+ id,
457
+ ...leb(inner.length),
458
+ ...inner,
459
+ ...bytes.subarray(end)
460
+ ]);
461
+ };
462
+ found = { memory, raise };
463
+ return false;
464
+ });
465
+ return found;
466
+ }
467
+ /** Imported plus defined memories. */
468
+ function memoryCount(bytes) {
469
+ let defined = 0;
470
+ eachSection(bytes, (id, c) => {
471
+ if (id !== 5)
472
+ return;
473
+ defined = u32(c);
474
+ return false;
475
+ });
476
+ return memoryImports(bytes).length + defined;
477
+ }
478
+ /**
479
+ * The name binaryen gives memory 0: the names section entry when there is one, else `mimport$0`
480
+ * for an imported memory and `0` for a defined one.
481
+ */
482
+ function memoryName(bytes, imported) {
483
+ let found = imported ? 'mimport$0' : '0';
484
+ eachSection(bytes, (id, c, end) => {
485
+ if (id !== 0 || name(c) !== 'name')
486
+ return;
487
+ while (c.at < end) {
488
+ const sub = byte(c);
489
+ const size = u32(c);
490
+ const stop = c.at + size;
491
+ if (sub === 6) {
492
+ for (let n = u32(c); n > 0; n--) {
493
+ const index = u32(c);
494
+ const value = name(c);
495
+ if (index === 0)
496
+ found = value;
497
+ }
498
+ return false;
499
+ }
500
+ c.at = stop;
501
+ }
502
+ });
503
+ return found;
504
+ }
505
+ /** Active data segments of memory 0 with constant offsets; any other offset form is refused. */
506
+ function activeSegments(bytes) {
507
+ const segments = [];
508
+ eachSection(bytes, (id, c) => {
509
+ if (id !== 11)
510
+ return;
511
+ for (let n = u32(c); n > 0; n--) {
512
+ const flags = u32(c);
513
+ if (flags > 2)
514
+ throw new RangeError(`unsupported data segment flags ${flags}`);
515
+ const memory = flags === 2 ? u32(c) : 0;
516
+ let offset = 0;
517
+ if (flags !== 1) {
518
+ const opcode = byte(c);
519
+ if (opcode === 0x41)
520
+ offset = s32(c) >>> 0;
521
+ else if (opcode === 0x42)
522
+ offset = s64(c);
523
+ else
524
+ throw new RangeError('unsupported data segment offset');
525
+ if (byte(c) !== 0x0b)
526
+ throw new RangeError('unsupported data segment offset');
527
+ }
528
+ const length = u32(c);
529
+ if (c.at + length > bytes.length)
530
+ throw truncatedModule();
531
+ if (flags !== 1 && memory === 0)
532
+ segments.push({ offset, data: bytes.subarray(c.at, c.at + length) });
533
+ c.at += length;
534
+ }
535
+ return false;
536
+ });
537
+ return segments;
538
+ }
539
+ /**
540
+ * Plays a baked module's active data segments over zeroed memory and compares each image page
541
+ * with the result, without instantiating. It reads the module bytes directly, so it works the same
542
+ * whether memory 0 is imported or defined. Passive segments are ignored, an offset other than
543
+ * `i32.const` or `i64.const` throws, and only the image pages are checked, not globals or other
544
+ * pages.
545
+ */
546
+ export function checkBaked(baked, image) {
547
+ assertImage(image);
548
+ const memory = new Uint8Array(image.byteLength);
549
+ for (const { offset, data } of activeSegments(baked))
550
+ if (offset < memory.length)
551
+ memory.set(data.subarray(0, memory.length - offset), offset);
552
+ for (let i = 0; i < image.pages.length; i++) {
553
+ const diff = firstDifference(memory, image.pages[i] * pageBytes, image.data, i * pageBytes);
554
+ if (diff >= 0)
555
+ return { equal: false, firstDifference: image.pages[i] * pageBytes + diff };
556
+ }
557
+ return { equal: true };
558
+ }
559
+ /**
560
+ * Every offset at which a needle's bytes occur in the image pages, ascending per needle. A match
561
+ * may span adjacent image pages and never spans a gap, so a needle straddling a delta page and an
562
+ * unchanged page is not found. Overlapping matches are all reported. A baked image is public, so
563
+ * this is how to prove a secret is not in it: pass the secret as bytes, and its base64 and hex
564
+ * forms as further needles.
565
+ */
566
+ export function findInImage(image, needles) {
567
+ assertImage(image);
568
+ needles.forEach((needle, i) => {
569
+ if (!needle.length)
570
+ throw new TypeError(`needle ${i} is empty`);
571
+ });
572
+ const found = [];
573
+ for (let i = 0; i < image.pages.length;) {
574
+ let j = i;
575
+ while (j + 1 < image.pages.length && image.pages[j + 1] === image.pages[j] + 1)
576
+ j++;
577
+ const run = image.data.subarray(i * pageBytes, (j + 1) * pageBytes);
578
+ const base = image.pages[i] * pageBytes;
579
+ needles.forEach((needle, index) => {
580
+ for (let at = run.indexOf(needle[0]); at >= 0; at = run.indexOf(needle[0], at + 1)) {
581
+ if (at + needle.length > run.length)
582
+ break;
583
+ let k = 1;
584
+ while (k < needle.length && run[at + k] === needle[k])
585
+ k++;
586
+ if (k === needle.length)
587
+ found.push({ needle: index, offset: base + at });
588
+ }
589
+ });
590
+ i = j + 1;
591
+ }
592
+ return found.sort((a, b) => a.needle - b.needle || a.offset - b.offset);
593
+ }
594
+ const latin1 = (data) => {
595
+ let text = '';
596
+ for (let at = 0; at < data.length; at += 8192)
597
+ text += String.fromCharCode(...data.subarray(at, at + 8192));
598
+ return text;
599
+ };
600
+ /** appends one active segment through the C entry point; setMemory drops the module's own segments */
601
+ function addSegment(binaryen, mod, segment, memory, offset, data, memory64) {
602
+ const api = binaryen;
603
+ const pointers = [];
604
+ const text = (value) => {
605
+ const pointer = api._malloc(value.length + 1);
606
+ api.stringToAscii(value, pointer);
607
+ pointers.push(pointer);
608
+ return pointer;
609
+ };
610
+ const segmentName = text(segment);
611
+ const memoryName = text(memory);
612
+ const bytes = text(latin1(data));
613
+ api._BinaryenAddDataSegment(mod.ptr, segmentName, memoryName, 0, memory64 ? mod.i64.const(BigInt(offset)) : mod.i32.const(offset | 0), bytes, data.length);
614
+ pointers.forEach((pointer) => api._free(pointer));
615
+ }
616
+ function setGlobal(binaryen, mod, index, value) {
617
+ const api = binaryen;
618
+ const refuse = (detail) => new ImageMismatchError('global', `global ${index} ${detail}`);
619
+ if (!Number.isInteger(index) || index < 0 || index >= mod.getNumGlobals())
620
+ throw refuse('does not exist');
621
+ const info = binaryen.getGlobalInfo(mod.getGlobalByIndex(index));
622
+ if (!info.mutable)
623
+ throw refuse('is not mutable');
624
+ if (!info.init || binaryen.getExpressionId(info.init) !== binaryen.ConstId)
625
+ throw refuse('is imported or has no constant initial value');
626
+ const type = info.type;
627
+ if (type === binaryen.i32 && typeof value === 'number' && Number.isInteger(value))
628
+ api._BinaryenConstSetValueI32(info.init, value | 0);
629
+ else if (type === binaryen.i64 && typeof value === 'bigint')
630
+ api._BinaryenConstSetValueI64(info.init, BigInt.asIntN(64, value));
631
+ else if (type === binaryen.f32 && typeof value === 'number')
632
+ api._BinaryenConstSetValueF32(info.init, value);
633
+ else if (type === binaryen.f64 && typeof value === 'number')
634
+ api._BinaryenConstSetValueF64(info.init, value);
635
+ else
636
+ throw refuse(`has a type that ${typeof value} does not fit`);
637
+ }
638
+ /**
639
+ * Returns the module with the image pages as active data segments after its own segments, and
640
+ * the image's changed mutable globals written as their initial values. Adjacent pages merge into
641
+ * one segment, split at `maxSegmentBytes`. The module must have exactly one memory.
642
+ *
643
+ * An imported memory is left alone: whoever instantiates the baked module creates it with at least
644
+ * `imagePages(image).memoryPages` pages. A defined memory whose initial pages are below the image
645
+ * size has them raised to the image size (only the memory section changes); its maximum, shared
646
+ * flag and memory64 flag stay as they are, and one already large enough is untouched.
647
+ *
648
+ * Throws `ImageMismatchError` for a wrong module digest (taken over `bytes` as passed), a module
649
+ * with no memory or with more than one, an image over the memory maximum, a global that cannot be rewritten and changed
650
+ * table slots (unless `allowTableChanges`).
651
+ */
652
+ export async function bakeModule(bytes, image, options = {}) {
653
+ assertImage(image);
654
+ const cap = options.maxSegmentBytes ?? maxSegmentBytes;
655
+ if (!Number.isInteger(cap) || cap < pageBytes || cap % pageBytes)
656
+ throw new RangeError('maxSegmentBytes must be a positive multiple of 65,536');
657
+ if (image.module !== undefined) {
658
+ const found = await moduleDigest(bytes);
659
+ if (found !== image.module)
660
+ throw new ImageMismatchError('digest', `image is for ${image.module}, module is ${found}`);
661
+ }
662
+ if (image.tableSlots?.length && !options.allowTableChanges)
663
+ throw new ImageMismatchError('table', `boot changed ${image.tableSlots.length} table slots`);
664
+ const located = findMemory(bytes);
665
+ if (!located)
666
+ throw new ImageMismatchError('no-memory', 'no memory');
667
+ const memories = memoryCount(bytes);
668
+ if (memories > 1)
669
+ throw new ImageMismatchError('memories', `module has ${memories} memories, only 1 is baked`);
670
+ const { memory: zero } = located;
671
+ const pages = image.byteLength / pageBytes;
672
+ if (zero.maximum !== undefined && pages > zero.maximum)
673
+ throw new ImageMismatchError('maximum', `image has ${pages} pages, maximum is ${zero.maximum}`);
674
+ const binaryen = (await import('binaryen')).default;
675
+ const mod = binaryen.readBinary(located.raise(pages));
676
+ try {
677
+ for (const [key, value] of Object.entries(image.globals ?? {}))
678
+ setGlobal(binaryen, mod, Number(key), value);
679
+ const memory = memoryName(bytes, zero.imported);
680
+ let count = 0;
681
+ const fresh = () => {
682
+ while (mod.getDataSegment(`folio_image${count}`))
683
+ count++;
684
+ return `folio_image${count++}`;
685
+ };
686
+ for (let i = 0; i < image.pages.length;) {
687
+ let j = i;
688
+ while (j + 1 < image.pages.length && image.pages[j + 1] === image.pages[j] + 1)
689
+ j++;
690
+ for (let from = i; from <= j; from += cap / pageBytes) {
691
+ const to = Math.min(j + 1, from + cap / pageBytes);
692
+ addSegment(binaryen, mod, fresh(), memory, image.pages[from] * pageBytes, image.data.subarray(from * pageBytes, to * pageBytes), zero.memory64);
693
+ }
694
+ i = j + 1;
695
+ }
696
+ return mod.emitBinary();
697
+ }
698
+ finally {
699
+ mod.dispose();
700
+ }
701
+ }