@threadedstack/wmd-web 0.1.37 → 0.1.39

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/src/boot.js CHANGED
@@ -45,9 +45,10 @@ import {
45
45
  CONSOLE_IN_LIMIT, chanCounters, chanView, consoleInputGate, createChanBlock, markGuestGone, markServiceDead, ringBell, ringRead,
46
46
  } from './host/chan.js'
47
47
  import { ControlClient } from './host/ctl.js'
48
+ import { chooseTwin, eventsOf, putBackTwin, specKeysDiffering, twinForBoot } from './gowasm/boot-setup.js'
48
49
  import { PAGE as CKPT_PAGE, requestCheckpoint } from './host/ckpt-point.js'
49
50
  import {
50
- CheckpointError, serviceErrorCode, assembleCheckpoint, bootKeyOf, checkCheckpointFits, checkPacksFit, checkVmKeyFits, packDigestsOf, fdTableBytes, parseCheckpoint, restoreFdTable, resumePorts, sha256Hex, validateFdTable,
51
+ CheckpointError, serviceErrorCode, assembleCheckpoint, bootKeyForChoice, bootKeyOf, checkCheckpointFits, checkPacksFit, checkVmKeyFits, packDigestsOf, fdTableBytes, parseCheckpoint, restoreFdTable, resumePorts, sha256Hex, validateFdTable,
51
52
  } from './host/ckpt.js'
52
53
  import { captureJit, jitSnapStats, modulesOf, ownersNeedingHub, restoreStore } from './host/jit-snap.js'
53
54
  export { CheckpointError, memoryStore, opfsStore } from './host/ckpt.js'
@@ -223,13 +224,15 @@ const fmtMiB = n => (Number.isFinite(n) ? `${Math.round((n / MiB) * 10) / 10} Mi
223
224
  * maximum is the whole 4 GiB (MEMORY0_SLACK_MIB): `slack` and maxPages cannot give more room there, so the text says a smaller guest RAM or
224
225
  * dropping the option (X24). Every other layout gets the one text it always had.
225
226
  */
226
- export function outOfMemoryText({ memoryBytes, memoryMaxBytes, reason, ramInMemory0 = false }) {
227
+ export function outOfMemoryText({ memoryBytes, memoryMaxBytes, reason, ramInMemory0 = false, named = true }) {
227
228
  const head = `out of memory: the emulator used ${fmtMiB(memoryBytes)} of its ${fmtMiB(memoryMaxBytes)} memory maximum and stopped (${reason}); `
228
229
  if (ramInMemory0) {
230
+ // `named`: the caller set the option itself. When the default or a checkpoint chose the layout there is no option to drop: say how to ask for the flat layout.
231
+ const way = named ? 'drop the option ramInMemory0 (the flat layout)' : 'ask for the flat layout (ramInMemory0: false, or flatRam: true)'
229
232
  return (
230
233
  head +
231
234
  "the option ramInMemory0 keeps the guest's RAM in memory 0 and fixes its maximum at the whole 4 GiB, so there is no more room to give: " +
232
- 'use a smaller guest RAM (--ram), or drop the option ramInMemory0 (the flat layout)'
235
+ `use a smaller guest RAM (--ram), or ${way}`
233
236
  )
234
237
  }
235
238
  return head + "give it more room above the guest's RAM (bootWmd maxPages, memoryMaxPages(args, slackMiB))"
@@ -291,12 +294,27 @@ export function memory0RamLimit(nav = globalThis.navigator, mem64 = haveMemory64
291
294
  }
292
295
 
293
296
  /**
294
- * X24: whether the option `o.ramInMemory0` (default off) puts this boot's RAM in memory 0 although it is above
295
- * MAX_BROWSER_RAM_MIB: true only when the option is true, flatRam is not forced on and --ram is above
296
- * MAX_BROWSER_RAM_MIB and at most the engine's limit. With the option absent it is always false.
297
+ * X24 default (#70): the value of the option `ramInMemory0` when the caller does not name it. This is the one line the flip changes
298
+ * (the test page's `?asDefault=1` and the unit tests set it, so they take the code path the flip takes). Not a caller's setting.
299
+ */
300
+ export const RAM_IN_MEMORY0 = { default: true }
301
+
302
+ /**
303
+ * Whether the option `ramInMemory0` is on for this value: absent (undefined or null) is RAM_IN_MEMORY0.default; a value that is named
304
+ * is on only when it is exactly true (false, 0, 1, '1', 'true' are off).
305
+ */
306
+ export function ramInMemory0On(v) {
307
+ return v === undefined || v === null ? RAM_IN_MEMORY0.default === true : v === true
308
+ }
309
+
310
+ /**
311
+ * X24: whether the option `ramInMemory0` (on for `o.ramInMemory0`, see ramInMemory0On) puts this boot's RAM in memory 0 although it is
312
+ * above MAX_BROWSER_RAM_MIB: true only when the option is on, flatRam is not forced on and --ram is above MAX_BROWSER_RAM_MIB and at
313
+ * most the engine's limit. An option that is on only by the default gives way to a caller's own allowLargeRam: true (its memory 0, its slack).
297
314
  */
298
315
  export function wantsRamInMemory0(args, o = {}, nav = globalThis.navigator, mem64 = haveMemory64()) {
299
- if (o.ramInMemory0 !== true || o.flatRam === true) return false
316
+ if (!ramInMemory0On(o.ramInMemory0) || o.flatRam === true) return false
317
+ if ((o.ramInMemory0 === undefined || o.ramInMemory0 === null) && o.allowLargeRam === true) return false
300
318
  let mib = 0
301
319
  try {
302
320
  mib = ramMiB(args, true)
@@ -444,6 +462,80 @@ export function memoryMaxPages(args, slackMiB = 1024, allowLargeRam = false) {
444
462
  return Math.min(65536, pages)
445
463
  }
446
464
 
465
+ /**
466
+ * X24 default (#70): the RAM layout a checkpoint (or base snapshot) header says it was taken with: {flat, maxPages}, or null when the header
467
+ * does not say it plainly (no boot description, an environment that is not a list, a memory maximum that is not a whole number of pages
468
+ * between vm.wasm's minimum and 4 GiB, a RAM size in `ramPages` that is not this boot's --ram, ramPages and the environment entry
469
+ * WMD_RAM_FLAT=1 that disagree, or another --ram than `mib`). A null header is refused later by checkCheckpointFits with the text it always had.
470
+ */
471
+ export function checkpointLayout(h, mib) {
472
+ const d = h && h.bootDesc
473
+ if (!mib || !d || !Array.isArray(d.env) || !Array.isArray(h.args)) return null
474
+ let hm = 0
475
+ try {
476
+ hm = ramMiB(h.args, true)
477
+ } catch {
478
+ return null
479
+ }
480
+ if (hm !== mib) return null
481
+ const mp = d.maxPages
482
+ if (!Number.isInteger(mp) || mp < VM_MIN_PAGES || mp > MEMORY0_MAX_PAGES) return null
483
+ const rp = h.ramPages === undefined ? 0 : h.ramPages
484
+ if (!Number.isInteger(rp) || rp < 0) return null
485
+ const flat = rp > 0
486
+ if (flat !== d.env.includes('WMD_RAM_FLAT=1')) return null
487
+ if (flat && rp !== mib * 16) return null
488
+ return { flat, maxPages: mp }
489
+ }
490
+
491
+ /**
492
+ * X24 default (#70): the RAM layout of a boot: {flat, maximum (memory 0's maximum, pages), ramPages (the RAM memory's 64 KiB pages, 0 when the
493
+ * RAM is in memory 0), ramMiB, why, options, changed}. The options choose it (flatRam; else the option ramInMemory0, whose value is
494
+ * RAM_IN_MEMORY0.default when absent; else allowLargeRam; else the RAM size), and a checkpoint or base snapshot header, when it says its own
495
+ * layout (checkpointLayout) and this browser can make it, decides instead: a flat checkpoint boots flat and a memory 0 checkpoint boots
496
+ * memory 0, with the checkpoint's memory maximum, whatever the default or the options say. `why` is 'checkpoint', 'flatRam',
497
+ * 'ramInMemory0' (the option named true), 'default' (the option on by the default), 'allowLargeRam' or 'ram' (the RAM size alone);
498
+ * `options` is the layout the options alone would have chosen and `changed` says the checkpoint moved it. Throws what a boot threw
499
+ * for a bad or too big --ram (the old refusal text) and for flatRam: true in a browser with no memory64.
500
+ */
501
+ export function chooseLayout(args, o = {}, header = null, nav = globalThis.navigator, mem64 = haveMemory64()) {
502
+ let mib = 0
503
+ try {
504
+ mib = ramMiB(args, true)
505
+ } catch {
506
+ mib = 0 // ramMiB (below, or the caller) reports the bad value
507
+ }
508
+ const flat0 = wantsFlatRam(args, o, nav, mem64)
509
+ const whole0 = !flat0 && wantsRamInMemory0(args, o, nav, mem64)
510
+ if (!flat0) ramMiB(args, o.allowLargeRam || whole0) // a bad or too big --ram is a clear error before anything is downloaded
511
+ const maximum0 = o.maxPages || (flat0 ? flatMaxPages(args) : memoryMaxPagesFor(args, o, 1024, nav, mem64))
512
+ const named = o.ramInMemory0 !== undefined && o.ramInMemory0 !== null
513
+ const why0 =
514
+ o.flatRam === true || o.flatRam === false
515
+ ? 'flatRam'
516
+ : whole0
517
+ ? named
518
+ ? 'ramInMemory0'
519
+ : 'default'
520
+ : mib > MAX_BROWSER_RAM_MIB && o.allowLargeRam === true
521
+ ? 'allowLargeRam'
522
+ : 'ram'
523
+ const kind = (flat, maxPages) => (flat ? 'flat' : mib > MAX_BROWSER_RAM_MIB && maxPages === MEMORY0_MAX_PAGES ? 'whole' : 'plain')
524
+ const out = (flat, maximum, why, changed) => ({ flat, maximum, ramPages: flat ? mib * 16 : 0, ramMiB: mib, why, options: flat0 ? 'flat' : 'memory0', changed })
525
+ const ck = header ? checkpointLayout(header, mib) : null
526
+ if (ck) {
527
+ // can this browser make the layout the checkpoint has? flat needs a second memory; memory 0 above 1536 MiB needs the engine's limit or allowLargeRam
528
+ const can = ck.flat
529
+ ? mem64
530
+ : mib <= MAX_BROWSER_RAM_MIB || (ck.maxPages === MEMORY0_MAX_PAGES && mib <= memory0RamLimit(nav, mem64)) || o.allowLargeRam === true
531
+ if (can) {
532
+ const moved = kind(ck.flat, ck.maxPages) !== kind(flat0, maximum0)
533
+ return out(ck.flat, moved ? ck.maxPages : maximum0, 'checkpoint', moved)
534
+ }
535
+ }
536
+ return out(flat0, maximum0, why0, false)
537
+ }
538
+
447
539
  /**
448
540
  * Time the throttle detector's calibration loop n times now (in its own Worker) and
449
541
  * resolve with the fastest run, in ms. A page can call this while it is in the
@@ -609,6 +701,19 @@ export async function bootWmd(o) {
609
701
  const t0 = absMs()
610
702
  const timings = { t0 }
611
703
  const ev = e => o.onEvent?.(e)
704
+ // X6 part 3: the Go twin's setup (src/gowasm/boot-setup.js): stub mounts in the bundle's spec and the service's gowasm field, from the pins; nothing for a
705
+ // caller that passed `gowasm: false`, named no source and has no default, or whose service has its own gowasm field
706
+ // Part 4: a boot that restores takes the twin choice its checkpoint was taken with (chooseTwin): here for a checkpoint in hand (o.restore), when the
707
+ // base snapshot's header is known for o.restoreLazy (below, with the layout), in vm.restore() before the running machine is stopped. A checkpoint taken
708
+ // with the twin that this boot has off (gowasm: false, no source, a setup that is not usable) restores (part 6): its spec text stays (the guest has the stub mounts),
709
+ // the service's gowasm field says `off` so the page starts no twin Worker, the channel service builds a GoEdge that is off from the start (every stub is answered
710
+ // with the fallback, the guest compiles), and one event {t: 'gowasm-off', rule: 'checkpoint-twin'} says so.
711
+ const twin = await twinForBoot(o)
712
+ const twinFirst = await chooseTwin(twin, o.restore?.header || null)
713
+ o = twinFirst.o
714
+ // the twin's events are said once: now, or, for a base snapshot (o.restoreLazy), when its header is known (its choice may supersede the boot's own reason)
715
+ let twinSaid = !o.restoreLazy
716
+ if (twinSaid) for (const e of eventsOf(twin, twinFirst)) ev(e)
612
717
  // W24: the start-up events (host/boot-events.js); be.close() at the end
613
718
  const be = createBootEvents({ emit: ev, t0, now: absMs })
614
719
  // the emulator's last stderr text, for the error a wait on a dead machine gives
@@ -630,13 +735,29 @@ export async function bootWmd(o) {
630
735
  // The flat layout (host/ram-mem.js): a guest with more RAM than memory 0 can hold gets its RAM in a memory64 of its
631
736
  // own. Chosen when --ram is above MAX_BROWSER_RAM_MIB and the engine has memory64 (o.flatRam forces it on or off);
632
737
  // without it such a --ram is the error it was.
633
- const flatRam = wantsFlatRam(o.args, o)
634
- if (!flatRam) ramMiB(o.args, o.allowLargeRam || wantsRamInMemory0(o.args, o)) // a bad or too big --ram is a clear error before anything is downloaded
635
- const maximum = o.maxPages || (flatRam ? flatMaxPages(o.args) : memoryMaxPagesFor(o.args, o))
636
- if (flatRam) env.push('WMD_RAM_FLAT=1')
637
- const ramMem = flatRam ? createRamMemory(ramMiB(o.args, true)) : null
738
+ // X24 default (#70): chooseLayout. A restore (o.restore, or a base snapshot's header once it is known) boots with the layout its checkpoint
739
+ // was taken with, whatever the default or the options say; settleLayout makes the second memory of a flat layout and tells the page once.
740
+ const layout0 = chooseLayout(o.args, o, o.restore?.header || null) // a bad or too big --ram is a clear error before anything is downloaded
741
+ let layout = layout0
742
+ let flatRam = layout0.flat
743
+ let maximum = layout0.maximum
744
+ let ramMem = null
638
745
  /** The RAM memory's pages (0: the RAM is in memory 0). A checkpoint of a flat guest also holds its RAM memory's pages (sections ram-index, ram). */
639
- const ramPages = ramMem ? ramMem.buffer.byteLength / CKPT_PAGE : 0
746
+ let ramPages = 0
747
+ let layoutSaid = false
748
+ const settleLayout = L => {
749
+ layout = L
750
+ flatRam = L.flat
751
+ maximum = L.maximum
752
+ const i = env.indexOf('WMD_RAM_FLAT=1')
753
+ if (i >= 0) env.splice(i, 1)
754
+ if (flatRam) env.push('WMD_RAM_FLAT=1')
755
+ ramMem = flatRam ? createRamMemory(L.ramMiB) : null
756
+ ramPages = L.ramPages // = ramMem.buffer.byteLength / CKPT_PAGE: createRamMemory(mib) holds mib * 16 pages
757
+ layoutSaid = true
758
+ be.now('layout', { t: 'boot', stage: 'layout', layout: flatRam ? 'flat' : 'memory0', why: L.why, options: L.options, ramMiB: L.ramMiB, maxPages: L.maximum })
759
+ }
760
+ if (!o.restoreLazy) settleLayout(layout0) // a base snapshot's layout is known when its header is
640
761
  // P-B9: checkpoints. restoreIn: the checkpoint's parts (parseCheckpoint refuses a malformed one).
641
762
  const ckptOn = !!o.checkpoint || !!o.restore || !!o.restoreLazy
642
763
  let restoreIn = o.restore ? parseCheckpoint(o.restore) : null
@@ -749,7 +870,7 @@ export async function bootWmd(o) {
749
870
  })
750
871
  filesP.catch(() => {}) // awaited below; must not go unhandled if vm.wasm fails first
751
872
  // P-B3: the channel services' packs (fetched in parallel with the rest); pack:<n> numbers them over all services
752
- const chanSvcs = o.channels?.services || []
873
+ let chanSvcs = o.channels?.services || []
753
874
  let packN = 0
754
875
  const packIds = chanSvcs.map(svc => (svc.layers || []).map(() => packN++))
755
876
  const layersP = A
@@ -761,7 +882,9 @@ export async function bootWmd(o) {
761
882
  ).then(downloaded)
762
883
  layersP.catch(() => {})
763
884
  let module, files, chanLayers, tableMin, vmBytes
764
- function baseRefused(err) {
885
+ let twinByBase = false // the base snapshot's header changed the twin choice (a header refused after that puts the options' choice back)
886
+ let twinChosen = null // chooseTwin's answer for the base snapshot's header: its events are said when the snapshot is accepted (or the options' own, when it is refused)
887
+ async function baseRefused(err) {
765
888
  const lazy = lazyIn || baseLazy
766
889
  lazyIn = null
767
890
  baseLazy = null
@@ -769,6 +892,21 @@ export async function bootWmd(o) {
769
892
  lazy?.abort?.(err)
770
893
  } catch {}
771
894
  if (!o.restoreFallback) throw err
895
+ // fix 10 (F1): the machine boots cold, so it takes the options' own twin choice (spec text, gowasm field, boot key) whatever refused the snapshot, the header or
896
+ // the checks of its body: this is the one place
897
+ if (twinByBase) {
898
+ const back = await putBackTwin(twin, o, bootDesc, { flat: flatRam, maxPages: maximum })
899
+ o = back.o
900
+ chanSvcs = o.channels?.services || []
901
+ twinByBase = false
902
+ if (back.key) {
903
+ bootKey = back.key.key
904
+ bootDesc = back.key.desc
905
+ if (heldAssets) heldAssets.keys = { ...heldAssets.keys, bootKey, bootDesc }
906
+ }
907
+ }
908
+ if (!twinSaid) for (const e of twin.events) ev(e)
909
+ twinSaid = true
772
910
  timings.baseFallback = { code: err && err.code ? err.code : 'error', message: err && err.message ? err.message : String(err) }
773
911
  // W24: the restore stage ends here, unused; the kernel stage follows
774
912
  be.now('restore', { t: 'boot', stage: 'restore', state: 'done', used: false, fallback: timings.baseFallback.code, bytes: baseBytes, total: baseTotal, source: baseSource })
@@ -782,12 +920,25 @@ export async function bootWmd(o) {
782
920
  try {
783
921
  const h = await raceAbort(lazyIn.header)
784
922
  checkVmKeyFits(h, vmKey)
923
+ settleLayout(chooseLayout(o.args, o, h)) // X24 default: the base snapshot's own layout
924
+ // part 4: and its own twin choice. The spec text is first used by the boot key and by the channel service's Worker, both below this point in this same
925
+ // try, so the choice made here is made before either has it; only the layers and ports of the services were used before (their packs download meanwhile)
926
+ const tw = await chooseTwin(twin, h)
927
+ if (tw.o !== o) {
928
+ o = { ...o, channels: tw.o.channels }
929
+ chanSvcs = o.channels?.services || []
930
+ twinByBase = true
931
+ }
932
+ twinChosen = tw
785
933
  lazyIn.proceed?.() // the reader decodes only from here: a refused header costs what was queued, not the file
786
934
  } catch (err) {
787
935
  if (signal?.aborted) throw err
788
- baseRefused(err)
936
+ await baseRefused(err) // (the machine that boots cold takes the options' own twin choice back there, whatever refused the snapshot)
789
937
  }
790
938
  }
939
+ if (!twinSaid && !lazyIn) for (const e of twin.events) ev(e) // no base snapshot after all
940
+ if (!lazyIn) twinSaid = true
941
+ if (!layoutSaid) settleLayout(layout0) // no base snapshot, or its header was refused: the options' layout
791
942
  const tc = absMs()
792
943
  be.now('compile', { t: 'boot', stage: 'compile', state: 'start', moduleBytes: vmBytes.byteLength, reused: !!A })
793
944
  module = A ? A.module : await raceAbort(WebAssembly.compile(vmBytes))
@@ -808,9 +959,20 @@ export async function bootWmd(o) {
808
959
  const tk = absMs()
809
960
  let packs
810
961
  if (A) {
811
- bootKey = A.keys.bootKey
812
- bootDesc = A.keys.bootDesc
813
962
  packs = A.keys.packs
963
+ const ad = A.keys.bootDesc
964
+ // part 4: the spec texts of this boot (the twin choice the checkpoint made) against the ones the assets' machine had
965
+ const cfgKeys = ad ? await specKeysDiffering(ad, chanSvcs) : {}
966
+ if (!ad || (ad.maxPages === maximum && Array.isArray(ad.env) && ad.env.includes('WMD_RAM_FLAT=1') === flatRam && !Object.keys(cfgKeys).length)) {
967
+ bootKey = A.keys.bootKey
968
+ bootDesc = A.keys.bootDesc
969
+ } else {
970
+ // X24 default: the checkpoint chose another RAM layout than the machine these assets came from had: the same key, with that layout
971
+ // (part 4: and the same with the other spec text when the checkpoint chose another twin state)
972
+ const k = await bootKeyForChoice(ad, { flat: flatRam, maxPages: maximum }, cfgKeys)
973
+ bootKey = k.key
974
+ bootDesc = k.desc
975
+ }
814
976
  } else {
815
977
  // the boot key samples each pack (head and tail); packs is the full digest of every layer (a SHA-256 tree over 8 MiB pieces), recorded in
816
978
  // every checkpoint this boot takes and checked against a base snapshot's before it is used
@@ -847,10 +1009,12 @@ export async function bootWmd(o) {
847
1009
  checkCheckpointFits(parsed.header, { vmKey, bootKey, bootDesc, maxPages: maximum, ramPages, hasJit: o.jit !== false, fmaFused: fmaFuses() })
848
1010
  checkPacksFit(parsed.header.packs, packDigests)
849
1011
  restoreIn = parsed
1012
+ if (!twinSaid) for (const e of twinChosen ? eventsOf(twin, twinChosen) : twin.events) ev(e) // the snapshot is accepted: the checkpoint's twin choice stands
1013
+ twinSaid = true
850
1014
  lazyIn = null // baseLazy stays: accept() when the restore has succeeded, reject() if it fails
851
1015
  } catch (err) {
852
1016
  if (signal?.aborted) throw err
853
- baseRefused(err)
1017
+ await baseRefused(err)
854
1018
  }
855
1019
  }
856
1020
  if (restoreIn) checkCheckpointFits(restoreIn.header, { vmKey, bootKey, bootDesc, maxPages: maximum, ramPages, hasJit: o.jit !== false, fmaFused: fmaFuses() })
@@ -1020,6 +1184,7 @@ export async function bootWmd(o) {
1020
1184
  // P-B10: the network Worker, when a net service has a relay
1021
1185
  let netWorker = null
1022
1186
  let goWorker = null // X6 (default off): the Wasm twin of the guest's Go compiler
1187
+ let goCspOff = null // takes the document's policy-violation listener of the live twin Worker off again
1023
1188
  let netStats = null
1024
1189
  let netMember = null // W56: this guest on an in-page switch (switch.js attach())
1025
1190
  const netWaiters = new Map()
@@ -1131,6 +1296,7 @@ export async function bootWmd(o) {
1131
1296
  else if (m.t === 'gowasm-stop') {
1132
1297
  goWorker?.terminate()
1133
1298
  goWorker = null
1299
+ goCspOff?.()
1134
1300
  }
1135
1301
  else if (m.t === 'gowasm-restart') {
1136
1302
  // the twin was in the middle of a compile that was cancelled: a Worker cannot be stopped inside one, so it ends and a new one starts
@@ -1207,10 +1373,36 @@ export async function bootWmd(o) {
1207
1373
  const mc = new MessageChannel()
1208
1374
  const w = (goWorker = new Worker(new URL('./host/gowasm-worker.js', import.meta.url), { type: 'module', name: 'wmd-gowasm' }))
1209
1375
  w.onerror = err => chanSvc?.postMessage({ t: 'gowasm-died', why: `the twin Worker failed: ${err.message || err}` })
1210
- w.postMessage({ t: 'init', port: mc.port2, wasmUrl: goSvc.gowasm.wasmUrl, wasmSha256: goSvc.gowasm.wasmSha256, modules: goSvc.gowasm.modules, preload: goSvc.gowasm.preload, cacheBytes: goSvc.gowasm.cacheBytes }, [mc.port2])
1376
+ // fix 10 (F4): a policy violation the document sees is told to the Worker too (the Worker listens for its own); its reason text then says the policy blocked the source
1377
+ if (typeof document !== 'undefined') {
1378
+ goCspOff?.() // one listener, for the live Worker
1379
+ const onViolation = e => {
1380
+ if (goWorker !== w) return // that Worker is gone
1381
+ try {
1382
+ w.postMessage({ t: 'csp', violation: { blockedURI: String(e.blockedURI), effectiveDirective: String(e.effectiveDirective || ''), disposition: String(e.disposition || 'enforce') } })
1383
+ } catch {}
1384
+ }
1385
+ document.addEventListener('securitypolicyviolation', onViolation)
1386
+ goCspOff = () => {
1387
+ document.removeEventListener('securitypolicyviolation', onViolation)
1388
+ goCspOff = null
1389
+ }
1390
+ }
1391
+ w.postMessage({ t: 'init', port: mc.port2, wasmUrl: goSvc.gowasm.wasmUrl, wasmSha256: goSvc.gowasm.wasmSha256, modules: goSvc.gowasm.modules, preload: goSvc.gowasm.preload, sources: goSvc.gowasm.sources, cacheBytes: goSvc.gowasm.cacheBytes }, [mc.port2])
1211
1392
  return mc.port1
1212
1393
  }
1213
- const gowasmPort = goSvc ? spawnGoTwin() : null
1394
+ // X6 part 3: a twin Worker that cannot start (a page whose CSP forbids it, no Worker support) must not stop the machine: the channel service takes the
1395
+ // stub mounts out of the bundle (no twin Worker) and one event says why
1396
+ let gowasmPort = null
1397
+ let gowasmWhy = ''
1398
+ // part 6: a service whose gowasm field says `off` (a checkpoint taken with the twin, restored in a boot that has the twin off) gets no Worker
1399
+ if (goSvc && !goSvc.gowasm.off) {
1400
+ try {
1401
+ gowasmPort = spawnGoTwin()
1402
+ } catch (err) {
1403
+ gowasmWhy = `the twin Worker could not start: ${(err && err.message) || err}`
1404
+ }
1405
+ }
1214
1406
  chanSvc.postMessage({
1215
1407
  t: 'init',
1216
1408
  sab: chanSab,
@@ -1231,6 +1423,7 @@ export async function bootWmd(o) {
1231
1423
  netPort,
1232
1424
  edge: o.edge ? { port9p: o.edge.port, root: o.edge.root || '', rt: o.edge.rt || '' } : undefined, // X5 (edge=1 only)
1233
1425
  gowasmPort,
1426
+ gowasmWhy,
1234
1427
  }, [...(netPort ? [netPort] : []), ...(gowasmPort ? [gowasmPort] : [])])
1235
1428
  consoleGate = consoleInputGate(chanSab, o.channels.consoleInputBytes ?? CONSOLE_IN_LIMIT)
1236
1429
  }
@@ -1406,7 +1599,8 @@ export async function bootWmd(o) {
1406
1599
  memoryBytes: timings.memoryBytes,
1407
1600
  memoryMaxBytes: timings.memoryMaxBytes,
1408
1601
  reason,
1409
- ramInMemory0: !flatRam && wantsRamInMemory0(o.args, o) && maximum === MEMORY0_MAX_PAGES, // X24: the whole 4 GiB, no room to give
1602
+ ramInMemory0: !flatRam && maximum === MEMORY0_MAX_PAGES && layout.ramMiB > MAX_BROWSER_RAM_MIB, // X24: the whole 4 GiB, no room to give
1603
+ named: o.ramInMemory0 === true, // the caller set the option itself (else the default or a checkpoint chose the layout)
1410
1604
  })
1411
1605
  emitErr(`\n[wmd-web] ${reason}\n`)
1412
1606
  }
@@ -1446,6 +1640,7 @@ export async function bootWmd(o) {
1446
1640
  failUpperWaiters('the machine has ended (its files ended with it)')
1447
1641
  netWorker?.terminate()
1448
1642
  goWorker?.terminate()
1643
+ goCspOff?.()
1449
1644
  netMember?.detach() // W56: its peers' streams to it fail; the name keeps its address
1450
1645
  if (netWorker) timings.net = netStats
1451
1646
  if (chanSab) timings.chan = { ...chanCounters(chanSab), service: chanStats, died: chanDied }
@@ -1514,6 +1709,7 @@ export async function bootWmd(o) {
1514
1709
  netWorker = null
1515
1710
  if (goWorker) goWorker.onerror = null
1516
1711
  goWorker = null
1712
+ goCspOff?.()
1517
1713
  netMember?.detach()
1518
1714
  module = files = null
1519
1715
  }
@@ -2014,7 +2210,16 @@ export async function bootWmd(o) {
2014
2210
  try {
2015
2211
  // everything that can fail without harming the running machine comes first: the checkpoint parses and is this boot's
2016
2212
  const parsed = parseCheckpoint(ckpt)
2017
- checkCheckpointFits(parsed.header, { vmKey, bootKey, bootDesc, maxPages: maximum, ramPages, hasJit: o.jit !== false, fmaFused: fmaFuses() })
2213
+ // X24 default (#70): the checkpoint decides the next machine's RAM layout (bootWmd does the same from the same header), so the check is
2214
+ // made against that layout's key, memory maximum and RAM memory, not this machine's
2215
+ const L = chooseLayout(o.args, { ...o, ...over }, parsed.header)
2216
+ // part 4: and its twin choice (the next machine's own, from the options as the caller gave them): a checkpoint taken with the twin restores whatever this boot's twin state (chooseTwin keeps its spec text and says the twin is off), the usual fit check follows, before this machine stops
2217
+ const nextOpts = { ...o, channels: twin.plain.channels, ...over }
2218
+ const tw = await chooseTwin(await twinForBoot(nextOpts), parsed.header)
2219
+ const cfgKeys = bootDesc ? await specKeysDiffering(bootDesc, tw.o.channels?.services) : {}
2220
+ let target = { key: bootKey, desc: bootDesc }
2221
+ if (bootDesc && (L.flat !== flatRam || L.maximum !== maximum || Object.keys(cfgKeys).length)) target = await bootKeyForChoice(bootDesc, { flat: L.flat, maxPages: L.maximum }, cfgKeys)
2222
+ checkCheckpointFits(parsed.header, { vmKey, bootKey: target.key, bootDesc: target.desc, maxPages: L.maximum, ramPages: L.ramPages, hasJit: o.jit !== false, fmaFused: fmaFuses() })
2018
2223
  if (!heldAssets) throw new CheckpointError('not-ready', 'this machine was booted without checkpoint support: it has no kept boot files to restore with')
2019
2224
  validateFdTable(parsed.ctl, heldAssets.files.length) // the fd table is checked against this boot's files now, not after the old machine is gone
2020
2225
  // the boot's own bytes (vm.wasm and its compiled Module, the kernel, the packs, the keys) are reused: nothing is
@@ -2033,7 +2238,7 @@ export async function bootWmd(o) {
2033
2238
  memory = null
2034
2239
  oldHub = keptHub
2035
2240
  keptHub = null
2036
- const next = await bootWmd({ ...o, ...over, checkpoint: true, restore: ckpt, assets, _adopt: oldHub, _net: { instance: netInstance, names: [...netNames] } })
2241
+ const next = await bootWmd({ ...nextOpts, checkpoint: true, restore: ckpt, assets, _adopt: oldHub, _net: { instance: netInstance, names: [...netNames] } })
2037
2242
  heldAssets = null // the new machine holds them
2038
2243
  return next
2039
2244
  } finally {
@@ -7,7 +7,7 @@
7
7
  // is built in the page instead (fast.js), unless fast: false.
8
8
 
9
9
  import { blobBytes } from '../blob.js'
10
- import { bootWmd, isWebKit } from '../boot.js'
10
+ import { bootWmd, isWebKit, memory0RamLimit, ramInMemory0On } from '../boot.js'
11
11
  import { MAIN_PROC_ID, containerBundle, fillRunRequest } from '../host/ctl.js'
12
12
  import { DiskError, deleteDisk, openDisk, sweepDisks } from '../host/disk.js'
13
13
  import { p9OptsOfVm } from '../host/p9mount.js'
@@ -397,7 +397,7 @@ function aborted(signal) {
397
397
  * the packs of an {index, packs} or a store hit must match the index's layer digests
398
398
  * @param {{url: string, protocol?: 'wisp'}} o.relay the guest's network
399
399
  * @param {number} [o.ram] MiB (default 1536)
400
- * @param {boolean} [o.ramInMemory0] X24 (default off; only exactly true turns it on): a RAM above 1536 MiB up to the engine's limit (boot.js MEMORY0_RAM_MAX_MIB) stays in memory 0, not flat; above it, flat as today
400
+ * @param {boolean} [o.ramInMemory0] X24 (off by default until the default flips; absent follows boot.js's RAM_IN_MEMORY0.default; only exactly true is on, only exactly false is off): a RAM above 1536 MiB up to the engine's limit (boot.js MEMORY0_RAM_MAX_MIB) stays in memory 0, not flat; above it, flat as today
401
401
  * @param {number} [o.cpus] default 2
402
402
  * @param {{namespace: string, mib?: number}|false} o.disk BuildKit's storage in OPFS (default 10240 MiB); false: memory
403
403
  * @param {string|Uint8Array} o.converter wmdpack.wasm
@@ -572,7 +572,8 @@ export async function createBuilder(o) {
572
572
  ...(o.features !== undefined ? { features: o.features } : {}), // X23: the guest folder's `features` (text, array or Set) when the files are bytes; with URLs bootWmd reads the folder's file
573
573
  args,
574
574
  // X24: with o.ramInMemory0 === true (boot.js's rule: only exactly true) a RAM above 1536 MiB up to the engine's limit stays in memory 0 (boot.js decides); above it, flat
575
- ...(o.ramInMemory0 === true ? { ramInMemory0: true } : ram > 1536 ? { flatRam: true } : {}),
575
+ // X24 default (#70): an option that is absent is boot.js's RAM_IN_MEMORY0.default; false is the way out (flat above 1536 MiB, as before the default)
576
+ ...(o.ramInMemory0 === true || (ramInMemory0On(o.ramInMemory0) && ram > 1536 && ram <= memory0RamLimit()) ? { ramInMemory0: true } : ram > 1536 ? { flatRam: true } : {}),
576
577
  ...(disk ? { disk } : {}),
577
578
  onStderr: s => {
578
579
  stderr = (stderr + s).slice(-16384)
@@ -0,0 +1,175 @@
1
+ // X6 default part 3, item 1: bootWmd does the twin's whole setup alone. Called first thing by bootWmd (src/boot.js) with its options; for each 9P
2
+ // service whose files hold bundle/config/config.json (what containerBundle returns, src/host/ctl.js) it adds the stub mounts to the spec text and sets
3
+ // the service's `gowasm` field with the mount destinations read from that spec. The consumer writes no twin line.
4
+ //
5
+ // What a consumer MAY pass, on bootWmd only:
6
+ // gowasm: false the twin is off; nothing is changed, nothing is said
7
+ // gowasm: { sources: [...] } the ordered sources of the twin's module (default GOWASM_SOURCES_DEFAULT; src/host/pinned-fetch.js)
8
+ // gowasm: { base: 'https://.../gowasm' } one file source: <base>/compile-<go release>.wasm (an app that serves its own copy)
9
+ // gowasm: { limits: {...} } beatLimitMs, readyLimitMs, runLimitMs, earlyReply, lateFallbackAt (tests)
10
+ // gowasm: { pins, packages } the pins and the package names (tests)
11
+ // gowasm: true as undefined, but a missing source list is said (one event) instead of silently off
12
+ // A service that already has its own `gowasm` field (a caller that calls gowasmSetup itself, the test page) is left as it is; a spec that already has
13
+ // the mounts (a caller that still passes `edge` to containerBundle) gets nothing added: adding twice changes nothing.
14
+ // The image decides: the channel service's Worker takes the stub mounts out of the spec for an image with no Go compile (GoEdge.pruneBundle) or when the
15
+ // twin's code cannot be loaded (noTwin), before the guest reads the spec; an image with a Go release that has no pin keeps the stubs, and its compiles go
16
+ // to the guest with one calm event (GoEdge, rule 'unpinned').
17
+ // A checkpoint: the service files are part of the boot key, so the spec text (with or without the twin's stub mounts) says which choice a checkpoint was taken with.
18
+ // A boot that restores takes the choice its checkpoint was taken with (chooseTwin, below), the way X24's RAM layout does (chooseLayout): a checkpoint taken
19
+ // without the twin restores into a boot that would have the twin on, and runs without it (one event, rule 'checkpoint'); a checkpoint taken with the twin keeps it,
20
+ // and one taken with the twin ALWAYS restores, also in a boot that has the twin off (gowasm: false, no source, a setup that is not usable): it keeps its own spec
21
+ // text (the guest has the stub mounts), the service's gowasm field says `off` (no Worker, nothing fetched), every compile runs in the guest, one event, rule
22
+ // 'checkpoint-twin'. A header with no boot description, or whose spec text is neither, changes nothing.
23
+ import { addEdgeToolMounts } from '../host/ctl.js'
24
+ import { bootKeyForChoice, sampleKey, specChoice } from '../host/ckpt.js'
25
+ import { GOWASM_SOURCES_DEFAULT, planOf } from './setup.js'
26
+
27
+ export { GOWASM_SOURCES_DEFAULT }
28
+ const CONFIG = 'bundle/config/config.json'
29
+ // the spec text does not depend on the sources, so a boot that does not use the twin still makes the text a checkpoint with the twin would hold
30
+ const TEXT_ONLY = [{ kind: 'file', base: 'https://twin.invalid/' }]
31
+ const textOf = raw => {
32
+ const d = raw && typeof raw === 'object' && !(raw instanceof Uint8Array) && 'data' in raw ? raw.data : raw
33
+ return typeof d === 'string' || d instanceof Uint8Array ? d : new Uint8Array(d)
34
+ }
35
+
36
+ /**
37
+ * @param {object} o bootWmd's options
38
+ * @returns {Promise<{o: object, events: object[], plain: object, twinOn: boolean, texts: {i: number, port: number, plain: string|Uint8Array, twin: string}[], off: string}>}
39
+ * o is the same object when nothing changes; events are {t: 'gowasm-off', why} (at most one). For chooseTwin: `plain` is the options as given, `twinOn` says
40
+ * whether `o` has the twin, `texts` holds, per 9P service the twin could change, its spec text without and with the twin (even when the twin is off for
41
+ * this boot: a checkpoint taken with it is told apart), and `off` says why it is off (empty when on).
42
+ */
43
+ export async function twinForBoot(o) {
44
+ const events = []
45
+ const res = (o2, extra = {}) => ({ o: o2, events, plain: o, twinOn: false, texts: [], off: '', offO: null, ...extra })
46
+ try {
47
+ const opt = o && o.gowasm
48
+ const given = opt && typeof opt === 'object' ? opt : {}
49
+ const sources = given.sources ?? (given.base ? [{ kind: 'file', base: given.base }] : GOWASM_SOURCES_DEFAULT)
50
+ const services = o && o.channels && Array.isArray(o.channels.services) ? o.channels.services : []
51
+ const mine = services.map((s, i) => [s, i]).filter(([s]) => s && (s.kind === '9p' || s.kind === 1) && s.files && typeof s.files === 'object' && !s.gowasm && s.files[CONFIG] !== undefined)
52
+ if (!mine.length) return res(o)
53
+ const consumerOff = opt === false || !sources
54
+ const plan = planOf({ sources: consumerOff ? TEXT_ONLY : sources, pins: given.pins, packages: given.packages, limits: given.limits || {} })
55
+ const consumerWhy = opt === false ? 'gowasm: false' : 'no source'
56
+ // the text of the spec with the stub mounts is decided by the tools alone, not by the sources or the limits: when this boot does not use the twin (the consumer's
57
+ // choice, or a setup that is not usable) it is made from the caller's pins and, when those are not usable, from the package's own, so a checkpoint taken with
58
+ // the twin can still be told apart and restored (part 6)
59
+ let textPlan = plan
60
+ if (plan.why) {
61
+ textPlan = planOf({ sources: TEXT_ONLY, pins: given.pins, packages: given.packages, limits: {} })
62
+ if (textPlan.why) textPlan = planOf({ sources: TEXT_ONLY, limits: {} })
63
+ }
64
+ /** The services with the twin's spec text (and a gowasm field made by `p`), the texts to tell, or null when a spec is not JSON. */
65
+ const build = (p, fieldOf) => {
66
+ const next = services.slice()
67
+ const texts = []
68
+ for (const [svc, i] of mine) {
69
+ const raw = svc.files[CONFIG]
70
+ let spec
71
+ try {
72
+ spec = JSON.parse(typeof raw === 'string' ? raw : new TextDecoder().decode(raw && typeof raw === 'object' && 'data' in raw ? raw.data : raw))
73
+ } catch {
74
+ return { bad: "the bundle's config is not JSON" }
75
+ }
76
+ if (!spec || !Array.isArray(spec.mounts)) return { bad: "the bundle's config has no mounts" }
77
+ spec.mounts = addEdgeToolMounts(spec.mounts, p.edge.tools)
78
+ const text = JSON.stringify(spec, null, 2) + '\n'
79
+ const given0 = textOf(raw)
80
+ if (!(typeof given0 === 'string' && given0 === text)) texts.push({ i, port: svc.port, plain: given0, twin: text })
81
+ next[i] = { ...svc, files: { ...svc.files, [CONFIG]: typeof raw === 'string' && raw === text ? raw : text }, gowasm: fieldOf(p.service(spec.mounts.map(m => m.destination))) }
82
+ }
83
+ return { next, texts }
84
+ }
85
+ /** What a restore of a checkpoint taken with the twin gets when the twin is off for this boot: the twin's text (the stubs stay), a gowasm field that says off. */
86
+ const offOf = (why, built) => (built.next ? { ...o, channels: { ...o.channels, services: built.next.map((sv, i) => (sv !== services[i] ? { ...sv, gowasm: { ...sv.gowasm, modules: [], preload: [], sources: undefined, off: why } } : sv)) } } : null)
87
+ const goOff = (why, event) => {
88
+ if (event) events.push({ t: 'gowasm-off', why })
89
+ const built = textPlan.why ? { bad: textPlan.why } : build(textPlan, f => f)
90
+ return built.next ? res(o, { texts: built.texts, off: why, offO: offOf(why, built) }) : res(o, { off: why })
91
+ }
92
+ if (plan.why) return consumerOff ? goOff(consumerWhy, false) : goOff(`the twin's setup is not usable: ${plan.why}`, true)
93
+ const built = build(plan, f => f)
94
+ if (built.bad) return consumerOff ? goOff(consumerWhy, false) : (events.push({ t: 'gowasm-off', why: built.bad }), res(o, { off: built.bad }))
95
+ if (consumerOff) {
96
+ if (opt === undefined) return res(o, { texts: built.texts, off: 'no source', offO: offOf('no source', built) })
97
+ if (opt === false) return res(o, { texts: built.texts, off: 'gowasm: false', offO: offOf('gowasm: false', built) })
98
+ events.push({ t: 'gowasm-off', why: 'no source of the twin is named: no sources and no default, so none is asked for' })
99
+ return res(o, { texts: built.texts, off: 'no source', offO: offOf('no source', built) })
100
+ }
101
+ return res({ ...o, channels: { ...o.channels, services: built.next } }, { twinOn: true, texts: built.texts })
102
+ } catch (e) {
103
+ return { o, events: [{ t: 'gowasm-off', why: `the twin's setup failed: ${(e && e.message) || e}` }], plain: o, twinOn: false, texts: [], off: 'failed', offO: null }
104
+ }
105
+ }
106
+
107
+ /**
108
+ * X6 default part 4: a restore takes the twin choice its checkpoint was taken with. `v` is twinForBoot's result and `header` the checkpoint's (or a base
109
+ * snapshot's) header; the only thing read of it is which of the two spec texts the first 9P service's recorded key matches (specChoice). Returns
110
+ * {o, events}: `o` is v.o unless the checkpoint was taken without the twin and this boot would have it (then the options as given, no stub mount, no
111
+
112
+ * gowasm field, and one event {t: 'gowasm-off', rule: 'checkpoint', why}). A checkpoint that has the twin in a boot that has it off (gowasm: false, no source,
113
+ * an unusable setup) restores with its own spec text and a gowasm field that says `off` (part 6, see below). A header with no description, a text that
114
+ * is neither, or services that disagree change nothing: the usual check of the restore decides, as it did before. X5 would call the same two functions
115
+ * with its own mounts' texts (specChoice names the text; its setup function returns what twinForBoot returns).
116
+ */
117
+ export async function chooseTwin(v, header) {
118
+ const none = { o: v.o, events: [] }
119
+ if (!header || typeof header !== 'object' || !v.texts || !v.texts.length) return none
120
+ const rec = []
121
+ for (const t of v.texts) rec.push(await specChoice(header, t.i, t.port, CONFIG, { plain: t.plain, twin: t.twin }))
122
+ if (rec[0] === null || rec.some(r => r !== rec[0])) return none
123
+ if (rec[0] === 'plain') {
124
+ if (!v.twinOn) return none
125
+ return { o: v.plain, events: [{ t: 'gowasm-off', rule: 'checkpoint', why: 'the checkpoint was taken without the Go twin, so this machine runs without it (its compiles run in the guest)' }] }
126
+ }
127
+ if (v.twinOn) return none
128
+ // Part 6: a checkpoint taken with the twin always restores, whatever this boot's twin state. The twin is off for this boot (gowasm: false, no source, a setup
129
+ // that is not usable): the machine keeps the checkpoint's spec text (its guest has the stub mounts), no twin Worker is started, nothing of the twin is fetched,
130
+ // every compile runs in the guest (GoEdge started off answers each stub with the fallback), and one calm event says so. A spec that is not JSON has no
131
+ // twin text to make: the usual check of the restore decides and says what differs.
132
+ if (!v.offO) return none
133
+ const why = `the checkpoint was taken with the Go twin and the twin is off in this boot (${v.off || 'off'}): the machine keeps the twin's stub mounts and runs its compiles in the guest`
134
+ return { o: v.offO, events: [{ t: 'gowasm-off', rule: 'checkpoint-twin', why }], supersedes: true }
135
+ }
136
+
137
+ /**
138
+ * The events a boot says for its twin choice, once each: twinForBoot's own and chooseTwin's. When the checkpoint's choice supersedes (a checkpoint taken with the
139
+ * twin, a boot that has it off), the one event of the checkpoint's rule says it, with the reason, and the boot's own reason (an unusable setup) is in that text.
140
+ */
141
+ export function eventsOf(v, c) {
142
+ return c.supersedes ? c.events : [...v.events, ...c.events]
143
+ }
144
+
145
+ /**
146
+ * The sample keys of the spec text of each 9P service that has one that differs from what the boot description `desc` records ({serviceIndex: key}; empty
147
+ * when they all agree or there is no description): the services' texts after the twin choice against a boot key made before it (held assets, vm.restore()).
148
+ */
149
+ export async function specKeysDiffering(desc, services) {
150
+ const out = {}
151
+ if (!desc || !Array.isArray(desc.services) || !Array.isArray(services)) return out
152
+ for (let i = 0; i < services.length; i++) {
153
+ const raw = services[i] && services[i].files ? services[i].files[CONFIG] : undefined
154
+ if (raw === undefined) continue
155
+ const d = textOf(raw)
156
+ const key = await sampleKey(typeof d === 'string' ? new TextEncoder().encode(d) : d)
157
+ if (desc.services[i] && desc.services[i].bundle && desc.services[i].bundle[CONFIG] !== key) out[i] = key
158
+ }
159
+ return out
160
+ }
161
+
162
+ /**
163
+ * X6 fix 10 (F1): a base snapshot that is refused after the twin choice was made from its header (the late checks: fit, packs, a body that cannot be read) and
164
+ * whose boot falls back to a cold start takes the options' own twin choice back: `o` with the channels of `twin.o` (no checkpoint stub text, no `gowasm.off`),
165
+ * and, when a boot key was already made with the checkpoint's text (`bootDesc`), the key and description a cold boot of those options makes. One function for
166
+ * every refusal (boot.js baseRefused), so a refusal path added later cannot forget it. `layout` is {flat, maxPages} of the machine as it boots.
167
+ * @returns {Promise<{o: object, key: {key: string, desc: object}|null}>}
168
+ */
169
+ export async function putBackTwin(twin, o, bootDesc, layout) {
170
+ const back = { ...o, channels: twin.o.channels }
171
+ if (!bootDesc) return { o: back, key: null }
172
+ const keys = await specKeysDiffering(bootDesc, back.channels?.services)
173
+ if (!Object.keys(keys).length) return { o: back, key: null }
174
+ return { o: back, key: await bootKeyForChoice(bootDesc, layout, keys) }
175
+ }