@threadedstack/wmd-web 0.1.62 → 0.1.63

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/RELEASE.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "wmd-web",
3
3
  "version": "0.5.1",
4
- "commit": "0f4c8957ac8af45e9d26401f91e1321102907353",
4
+ "commit": "a89d6f6fefb5bad1a8de11dd97045475ede4ffb4",
5
5
  "previous": null,
6
6
  "decisions": [
7
7
  "D-388",
@@ -84,15 +84,16 @@
84
84
  "D-688",
85
85
  "D-689",
86
86
  "D-690",
87
- "D-691"
87
+ "D-691",
88
+ "D-692"
88
89
  ],
89
- "vmSources": "eedab6f96cad4777f4e9f945f1c81920df054c6f",
90
+ "vmSources": "15a7fd5f0aafeea5d6c4dc2a776d567c349ccff5",
90
91
  "guest": {
91
92
  "arch": "arm64",
92
93
  "files": {
93
94
  "vm.wasm": {
94
- "sha256": "9da8344493105efb6d95af491e457832c8c093a159148b578a75714f8d38c54a",
95
- "bytes": 1580846
95
+ "sha256": "2042f749daaba60dac5e65c689bd3937eb4a1ed3bc87f66d47ace6416974f631",
96
+ "bytes": 1580906
96
97
  },
97
98
  "Image": {
98
99
  "sha256": "b7a8843d3469e2f5c32973ce2e6d663f90e07099ed2e9e9aee2ceac0e6a0685b",
@@ -182,11 +183,11 @@
182
183
  "guest/arm64/Image-4k": "55ab90773d080416f1539ae2caac0a49bb98e2bb34ce9384849725fb8e601551",
183
184
  "guest/arm64/features": "4dc6f2a114c7c87a67eb9f0fe53c52b6b8128bb30830a6be498432a3701587f4",
184
185
  "guest/arm64/initramfs.cpio.gz": "ac7c0fc194b059579943c3d8ceaa0757c3e3e248231c2ad779260e97d5084cd3",
185
- "guest/arm64/vm.wasm": "9da8344493105efb6d95af491e457832c8c093a159148b578a75714f8d38c54a",
186
+ "guest/arm64/vm.wasm": "2042f749daaba60dac5e65c689bd3937eb4a1ed3bc87f66d47ace6416974f631",
186
187
  "package.json": "6de9aa9fabdb395651d39997c17e094f01a574f54a36f0af31bd3ffaae53cda1",
187
188
  "src/base.js": "c79df2c3d4a6519fb9a6ef5cda39d66a5b9bc1a6dd009d21e7455e141943079f",
188
189
  "src/blob.js": "bb2a2f0d87ce236280a7be2f246c926010dfe07f649c27da5e70d8eb5eaf7061",
189
- "src/boot.js": "a6d17aa1a8b254101f0ea76739ac7d0be9e29f28e7fb414a826f17784b3c7ffd",
190
+ "src/boot.js": "6227ef7a101e1261075f9054f6770a590084fa96319a4abb7a066660a2cb04b5",
190
191
  "src/build/builder.js": "57a8436acc00147d031a42cccffe508f8deb3735b0ab4f9efcc2aa1cf7c6859c",
191
192
  "src/build/context.js": "d38097c61dbdadc4d41290c010425a4422f499aba473fa2b83f2a5c41e543571",
192
193
  "src/build/dockerfile.js": "5957fe3d4ac8ff8b312f980ee04bd1d98ad4373a61f9a33e02f1ff1108b6ea53",
@@ -298,7 +299,7 @@
298
299
  "src/host/ckpt-chain.js": "c208a882da772acafe1373ea1d7e04723e26e870396d4202ef330d4eaf758596",
299
300
  "src/host/ckpt-file.js": "709344bfadf7c8151d51f70787b9e9d4b074ed1f5f80af113f11215851b9c28a",
300
301
  "src/host/ckpt-io.js": "92e437fb3b118c4269ecc4aafec6e17cf99936d3fc0c410e38f48b9146e791fb",
301
- "src/host/ckpt-point.js": "3d0896281eaf3f49e9b97928dd941a32c20da7ddfc7b239d11712f762e90ec9f",
302
+ "src/host/ckpt-point.js": "328a327cc5447ca5a241f115a1c08265017821a9a93962208c0b20dc81908a66",
302
303
  "src/host/ckpt-save.js": "7bb07f536005fb5e7d9db6a09169a5ce1e3865d337ab65ce798a111334c6aa07",
303
304
  "src/host/ckpt.js": "371acb574e31e94201ae1ff32a7cfad85801ae3eae2896cde7d53a96430c502d",
304
305
  "src/host/clock.js": "aba6af3a8b1a985ae340892222e4b482d33afe20f5c8b3a4c7403ce87d1e247c",
@@ -321,12 +322,13 @@
321
322
  "src/host/jit-hub.js": "cf3fc9f9d4e3fb50c41d6de5e2523f380d3c6c1feaf61c15d90cde89aec2f4c3",
322
323
  "src/host/jit-snap.js": "3932f36047c9edeb7f59282d1c37fef19c8f5a9fe4bd0192fb93aa64030fe51d",
323
324
  "src/host/jit.js": "72ef7334506fde2b3724cee93b52a987fbd6d45473b8de93d914db8a80ae9e17",
324
- "src/host/layout.js": "287f9f86da57506a7fa706a2ff401a49902dca6ccb9b9dfa78eb6aebfcf4a6cc",
325
+ "src/host/layout.js": "9dc4cef8bf52dc6774dc9f08caed31c731a3f3063a5a96960dbaa2cc998fc2df",
325
326
  "src/host/monitor.js": "ae1741ba35668bcc6192642246494433b175668933921634c699af5a0a69acc0",
326
327
  "src/host/opfs-avail.js": "a98945c0f1792f29bc0147de662173cc9275a43dbeb44ec575ecb8ee44d5f122",
327
328
  "src/host/p9mount.js": "cd27abd769b19ed8b26050ddd8b6d61f81faa5a431924217dd0bf2593258d5b9",
328
329
  "src/host/pinned-fetch.js": "873eb804604c150f6c8e488eb6c49fb8dc7a85108e80bf1a831904b9555726eb",
329
330
  "src/host/ram-mem.js": "bf4036d5d12be1d5d2f5223e526b0b8e225bc702ae7e60a2a59fdfe9fbbb49e3",
331
+ "src/host/restore-mem.js": "d53526a77a900b95e545990249124b0e3213a2c422920ce06bf9313944b27d67",
330
332
  "src/host/stdio.js": "07881f378ac805bfd8e385dd51184fe5f16c67667b775fed28551f66b4100e66",
331
333
  "src/host/threads.js": "952381940e7f43114867e9a9714528f2f20c8064b6b0f2018ab075128dc601be",
332
334
  "src/host/wasi.js": "fbafa239b8fb4083f7e8c910b1adab38901e8e7cffd247284a9abb2847eaf4bd",
@@ -353,7 +355,7 @@
353
355
  "src/registry/pull.js": "24f2e01a76c9f7f27896af69b989f8c97f0ca31712b3e8110aaa5b5e3148b04b",
354
356
  "src/registry/ref.js": "24038e0fbcb6ac143cb8e8f7b9fac4dd0803d0891961786dc88dba01a4402e7b",
355
357
  "src/registry/wasi-mem.js": "8a8474a090a778db9eabfc2610f8c57f7f66b684ba7b7f8994aabd3ecb07a65a",
356
- "src/worker.js": "80904f024ec99119f53b91a38e1b18277215246f45547bb93a097d69c973b832",
358
+ "src/worker.js": "a512f77ccce1b44f119882e7e67d3d5f6d41ca87bf9f2d1e75e7b871a1d3e979",
357
359
  "src/workers.json": "2dd90729f76d5867a3a2974cdc958b610340383fc81a7a4d651272ba15c7e7dc"
358
360
  },
359
361
  "builder": {
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@threadedstack/wmd-web",
3
- "version": "0.1.62",
3
+ "version": "0.1.63",
4
4
  "license": "MIT",
5
5
  "homepage": "https://github.com/threadedstack/wmd-releases",
6
6
  "repository": {
@@ -9,8 +9,8 @@
9
9
  },
10
10
  "description": "Browser host for wmd's guest vm.wasm (Web Workers + shared memory + WASI preview1)",
11
11
  "wmd": {
12
- "tag": "v0.1.62",
13
- "commit": "0f4c8957ac8af45e9d26401f91e1321102907353",
12
+ "tag": "v0.1.63",
13
+ "commit": "a89d6f6fefb5bad1a8de11dd97045475ede4ffb4",
14
14
  "web": "0.5.1"
15
15
  },
16
16
  "type": "module",
package/src/boot.js CHANGED
@@ -37,6 +37,7 @@ import {
37
37
  slotIndex,
38
38
  } from './host/layout.js'
39
39
  import { gcNudgeEvery } from './host/gcnudge.js'
40
+ import { adoptRestoreMemory, quitThreads } from './host/restore-mem.js'
40
41
  import { createRamMemory, haveMemory64 } from './host/ram-mem.js'
41
42
  import { baseStorageEvent, bootFileName, cachedFromTiming, createBootEvents, createWorkerList, readBody, timingCount, vcpusOf } from './host/boot-events.js'
42
43
  import { createJitStore, readJitStats, tableMinOf } from './host/jit.js'
@@ -549,6 +550,15 @@ export function outOfMemoryText({ memoryBytes, memoryMaxBytes, reason, ramInMemo
549
550
  return head + "give it more room above the guest's RAM (bootWmd maxPages, memoryMaxPages(args, slackMiB))"
550
551
  }
551
552
 
553
+ /** IOS-6 (b) (D-692): whether this vm.wasm ends on the page's quit request (its vm_host_req_quit export); an older one ignores it */
554
+ export function vmCanQuit(module) {
555
+ try {
556
+ return WebAssembly.Module.exports(module).some(e => e.name === 'vm_host_req_quit')
557
+ } catch {
558
+ return false
559
+ }
560
+ }
561
+
552
562
  // Host-side endings (vm.exited code < 0; guest exit codes are >= 0).
553
563
  export const EXIT_STOPPED = -1 // reason 'stopped' (vm.stop()) or 'aborted' (the AbortSignal)
554
564
  export const EXIT_NO_PROGRESS = -2 // the progress watchdog fired
@@ -1151,6 +1161,9 @@ async function bootMachine(o) {
1151
1161
  let baseLazy = lazyIn // kept until the restore has succeeded (accept) or failed (reject)
1152
1162
  // The handle must not keep the checkpoint it came from alive (about 500 MB): vm.restore() builds the next machine from
1153
1163
  // `o`, so `o` carries no restore and no assets. (A caller that holds the checkpoint object holds it for its own reasons.)
1164
+ // IOS-6 (b): the replaced machine's memory 0 ({memory, maximum, topPages, touched, zero}), handed over by vm.restore() once none of its
1165
+ // threads is in vm.wasm (it asked vm.wasm to quit)
1166
+ let memIn = o._memory || null
1154
1167
  const adoptIn = o._adopt || null // W57: the replaced machine's JIT hub, kept running by vm.restore() on the same handle
1155
1168
  // W59: the network's identity across vm.restore(): the machine's instance id (one per bootWmd handle chain; the relay
1156
1169
  // replaces this instance's old session) and its placeholder map (names the guest looked up -> 198.18.0.0/15 addresses).
@@ -1167,9 +1180,10 @@ async function bootMachine(o) {
1167
1180
  let netStatus = null
1168
1181
  const netStatusCbs = new Set()
1169
1182
  const netNameWaiters = new Map()
1170
- o = { ...o, restore: undefined, restoreLazy: undefined, assets: o.assets && undefined, _assets: o.assets, _adopt: undefined, _net: undefined }
1183
+ o = { ...o, restore: undefined, restoreLazy: undefined, assets: o.assets && undefined, _assets: o.assets, _adopt: undefined, _net: undefined, _memory: undefined }
1171
1184
  let heldAssets = null // what vm.restore() hands the next boot: bytes, Module, boot files, packs, keys
1172
1185
  let restoring = false
1186
+ let quitting = false // IOS-6 (b): vm.restore() asked vm.wasm to quit
1173
1187
  let ck = null // the checkpoint being taken (declared early: finish() looks at it)
1174
1188
  const ckptT = {}
1175
1189
  let vmKey = null
@@ -1451,7 +1465,18 @@ async function bootMachine(o) {
1451
1465
  // IOS-2: memory 0 starts at vm.wasm's own declared minimum, and its heap grows as it is used. Mobile WebKit counts every byte of the initial
1452
1466
  // memory at once (D-516); VM_MIN_PAGES stays the heap room of the maximum. A vm.wasm that declares more (or bytes that cannot be read) gets that.
1453
1467
  const declaredMin = vmMemoryMinPages(new Uint8Array(vmBytes))
1454
- let memory = new WebAssembly.Memory({ initial: declaredMin ?? VM_MIN_PAGES, maximum, shared: true })
1468
+ // IOS-6 (b): a restore by vm.restore() takes the old machine's memory 0 (its written pages zeroed) instead of a second one; mobile WebKit
1469
+ // counted both
1470
+ const adopted = restoreIn ? adoptRestoreMemory(memIn, { maximum, flat: flatRam, minPages: declaredMin ?? VM_MIN_PAGES }) : null
1471
+ const reused = adopted?.memory || null
1472
+ memIn = null
1473
+ let memory = reused || new WebAssembly.Memory({ initial: declaredMin ?? VM_MIN_PAGES, maximum, shared: true })
1474
+ if (restoreIn) {
1475
+ ckptT.memoryReused = !!reused
1476
+ if (adopted) ckptT.memoryZeroedPages = adopted.zeroedPages
1477
+ }
1478
+ // the size the instance's start function could write (a reused memory may be larger: it cannot shrink)
1479
+ const instancePages = (reused ? declaredMin ?? VM_MIN_PAGES : memory.buffer.byteLength / CKPT_PAGE)
1455
1480
  const memoryInitialBytes = memory.buffer.byteLength
1456
1481
  const ctlSab = createControl()
1457
1482
  const ctl = new Int32Array(ctlSab)
@@ -1484,7 +1509,7 @@ async function bootMachine(o) {
1484
1509
  }
1485
1510
  async function restoreMemoryNow() {
1486
1511
  const tm = absMs()
1487
- const have = memory.buffer.byteLength / CKPT_PAGE // the size the instance made: its start function wrote nothing above it
1512
+ const have = memory.buffer.byteLength / CKPT_PAGE
1488
1513
  if (restoreIn.header.memPages > have) memory.grow(restoreIn.header.memPages - have)
1489
1514
  const kept = new Uint8Array(restoreIn.header.memPages)
1490
1515
  if (restoreIn.into) {
@@ -1526,7 +1551,7 @@ async function bootMachine(o) {
1526
1551
  }
1527
1552
  // pages the instance's start function wrote that were zero at the checkpoint (the runner's zero_absent): the static region
1528
1553
  let zeroed = 0
1529
- const w = new Int32Array(memory.buffer, 0, restoreZeroScanPages(restoreIn.header.memPages, have) * (CKPT_PAGE / 4))
1554
+ const w = new Int32Array(memory.buffer, 0, restoreZeroScanPages(restoreIn.header.memPages, instancePages) /* the size the instance made: its start function wrote nothing above it */ * (CKPT_PAGE / 4))
1530
1555
  for (let p = 0; p * (CKPT_PAGE / 4) < w.length; p++) {
1531
1556
  if (kept[p]) continue
1532
1557
  const lo = p * (CKPT_PAGE / 4)
@@ -2205,7 +2230,8 @@ async function bootMachine(o) {
2205
2230
  if (!done && wl.tid(wid(m.slot), m.ev === 'start' ? m.tid : null)) workersEv()
2206
2231
  break
2207
2232
  case 'exit':
2208
- finish(m.code, 'exit')
2233
+ if (quitting) finish(EXIT_STOPPED, 'stopped') // IOS-6 (b): vm.restore() asked vm.wasm to end: the machine was stopped, not exited
2234
+ else finish(m.code, 'exit')
2209
2235
  break
2210
2236
  case 'resume-instantiated':
2211
2237
  restoreMemory()
@@ -2771,6 +2797,7 @@ async function bootMachine(o) {
2771
2797
  // page reload (bootWmd({restore})) they are fetched, as for any boot.
2772
2798
  const reuse = !['vmUrl', 'files', 'channels', 'args', 'env', 'maxPages'].some(k => k in over)
2773
2799
  const assets = reuse ? heldAssets : null
2800
+ const ckSaving = !!ck // IOS-6 (b): its store may still read this memory: the next machine does not take it
2774
2801
  if (ck) ckptFail(new CheckpointError('restore', 'a restore began: the checkpoint in progress was abandoned'))
2775
2802
  // W57: this machine's hub outlives it until the next one's hub has taken the Modules it can reuse (the same
2776
2803
  // code: Firefox would otherwise hold two copies of the guest's code, and two guests' restores filled its 2 GiB)
@@ -2778,12 +2805,23 @@ async function bootMachine(o) {
2778
2805
  let oldHub = null
2779
2806
  try {
2780
2807
  for (const e of edgeEvents) ev(e) // the restore is taken (the checks above passed): node's choice is said once
2808
+ // IOS-6 (b): the next machine takes this one's memory 0 when no thread of this one can write it again: vm.wasm is asked to quit
2809
+ // (its threads wake, are joined, and its entry returns) and the page waits until none is in vm.wasm (RAM in memory 0, the same
2810
+ // maximum, no checkpoint save reading it); else it makes its own, as before
2811
+ let memOut = null
2812
+ if (!flatRam && !L.flat && L.maximum === maximum && !ckSaving && !done && vmCanQuit(module)) {
2813
+ quitting = true
2814
+ const tq = absMs()
2815
+ const q = await quitThreads(memory, ctl, { timeoutMs: o.restoreQuitMs ?? 2000 })
2816
+ timings.restoreQuitMs = Math.round(absMs() - tq)
2817
+ if (q) memOut = { memory, maximum, ...q }
2818
+ }
2781
2819
  finish(EXIT_STOPPED, 'stopped')
2782
2820
  await exited
2783
2821
  memory = null
2784
2822
  oldHub = keptHub
2785
2823
  keptHub = null
2786
- const next = await bootWmd({ ...nextOpts, checkpoint: true, restore: ckpt, assets, _adopt: oldHub, _net: { instance: netInstance, names: [...netNames] } })
2824
+ const next = await bootWmd({ ...nextOpts, checkpoint: true, restore: ckpt, assets, _adopt: oldHub, _net: { instance: netInstance, names: [...netNames] }, _memory: memOut })
2787
2825
  heldAssets = null // the new machine holds them
2788
2826
  closeEdge?.close() // a checkpoint taken without node: the setup of the machine that had it is let go
2789
2827
  return next
@@ -2,7 +2,7 @@
2
2
  // The files of node in the sandboxed frame: the path under a source (the option edge: { sources } of bootWmd), the role the frame gives the file, its
3
3
  // sha256 and its size. The page accepts a file only when it has exactly this sha256 and size. The notice files travel with the rest.
4
4
  // EDGE_PACKAGE is the package that holds these files, for the {name} {version} {file} of a registry source's url (null: none named).
5
- export const EDGE_PACKAGE = { name: '@threadedstack/wmd-node', version: '0.1.62' }
5
+ export const EDGE_PACKAGE = { name: '@threadedstack/wmd-node', version: '0.1.63' }
6
6
  export const EDGE_PINS = [
7
7
  { path: 'wmd_browser_bg.wasm', role: 'wasm', sha256: '1e3db7f2c5f4be0ee44e5f2c0205cf8ca11f906d9addd5512915fad4821661c2', size: 6334959 },
8
8
  { path: 'wmd_browser.js', role: 'glue', sha256: 'b389b072096881ba39b22cd705d3a230af02acc5409c61fb4f997d1081c4df6f', size: 75647 },
@@ -41,6 +41,8 @@ export const VM_POINT_CKPT = 2
41
41
  export const POINT_STATUS = { 0: 'ok', 1: 'a vCPU did not reach a block boundary in time', 2: 'the file share did not drain in time' }
42
42
  /** The page asks the guest for a checkpoint by storing this in the word. */
43
43
  export const REQ_CKPT = VM_POINT_CKPT
44
+ /** IOS-6 (b) (D-692): and to end the machine, every thread out of vm.wasm (VM_HOST_REQ_QUIT, guest/vm/include/vm/snapshot.h) */
45
+ export const REQ_QUIT = 3
44
46
 
45
47
  /** Pages per chunk of the memory section (32 MiB). */
46
48
  export const CHUNK_PAGES = 512
@@ -246,11 +248,11 @@ export function createCkptImports({ memory, ram = null, touched = () => null, ze
246
248
  }
247
249
 
248
250
  /** Asks the guest for a checkpoint: false when its ctl thread has not attached (no checkpoint support, or not booted far enough). */
249
- export function requestCheckpoint(memory, ctl) {
251
+ export function requestCheckpoint(memory, ctl, req = REQ_CKPT) {
250
252
  const addr = Atomics.load(ctl, CTL_CK_HOSTREQ)
251
253
  if (!addr) return false
252
254
  const w = new Int32Array(memory.buffer, addr & ~3, 1)
253
- Atomics.store(w, 0, REQ_CKPT)
255
+ Atomics.store(w, 0, req)
254
256
  Atomics.notify(w, 0, 1)
255
257
  return true
256
258
  }
@@ -92,7 +92,15 @@ export const CTL_CK_STREAM = CKPT_BASE + 5
92
92
  // IOS-6 (a): how long vCPU 0 waits at a point for the page's go, ms (0: its default, 60 s); bootWmd({ckptGoTimeoutMs}) sets it
93
93
  export const CTL_CK_GO_MS = CKPT_BASE + 7
94
94
 
95
- export const CTL_INTS = CKPT_BASE + 8
95
+ // IOS-6 (b): guest threads inside vm.wasm (made or running an instance); vm.restore() hands memory 0 to the next machine once it is 0 (restore-mem.js)
96
+ export const CTL_IN_WASM = CKPT_BASE + 6
97
+ // IOS-6 (b): what the main thread leaves the page when vm.wasm's entry returns (worker.js): which pages of memory 0 may be non-zero
98
+ export const CTL_QUIT_SET = CKPT_BASE + 8 // 1 once the three below are written
99
+ export const CTL_QUIT_TOP = CKPT_BASE + 9 // vm_heap_top in 64 KiB pages (rounded up): nothing above it was written
100
+ export const CTL_QUIT_TOUCHED = CKPT_BASE + 10 // vm_touched_map's address (0: none): RAM pages never written
101
+ export const CTL_QUIT_ZERO = CKPT_BASE + 11 // vm_zero_ranges' address (0: none): ranges that are zero
102
+
103
+ export const CTL_INTS = CKPT_BASE + 12
96
104
  export const CTL_BYTES = CTL_INTS * 4
97
105
 
98
106
  export const slotIndex = (slot, field) => POOL_BASE + slot * SLOT_INTS + field
@@ -0,0 +1,88 @@
1
+ // IOS-6 (b) (D-692): vm.restore() reuses the old machine's memory 0 for the next machine. Before this the next boot made a new shared memory
2
+ // (about 470 MB on a phone) while the old one was still alive, and mobile WebKit counted both: wmn's rewind took its page from 1081 to 1771
3
+ // MiB, and a desktop Chromium restore rose 623 MiB.
4
+ // A memory may be handed over only when no thread of the old machine can write it again. vm.wasm's own threads park in wasm atomic waits
5
+ // the page cannot wake (D-689), so the page asks vm.wasm to end: it stores REQ_QUIT in the machine's host_req word, vm.wasm's ctl thread
6
+ // calls machine_exit (every vCPU wait checks `exiting` and is woken) and machine_run's tail wakes and joins every service thread, then
7
+ // vm.wasm's entry returns. Each Worker counts itself in CTL_IN_WASM while it makes or runs an instance (worker.js); the main Worker, when
8
+ // the entry has returned, leaves which pages may be non-zero (publishQuitState). The page waits for the count to reach 0. A thread that
9
+ // stays (a machine stopped at a checkpoint point, a long host wait) makes the restore take a new memory, as before.
10
+ import { CTL_EXIT, CTL_IN_WASM, CTL_QUIT_SET, CTL_QUIT_TOP, CTL_QUIT_TOUCHED, CTL_QUIT_ZERO } from './layout.js'
11
+ import { REQ_QUIT, requestCheckpoint, touchedSkips, zeroRangeSkips } from './ckpt-point.js'
12
+
13
+ export { CTL_IN_WASM, CTL_QUIT_SET, CTL_QUIT_TOP, CTL_QUIT_TOUCHED, CTL_QUIT_ZERO }
14
+
15
+ const PAGE = 65536
16
+
17
+ /** A Worker is about to make an instance or run one. False when the machine has stopped: it must not touch the memory. */
18
+ export function enterWasm(ctl) {
19
+ Atomics.add(ctl, CTL_IN_WASM, 1)
20
+ if (Atomics.load(ctl, CTL_EXIT) === 0) return true
21
+ Atomics.sub(ctl, CTL_IN_WASM, 1)
22
+ return false
23
+ }
24
+
25
+ export function leaveWasm(ctl) {
26
+ Atomics.sub(ctl, CTL_IN_WASM, 1)
27
+ }
28
+
29
+ /**
30
+ * The main Worker, once vm.wasm's entry has returned (or thrown): heapTop (vm_heap_top, bytes; nothing above it was written), touched
31
+ * (vm_touched_map's address, 0: none) and zero (vm_zero_ranges' address, 0: none), read from its instance before it leaves vm.wasm.
32
+ */
33
+ export function publishQuitState(ctl, { heapTop, touched = 0, zero = 0 }) {
34
+ if (!(heapTop > 0)) return
35
+ Atomics.store(ctl, CTL_QUIT_TOP, Math.ceil(heapTop / PAGE))
36
+ Atomics.store(ctl, CTL_QUIT_TOUCHED, touched >>> 0)
37
+ Atomics.store(ctl, CTL_QUIT_ZERO, zero >>> 0)
38
+ Atomics.store(ctl, CTL_QUIT_SET, 1)
39
+ }
40
+
41
+ /**
42
+ * Ask vm.wasm to end and wait (at most timeoutMs) until none of its threads is in vm.wasm. Resolves {topPages, touched, zero} (the main
43
+ * thread's state) or null: no ctl thread to ask, a thread still in vm.wasm at the timeout, or no state left.
44
+ */
45
+ export async function quitThreads(memory, ctl, { timeoutMs = 2000 } = {}) {
46
+ if (!requestCheckpoint(memory, ctl, REQ_QUIT)) return null
47
+ const end = performance.now() + timeoutMs
48
+ for (;;) {
49
+ if (Atomics.load(ctl, CTL_IN_WASM) <= 0) {
50
+ if (Atomics.load(ctl, CTL_QUIT_SET) !== 1) return null
51
+ return { topPages: Atomics.load(ctl, CTL_QUIT_TOP), touched: Atomics.load(ctl, CTL_QUIT_TOUCHED) >>> 0, zero: Atomics.load(ctl, CTL_QUIT_ZERO) >>> 0 }
52
+ }
53
+ if (performance.now() >= end) return null
54
+ await new Promise(r => setTimeout(r, 2))
55
+ }
56
+ }
57
+
58
+ /**
59
+ * The memory 0 a restoring boot uses instead of a new one: the old machine's (memIn = {memory, maximum, topPages, touched, zero}) with every
60
+ * page that may be non-zero written to zero, grown to at least minPages. vm.wasm's start function initialises its static data and TLS only
61
+ * on a memory whose init flag is 0 (worker.js), and a restore relies on pages it does not write being zero. Pages at or above topPages,
62
+ * guest RAM pages the touched map says were never written, and pages vm_zero_ranges lists are zero already and are neither read nor
63
+ * written (either would make the browser commit them). Resolves {memory, zeroedPages}; null when there is none to take: another maximum,
64
+ * a flat layout (its RAM is a second memory), not a memory, no heap top.
65
+ */
66
+ export function adoptRestoreMemory(memIn, { maximum, flat, minPages }) {
67
+ if (!memIn || flat || memIn.maximum !== maximum || !(memIn.memory instanceof WebAssembly.Memory) || !(memIn.topPages > 0)) return null
68
+ const m = memIn.memory
69
+ const have = m.buffer.byteLength / PAGE
70
+ const top = Math.min(memIn.topPages, have)
71
+ const ram = memIn.touched ? touchedSkips(m, memIn.touched).mem0 : null
72
+ const zr = memIn.zero ? zeroRangeSkips(m, memIn.zero) : null
73
+ // the skips are read from the old memory: decide every page before writing any
74
+ const dirty = []
75
+ for (let p = 0; p < top; p++) if (!(ram && ram(p)) && !(zr && zr(p))) dirty.push(p)
76
+ const u8 = new Uint8Array(m.buffer)
77
+ let lo = -1
78
+ for (let i = 0; i <= dirty.length; i++) {
79
+ const p = dirty[i]
80
+ if (lo >= 0 && (i === dirty.length || p !== dirty[i - 1] + 1)) {
81
+ u8.fill(0, lo * PAGE, (dirty[i - 1] + 1) * PAGE)
82
+ lo = -1
83
+ }
84
+ if (i < dirty.length && lo < 0) lo = p
85
+ }
86
+ if (minPages > have) m.grow(minPages - have)
87
+ return { memory: m, zeroedPages: dirty.length }
88
+ }
package/src/worker.js CHANGED
@@ -32,6 +32,7 @@ import {
32
32
  } from './host/layout.js'
33
33
  import { createThreadSpawn, threadDone, waitForWork } from './host/threads.js'
34
34
  import { WasiExit, createWasi } from './host/wasi.js'
35
+ import { enterWasm, leaveWasm, publishQuitState } from './host/restore-mem.js'
35
36
  import { createJitDoor, poolProbe, TABLE_MIN } from './host/jit.js'
36
37
  import { stdioWriter } from './host/stdio.js'
37
38
  import { createWmdImports } from './host/wmd-imports.js'
@@ -252,6 +253,21 @@ async function run(m) {
252
253
  }
253
254
 
254
255
  if (role === 'main') {
256
+ // IOS-6 (b): counted in while it makes and runs its instance: vm.restore() reuses this memory only once no thread is in vm.wasm
257
+ if (!enterWasm(ctl)) return
258
+ try {
259
+ await runMain()
260
+ } finally {
261
+ // vm.wasm's entry has returned (its quit request, a power-off, an exit): which pages of memory 0 may be non-zero, for the next
262
+ // machine that takes this memory (restore-mem.js adoptRestoreMemory). Every other thread of it has been joined by then.
263
+ try {
264
+ if (heapTopFn) publishQuitState(ctl, { heapTop: heapTopFn(), touched: touchedFn?.() ?? 0, zero: zeroFn?.() ?? 0 })
265
+ } catch {}
266
+ leaveWasm(ctl)
267
+ }
268
+ return
269
+ }
270
+ async function runMain() {
255
271
  const inst = instantiate()
256
272
  if (typeof inst.exports.vm_heap_top === 'function') heapTopFn = () => Number(inst.exports.vm_heap_top())
257
273
  if (typeof inst.exports.vm_touched_map === 'function') touchedFn = () => inst.exports.vm_touched_map() >>> 0
@@ -286,7 +302,6 @@ async function run(m) {
286
302
  } catch (err) {
287
303
  fatal(m, err, 1)
288
304
  }
289
- return
290
305
  }
291
306
 
292
307
  // Pool Worker: announce, then loop serving spawn requests.
@@ -307,6 +322,8 @@ async function run(m) {
307
322
  self.postMessage({ t: 'thread', ev: 'start', tid: work.tid, slot })
308
323
  myTid = work.tid
309
324
  let inst
325
+ // IOS-6: a thread whose work came after the machine stopped makes no instance (its start function would write a memory vm.restore() reuses)
326
+ if (!enterWasm(ctl)) return
310
327
  try {
311
328
  inst = instantiate()
312
329
  await jit?.syncAsync() // a new thread's table starts with every live slot (spawn.rs)
@@ -314,6 +331,8 @@ async function run(m) {
314
331
  } catch (err) {
315
332
  fatal(m, err, work.tid)
316
333
  return
334
+ } finally {
335
+ leaveWasm(ctl)
317
336
  }
318
337
  threadDone(ctl, slot)
319
338
  self.postMessage({ t: 'thread', ev: 'end', tid: work.tid, slot })
package/wmdpack.wasm CHANGED
Binary file