-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathkernel.ts
More file actions
1679 lines (1511 loc) · 52.4 KB
/
kernel.ts
File metadata and controls
1679 lines (1511 loc) · 52.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Kernel implementation.
*
* The kernel is the OS. It owns VFS, FD table, process table, device layer,
* pipe manager, command registry, and permissions. Runtimes are execution
* engines that make "syscalls" to the kernel.
*/
import type {
Kernel,
KernelInterface,
KernelOptions,
KernelLogger,
ExecOptions,
ExecResult,
SpawnOptions,
ManagedProcess,
RuntimeDriver,
ProcessContext,
ProcessInfo,
FDStat,
FDEntry,
OpenShellOptions,
ShellHandle,
ConnectTerminalOptions,
} from "./types.js";
import type { VirtualFileSystem, VirtualStat } from "./vfs.js";
import { createDeviceBackend } from "./device-backend.js";
import { createProcBackend } from "./proc-backend.js";
import { MountTable } from "./mount-table.js";
import { FDTableManager, ProcessFDTable } from "./fd-table.js";
import { ProcessTable } from "./process-table.js";
import { PipeManager } from "./pipe-manager.js";
import { PtyManager } from "./pty.js";
import { FileLockManager } from "./file-lock.js";
import { CommandRegistry } from "./command-registry.js";
import { wrapFileSystem, checkChildProcess } from "./permissions.js";
import { UserManager } from "./user.js";
import { SocketTable } from "./socket-table.js";
import { TimerTable } from "./timer-table.js";
import {
FILETYPE_REGULAR_FILE,
FILETYPE_DIRECTORY,
FILETYPE_PIPE,
FILETYPE_CHARACTER_DEVICE,
SEEK_SET,
SEEK_CUR,
SEEK_END,
O_APPEND,
O_CREAT,
O_EXCL,
O_TRUNC,
SIGTERM,
SIGPIPE,
SIGWINCH,
F_DUPFD,
F_GETFD,
F_SETFD,
F_GETFL,
F_DUPFD_CLOEXEC,
FD_CLOEXEC,
KernelError,
noopKernelLogger,
} from "./types.js";
export function createKernel(options: KernelOptions): Kernel {
return new KernelImpl(options);
}
class KernelImpl implements Kernel {
private vfs: VirtualFileSystem;
private mountTable: MountTable;
private fdTableManager = new FDTableManager();
private processTable!: ProcessTable;
private pipeManager = new PipeManager();
private ptyManager!: PtyManager;
private fileLockManager = new FileLockManager();
private commandRegistry = new CommandRegistry();
readonly socketTable: SocketTable;
readonly timerTable: TimerTable;
private userManager: UserManager;
private drivers: RuntimeDriver[] = [];
private driverPids = new Map<string, Set<number>>();
private permissions?: import("./types.js").Permissions;
private maxProcesses?: number;
private env: Record<string, string>;
private cwd: string;
private disposed = false;
private pendingBinEntries: Promise<void>[] = [];
private posixDirsReady: Promise<void>;
private log: KernelLogger;
constructor(options: KernelOptions) {
this.log = options.logger ?? noopKernelLogger;
this.processTable = new ProcessTable(this.log.child({ component: "process" }));
this.ptyManager = new PtyManager(
(pgid, signal, excludeLeaders) => {
try {
if (excludeLeaders) {
return this.processTable.killGroupExcludeLeaders(pgid, signal);
}
this.processTable.kill(-pgid, signal);
} catch { /* no-op if pgid gone */ }
return 0;
},
this.log.child({ component: "pty" }),
);
// Build mount table: root FS → /dev → /proc → user mounts.
const mt = new MountTable(options.filesystem);
mt.mount("/dev", createDeviceBackend());
mt.mount("/proc", createProcBackend({
processTable: this.processTable,
fdTableManager: this.fdTableManager,
hostname: options.env?.HOSTNAME,
mountTable: mt,
}));
// Mount user-supplied filesystems
if (options.mounts) {
for (const m of options.mounts) {
mt.mount(m.path, m.fs, { readOnly: m.readOnly });
}
}
this.mountTable = mt;
// Apply permission wrapping on top of the mount table
let fs: VirtualFileSystem = mt;
if (options.permissions) {
fs = wrapFileSystem(fs, options.permissions);
}
this.vfs = fs;
this.permissions = options.permissions;
this.maxProcesses = options.maxProcesses;
this.env = { ...options.env };
this.cwd = options.cwd ?? "/home/user";
this.userManager = new UserManager();
this.socketTable = new SocketTable({
vfs: this.vfs,
networkCheck: options.permissions?.network,
hostAdapter: options.hostNetworkAdapter,
getSignalState: (pid) => this.processTable.getSignalState(pid),
processExists: (pid) => this.processTable.get(pid) !== undefined,
});
this.timerTable = new TimerTable();
// Clean up FD table and sockets when a process exits
this.processTable.onProcessExit = (pid) => {
this.log.debug({ pid }, "process exit cleanup");
this.cleanupProcessFDs(pid);
this.socketTable.closeAllForProcess(pid);
this.timerTable.clearAllForProcess(pid);
};
// Clean up driver PID ownership when zombie is reaped
this.processTable.onProcessReap = (pid) => {
const entry = this.processTable.get(pid);
if (entry) this.driverPids.get(entry.driver)?.delete(pid);
};
// Deliver SIGPIPE default action: terminate writer with 128+SIGPIPE
this.pipeManager.onBrokenPipe = (pid) => {
try {
this.processTable.kill(pid, SIGPIPE);
} catch {
// Process may already be exited
}
};
// Create standard POSIX directory hierarchy so all programs see /tmp,
// /usr, /etc, etc. — matching a real Linux root filesystem layout.
this.posixDirsReady = this.initPosixDirs();
}
private async initPosixDirs(): Promise<void> {
// /dev and /proc are auto-created by MountTable mounts — don't create them here.
const dirs = [
"/tmp",
"/bin",
"/lib",
"/sbin",
"/boot",
"/etc",
"/root",
"/run",
"/srv",
"/sys",
"/opt",
"/mnt",
"/media",
"/home",
"/usr",
"/usr/bin",
"/usr/games",
"/usr/include",
"/usr/lib",
"/usr/libexec",
"/usr/man",
"/usr/sbin",
"/usr/share",
"/usr/share/man",
"/var",
"/var/cache",
"/var/empty",
"/var/lib",
"/var/lock",
"/var/log",
"/var/run",
"/var/spool",
"/var/tmp",
];
for (const dir of dirs) {
try {
await this.vfs.mkdir(dir, { recursive: true });
} catch {
// Directory may already exist
}
}
// Standard utility that many scripts expect
try {
await this.vfs.writeFile("/usr/bin/env", new Uint8Array(1));
} catch {
// File may already exist
}
}
// -----------------------------------------------------------------------
// Kernel public API
// -----------------------------------------------------------------------
async mount(driver: RuntimeDriver): Promise<void> {
this.assertNotDisposed();
await this.posixDirsReady;
this.log.debug({ driver: driver.name, commands: driver.commands }, "mounting runtime driver");
// Track PIDs owned by this driver
if (!this.driverPids.has(driver.name)) {
this.driverPids.set(driver.name, new Set());
}
// Initialize the driver with a scoped kernel interface
await driver.init(this.createKernelInterface(driver.name));
// Register commands
this.commandRegistry.register(driver);
this.drivers.push(driver);
// Populate /bin stubs for shell PATH lookup
await this.commandRegistry.populateBin(this.vfs);
this.log.info({ driver: driver.name, commands: driver.commands }, "runtime driver mounted");
}
mountFs(path: string, fs: VirtualFileSystem, options?: { readOnly?: boolean }): void {
this.assertNotDisposed();
this.mountTable.mount(path, fs, options);
}
unmountFs(path: string): void {
this.assertNotDisposed();
this.mountTable.unmount(path);
}
async dispose(): Promise<void> {
if (this.disposed) return;
this.disposed = true;
this.log.info({}, "kernel disposing");
// Terminate all running processes
await this.processTable.terminateAll();
// Clean up all sockets
this.socketTable.disposeAll();
this.timerTable.disposeAll();
// Dispose all drivers (reverse mount order)
for (let i = this.drivers.length - 1; i >= 0; i--) {
try {
await this.drivers[i].dispose();
} catch {
// Best effort cleanup
}
}
this.drivers.length = 0;
}
/**
* Flush pending /bin stub entries created by on-demand command discovery.
* Ensures VFS is consistent before shell PATH lookups.
*/
async flushPendingBinEntries(): Promise<void> {
if (this.pendingBinEntries.length > 0) {
await Promise.all(this.pendingBinEntries);
this.pendingBinEntries.length = 0;
}
}
async exec(command: string, options?: ExecOptions): Promise<ExecResult> {
this.assertNotDisposed();
this.log.debug({ command, timeout: options?.timeout, cwd: options?.cwd }, "exec start");
// Flush pending /bin stubs before shell PATH lookup
await this.flushPendingBinEntries();
// Route through shell
const shell = this.commandRegistry.resolve("sh");
if (shell) {
const proc = this.spawnInternal("sh", ["-c", command], options);
return this.#collectExecResult(proc, options);
}
// No shell available. If 'node' is registered (e.g. NodeRuntime mounted),
// fall back to direct node execution — parse command string into node args.
// This makes the README example work out-of-the-box:
// kernel.exec("node -e \"console.log('hello')\"")
const nodeCmd = this.commandRegistry.resolve("node");
if (nodeCmd) {
// Parse command string into individual args (handles quotes)
const args = this.#parseCommandArgs(command);
if (args.length > 0 && args[0] === "node") {
args.shift(); // strip 'node' prefix, keep the rest
const proc = this.spawnInternal("node", args, options);
return this.#collectExecResult(proc, options);
}
}
throw new Error(
"No shell available. Mount a WasmVM runtime to enable exec(), " +
"or mount a runtime that registers the 'node' command and use " +
"`kernel.exec('node -e \"code\"')`.",
);
}
/**
* Parse a command string into individual arguments.
* Handles single quotes, double quotes, and basic shell tokenization.
*/
#parseCommandArgs(command: string): string[] {
const args: string[] = [];
let current = "";
let inSingle = false;
let inDouble = false;
let i = 0;
while (i < command.length) {
const ch = command[i];
if (inSingle) {
if (ch === "'") {
inSingle = false;
} else {
current += ch;
}
i++;
} else if (inDouble) {
if (ch === '"') {
inDouble = false;
} else if (ch === "\\" && i + 1 < command.length) {
// Handle escape sequences in double quotes
current += command[i + 1];
i += 2;
} else {
current += ch;
i++;
}
} else {
if (ch === "'") {
inSingle = true;
i++;
} else if (ch === '"') {
inDouble = true;
i++;
} else if (ch === " ") {
if (current.length > 0) {
args.push(current);
current = "";
}
i++;
} else {
current += ch;
i++;
}
}
}
if (current.length > 0) {
args.push(current);
}
return args;
}
/**
* Collect stdout/stderr from a spawned process for exec().
*/
async #collectExecResult(
proc: InternalProcess,
options?: ExecOptions,
): Promise<ExecResult> {
// Write stdin if provided
if (options?.stdin) {
const data =
typeof options.stdin === "string"
? new TextEncoder().encode(options.stdin)
: options.stdin;
proc.writeStdin(data);
proc.closeStdin();
}
// Collect output
const stdoutChunks: Uint8Array[] = [];
const stderrChunks: Uint8Array[] = [];
proc.onStdout = (data) => {
stdoutChunks.push(data);
options?.onStdout?.(data);
};
proc.onStderr = (data) => {
stderrChunks.push(data);
options?.onStderr?.(data);
};
// Wait with optional timeout
let exitCode: number;
if (options?.timeout) {
let timer: ReturnType<typeof setTimeout> | undefined;
try {
exitCode = await Promise.race([
proc.wait().then((code) => {
clearTimeout(timer);
return code;
}),
new Promise<number>((_, reject) => {
timer = setTimeout(() => {
// Kill process and detach output callbacks
this.log.warn({ timeout: options.timeout }, "exec timeout, sending SIGTERM");
proc.onStdout = null;
proc.onStderr = null;
proc.kill(SIGTERM);
reject(new KernelError("ETIMEDOUT", "exec timeout"));
}, options.timeout);
}),
]);
} catch (err) {
clearTimeout(timer);
throw err;
}
} else {
exitCode = await proc.wait();
}
return {
exitCode,
stdout: concatUint8(stdoutChunks),
stderr: concatUint8(stderrChunks),
};
}
spawn(
command: string,
args: string[],
options?: SpawnOptions,
): ManagedProcess {
this.assertNotDisposed();
return this.spawnManaged(command, args, options);
}
openShell(options?: OpenShellOptions): ShellHandle {
this.assertNotDisposed();
const command = options?.command ?? "sh";
const args = options?.args ?? [];
this.log.debug({ command, args, cols: options?.cols, rows: options?.rows, cwd: options?.cwd }, "openShell start");
// Allocate a controller PID with an FD table to hold the PTY master
const controllerPid = this.processTable.allocatePid();
const controllerTable = this.fdTableManager.create(controllerPid);
// Create PTY pair in the controller's FD table
const { masterFd, slaveFd } = this.ptyManager.createPtyFDs(controllerTable);
const masterDescId = controllerTable.get(masterFd)!.description.id;
// Spawn shell with PTY slave as stdin/stdout/stderr
// Propagate terminal dimensions as POSIX COLUMNS/LINES env vars
const cols = options?.cols;
const rows = options?.rows;
const dimEnv: Record<string, string> = {};
if (cols !== undefined) dimEnv.COLUMNS = String(cols);
if (rows !== undefined) dimEnv.LINES = String(rows);
const proc = this.spawnInternal(command, args, {
env: { ...options?.env, ...dimEnv },
cwd: options?.cwd,
stdinFd: slaveFd,
stdoutFd: slaveFd,
stderrFd: slaveFd,
}, controllerPid);
// Shell becomes its own process group leader, set as PTY foreground
this.processTable.setpgid(proc.pid, proc.pid);
this.ptyManager.setForegroundPgid(masterDescId, proc.pid);
this.ptyManager.setSessionLeader(masterDescId, proc.pid);
this.log.debug({ shellPid: proc.pid, controllerPid, masterFd, masterDescId }, "openShell PTY attached");
// Close controller's copy of slave FD (child inherited its own copy via fork).
// Without this, slave refCount stays >0 after shell exits, preventing EOF on master.
const slaveEntry = controllerTable.get(slaveFd);
const slaveDescId = slaveEntry!.description.id;
controllerTable.close(slaveFd);
if (slaveEntry!.description.refCount <= 0) {
this.ptyManager.close(slaveDescId);
}
// Start read pump: master reads → onData callback
// Use object wrapper so TypeScript doesn't narrow to null in the async closure
const pump = { onData: null as ((data: Uint8Array) => void) | null, exited: false };
const pumpPromise = (async () => {
try {
while (!pump.exited) {
const data = await this.ptyManager.read(masterDescId, 4096);
if (!data || data.length === 0) break;
try {
pump.onData?.(data);
} catch (cbErr) {
// Propagate callback errors — don't silently swallow
console.error("openShell readPump: onData callback error:", cbErr);
}
}
} catch (err) {
// Master closed or PTY gone — expected when shell exits
if (pump.exited) return;
console.error("openShell readPump: PTY read error:", err);
}
})();
// wait() resolves after both shell exit AND pump drain
const waitPromise = proc.wait().then(async (exitCode) => {
pump.exited = true;
// Wait for pump to finish delivering remaining data
await pumpPromise;
// Clean up controller PID's FD table (incl. PTY master)
this.cleanupProcessFDs(controllerPid);
return exitCode;
});
return {
pid: proc.pid,
write: (data) => {
const bytes = typeof data === "string"
? new TextEncoder().encode(data)
: data;
this.ptyManager.write(masterDescId, bytes);
},
get onData() { return pump.onData; },
set onData(fn) { pump.onData = fn; },
resize: (_cols, _rows) => {
const fgPgid = this.ptyManager.getForegroundPgid(masterDescId);
this.log.trace({ shellPid: proc.pid, cols: _cols, rows: _rows, fgPgid }, "PTY resize");
if (fgPgid > 0) {
try { this.processTable.kill(-fgPgid, SIGWINCH); } catch { /* pgid may be gone */ }
}
},
kill: (signal) => {
proc.kill(signal ?? SIGTERM);
},
wait: () => waitPromise,
};
}
async connectTerminal(options?: ConnectTerminalOptions): Promise<number> {
this.assertNotDisposed();
this.log.debug({ command: options?.command, cols: options?.cols, rows: options?.rows }, "connectTerminal start");
const stdin = process.stdin;
const stdout = process.stdout;
const isTTY = stdin.isTTY;
let onStdinData: ((data: Buffer) => void) | undefined;
let onResize: (() => void) | undefined;
try {
const shell = this.openShell(options);
// Set raw mode so keypresses pass through directly
if (isTTY) stdin.setRawMode(true);
// Forward stdin to shell
onStdinData = (data: Buffer) => shell.write(data);
stdin.on("data", onStdinData);
stdin.resume();
// Forward shell output to stdout or custom handler
const outputHandler = options?.onData
?? ((data: Uint8Array) => { stdout.write(data); });
shell.onData = outputHandler;
// Forward terminal resize → PTY SIGWINCH
if (stdout.isTTY) {
onResize = () => {
shell.resize(stdout.columns, stdout.rows);
};
stdout.on("resize", onResize);
}
return await shell.wait();
} finally {
// Restore terminal — guard each cleanup since setup may have partially completed
if (onStdinData) stdin.removeListener("data", onStdinData);
stdin.pause();
if (isTTY) stdin.setRawMode(false);
if (onResize && stdout.isTTY) stdout.removeListener("resize", onResize);
}
}
// Filesystem convenience wrappers
readFile(path: string): Promise<Uint8Array> { return this.vfs.readFile(path); }
writeFile(path: string, content: string | Uint8Array): Promise<void> { return this.vfs.writeFile(path, content); }
mkdir(path: string): Promise<void> { return this.vfs.mkdir(path); }
readdir(path: string): Promise<string[]> { return this.vfs.readDir(path); }
stat(path: string): Promise<VirtualStat> { return this.vfs.stat(path); }
exists(path: string): Promise<boolean> { return this.vfs.exists(path); }
removeFile(path: string): Promise<void> { return this.vfs.removeFile(path); }
removeDir(path: string): Promise<void> { return this.vfs.removeDir(path); }
rename(oldPath: string, newPath: string): Promise<void> { return this.vfs.rename(oldPath, newPath); }
// Introspection
get commands(): ReadonlyMap<string, string> {
return this.commandRegistry.list();
}
get processes(): ReadonlyMap<number, ProcessInfo> {
return this.processTable.listProcesses();
}
get zombieTimerCount(): number {
return this.processTable.zombieTimerCount;
}
// -----------------------------------------------------------------------
// Internal spawn
// -----------------------------------------------------------------------
private spawnInternal(
command: string,
args: string[],
options?: SpawnOptions,
callerPid?: number,
): InternalProcess {
this.log.debug({ command, args, callerPid, cwd: options?.cwd }, "spawn start");
let driver = this.commandRegistry.resolve(command);
// On-demand discovery: ask mounted drivers to resolve unknown commands
if (!driver) {
const basename = command.includes("/")
? command.split("/").pop()!
: command;
if (basename) {
for (const d of this.drivers) {
if (d.tryResolve?.(basename)) {
this.commandRegistry.registerCommand(basename, d);
// Store pending promise so exec() can flush before shell PATH lookup
const p = this.commandRegistry.populateBinEntry(this.vfs, basename);
this.pendingBinEntries.push(p);
p.then(() => {
const idx = this.pendingBinEntries.indexOf(p);
if (idx >= 0) this.pendingBinEntries.splice(idx, 1);
});
driver = d;
break;
}
}
}
}
if (!driver) {
this.log.warn({ command }, "command not found");
throw new KernelError("ENOENT", `command not found: ${command}`);
}
// Check childProcess permission
try {
checkChildProcess(this.permissions, command, args, options?.cwd);
} catch (err) {
this.log.warn({ command, args }, "spawn permission denied");
throw err;
}
// Enforce maxProcesses budget
if (this.maxProcesses !== undefined && this.processTable.runningCount() >= this.maxProcesses) {
this.log.warn({ command, running: this.processTable.runningCount(), max: this.maxProcesses }, "process limit reached");
throw new KernelError("EAGAIN", "maximum process limit reached");
}
// Allocate PID atomically
const pid = this.processTable.allocatePid();
// Register PID ownership before driver.spawn() so the driver can use it
this.driverPids.get(driver.name)?.add(pid);
// Cross-runtime spawn: parent driver must also track child PID so
// it can waitpid/kill/interact with the child process
if (callerPid !== undefined) {
for (const [name, pids] of this.driverPids) {
if (name !== driver.name && pids.has(callerPid)) {
pids.add(pid);
break;
}
}
}
// Create FD table — wire pipe FDs when overrides are provided
const table = this.createChildFDTable(pid, options, callerPid);
// Check which stdio channels are piped (data flows through kernel, not callbacks)
const stdoutPiped = this.isStdioPiped(table, 1);
const stderrPiped = this.isStdioPiped(table, 2);
// Buffer stdout/stderr — wired before spawn so nothing is lost
const stdoutBuf: Uint8Array[] = [];
const stderrBuf: Uint8Array[] = [];
// Resolve output callbacks. Drivers invoke BOTH ctx.onStdout and
// proc.onStdout per message, so the two must never point at the same
// callback — otherwise the host sees every chunk twice.
//
// ctx callbacks — kernel-internal routing (pipes, parent forwarding)
// + temporary buffer during spawn() to catch any
// synchronous output (disabled right after spawn).
// proc callbacks — user / host callback (options.onStdout) or buffer
// for later replay. Set AFTER spawn returns.
let ctxStdoutCb: ((data: Uint8Array) => void) | undefined;
let ctxStderrCb: ((data: Uint8Array) => void) | undefined;
if (stdoutPiped) {
ctxStdoutCb = this.createPipedOutputCallback(table, 1, pid);
} else if (!options?.onStdout && callerPid !== undefined) {
const parent = this.processTable.get(callerPid);
if (parent?.driverProcess.onStdout) {
ctxStdoutCb = parent.driverProcess.onStdout;
}
}
if (stderrPiped) {
ctxStderrCb = this.createPipedOutputCallback(table, 2, pid);
} else if (!options?.onStderr && callerPid !== undefined) {
const parent = this.processTable.get(callerPid);
if (parent?.driverProcess.onStderr) {
ctxStderrCb = parent.driverProcess.onStderr;
}
}
// Inherit env from parent process if spawned by another process, else use kernel defaults
const parentEntry = callerPid ? this.processTable.get(callerPid) : undefined;
const baseEnv = parentEntry?.env ?? this.env;
// Detect PTY slave on stdio FDs
const stdinIsTTY = this.isFdPtySlave(table, 0);
const stdoutIsTTY = this.isFdPtySlave(table, 1);
const stderrIsTTY = this.isFdPtySlave(table, 2);
// Build process context with pre-wired callbacks.
// When not piped/forwarded, ctx gets a temporary buffer so that any
// data emitted synchronously during driver.spawn() is captured.
const resolvedCwd = options?.cwd ?? this.cwd;
const ctx: ProcessContext = {
pid,
ppid: callerPid ?? 0,
env: { ...baseEnv, ...options?.env, PWD: resolvedCwd },
cwd: resolvedCwd,
fds: { stdin: 0, stdout: 1, stderr: 2 },
stdinIsTTY,
stdoutIsTTY,
stderrIsTTY,
streamStdin: options?.streamStdin,
onStdout: ctxStdoutCb ?? (stdoutPiped ? undefined : (data) => stdoutBuf.push(data)),
onStderr: ctxStderrCb ?? (stderrPiped ? undefined : (data) => stderrBuf.push(data)),
};
// Spawn via driver
const driverProcess = driver.spawn(command, args, ctx);
this.log.debug({
pid, command, driver: driver.name, callerPid,
stdinIsTTY, stdoutIsTTY, stderrIsTTY,
}, "process spawned");
// After spawn, disable the temporary ctx buffer so that async output
// flows only through proc.onStdout — prevents double-delivery.
// Pipe/parent-forwarding callbacks stay active (they live in ctxStdoutCb).
if (!stdoutPiped) {
ctx.onStdout = ctxStdoutCb;
}
if (!stderrPiped) {
ctx.onStderr = ctxStderrCb;
}
// User/host callback goes ONLY on driverProcess (never on ctx) to
// avoid double-delivery — drivers invoke both ctx and proc callbacks.
if (!stdoutPiped) {
driverProcess.onStdout = options?.onStdout ?? ((data) => stdoutBuf.push(data));
}
if (!stderrPiped) {
driverProcess.onStderr = options?.onStderr ?? ((data) => stderrBuf.push(data));
}
// Register in process table
const entry = this.processTable.register(
pid,
driver.name,
command,
args,
ctx,
driverProcess,
);
return {
pid: entry.pid,
driverProcess,
wait: () => driverProcess.wait(),
writeStdin: (data) => driverProcess.writeStdin(data),
closeStdin: () => driverProcess.closeStdin(),
kill: (signal) => driverProcess.kill(signal ?? 15),
get onStdout() { return driverProcess.onStdout; },
set onStdout(fn) {
driverProcess.onStdout = fn;
// Replay buffered data
if (fn) for (const chunk of stdoutBuf) fn(chunk);
stdoutBuf.length = 0;
},
get onStderr() { return driverProcess.onStderr; },
set onStderr(fn) {
driverProcess.onStderr = fn;
if (fn) for (const chunk of stderrBuf) fn(chunk);
stderrBuf.length = 0;
},
};
}
private spawnManaged(
command: string,
args: string[],
options?: SpawnOptions,
callerPid?: number,
): ManagedProcess {
const internal = this.spawnInternal(command, args, options, callerPid);
let exitCode: number | null = null;
// Note: options.onStdout/onStderr are already wired through ctx.onStdout
// by spawnInternal. Do NOT also set them on driverProcess.onStdout here —
// the driver calls both ctx.onStdout and proc.onStdout per message, so
// setting both to the same callback would double-deliver output.
internal.driverProcess.wait().then((code) => {
exitCode = code;
});
return {
pid: internal.pid,
writeStdin: (data) => {
const bytes = typeof data === "string"
? new TextEncoder().encode(data)
: data;
internal.writeStdin(bytes);
},
closeStdin: () => internal.closeStdin(),
kill: (signal) => this.processTable.kill(internal.pid, signal ?? 15),
wait: () => internal.driverProcess.wait(),
get exitCode() { return exitCode; },
};
}
// -----------------------------------------------------------------------
// Kernel interface (exposed to drivers)
// -----------------------------------------------------------------------
private createKernelInterface(driverName: string): KernelInterface {
// Validate that the calling driver owns the target PID
const assertOwns = (pid: number) => {
if (this.driverPids.get(driverName)?.has(pid)) return;
// Check if any driver owns this PID — if not, the PID doesn't exist
for (const pids of this.driverPids.values()) {
if (pids.has(pid)) {
throw new KernelError("EPERM", `driver "${driverName}" does not own PID ${pid}`);
}
}
throw new KernelError("ESRCH", `no such process ${pid}`);
};
const kernelInterface: KernelInterface & {
fdPollWait: (pid: number, fd: number, timeoutMs?: number) => Promise<void>;
} = {
vfs: this.vfs,
// FD operations
fdOpen: (pid, path, flags, mode) => {
assertOwns(pid);
// /dev/fd/N → dup(N): equivalent to open() on the underlying FD
if (path.startsWith("/dev/fd/")) {
const raw = path.slice(8);
const n = parseInt(raw, 10);
if (isNaN(n) || n < 0 || String(n) !== raw) throw new KernelError("EBADF", `bad file descriptor: ${path}`);
const table = this.getTable(pid);
const entry = table.get(n);
if (!entry) throw new KernelError("EBADF", `bad file descriptor ${n}`);
return table.dup(n);
}
const created = (flags & (O_CREAT | O_EXCL | O_TRUNC)) !== 0
? this.prepareOpenSync(path, flags)
: false;
const table = this.getTable(pid);
const filetype = FILETYPE_REGULAR_FILE;
const fd = table.open(path, flags, filetype);
const fdEntry = table.get(fd);
// Stash the effective mode for the first write that materializes a new file.
if (created && (flags & O_CREAT)) {
const entry = this.processTable.get(pid);
const umask = entry?.umask ?? 0o022;
const requestedMode = mode ?? 0o666;
if (fdEntry) {
fdEntry.description.creationMode = requestedMode & ~umask;
}
}
return fd;
},
fdRead: async (pid, fd, length) => {
assertOwns(pid);
const table = this.getTable(pid);
const entry = table.get(fd);
if (!entry) throw new KernelError("EBADF", `bad file descriptor ${fd}`);
// Pipe reads route through PipeManager
if (this.pipeManager.isPipe(entry.description.id)) {
const data = await this.pipeManager.read(entry.description.id, length);
return data ?? new Uint8Array(0);
}
// PTY reads route through PtyManager
if (this.ptyManager.isPty(entry.description.id)) {
const data = await this.ptyManager.read(entry.description.id, length);
return data ?? new Uint8Array(0);
}
// Positional read from VFS — avoids loading entire file
const cursor = Number(entry.description.cursor);
const slice = await this.preadDescription(entry.description, cursor, length);
entry.description.cursor += BigInt(slice.length);
return slice;
},
fdWrite: (pid, fd, data) => {
assertOwns(pid);
const table = this.getTable(pid);
const entry = table.get(fd);
if (!entry) throw new KernelError("EBADF", `bad file descriptor ${fd}`);
if (this.pipeManager.isPipe(entry.description.id)) {
return this.pipeManager.write(entry.description.id, data, pid);
}
if (this.ptyManager.isPty(entry.description.id)) {
return this.ptyManager.write(entry.description.id, data);
}
// Write to VFS at cursor position (async — returns Promise)
return this.vfsWrite(entry, data);
},
fdClose: (pid, fd) => {
assertOwns(pid);
const table = this.getTable(pid);
const entry = table.get(fd);
if (!entry) return;
const descId = entry.description.id;
const isPipe = this.pipeManager.isPipe(descId);
const isPty = this.ptyManager.isPty(descId);
// Close FD first (decrements refCount on shared FileDescription)
table.close(fd);
// Only signal pipe/pty/lock closure when last reference is dropped
if (entry.description.refCount <= 0) {
this.releaseDescriptionInode(entry.description);
if (isPipe) this.pipeManager.close(descId);
if (isPty) this.ptyManager.close(descId);
this.fileLockManager.releaseByDescription(descId);
}
},
fdSeek: async (pid, fd, offset, whence) => {
assertOwns(pid);
const table = this.getTable(pid);
const entry = table.get(fd);
if (!entry) throw new KernelError("EBADF", `bad file descriptor ${fd}`);
// Pipes and PTYs are not seekable
if (this.pipeManager.isPipe(entry.description.id) || this.ptyManager.isPty(entry.description.id)) {
throw new KernelError("ESPIPE", "illegal seek");
}
let newCursor: bigint;
switch (whence) {
case SEEK_SET: