@waffle-os/runtime 0.0.156 → 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 (75) 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 +71 -0
  11. package/core/index.ts +4 -0
  12. package/core/open-file.ts +212 -18
  13. package/core/wasi.ts +397 -46
  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 +13 -0
  23. package/dist/core/open-file.js +166 -13
  24. package/dist/core/wasi.js +353 -27
  25. package/dist/fs/backend.js +29 -2
  26. package/dist/fs/client.js +199 -6
  27. package/dist/fs/index.js +21 -1
  28. package/dist/fs/indexeddb.js +30 -2
  29. package/dist/fs/locks.js +1112 -0
  30. package/dist/fs/memory.js +109 -1
  31. package/dist/fs/multitab-backend.js +315 -195
  32. package/dist/fs/multitab-protocol.js +1 -0
  33. package/dist/fs/persistent.js +13 -6
  34. package/dist/fs/protocol.js +9 -3
  35. package/dist/fs/service.js +386 -22
  36. package/dist/fs/shared.js +54 -1
  37. package/dist/fs/storage-geometry.js +2 -0
  38. package/dist/interrupt/rewriter-internal.js +4 -1
  39. package/dist/proc/abi.js +80 -6
  40. package/dist/proc/errors.js +1 -0
  41. package/dist/proc/filesystem-codec.js +40 -9
  42. package/dist/proc/index.js +10 -1
  43. package/dist/proc/pty.js +193 -0
  44. package/dist/proc/worker-client.js +11 -2
  45. package/dist/proc/worker-pipes.js +51 -0
  46. package/dist/runtime.js +11 -2
  47. package/dist/search/engine.js +53 -0
  48. package/dist/tooling/program/program-transformer.json +1 -1
  49. package/fs/backend.ts +33 -1
  50. package/fs/client.ts +225 -6
  51. package/fs/index.ts +22 -1
  52. package/fs/indexeddb.ts +36 -2
  53. package/fs/locks.ts +1406 -0
  54. package/fs/memory.ts +114 -1
  55. package/fs/multitab-backend.ts +561 -303
  56. package/fs/multitab-protocol.ts +1 -0
  57. package/fs/persistent.ts +14 -3
  58. package/fs/protocol.ts +17 -5
  59. package/fs/service.ts +468 -23
  60. package/fs/shared.ts +60 -2
  61. package/fs/storage-geometry.ts +3 -0
  62. package/index.ts +2 -0
  63. package/interrupt/rewriter-internal.ts +4 -1
  64. package/package.json +2 -2
  65. package/proc/abi.ts +79 -6
  66. package/proc/errors.ts +1 -0
  67. package/proc/filesystem-codec.ts +39 -9
  68. package/proc/index.ts +11 -0
  69. package/proc/pty.ts +227 -0
  70. package/proc/worker-client.ts +28 -6
  71. package/proc/worker-pipes.ts +57 -0
  72. package/runtime.ts +12 -2
  73. package/search/engine.ts +49 -0
  74. package/testing/indexeddb-storage-browser.ts +173 -2
  75. package/tooling/program/program-transformer.json +1 -1
@@ -105,6 +105,9 @@ function workerCompletionMessage(result, completed, state) {
105
105
  function logicalProcessIdentity(state) {
106
106
  return state?.processIdentity ?? null;
107
107
  }
108
+ function wasiProcessPid(state, identity) {
109
+ return logicalProcessIdentity(state)?.pid ?? identity?.pid;
110
+ }
108
111
 
109
112
  export class RuntimeWorkerSignal extends ExecutionUnwind {
110
113
  signal;
@@ -264,10 +267,20 @@ function closeDiscardedStdio(discarded, tableOwned) {
264
267
  if (errors.length)
265
268
  throw new AggregateError(errors, "stdio release failed");
266
269
  }
267
- function disposeProcessDescriptors(wasi, discarded) {
270
+ function disposeProcessDescriptors(wasi, discarded, posixMode = { kind: "process-exit" }) {
268
271
  const tableOwned = tableOwnedStdio(wasi.descriptors, discarded);
269
272
  const errors = [];
270
273
  wasi.dropWatches();
274
+ try {
275
+ if (posixMode.kind === "exec")
276
+ wasi.releaseUninheritedPosixLocks(posixMode.keptFds);
277
+ else if (posixMode.kind === "thread-member")
278
+ wasi.suppressPosixClose();
279
+ else
280
+ wasi.releasePosixLocks();
281
+ } catch (error) {
282
+ errors.push(error);
283
+ }
271
284
  try {
272
285
  wasi.descriptors.dispose();
273
286
  } catch (error) {
@@ -350,6 +363,9 @@ async function bootstrapAllocated(req, executor, host, { postToHost, addListener
350
363
  const fs = new FilesystemClient(req.filesystem);
351
364
  const { cancellation, notifications, startupCancelled, cancelStartup } = startupControl(req.notifications, fs);
352
365
  let runtimeProcess = null;
366
+ let isThreadMember = false;
367
+ let hasSpawnedThread = false;
368
+ let execHandoff;
353
369
  let process;
354
370
  let processSignalExit;
355
371
  let discardedStdio = [];
@@ -550,7 +566,18 @@ async function bootstrapAllocated(req, executor, host, { postToHost, addListener
550
566
  }
551
567
  const descriptorsReleased = attempt(() => {
552
568
  if (wasi) {
553
- disposeProcessDescriptors(wasi, discardedStdio);
569
+ if (replacing && execHandoff) {
570
+ if (fs.locks.hasActivePosixLocks?.()) {
571
+ fs.locks.handoffPosix?.(execHandoff.successorOwner);
572
+ }
573
+ disposeProcessDescriptors(wasi, discardedStdio, {
574
+ kind: "exec",
575
+ keptFds: execHandoff.keptFds
576
+ });
577
+ return;
578
+ }
579
+ const posixMode = isThreadMember || hasSpawnedThread ? { kind: "thread-member" } : { kind: "process-exit" };
580
+ disposeProcessDescriptors(wasi, discardedStdio, posixMode);
554
581
  return;
555
582
  }
556
583
  const streams = ownedStreams(ownedStdio);
@@ -701,6 +728,7 @@ async function bootstrapAllocated(req, executor, host, { postToHost, addListener
701
728
  }
702
729
  const interrupt = runtimeState?.signals.interrupt ?? (executor.interrupt ? new Int32ArrayConstructor(executor.interrupt) : undefined);
703
730
  if (runtimeState) {
731
+ isThreadMember = runtimeState.processKind === "thread";
704
732
  outcome = runtimeState.signals.outcome;
705
733
  requestedSignal = runtimeState.signals.requestedSignal;
706
734
  }
@@ -840,6 +868,7 @@ async function bootstrapAllocated(req, executor, host, { postToHost, addListener
840
868
  const hostCallFd = executor.hostCallFd;
841
869
  const reservedFds = bindingTargets(req.runtimeProcess, req.network, hostCallFd);
842
870
  wasi = new Wasi({
871
+ pid: wasiProcessPid(runtimeState, identity),
843
872
  hostCallFd,
844
873
  args: req.args,
845
874
  env,
@@ -869,6 +898,7 @@ async function bootstrapAllocated(req, executor, host, { postToHost, addListener
869
898
  }
870
899
  checkActive();
871
900
  },
901
+ checkActive,
872
902
  interrupt,
873
903
  interruptPending: runtimeState ? () => signalPending(runtimeState.signals) : executor.interruptPending ? () => executor.interruptPending() : undefined,
874
904
  wait: (word, expected, ms) => {
@@ -929,12 +959,16 @@ async function bootstrapAllocated(req, executor, host, { postToHost, addListener
929
959
  checkActive();
930
960
  return pipes.createPipe();
931
961
  },
962
+ createPty: (cols, rows) => {
963
+ checkActive();
964
+ return pipes.createPty(cols, rows);
965
+ },
932
966
  revokeProcess: (pid) => pipes.revokeProcess(pid),
933
967
  registerRevocation: (hook) => {
934
968
  listenAbort(cancellation.signal, hook);
935
969
  return () => unlistenAbort(cancellation.signal, hook);
936
970
  },
937
- prepareExec: (_pid, cleanupFailed) => {
971
+ prepareExec: (_pid, cleanupFailed, keptFds) => {
938
972
  checkActive();
939
973
  const end = fs.beginTransfer();
940
974
  let filesystem;
@@ -947,9 +981,19 @@ async function bootstrapAllocated(req, executor, host, { postToHost, addListener
947
981
  try {
948
982
  const data = executor.spawnData?.();
949
983
  checkActive();
950
- filesystem = createProcessFilesystemIdentity(fs.connection);
984
+ const posixOwner = fs.connection.posixOwner ?? fs.connection.owner;
985
+ filesystem = createProcessFilesystemIdentity(fs.connection, posixOwner);
986
+ const keptSet = new SetConstructor;
987
+ if (keptFds) {
988
+ for (let i = 0;i < keptFds.length; i++)
989
+ setAdd(keptSet, keptFds[i]);
990
+ }
991
+ const successorOwner = filesystem.owner;
951
992
  return {
952
993
  cancel,
994
+ commit: () => {
995
+ execHandoff = { successorOwner, keptFds: keptSet };
996
+ },
953
997
  release: end,
954
998
  data: { ...data, filesystem, pipeRegistry: pipes.registry.handle() },
955
999
  codec: createRuntimeTerminalCodec({
@@ -968,7 +1012,7 @@ async function bootstrapAllocated(req, executor, host, { postToHost, addListener
968
1012
  }
969
1013
  },
970
1014
  beginSpawnTransfer: () => fs.beginTransfer(),
971
- prepareSpawn: (pid, cleanupFailed) => {
1015
+ prepareSpawn: (pid, cleanupFailed, processKind) => {
972
1016
  checkActive();
973
1017
  let filesystem;
974
1018
  let enrolled = false;
@@ -985,9 +1029,17 @@ async function bootstrapAllocated(req, executor, host, { postToHost, addListener
985
1029
  checkActive();
986
1030
  pipes.registry.registerProcess(pid);
987
1031
  enrolled = true;
988
- filesystem = createProcessFilesystemIdentity(fs.connection);
1032
+ const threadSpawn = processKind === "thread";
1033
+ const posixOwner = threadSpawn ? fs.connection.posixOwner ?? fs.connection.owner : undefined;
1034
+ filesystem = createProcessFilesystemIdentity(fs.connection, posixOwner);
1035
+ const childOwner = filesystem.owner;
989
1036
  return {
990
1037
  cancel,
1038
+ commit: threadSpawn ? () => {
1039
+ hasSpawnedThread = true;
1040
+ if (fs.locks.hasActivePosixLocks?.())
1041
+ fs.locks.handoffPosix?.(childOwner);
1042
+ } : undefined,
991
1043
  data: { ...data, filesystem, pipeRegistry: pipes.registry.handle() },
992
1044
  codec: createRuntimeTerminalCodec({
993
1045
  fallback: pipes.codec(createFilesystemDescriptorCodec(fs, filesystem))
@@ -1033,6 +1085,7 @@ async function bootstrapAllocated(req, executor, host, { postToHost, addListener
1033
1085
  wake: runtimeProcess.wake,
1034
1086
  futexReady: groupMember.watchReady,
1035
1087
  createPipe: () => runtimeProcess.createPipe(),
1088
+ createPty: (cols, rows) => runtimeProcess.createPty(cols, rows),
1036
1089
  wait
1037
1090
  });
1038
1091
  installProcessImports(processImports, process.imports, checkActive, observedPoll);
@@ -44,12 +44,19 @@ export class DescriptorTable {
44
44
  entries = new MapConstructor;
45
45
  next = 0;
46
46
  cleanupFailures = [];
47
+ #onClose;
48
+ setOnClose(callback) {
49
+ this.#onClose = callback;
50
+ }
47
51
  recordCleanupFailure(error) {
48
52
  arrayAppend(this.cleanupFailures, error);
49
53
  }
50
54
  get(fd) {
51
55
  return mapGet(this.entries, fd);
52
56
  }
57
+ forEach(callback) {
58
+ mapForEach(this.entries, callback);
59
+ }
53
60
  hasResource(resource) {
54
61
  let found = false;
55
62
  mapForEach(this.entries, (entry) => {
@@ -86,7 +93,7 @@ export class DescriptorTable {
86
93
  case "terminal":
87
94
  return 2;
88
95
  case "device":
89
- return 0;
96
+ return entry.resource.virtualFile ? 3 : 0;
90
97
  case "file":
91
98
  return 3;
92
99
  case "directory":
@@ -168,6 +175,7 @@ export class DescriptorTable {
168
175
  return false;
169
176
  mapDelete(this.entries, fd);
170
177
  this.next = Math.min(this.next, fd);
178
+ this.#onClose?.(entry);
171
179
  entry.description.drop();
172
180
  return true;
173
181
  }
@@ -1,5 +1,69 @@
1
+ import { allocateSharedControl } from "../memory/allocator.js";
2
+ import {
3
+ atomicsCompareExchange,
4
+ atomicsLoad,
5
+ atomicsStore,
6
+ BigInt64ArrayConstructor,
7
+ reflectApply
8
+ } from "../proc/intrinsics/core.js";
9
+ const BigIntConstructor = BigInt;
10
+ const Uint8ArrayConstructor = Uint8Array;
11
+ const WeakMapConstructor = WeakMap;
12
+ const weakMapGet = WeakMap.prototype.get;
13
+ const weakMapSet = WeakMap.prototype.set;
14
+ const stringCharCodeAt = String.prototype.charCodeAt;
15
+ const copyBytes = Uint8Array.prototype.set;
16
+ const sliceBytes = Uint8Array.prototype.subarray;
17
+ const apply = reflectApply;
18
+ const MAX_VIRTUAL_OFFSET = 0x7fffffffffffffffn;
19
+ const virtualCursors = new WeakMapConstructor;
20
+ export const MACHINE_ID_INO = 2147483646;
21
+ export const MACHINE_ID_FILE_SIZE = 33;
1
22
  function discard(chunks) {
2
- return chunks.reduce((total, chunk) => total + chunk.length, 0);
23
+ let total = 0;
24
+ for (let i = 0;i < chunks.length; i++)
25
+ total += chunks[i].length;
26
+ return total;
27
+ }
28
+ export function isValidMachineId(value) {
29
+ if (value.length !== 32)
30
+ return false;
31
+ for (let i = 0;i < 32; i++) {
32
+ const code = apply(stringCharCodeAt, value, [i]);
33
+ const isDigit = code >= 48 && code <= 57;
34
+ const isLowerHex = code >= 97 && code <= 102;
35
+ if (!isDigit && !isLowerHex)
36
+ return false;
37
+ }
38
+ return true;
39
+ }
40
+ export function validateMachineId(value) {
41
+ if (typeof value !== "string" || !isValidMachineId(value))
42
+ throw new TypeError("machineId must be 32 lowercase hexadecimal characters");
43
+ return value;
44
+ }
45
+ function encodeMachineIdBytes(machineId) {
46
+ const bytes = new Uint8ArrayConstructor(MACHINE_ID_FILE_SIZE);
47
+ for (let i = 0;i < 32; i++)
48
+ bytes[i] = apply(stringCharCodeAt, machineId, [i]);
49
+ bytes[32] = 10;
50
+ return bytes;
51
+ }
52
+ export function readVirtualFileBytes(data, chunks, offset) {
53
+ let pos = offset;
54
+ let total = 0;
55
+ for (let i = 0;i < chunks.length; i++) {
56
+ if (pos >= data.length)
57
+ break;
58
+ const chunk = chunks[i];
59
+ const count = Math.min(chunk.length, data.length - pos);
60
+ if (count > 0) {
61
+ apply(copyBytes, chunk, [apply(sliceBytes, data, [pos, pos + count])]);
62
+ pos += count;
63
+ total += count;
64
+ }
65
+ }
66
+ return total;
3
67
  }
4
68
  export function createNullDevice(fdflags = 0) {
5
69
  return {
@@ -14,3 +78,149 @@ export function createNullDevice(fdflags = 0) {
14
78
  close() {}
15
79
  };
16
80
  }
81
+ function readCursorBigInt(cursor) {
82
+ if (!cursor.cell)
83
+ return cursor.local;
84
+ const raw = atomicsLoad(cursor.cell, 0);
85
+ return raw < 0n ? 0n : raw;
86
+ }
87
+ function writeCursorBigInt(cursor, next) {
88
+ let clamped = next;
89
+ if (clamped < 0n)
90
+ clamped = 0n;
91
+ if (clamped > MAX_VIRTUAL_OFFSET)
92
+ clamped = MAX_VIRTUAL_OFFSET;
93
+ if (cursor.cell)
94
+ atomicsStore(cursor.cell, 0, clamped);
95
+ else
96
+ cursor.local = clamped;
97
+ }
98
+ function claimCursorSpan(cursor, dataLength, requested) {
99
+ const dataLenBig = BigIntConstructor(dataLength);
100
+ if (!cursor.cell) {
101
+ const start = cursor.local;
102
+ if (start >= dataLenBig)
103
+ return dataLength;
104
+ const startNum = Number(start);
105
+ const count = Math.min(requested, dataLength - startNum);
106
+ cursor.local = start + BigIntConstructor(count);
107
+ return startNum;
108
+ }
109
+ for (;; ) {
110
+ const raw = atomicsLoad(cursor.cell, 0);
111
+ const start = raw < 0n ? 0n : raw;
112
+ if (start >= dataLenBig)
113
+ return dataLength;
114
+ const startNum = Number(start);
115
+ const count = Math.min(requested, dataLength - startNum);
116
+ if (count === 0)
117
+ return startNum;
118
+ const next = start + BigIntConstructor(count);
119
+ if (atomicsCompareExchange(cursor.cell, 0, raw, next) === raw)
120
+ return startNum;
121
+ }
122
+ }
123
+ function cursorForState(state) {
124
+ const cursor = apply(weakMapGet, virtualCursors, [state]);
125
+ if (!cursor)
126
+ throw new TypeError("missing virtual file cursor");
127
+ return cursor;
128
+ }
129
+ export function tellVirtualFile(state) {
130
+ return readCursorBigInt(cursorForState(state));
131
+ }
132
+ export function seekVirtualFile(state, delta, whence) {
133
+ const cursor = cursorForState(state);
134
+ if (whence === 0 || whence === 2) {
135
+ const base = whence === 0 ? 0n : BigIntConstructor(state.data.length);
136
+ const next = base + delta;
137
+ if (next < 0n || next > MAX_VIRTUAL_OFFSET)
138
+ return -28;
139
+ if (cursor.cell)
140
+ atomicsStore(cursor.cell, 0, next);
141
+ else
142
+ cursor.local = next;
143
+ return next;
144
+ }
145
+ if (whence !== 1)
146
+ return -28;
147
+ if (!cursor.cell) {
148
+ const next = cursor.local + delta;
149
+ if (next < 0n || next > MAX_VIRTUAL_OFFSET)
150
+ return -28;
151
+ cursor.local = next;
152
+ return next;
153
+ }
154
+ for (;; ) {
155
+ const raw = atomicsLoad(cursor.cell, 0);
156
+ const current = raw < 0n ? 0n : raw;
157
+ const next = current + delta;
158
+ if (next < 0n || next > MAX_VIRTUAL_OFFSET)
159
+ return -28;
160
+ if (delta === 0n)
161
+ return current;
162
+ if (atomicsCompareExchange(cursor.cell, 0, raw, next) === raw)
163
+ return next;
164
+ }
165
+ }
166
+ export function shareMachineIdOffset(state) {
167
+ const cursor = cursorForState(state);
168
+ if (cursor.buffer)
169
+ return cursor.buffer;
170
+ const buffer = allocateSharedControl(8);
171
+ const cell = new BigInt64ArrayConstructor(buffer);
172
+ atomicsStore(cell, 0, cursor.local);
173
+ cursor.buffer = buffer;
174
+ cursor.cell = cell;
175
+ return buffer;
176
+ }
177
+ export function createMachineIdFile(machineId, fdflags = 0, offsetOrBuffer = 0) {
178
+ const data = encodeMachineIdBytes(machineId);
179
+ const cursor = typeof offsetOrBuffer === "number" ? { local: BigIntConstructor(Math.max(0, Math.trunc(offsetOrBuffer))) } : {
180
+ buffer: offsetOrBuffer,
181
+ cell: new BigInt64ArrayConstructor(offsetOrBuffer),
182
+ local: 0n
183
+ };
184
+ const state = {
185
+ ino: MACHINE_ID_INO,
186
+ machineId,
187
+ data,
188
+ get offset() {
189
+ return Number(readCursorBigInt(cursor));
190
+ },
191
+ set offset(next) {
192
+ if (!Number.isFinite(next))
193
+ return;
194
+ writeCursorBigInt(cursor, BigIntConstructor(Math.max(0, Math.trunc(next))));
195
+ }
196
+ };
197
+ apply(weakMapSet, virtualCursors, [state, cursor]);
198
+ const read = (chunks) => {
199
+ let requested = 0;
200
+ for (let i = 0;i < chunks.length; i++)
201
+ requested += chunks[i].length;
202
+ const start = claimCursorSpan(cursor, data.length, requested);
203
+ return readVirtualFileBytes(data, chunks, start);
204
+ };
205
+ return {
206
+ kind: "device",
207
+ device: "machine-id",
208
+ virtualFile: state,
209
+ fdflags,
210
+ read,
211
+ tryRead: read,
212
+ write: () => -2,
213
+ tryWrite: () => -2,
214
+ readiness: () => {
215
+ const current = readCursorBigInt(cursor);
216
+ const dataLenBig = BigIntConstructor(data.length);
217
+ return {
218
+ readable: true,
219
+ writable: false,
220
+ hangup: false,
221
+ nbytes: current >= dataLenBig ? 0 : data.length - Number(current)
222
+ };
223
+ },
224
+ close() {}
225
+ };
226
+ }
@@ -4,8 +4,22 @@ import {
4
4
  RIGHT_PATH_OPEN as PATH_OPEN,
5
5
  RIGHT_PATH_FILESTAT_SET_SIZE as PATH_RESIZE
6
6
  } from "./rights.js";
7
+ import { createMachineIdFile } from "./devices.js";
8
+ import { releaseOriginOfd } from "./open-file.js";
7
9
  import { normalize } from "./path.js";
8
- export function reopenDescriptor(table, fs, fd, oflags, fdflags, base, inheriting = 0n) {
10
+ function resolveNonFileRights(source, base, inheriting, intersectCapabilities, accessMask) {
11
+ if (intersectCapabilities) {
12
+ if ((base & accessMask & ~source.rightsBase) !== 0n)
13
+ return -2;
14
+ return { base: base & source.rightsBase, inheriting: inheriting & source.rightsInheriting };
15
+ }
16
+ if ((base & source.rightsBase) !== base)
17
+ return -2;
18
+ if ((inheriting & source.rightsInheriting) !== inheriting)
19
+ return -2;
20
+ return { base, inheriting };
21
+ }
22
+ export function reopenDescriptor(table, fs, fd, oflags, fdflags, base, inheriting = 0n, intersectCapabilities = false) {
9
23
  const source = table.get(fd);
10
24
  if (!source)
11
25
  return -8;
@@ -13,16 +27,29 @@ export function reopenDescriptor(table, fs, fd, oflags, fdflags, base, inheritin
13
27
  return -28;
14
28
  base = BigInt.asUintN(64, base);
15
29
  inheriting = BigInt.asUintN(64, inheriting);
30
+ if (source.resource.kind === "device" && source.resource.virtualFile) {
31
+ if (oflags & 2)
32
+ return -54;
33
+ if ((oflags & 8) !== 0 || (base & WRITE) !== 0n)
34
+ return -2;
35
+ const rights = resolveNonFileRights(source, base, inheriting, intersectCapabilities, READ | WRITE);
36
+ if (typeof rights === "number")
37
+ return rights;
38
+ return table.open(createMachineIdFile(source.resource.virtualFile.machineId, fdflags), rights.base, rights.inheriting);
39
+ }
16
40
  if (source.resource.kind !== "file") {
17
41
  if (oflags & 2 && source.resource.kind !== "directory")
18
42
  return -54;
19
43
  if (oflags & 8 && source.resource.kind === "directory")
20
44
  return -31;
21
- if ((base & source.rightsBase) !== base)
22
- return -2;
23
- if ((inheriting & source.rightsInheriting) !== inheriting)
24
- return -2;
25
- return table.add(source.description, { rightsBase: base, rightsInheriting: inheriting });
45
+ const access = source.resource.kind === "directory" ? WRITE : READ | WRITE;
46
+ const rights = resolveNonFileRights(source, base, inheriting, intersectCapabilities, access);
47
+ if (typeof rights === "number")
48
+ return rights;
49
+ return table.add(source.description, {
50
+ rightsBase: rights.base,
51
+ rightsInheriting: rights.inheriting
52
+ });
26
53
  }
27
54
  if (oflags & 2)
28
55
  return -54;
@@ -54,7 +81,8 @@ export function openInode(table, fs, handle, kind, oflags, fdflags, base, inheri
54
81
  return -error;
55
82
  }
56
83
  fs.retain(handle);
57
- return table.open(kind === "directory" ? { kind, handle } : { kind, handle, offset: 0, append: (fdflags & 1) !== 0, fdflags }, base, inheriting, () => fs.release(handle));
84
+ const resource = kind === "directory" ? { kind, handle } : { kind, handle, offset: 0, append: (fdflags & 1) !== 0, fdflags };
85
+ return table.open(resource, base, inheriting, () => releaseOriginOfd(fs, resource));
58
86
  }
59
87
  function descriptorPath(path) {
60
88
  if (path === "/dev/stdin")
@@ -84,7 +112,7 @@ function virtualEntry(table, prefix) {
84
112
  handle: resource.kind === "directory" || resource.kind === "file" ? resource.handle : undefined
85
113
  };
86
114
  }
87
- function lookupEntry(table, fs, parent, name) {
115
+ function lookupEntry(table, fs, parent, name, hasMachineId) {
88
116
  const prefix = parent.prefix === undefined || parent.source !== undefined ? undefined : `${parent.prefix}/${name}`;
89
117
  const virtual = prefix === undefined ? undefined : virtualEntry(table, prefix);
90
118
  if (virtual !== undefined)
@@ -94,6 +122,10 @@ function lookupEntry(table, fs, parent, name) {
94
122
  return path;
95
123
  if (path?.node !== undefined)
96
124
  return { prefix, handle: path.node, kind: fs.stat(path.node).kind, resolved: path };
125
+ if (hasMachineId && prefix === "/etc/machine-id")
126
+ return { prefix, kind: "virtual-file" };
127
+ if (hasMachineId && prefix === "/etc")
128
+ return { prefix, kind: "directory", syntheticEtc: true };
97
129
  if (prefix !== undefined && virtualDirectories.includes(prefix))
98
130
  return { prefix, kind: "directory" };
99
131
  return path ? { prefix, kind: "missing", resolved: path } : 44;
@@ -124,7 +156,19 @@ function virtualShadow(fs, root, path) {
124
156
  }
125
157
  return false;
126
158
  }
127
- function resolveOrdinaryPath(fs, handle, root, path, finalLink, rooted) {
159
+ function virtualMachineIdMatch(fs, root, resolved, hasMachineId) {
160
+ if (!hasMachineId || resolved.node !== undefined || resolved.name !== "machine-id")
161
+ return;
162
+ if (resolved.parent === undefined)
163
+ return;
164
+ const etc = fs.resolve(root, "etc", true, true);
165
+ if (typeof etc === "number" || etc.node === undefined)
166
+ return;
167
+ if (!sameInode(fs, etc.node, resolved.parent))
168
+ return;
169
+ return resolved.trailingSlash ? 54 : { virtualFile: "machine-id" };
170
+ }
171
+ function resolveOrdinaryPath(fs, handle, root, path, finalLink, rooted, hasMachineId) {
128
172
  if (path.includes("dev") || path.includes("proc")) {
129
173
  const normalized = normalize(path);
130
174
  if (descriptorPath(normalized) !== undefined || devicePath(normalized) !== undefined)
@@ -133,7 +177,12 @@ function resolveOrdinaryPath(fs, handle, root, path, finalLink, rooted) {
133
177
  const resolved = fs.resolve(handle, path, finalLink === "follow", rooted);
134
178
  if (typeof resolved === "number")
135
179
  return resolved === 44 ? undefined : resolved;
136
- return virtualShadow(fs, root(), resolved) ? undefined : { resolved };
180
+ if (virtualShadow(fs, root(), resolved))
181
+ return;
182
+ const virtualFile = virtualMachineIdMatch(fs, root(), resolved, hasMachineId);
183
+ if (virtualFile !== undefined)
184
+ return virtualFile;
185
+ return { resolved };
137
186
  }
138
187
  function followedTarget(fs, link, rest, finalLink, expansions, rooted) {
139
188
  const final = !rest.some(Boolean);
@@ -157,18 +206,20 @@ class AliasWalk {
157
206
  root;
158
207
  finalLink;
159
208
  rooted;
209
+ hasMachineId;
160
210
  current;
161
211
  parents = [];
162
212
  pending;
163
213
  offset = 0;
164
214
  expansions = 0;
165
215
  dot = false;
166
- constructor(table, fs, root, start, path, finalLink, rooted) {
216
+ constructor(table, fs, root, start, path, finalLink, rooted, hasMachineId) {
167
217
  this.table = table;
168
218
  this.fs = fs;
169
219
  this.root = root;
170
220
  this.finalLink = finalLink;
171
221
  this.rooted = rooted;
222
+ this.hasMachineId = hasMachineId;
172
223
  this.current = start;
173
224
  this.pending = path.split("/");
174
225
  }
@@ -186,12 +237,14 @@ class AliasWalk {
186
237
  const error = searchEntry(this.fs, this.current);
187
238
  if (error)
188
239
  return error;
240
+ if (this.current.syntheticEtc && part !== "." && part !== "machine-id")
241
+ return 44;
189
242
  this.dot = part === "." || part === "..";
190
243
  if (part === ".")
191
244
  return;
192
245
  if (part === "..")
193
246
  return this.up();
194
- const next = lookupEntry(this.table, this.fs, this.current, part);
247
+ const next = lookupEntry(this.table, this.fs, this.current, part, this.hasMachineId);
195
248
  if (typeof next === "number")
196
249
  return next;
197
250
  if (next.kind === "missing")
@@ -266,6 +319,8 @@ class AliasWalk {
266
319
  return { source: current.source };
267
320
  if (current.kind === "device")
268
321
  return { device: "null" };
322
+ if (current.kind === "virtual-file")
323
+ return { virtualFile: "machine-id" };
269
324
  if (current.handle === undefined)
270
325
  return;
271
326
  if (!this.dot && current.resolved)
@@ -280,15 +335,21 @@ function rootHandle(table, fs, directory) {
280
335
  const root = table.rootPreopen()?.resource;
281
336
  return root?.kind === "directory" ? root.handle : fs.preopen("/");
282
337
  }
283
- export function resolveDescriptorPath(table, fs, directory, path, finalLink, rooted = false) {
338
+ export function resolveDescriptorPath(table, fs, directory, path, finalLink, rooted = false, hasMachineId = fs.machineId !== undefined) {
284
339
  if (directory.resource.kind !== "directory")
285
340
  return;
286
341
  const handle = directory.resource.handle;
287
- if (!rooted && directory.preopen !== "/" && fs.stat(handle).ino !== fs.stat(fs.preopen("/")).ino)
288
- return;
342
+ if (!rooted && directory.preopen !== "/" && fs.stat(handle).ino !== fs.stat(fs.preopen("/")).ino) {
343
+ if (!hasMachineId || !path.includes("machine-id"))
344
+ return;
345
+ const resolved = fs.resolve(handle, path, finalLink === "follow", false);
346
+ if (typeof resolved === "number")
347
+ return;
348
+ return virtualMachineIdMatch(fs, fs.preopen("/"), resolved, true);
349
+ }
289
350
  let rootCache;
290
351
  const root = () => rootCache ??= rooted ? rootHandle(table, fs, directory) : handle;
291
- const ordinary = resolveOrdinaryPath(fs, handle, root, path, finalLink, rooted);
352
+ const ordinary = resolveOrdinaryPath(fs, handle, root, path, finalLink, rooted, hasMachineId);
292
353
  if (ordinary !== undefined || !path)
293
354
  return ordinary;
294
355
  const rootEntry = { prefix: "", kind: "directory", handle: root() };
@@ -296,7 +357,7 @@ export function resolveDescriptorPath(table, fs, directory, path, finalLink, roo
296
357
  if (path.startsWith("/"))
297
358
  return 63;
298
359
  const start = { prefix: undefined, kind: "directory", handle };
299
- return new AliasWalk(table, fs, rootEntry, start, path, finalLink, rooted).run();
360
+ return new AliasWalk(table, fs, rootEntry, start, path, finalLink, rooted, hasMachineId).run();
300
361
  }
301
- return new AliasWalk(table, fs, rootEntry, rootEntry, path, finalLink, rooted).run();
362
+ return new AliasWalk(table, fs, rootEntry, rootEntry, path, finalLink, rooted, hasMachineId).run();
302
363
  }
@@ -37,3 +37,16 @@ export function fileTimeMs(time) {
37
37
  export function isFileTime(value) {
38
38
  return typeof value === "bigint" && value >= 0n && value <= MAX_FILE_TIME;
39
39
  }
40
+ export const LOCK_SH = 1;
41
+ export const LOCK_EX = 2;
42
+ export const LOCK_NB = 4;
43
+ export const LOCK_UN = 8;
44
+ export const F_GETLK = 0;
45
+ export const F_SETLK = 1;
46
+ export const F_SETLKW = 2;
47
+ export const F_OFD_GETLK = 3;
48
+ export const F_OFD_SETLK = 4;
49
+ export const F_OFD_SETLKW = 5;
50
+ export const F_RDLCK = 0;
51
+ export const F_WRLCK = 1;
52
+ export const F_UNLCK = 2;