@waffle-os/runtime 0.0.155 → 0.0.157

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.
Files changed (77) hide show
  1. package/browser/filesystem-backend.ts +11 -1
  2. package/browser/preview-protocol.ts +2 -0
  3. package/browser/preview.ts +128 -18
  4. package/browser/runtime-terminals.ts +65 -24
  5. package/browser/shared-fs.ts +141 -14
  6. package/browser/worker.ts +73 -6
  7. package/core/descriptors.ts +19 -2
  8. package/core/devices.ts +237 -2
  9. package/core/fd-reopen.ts +105 -20
  10. package/core/filesystem.ts +79 -0
  11. package/core/index.ts +4 -0
  12. package/core/open-file.ts +212 -18
  13. package/core/wasi.ts +449 -47
  14. package/dist/browser/filesystem-backend.js +4 -2
  15. package/dist/browser/preview.js +120 -17
  16. package/dist/browser/runtime-terminals.js +53 -10
  17. package/dist/browser/shared-fs.js +124 -11
  18. package/dist/browser/worker.js +59 -6
  19. package/dist/core/descriptors.js +9 -1
  20. package/dist/core/devices.js +211 -1
  21. package/dist/core/fd-reopen.js +79 -18
  22. package/dist/core/filesystem.js +14 -0
  23. package/dist/core/open-file.js +166 -13
  24. package/dist/core/wasi.js +402 -29
  25. package/dist/fs/backend.js +51 -3
  26. package/dist/fs/client.js +204 -7
  27. package/dist/fs/cold-read-cache.js +23 -0
  28. package/dist/fs/index.js +21 -1
  29. package/dist/fs/indexeddb.js +30 -2
  30. package/dist/fs/locks.js +1112 -0
  31. package/dist/fs/memory.js +126 -2
  32. package/dist/fs/multitab-backend.js +317 -196
  33. package/dist/fs/multitab-protocol.js +2 -0
  34. package/dist/fs/persistent.js +32 -7
  35. package/dist/fs/protocol.js +9 -3
  36. package/dist/fs/service.js +387 -22
  37. package/dist/fs/shared.js +54 -1
  38. package/dist/fs/storage-geometry.js +2 -0
  39. package/dist/interrupt/rewriter-internal.js +4 -1
  40. package/dist/proc/abi.js +80 -6
  41. package/dist/proc/errors.js +1 -0
  42. package/dist/proc/filesystem-codec.js +40 -9
  43. package/dist/proc/index.js +10 -1
  44. package/dist/proc/pty.js +193 -0
  45. package/dist/proc/worker-client.js +11 -2
  46. package/dist/proc/worker-pipes.js +51 -0
  47. package/dist/runtime.js +11 -2
  48. package/dist/search/engine.js +53 -0
  49. package/dist/tooling/program/program-transformer.json +1 -1
  50. package/fs/backend.ts +54 -2
  51. package/fs/client.ts +230 -6
  52. package/fs/cold-read-cache.ts +38 -0
  53. package/fs/index.ts +22 -1
  54. package/fs/indexeddb.ts +36 -2
  55. package/fs/locks.ts +1406 -0
  56. package/fs/memory.ts +132 -1
  57. package/fs/multitab-backend.ts +563 -304
  58. package/fs/multitab-protocol.ts +2 -0
  59. package/fs/persistent.ts +46 -4
  60. package/fs/protocol.ts +17 -5
  61. package/fs/service.ts +469 -23
  62. package/fs/shared.ts +60 -2
  63. package/fs/storage-geometry.ts +3 -0
  64. package/index.ts +2 -0
  65. package/interrupt/rewriter-internal.ts +4 -1
  66. package/package.json +2 -2
  67. package/proc/abi.ts +79 -6
  68. package/proc/errors.ts +1 -0
  69. package/proc/filesystem-codec.ts +39 -9
  70. package/proc/index.ts +11 -0
  71. package/proc/pty.ts +227 -0
  72. package/proc/worker-client.ts +28 -6
  73. package/proc/worker-pipes.ts +57 -0
  74. package/runtime.ts +12 -2
  75. package/search/engine.ts +49 -0
  76. package/testing/indexeddb-storage-browser.ts +173 -2
  77. package/tooling/program/program-transformer.json +1 -1
package/core/wasi.ts CHANGED
@@ -34,33 +34,65 @@ import {
34
34
  import { resolveDescriptorPath, reopenDescriptor, openInode } from "./fd-reopen.js";
35
35
  import { ExecutionUnwind } from "./unwind.js";
36
36
  import { type ControlCells, controlLoad, controlWait } from "../proc/control.js";
37
- import { withFileOffset } from "./open-file.js";
37
+ import {
38
+ markResourceOfdLocked,
39
+ releaseOriginOfd,
40
+ resourceOfdId,
41
+ withFileOffset,
42
+ } from "./open-file.js";
38
43
  // WASI preview1 adapter over filesystem handles and shared open descriptions.
39
44
  // Runs synchronously in a guest worker; services supply blocking I/O and readiness.
40
45
 
41
46
  import {
47
+ F_GETLK,
48
+ F_OFD_GETLK,
49
+ F_OFD_SETLK,
50
+ F_OFD_SETLKW,
51
+ F_RDLCK,
52
+ F_SETLKW,
53
+ F_UNLCK,
54
+ F_WRLCK,
42
55
  FilesystemError,
43
56
  fileTimeNow,
57
+ LOCK_EX,
58
+ LOCK_NB,
59
+ LOCK_SH,
60
+ LOCK_UN,
61
+ permissionsFor,
62
+ PROBE_PATH_LIMIT,
44
63
  type FileHandle,
45
64
  type FileSystem,
46
65
  type FileStat,
47
66
  type FileTime,
67
+ type LockWaitControl,
68
+ type ProbeKind,
48
69
  type ResolvedPath,
49
70
  } from "./filesystem.js";
50
71
  import {
51
72
  DescriptorTable,
52
73
  OpenDescription,
53
74
  MAX_DESCRIPTOR,
75
+ type Descriptor,
54
76
  type Readiness,
55
77
  type Resource,
56
78
  type Stream,
57
79
  } from "./descriptors.js";
58
80
  import { memoryViews, type MemoryViews } from "./memory-views.js";
59
81
  import { GuestWatchTable, type GuestWatchReadiness } from "../fs/guest-watch.js";
60
- import { createNullDevice } from "./devices.js";
82
+ import {
83
+ createMachineIdFile,
84
+ createNullDevice,
85
+ MACHINE_ID_FILE_SIZE,
86
+ MACHINE_ID_INO,
87
+ readVirtualFileBytes,
88
+ seekVirtualFile,
89
+ tellVirtualFile,
90
+ validateMachineId,
91
+ } from "./devices.js";
61
92
 
62
93
  // errno
63
94
  const SUCCESS = 0;
95
+ const EACCES = 2;
64
96
  const EBADF = 8;
65
97
  const EEXIST = 20;
66
98
  const EFAULT = 21;
@@ -77,6 +109,7 @@ const ENOSYS = 52;
77
109
  const ENOTDIR = 54;
78
110
  const ENOTSUP = 58;
79
111
  const ENOTSOCK = 57;
112
+ const EOVERFLOW = 61;
80
113
  const ESPIPE = 70;
81
114
  const ENOTCAPABLE = 76;
82
115
 
@@ -126,9 +159,13 @@ export class WasiExit extends ExecutionUnwind {
126
159
  }
127
160
 
128
161
  export interface WasiOptions {
162
+ /** Logical process PID reported in advisory lock queries (F_GETLK). Defaults to 1. */
163
+ pid?: number;
129
164
  args: readonly string[];
130
165
  env: Record<string, string>;
131
166
  fs: FileSystem;
167
+ /** Optional explicit 32-char lowercase hex machine-id(5) override for virtual `/etc/machine-id`. */
168
+ machineId?: string;
132
169
  /** Explicit guest adapter namespaces; unknown imports fail before instantiation. */
133
170
  namespaces?: WebAssembly.Imports;
134
171
  /** Reserved socket number used by a guest adapter, not an ordinary descriptor. */
@@ -147,6 +184,8 @@ export interface WasiOptions {
147
184
  diagnostic?(data: Uint8Array): void;
148
185
  /** Blocks the calling thread for `ms` milliseconds when no shared notification exists. */
149
186
  sleep(ms: number): void;
187
+ /** Checked before blocking waits so fatal signals unwind instead of returning EINTR. */
188
+ checkActive?(): void;
150
189
  /** Wake word; without interruptPending, a nonzero value is ready. Poll never consumes it. */
151
190
  interrupt?: ControlCells;
152
191
  /** Nonconsuming readiness when interrupt is advisory (for example handled process signals). */
@@ -161,7 +200,7 @@ export interface WasiOptions {
161
200
  // replaces globalThis.performance and crypto with the runtime's polyfills, which call back into
162
201
  // bun.wasm, which calls clock_time_get / random_get here.
163
202
  const encoder = new TextEncoder();
164
- const decoder = new TextDecoder();
203
+ const decoder = new TextDecoder("utf-8", { ignoreBOM: true });
165
204
  const fatalDecoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
166
205
  const perfNow = performance.now.bind(performance);
167
206
  const timeOrigin = performance.timeOrigin;
@@ -198,6 +237,30 @@ function guestPathname(bytes: Uint8Array, ptr: number, len: number): string | un
198
237
  }
199
238
  }
200
239
 
240
+ /** `runtime_fs.path_probe` kinds: 1 a regular file, 2 a directory. */
241
+ const PROBE_KINDS: readonly (ProbeKind | undefined)[] = [undefined, "file", "directory"];
242
+
243
+ /** A path_probe list: one to PROBE_PATH_LIMIT pathnames, each ended by a NUL, exact UTF-8 bytes
244
+ * (a leading U+FEFF kept). Undefined for malformed UTF-8, a missing final NUL, an empty list or
245
+ * too many pathnames. */
246
+ function probePathnames(bytes: Uint8Array, ptr: number, len: number): string[] | undefined {
247
+ if (len === 0 || bytes[ptr + len - 1] !== 0) return undefined;
248
+ const end = ptr + len;
249
+ const paths: string[] = [];
250
+ let start = ptr;
251
+ for (let at = ptr; at < end; at++) {
252
+ if (bytes[at] !== 0) continue;
253
+ if (paths.length === PROBE_PATH_LIMIT) return undefined;
254
+ try {
255
+ paths.push(decodeBytes(bytes, start, at - start, fatalDecoder));
256
+ } catch {
257
+ return undefined;
258
+ }
259
+ start = at + 1;
260
+ }
261
+ return paths;
262
+ }
263
+
201
264
  function writeUtf8Prefix(target: string, output: Uint8Array): number {
202
265
  if (output.length === 0) return 0;
203
266
  // Browser encodeInto rejects resizable backing buffers, including fixed-length views.
@@ -266,6 +329,7 @@ export class Wasi {
266
329
  hostCall: ((slot: number, args: number[]) => number) | null = null;
267
330
  readonly descriptors = new DescriptorTable();
268
331
  private watches?: GuestWatchTable;
332
+ private posixLockedHandles?: Set<FileHandle>;
269
333
  private importedMemory?: WebAssembly.Memory;
270
334
  private boundMemory?: WebAssembly.Memory;
271
335
  private hostWrite?: FdWrite;
@@ -278,6 +342,50 @@ export class Wasi {
278
342
  private rootedSnapshot?: boolean;
279
343
  /** The handle a `/` preopen spelled exactly `/` opened: the filesystem root, known for free. */
280
344
  private literalRoot?: number;
345
+ private readonly explicitMachineId?: string;
346
+ private machineId(): string | undefined {
347
+ return this.explicitMachineId ?? this.opts.fs.machineId;
348
+ }
349
+ private virtualMachineIdStat(): FileStat {
350
+ return {
351
+ kind: "file",
352
+ ino: MACHINE_ID_INO,
353
+ nlink: 1,
354
+ size: MACHINE_ID_FILE_SIZE,
355
+ atime: 0n,
356
+ mtime: 0n,
357
+ ctime: 0n,
358
+ mode: 0o444,
359
+ };
360
+ }
361
+ private resolveVirtualMachineId(
362
+ entry: Descriptor,
363
+ path: string,
364
+ follow: boolean,
365
+ ): "machine-id" | number | undefined {
366
+ if (this.machineId() === undefined) return undefined;
367
+ const alias = resolveDescriptorPath(
368
+ this.descriptors,
369
+ this.opts.fs,
370
+ entry,
371
+ path,
372
+ follow ? "follow" : "nofollow",
373
+ this.rooted,
374
+ true,
375
+ );
376
+ if (typeof alias === "number") return alias;
377
+ if (alias !== undefined && "virtualFile" in alias) return alias.virtualFile;
378
+ return undefined;
379
+ }
380
+ private relativeVirtualMachineId(handle: FileHandle): string {
381
+ const rootHandle = this.opts.fs.preopen("/");
382
+ if (
383
+ handle === rootHandle ||
384
+ this.opts.fs.stat(handle).ino === this.opts.fs.stat(rootHandle).ino
385
+ )
386
+ return "etc/machine-id";
387
+ return "machine-id";
388
+ }
281
389
  private get rooted(): boolean {
282
390
  return (this.rootedSnapshot ??= this.rootNamespace());
283
391
  }
@@ -319,6 +427,7 @@ export class Wasi {
319
427
  }
320
428
 
321
429
  constructor(private opts: WasiOptions) {
430
+ if (opts.machineId !== undefined) this.explicitMachineId = validateMachineId(opts.machineId);
322
431
  const reserved = new Set<number>();
323
432
  for (const fd of opts.reservedFds ?? []) {
324
433
  if (!Number.isInteger(fd) || fd < 0 || fd > MAX_DESCRIPTOR || reserved.has(fd))
@@ -364,6 +473,9 @@ export class Wasi {
364
473
  this.openFileAt(fd, { kind: "directory", handle }, RIGHTS_ALL, RIGHTS_ALL, name);
365
474
  fd++;
366
475
  }
476
+ if (opts.fs.locks) {
477
+ this.descriptors.setOnClose((closed) => this.releasePosixHandle(closed.resource));
478
+ }
367
479
  }
368
480
 
369
481
  private openDevice(
@@ -383,6 +495,26 @@ export class Wasi {
383
495
  );
384
496
  }
385
497
 
498
+ private openVirtualMachineId(
499
+ fdflags: number,
500
+ base: bigint,
501
+ inheriting: bigint,
502
+ oflags: number,
503
+ out: number,
504
+ ): number {
505
+ if ((out >>> 0) + 4 > this.bytes().length) return EFAULT;
506
+ if (oflags & O_DIRECTORY) return ENOTDIR;
507
+ if (oflags & O_CREAT && oflags & O_EXCL) return EEXIST;
508
+ if (oflags & ~15 || fdflags & ~31) return EINVAL;
509
+ if ((oflags & O_TRUNC) !== 0 || (base & RIGHT_FD_WRITE) !== 0n) return EACCES;
510
+ const id = this.machineId();
511
+ if (id === undefined) return ENOENT;
512
+ return this.writeResult(
513
+ this.descriptors.open(createMachineIdFile(id, fdflags), base, inheriting),
514
+ out >>> 0,
515
+ );
516
+ }
517
+
386
518
  private openFileAt(
387
519
  fd: number,
388
520
  resource: Extract<Resource, { handle: number }>,
@@ -396,11 +528,28 @@ export class Wasi {
396
528
  resource,
397
529
  base,
398
530
  inheriting,
399
- () => this.opts.fs.release(resource.handle),
531
+ () => releaseOriginOfd(this.opts.fs, resource),
400
532
  preopen,
401
533
  );
402
534
  }
403
535
 
536
+ /** Release all POSIX process-scoped byte-range locks held by this guest. */
537
+ releasePosixLocks(): void {
538
+ if (!this.posixLockedHandles || this.posixLockedHandles.size === 0) return;
539
+ const handles = Array.from(this.posixLockedHandles);
540
+ this.posixLockedHandles.clear();
541
+ const pid = this.opts.pid ?? 1;
542
+ for (let i = 0; i < handles.length; i++) {
543
+ this.opts.fs.locks?.releasePosix(handles[i]!, pid);
544
+ }
545
+ }
546
+
547
+ /** Suppress per-descriptor POSIX lock release during thread-member teardown. */
548
+ suppressPosixClose(): void {
549
+ this.descriptors.setOnClose(undefined);
550
+ this.posixLockedHandles?.clear();
551
+ }
552
+
404
553
  /** runtime_proc uses positive errno and checks output memory before changing the inode. */
405
554
  fdReopen(fd: number, oflags: number, fdflags: number, base: bigint, out: number): number {
406
555
  try {
@@ -418,6 +567,7 @@ export class Wasi {
418
567
  base: bigint,
419
568
  inheriting: bigint,
420
569
  out: number,
570
+ intersectCapabilities = false,
421
571
  ): number {
422
572
  if ((out >>> 0) + 4 > this.bytes().length) return 21;
423
573
  const result = reopenDescriptor(
@@ -428,6 +578,7 @@ export class Wasi {
428
578
  fdflags,
429
579
  base,
430
580
  inheriting,
581
+ intersectCapabilities,
431
582
  );
432
583
  return this.writeResult(result, out >>> 0);
433
584
  }
@@ -495,11 +646,14 @@ export class Wasi {
495
646
  const filesystem: Record<string, (...args: never[]) => number> = {
496
647
  path_permissions_get: this.pathPermissions.bind(this),
497
648
  path_realpath: this.pathRealpath.bind(this),
649
+ path_probe: this.pathProbe.bind(this),
498
650
  watch_open: this.watchOpen.bind(this),
499
651
  watch_ready: () => (this.watches?.ready() ? 1 : 0),
500
652
  watch_read: this.watchRead.bind(this),
501
653
  watch_next: this.watchNext.bind(this),
502
654
  watch_close: (id: number) => this.watches?.close(id >>> 0) ?? EBADF,
655
+ fd_flock: this.fdFlock.bind(this),
656
+ fd_lock: this.fdLock.bind(this),
503
657
  };
504
658
  const out: WebAssembly.Imports = Object.create(null);
505
659
  this.importedMemory = undefined;
@@ -736,6 +890,166 @@ export class Wasi {
736
890
  return SUCCESS;
737
891
  }
738
892
 
893
+ private lockWaitControl(): LockWaitControl | undefined {
894
+ if (
895
+ !this.opts.checkActive &&
896
+ !this.opts.interruptPending &&
897
+ !this.opts.interrupt &&
898
+ !this.opts.wait
899
+ )
900
+ return undefined;
901
+ return {
902
+ checkActive: this.opts.checkActive,
903
+ interruptPending: () =>
904
+ this.opts.interruptPending?.() ??
905
+ (this.opts.interrupt !== undefined && controlLoad(this.opts.interrupt, 0) !== 0),
906
+ wait: this.opts.wait
907
+ ? (word, expected, ms) => this.opts.wait!(word, expected, ms)
908
+ : undefined,
909
+ };
910
+ }
911
+
912
+ private resolveRangeBase(
913
+ resource: Extract<Resource, { kind: "file" | "directory" }>,
914
+ whence: number,
915
+ ): bigint | null {
916
+ switch (whence) {
917
+ case 0:
918
+ return 0n;
919
+ case 1:
920
+ return BigInt(resource.kind === "file" ? resource.offset : 0);
921
+ case 2:
922
+ return BigInt(this.opts.fs.stat(resource.handle).size);
923
+ default:
924
+ return null;
925
+ }
926
+ }
927
+
928
+ private resolveRange(
929
+ resource: Extract<Resource, { kind: "file" | "directory" }>,
930
+ whence: number,
931
+ start: bigint,
932
+ len: bigint,
933
+ ): { readonly start: number; readonly len: number } | number {
934
+ const base = this.resolveRangeBase(resource, whence);
935
+ if (base === null) return EINVAL;
936
+ const pos = base + start;
937
+ if (len === 0n) {
938
+ if (pos < 0n) return EINVAL;
939
+ if (pos > MAX_FILE_SIZE) return EOVERFLOW;
940
+ return { start: Number(pos), len: 0 };
941
+ }
942
+ const rangeStart = len > 0n ? pos : pos + len;
943
+ const rangeEnd = len > 0n ? pos + len : pos;
944
+ if (rangeStart < 0n || rangeEnd < 0n) return EINVAL;
945
+ if (rangeStart > MAX_FILE_SIZE || rangeEnd > MAX_FILE_SIZE) return EOVERFLOW;
946
+ return { start: Number(rangeStart), len: Number(rangeEnd - rangeStart) };
947
+ }
948
+
949
+ private releasePosixHandle(resource: Resource): void {
950
+ if (resource.kind !== "file" && resource.kind !== "directory") return;
951
+ const tracked = this.posixLockedHandles?.delete(resource.handle) === true;
952
+ const locks = this.opts.fs.locks;
953
+ if (!locks) return;
954
+ if (!tracked && !locks.hasActivePosixLocks?.()) return;
955
+ locks.releasePosix(resource.handle, this.opts.pid ?? 1);
956
+ }
957
+
958
+ /** Release POSIX locks only for descriptors not inherited across a successful execve. */
959
+ releaseUninheritedPosixLocks(keptFds: ReadonlySet<number>): void {
960
+ this.descriptors.setOnClose(undefined);
961
+ const closedResources: Resource[] = [];
962
+ this.descriptors.forEach((entry, fd) => {
963
+ if (!keptFds.has(fd)) closedResources.push(entry.resource);
964
+ });
965
+ for (let i = 0; i < closedResources.length; i++) {
966
+ this.releasePosixHandle(closedResources[i]!);
967
+ }
968
+ this.posixLockedHandles?.clear();
969
+ }
970
+
971
+ /** runtime_fs.fd_flock: advisory whole-file lock (flock(2)), OFD-scoped. */
972
+ private fdFlock(fd: number, operation: number): number {
973
+ const entry = this.descriptors.get(fd >>> 0);
974
+ if (!entry) return EBADF;
975
+ if (entry.resource.kind !== "file" && entry.resource.kind !== "directory") return EINVAL;
976
+ if ((operation & ~(LOCK_SH | LOCK_EX | LOCK_NB | LOCK_UN)) !== 0) return EINVAL;
977
+ const base = operation & ~LOCK_NB;
978
+ if (base !== LOCK_SH && base !== LOCK_EX && base !== LOCK_UN) return EINVAL;
979
+ const locks = this.opts.fs.locks;
980
+ if (!locks) return ENOTSUP;
981
+ const owner = locks.owner ?? 0;
982
+ const ofdId = resourceOfdId(entry.resource, owner);
983
+ const blocking = (operation & LOCK_NB) === 0 && base !== LOCK_UN;
984
+ const err = locks.flock(
985
+ entry.resource.handle,
986
+ ofdId,
987
+ operation,
988
+ blocking ? this.lockWaitControl() : undefined,
989
+ );
990
+ if (err === SUCCESS && base !== LOCK_UN) markResourceOfdLocked(entry.resource, owner);
991
+ return err;
992
+ }
993
+
994
+ /** runtime_fs.fd_lock: POSIX (F_GETLK/F_SETLK/F_SETLKW) and OFD byte-range advisory locks. */
995
+ private fdLock(
996
+ fd: number,
997
+ cmd: number,
998
+ type: number,
999
+ whence: number,
1000
+ start: bigint,
1001
+ len: bigint,
1002
+ outPtr: number,
1003
+ ): number {
1004
+ if (cmd < F_GETLK || cmd > F_OFD_SETLKW) return EINVAL;
1005
+ if (type !== F_RDLCK && type !== F_WRLCK && type !== F_UNLCK) return EINVAL;
1006
+ if (whence < 0 || whence > 2) return EINVAL;
1007
+ const isGet = cmd === F_GETLK || cmd === F_OFD_GETLK;
1008
+ const out = outPtr >>> 0;
1009
+ if (isGet && out + 24 > this.bytes().length) return EFAULT;
1010
+ const entry = this.descriptors.get(fd >>> 0);
1011
+ if (!entry) return EBADF;
1012
+ if (entry.resource.kind !== "file" && entry.resource.kind !== "directory") return EINVAL;
1013
+ if (!isGet && type === F_RDLCK && !(entry.rightsBase & RIGHT_FD_READ)) return EBADF;
1014
+ if (!isGet && type === F_WRLCK && !(entry.rightsBase & RIGHT_FD_WRITE)) return EBADF;
1015
+ const locks = this.opts.fs.locks;
1016
+ if (!locks) return ENOTSUP;
1017
+ const resolved = this.resolveRange(entry.resource, whence, start, len);
1018
+ if (typeof resolved === "number") return resolved;
1019
+ const owner = locks.owner ?? 0;
1020
+ const isOfd = cmd === F_OFD_GETLK || cmd === F_OFD_SETLK || cmd === F_OFD_SETLKW;
1021
+ const ofdId = isOfd ? resourceOfdId(entry.resource, owner) : undefined;
1022
+ const range = { type, start: resolved.start, len: resolved.len } as const;
1023
+ const pid = this.opts.pid ?? 1;
1024
+ if (isGet) {
1025
+ const conflict = locks.getRangeLock(entry.resource.handle, ofdId, range, pid);
1026
+ if (typeof conflict === "number") return conflict;
1027
+ const view = this.view();
1028
+ if (out + 24 > view.byteLength) return EFAULT;
1029
+ view.setUint32(out, conflict.type, true);
1030
+ view.setInt32(out + 4, conflict.pid, true);
1031
+ view.setBigInt64(out + 8, BigInt(conflict.start), true);
1032
+ view.setBigInt64(out + 16, BigInt(conflict.len), true);
1033
+ return SUCCESS;
1034
+ }
1035
+ const blocking = (cmd === F_SETLKW || cmd === F_OFD_SETLKW) && type !== F_UNLCK;
1036
+ const err = locks.setRangeLock(
1037
+ entry.resource.handle,
1038
+ ofdId,
1039
+ pid,
1040
+ range,
1041
+ blocking,
1042
+ blocking ? this.lockWaitControl() : undefined,
1043
+ );
1044
+ if (err !== SUCCESS || type === F_UNLCK) return err;
1045
+ if (isOfd) {
1046
+ markResourceOfdLocked(entry.resource, owner);
1047
+ return err;
1048
+ }
1049
+ (this.posixLockedHandles ??= new Set()).add(entry.resource.handle);
1050
+ return err;
1051
+ }
1052
+
739
1053
  /** runtime_fs.path_realpath: realpath(3) of `path` from `fd` in one filesystem request. Writes
740
1054
  * the UTF-8 result's length to `used`; a result longer than `capacity` is ENOBUFS, with
741
1055
  * nothing written to `buf`. See docs/host-abi.md. */
@@ -763,7 +1077,15 @@ export class Wasi {
763
1077
  if (!entry) return EBADF;
764
1078
  if (entry.resource.kind !== "directory") return ENOTDIR;
765
1079
  if (!(entry.rightsBase & RIGHT_PATH_FILESTAT_GET)) return ENOTCAPABLE;
766
- const real = this.opts.fs.realpath(entry.resource.handle, path, this.rooted);
1080
+ let real = this.opts.fs.realpath(entry.resource.handle, path, this.rooted);
1081
+ if (real === ENOENT) {
1082
+ const virtual = this.resolveVirtualMachineId(entry, path, true);
1083
+ if (typeof virtual === "number") return virtual;
1084
+ if (virtual === "machine-id")
1085
+ real = this.rooted
1086
+ ? "/etc/machine-id"
1087
+ : this.relativeVirtualMachineId(entry.resource.handle);
1088
+ }
767
1089
  if (typeof real === "number") return real;
768
1090
  const encoded = encoder.encode(real);
769
1091
  // Reacquire after the service round trip; another thread may have grown shared memory.
@@ -773,6 +1095,30 @@ export class Wasi {
773
1095
  return SUCCESS;
774
1096
  }
775
1097
 
1098
+ /** runtime_fs.path_probe: the index of the first NUL-terminated pathname in `ptr..ptr+len`
1099
+ * that names a regular file (`kind` 1) or a directory (`kind` 2), each looked up from `fd` as
1100
+ * path_filestat_get with the follow flag does, in one filesystem request. Writes the index, or
1101
+ * 0xffffffff when none matches, to the u32 at `found`. See docs/host-abi.md. */
1102
+ private pathProbe(fd: number, ptr: number, len: number, kind: number, found: number): number {
1103
+ ptr >>>= 0;
1104
+ len >>>= 0;
1105
+ found >>>= 0;
1106
+ const bytes = this.bytes();
1107
+ if (ptr + len > bytes.length || found + 4 > bytes.length) return EFAULT;
1108
+ const paths = probePathnames(bytes, ptr, len);
1109
+ if (paths === undefined) return EINVAL;
1110
+ const wanted = PROBE_KINDS[kind >>> 0];
1111
+ if (wanted === undefined) return EINVAL;
1112
+ const entry = this.descriptors.get(fd >>> 0);
1113
+ if (!entry) return EBADF;
1114
+ if (entry.resource.kind !== "directory") return ENOTDIR;
1115
+ if (!(entry.rightsBase & RIGHT_PATH_FILESTAT_GET)) return ENOTCAPABLE;
1116
+ const index = this.opts.fs.probe(entry.resource.handle, paths, wanted, this.rooted);
1117
+ // Reacquire after the service round trip; another thread may have grown shared memory.
1118
+ this.view().setUint32(found, index < 0 ? 0xffffffff : index, true);
1119
+ return SUCCESS;
1120
+ }
1121
+
776
1122
  private pathPermissions(
777
1123
  fd: number,
778
1124
  ptr: number,
@@ -798,9 +1144,17 @@ export class Wasi {
798
1144
  if (entry.resource.kind !== "directory") return ENOTDIR;
799
1145
  if (!(entry.rightsBase & RIGHT_PATH_FILESTAT_GET)) return ENOTCAPABLE;
800
1146
  const resolved = this.opts.fs.resolve(entry.resource.handle, path, false, this.rooted);
801
- if (typeof resolved === "number") return resolved;
802
- if (resolved.node === undefined) return ENOENT;
803
- const result = this.opts.fs.permissions?.(resolved.node);
1147
+ let result =
1148
+ typeof resolved !== "number" && resolved.node !== undefined
1149
+ ? this.opts.fs.permissions?.(resolved.node)
1150
+ : undefined;
1151
+ if (typeof resolved === "number" || resolved.node === undefined) {
1152
+ if (typeof resolved === "number" && resolved !== ENOENT) return resolved;
1153
+ const virtual = this.resolveVirtualMachineId(entry, path, false);
1154
+ if (typeof virtual === "number") return virtual;
1155
+ if (virtual !== "machine-id") return ENOENT;
1156
+ result = permissionsFor("file", 0o444);
1157
+ }
804
1158
  if (!result) return ENOTSUP;
805
1159
  const view = this.view();
806
1160
  view.setUint32(out, result.mode, true);
@@ -956,27 +1310,22 @@ export class Wasi {
956
1310
  const entry = this.descriptors.get(fd);
957
1311
  if (!entry) return EBADF;
958
1312
  const view = this.view();
959
- const filetype =
960
- entry.resource.kind === "terminal" || entry.resource.kind === "device"
961
- ? FT_CHAR
962
- : entry.resource.kind === "directory"
963
- ? FT_DIR
964
- : entry.resource.kind === "socket"
965
- ? FT_SOCKET
966
- : entry.resource.kind === "pipe"
967
- ? 0
968
- : FT_FILE;
1313
+ const resource = entry.resource;
1314
+ let filetype = FT_FILE;
1315
+ if (resource.kind === "terminal") filetype = FT_CHAR;
1316
+ else if (resource.kind === "device") filetype = resource.virtualFile ? FT_FILE : FT_CHAR;
1317
+ else if (resource.kind === "directory") filetype = FT_DIR;
1318
+ else if (resource.kind === "socket") filetype = FT_SOCKET;
1319
+ else if (resource.kind === "pipe") filetype = 0;
1320
+ let fdflags = 0;
1321
+ if (resource.kind === "file") {
1322
+ fdflags =
1323
+ ((resource.fdflags ?? 0) & ~FDFLAG_APPEND) | (resource.append ? FDFLAG_APPEND : 0);
1324
+ } else if (resource.kind !== "directory") {
1325
+ fdflags = resource.fdflags ?? 0;
1326
+ }
969
1327
  view.setUint8(ptr, filetype);
970
- view.setUint16(
971
- ptr + 2,
972
- entry.resource.kind === "file"
973
- ? ((entry.resource.fdflags ?? 0) & ~FDFLAG_APPEND) |
974
- (entry.resource.append ? FDFLAG_APPEND : 0)
975
- : entry.resource.kind === "directory"
976
- ? 0
977
- : (entry.resource.fdflags ?? 0),
978
- true,
979
- );
1328
+ view.setUint16(ptr + 2, fdflags, true);
980
1329
  view.setBigUint64(ptr + 8, entry.rightsBase, true);
981
1330
  view.setBigUint64(ptr + 16, entry.rightsInheriting, true);
982
1331
  return SUCCESS;
@@ -1013,18 +1362,26 @@ export class Wasi {
1013
1362
  return SUCCESS;
1014
1363
  },
1015
1364
  fd_filestat_get: this.descriptorCall(RIGHT_FD_FILESTAT_GET, (resource, ptr: number) => {
1365
+ if (resource.kind === "device" && resource.virtualFile) {
1366
+ this.writeFilestat(ptr, this.virtualMachineIdStat());
1367
+ return SUCCESS;
1368
+ }
1369
+ let streamType = FT_CHAR;
1370
+ if (resource.kind === "pipe") streamType = 0;
1371
+ else if (resource.kind === "socket") streamType = FT_SOCKET;
1016
1372
  this.writeFilestat(
1017
1373
  ptr,
1018
1374
  resource.kind === "file" || resource.kind === "directory"
1019
1375
  ? this.opts.fs.stat(resource.handle)
1020
1376
  : null,
1021
- resource.kind === "pipe" ? 0 : resource.kind === "socket" ? FT_SOCKET : FT_CHAR,
1377
+ streamType,
1022
1378
  );
1023
1379
  return SUCCESS;
1024
1380
  }),
1025
1381
  fd_filestat_set_size: this.descriptorCall(
1026
1382
  RIGHT_FD_FILESTAT_SET_SIZE,
1027
1383
  (resource, size: bigint) => {
1384
+ if (resource.kind === "device" && resource.virtualFile) return EACCES;
1028
1385
  if (resource.kind !== "file") return EINVAL;
1029
1386
  if (!isSupportedFileSize(size)) return EFBIG;
1030
1387
  return this.opts.fs.resize(resource.handle, Number(size), true);
@@ -1042,6 +1399,17 @@ export class Wasi {
1042
1399
  RIGHT_FD_READ | RIGHT_FD_SEEK,
1043
1400
  (resource, iovs: number, count: number, offset: bigint, nreadPtr: number) => {
1044
1401
  if (resource.kind === "directory") return EISDIR;
1402
+ if (resource.kind === "device" && resource.virtualFile) {
1403
+ if (offset < 0n) return EINVAL;
1404
+ return this.writeResult(
1405
+ readVirtualFileBytes(
1406
+ resource.virtualFile.data,
1407
+ this.iovecs(iovs, count),
1408
+ Number(offset),
1409
+ ),
1410
+ nreadPtr,
1411
+ );
1412
+ }
1045
1413
  if (resource.kind !== "file") return ESPIPE;
1046
1414
  if (offset < 0n) return EINVAL;
1047
1415
  return this.writeResult(
@@ -1054,6 +1422,7 @@ export class Wasi {
1054
1422
  RIGHT_FD_WRITE | RIGHT_FD_SEEK,
1055
1423
  (resource, iovs: number, count: number, offset: bigint, nwrittenPtr: number) => {
1056
1424
  if (resource.kind === "directory") return EISDIR;
1425
+ if (resource.kind === "device" && resource.virtualFile) return EACCES;
1057
1426
  if (resource.kind !== "file") return ESPIPE;
1058
1427
  if (offset < 0n) return EINVAL;
1059
1428
  return this.writeResult(
@@ -1115,26 +1484,27 @@ export class Wasi {
1115
1484
  return SUCCESS;
1116
1485
  },
1117
1486
  ),
1118
- fd_renumber: (from: number, to: number) => {
1119
- return this.descriptors.renumber(from, to) ? SUCCESS : EBADF;
1120
- },
1487
+ fd_renumber: (from: number, to: number) =>
1488
+ this.descriptors.renumber(from, to) ? SUCCESS : EBADF,
1121
1489
  fd_seek: (fd: number, offset: bigint, whence: number, newOffsetPtr: number) => {
1122
1490
  const entry = this.descriptors.get(fd);
1123
1491
  if (!entry) return EBADF;
1124
1492
  const right = offset === 0n && whence === 1 ? RIGHT_FD_TELL | RIGHT_FD_SEEK : RIGHT_FD_SEEK;
1125
1493
  if (!(entry.rightsBase & right)) return ENOTCAPABLE;
1126
1494
  if (entry.resource.kind === "directory") return EISDIR;
1495
+ if (entry.resource.kind === "device" && entry.resource.virtualFile) {
1496
+ const next = seekVirtualFile(entry.resource.virtualFile, offset, whence);
1497
+ if (typeof next === "number") return -next;
1498
+ this.view().setBigUint64(newOffsetPtr, next, true);
1499
+ return SUCCESS;
1500
+ }
1127
1501
  if (entry.resource.kind !== "file") return ESPIPE;
1128
1502
  const file = entry.resource;
1129
1503
  const result = withFileOffset(file, () => {
1130
- const base =
1131
- whence === 0
1132
- ? 0
1133
- : whence === 1
1134
- ? file.offset
1135
- : whence === 2
1136
- ? this.opts.fs.stat(file.handle).size
1137
- : NaN;
1504
+ let base = Number.NaN;
1505
+ if (whence === 0) base = 0;
1506
+ else if (whence === 1) base = file.offset;
1507
+ else if (whence === 2) base = this.opts.fs.stat(file.handle).size;
1138
1508
  const pos = base + Number(offset);
1139
1509
  if (!(pos >= 0)) return -EINVAL;
1140
1510
  file.offset = pos;
@@ -1144,6 +1514,10 @@ export class Wasi {
1144
1514
  return result < 0 ? -result : result;
1145
1515
  },
1146
1516
  fd_tell: this.descriptorCall(RIGHT_FD_TELL, (resource, ptr: number) => {
1517
+ if (resource.kind === "device" && resource.virtualFile) {
1518
+ this.view().setBigUint64(ptr, tellVirtualFile(resource.virtualFile), true);
1519
+ return SUCCESS;
1520
+ }
1147
1521
  if (resource.kind !== "file") return ESPIPE;
1148
1522
  this.view().setBigUint64(ptr, BigInt(resource.offset), true);
1149
1523
  return SUCCESS;
@@ -1175,11 +1549,22 @@ export class Wasi {
1175
1549
  return typeof result === "number" ? SUCCESS : result.error;
1176
1550
  },
1177
1551
  path_filestat_get: (fd: number, flags: number, ptr: number, len: number, buf: number) => {
1178
- const path = this.resolve(fd, ptr, len, RIGHT_PATH_FILESTAT_GET, lookupFlags(flags));
1179
- if (typeof path === "number") return path;
1180
- const node = path.node;
1181
- if (node === undefined) return ENOENT;
1182
- this.writeFilestat(buf, this.opts.fs.stat(node));
1552
+ const follow = lookupFlags(flags);
1553
+ const path = this.resolve(fd, ptr, len, RIGHT_PATH_FILESTAT_GET, follow);
1554
+ if (typeof path === "number" || path.node === undefined) {
1555
+ if (typeof path === "number" && path !== ENOENT) return path;
1556
+ const entry = this.descriptors.get(fd);
1557
+ if (!entry) return EBADF;
1558
+ const name = this.str(ptr, len);
1559
+ const virtual = this.resolveVirtualMachineId(entry, name, followsFinal(follow, name));
1560
+ if (typeof virtual === "number") return virtual;
1561
+ if (virtual === "machine-id") {
1562
+ this.writeFilestat(buf, this.virtualMachineIdStat());
1563
+ return SUCCESS;
1564
+ }
1565
+ return ENOENT;
1566
+ }
1567
+ this.writeFilestat(buf, this.opts.fs.stat(path.node));
1183
1568
  return SUCCESS;
1184
1569
  },
1185
1570
  path_filestat_set_times: (
@@ -1247,23 +1632,39 @@ export class Wasi {
1247
1632
  const name = this.str(ptr, len);
1248
1633
  const exclusive = (oflags & O_CREAT && oflags & O_EXCL) !== 0;
1249
1634
  const follow = !exclusive && followsFinal(lookupFlags(dirflags), name);
1635
+ let finalLink: "exclusive-create" | "follow" | "nofollow" = "nofollow";
1636
+ if (exclusive) finalLink = "exclusive-create";
1637
+ else if (follow) finalLink = "follow";
1250
1638
  const alias = resolveDescriptorPath(
1251
1639
  this.descriptors,
1252
1640
  this.opts.fs,
1253
1641
  dir,
1254
1642
  name,
1255
- exclusive ? "exclusive-create" : follow ? "follow" : "nofollow",
1643
+ finalLink,
1256
1644
  this.rooted,
1645
+ this.machineId() !== undefined,
1257
1646
  );
1258
1647
  if (typeof alias === "number") return alias;
1259
1648
  if (alias !== undefined && !("resolved" in alias)) {
1649
+ if ("virtualFile" in alias) {
1650
+ if (fdOut + 4 > this.bytes().length) return EFAULT;
1651
+ return this.openVirtualMachineId(fdflags, rightsBase, rightsInheriting, oflags, fdOut);
1652
+ }
1260
1653
  if ("device" in alias) {
1261
1654
  if (fdOut + 4 > this.bytes().length) return EFAULT;
1262
1655
  return this.openDevice(fdflags, rightsBase, rightsInheriting, oflags, fdOut);
1263
1656
  }
1264
1657
  if (!this.descriptors.get(alias.source)) return ENOENT;
1265
1658
  if (fdOut + 4 > this.bytes().length) return EFAULT;
1266
- return this.reopen(alias.source, oflags, fdflags, rightsBase, rightsInheriting, fdOut);
1659
+ return this.reopen(
1660
+ alias.source,
1661
+ oflags,
1662
+ fdflags,
1663
+ rightsBase,
1664
+ rightsInheriting,
1665
+ fdOut,
1666
+ true,
1667
+ );
1267
1668
  }
1268
1669
  const path =
1269
1670
  alias?.resolved ?? this.opts.fs.resolve(dir.resource.handle, name, follow, this.rooted);
@@ -1524,6 +1925,7 @@ export class Wasi {
1524
1925
 
1525
1926
  proc_exit: (code: number) => {
1526
1927
  this.dropWatches();
1928
+ this.releasePosixLocks();
1527
1929
  this.descriptors.dispose();
1528
1930
  // Match native process exits; negative i32 values must not alias child-control errors.
1529
1931
  throw new WasiExit(code & 0xff);