process-inspector.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. /** Platform process-table inspection for terminal readiness, signals, and teardown. */
  2. import { closeSync, openSync, readFileSync, readdirSync, readlinkSync, readSync, statSync } from 'node:fs'
  3. import { execFileSync } from 'node:child_process'
  4. import type { SubprocessTerminalSignal } from '@deepseek-ai/dsh-subprocess'
  5. import { createWindowsProcessInspector } from './windows-inspector.ts'
  6. /** PID plus start identity, preventing teardown escalation after PID reuse. */
  7. export interface ProcessIdentity {
  8. pid: number
  9. started: string
  10. }
  11. interface FileStatus {
  12. readonly rdev: number
  13. isCharacterDevice(): boolean
  14. }
  15. /**
  16. * One observation of the platform process table, shared by every question a
  17. * single readiness poll or teardown pass asks.
  18. *
  19. * The table is read at most once, on the first question that needs it — a
  20. * `/bin/ps` fork on macOS, a `/proc` walk on Linux, a Toolhelp32 enumeration on
  21. * Windows. Later questions never re-read it, which is what keeps a poll's cost
  22. * independent of how many descendants the running command spawned. Windows
  23. * liveness needs no table at all: wait state is a per-handle question there, so
  24. * a snapshot asked only for liveness never enumerates.
  25. *
  26. * A snapshot answers what the process table showed, which is what batch
  27. * filtering wants and what signalling must not use: {@link ProcessInspector.isAlive}
  28. * is the fence a signal takes, because it reads current state instead.
  29. */
  30. export interface ProcessSnapshot {
  31. /**
  32. * Return the root and its transitive descendants as observed, children first.
  33. * @param rootPid - tree root to descend from.
  34. * @returns Observed root and descendants, children before parents.
  35. */
  36. tree(rootPid: number): ProcessIdentity[]
  37. /**
  38. * Return observed members of one POSIX process session.
  39. * @param sessionId - POSIX session identifier.
  40. * @returns Observed session members, empty where the platform's table omits session ids.
  41. */
  42. session(sessionId: number): ProcessIdentity[]
  43. /**
  44. * Return whether the exact identity was a non-quiescent process.
  45. * @param identity - PID plus start identity to match.
  46. * @returns Whether that exact identity — not merely that PID — was running.
  47. */
  48. alive(identity: ProcessIdentity): boolean
  49. }
  50. /** Injectable OS process operations used by one local PTY session. */
  51. export interface ProcessInspector {
  52. foregroundPgid(shellPid: number): number | undefined
  53. /**
  54. * Report whether the foreground group waits on the terminal shell's stdin.
  55. *
  56. * @param pgid Foreground process-group identifier.
  57. * @param shellPid Persistent terminal shell process identifier.
  58. * @returns Whether a group member is blocked reading the shell's terminal input.
  59. */
  60. isStdinWaiting(pgid: number, shellPid: number): boolean
  61. /**
  62. * Read the process table once and answer tree, session, and liveness from it.
  63. * @returns A process-table observation whose reads are shared.
  64. */
  65. snapshot(): ProcessSnapshot
  66. /**
  67. * Return whether the exact identity is a non-quiescent process right now.
  68. *
  69. * Reads the narrowest per-identity source the platform offers rather than a
  70. * whole table, so a signalling round can re-check every target without
  71. * paying for a scan. Callers filtering many members at once want
  72. * {@link ProcessSnapshot.alive} instead.
  73. *
  74. * @param identity - PID plus start identity to match.
  75. * @returns Whether that exact identity — not merely that PID — is running.
  76. */
  77. isAlive(identity: ProcessIdentity): boolean
  78. signalGroup(pgid: number, signal: SubprocessTerminalSignal): void
  79. /**
  80. * Signal one exact process identity, fenced against PID reuse.
  81. *
  82. * The fence reads current state immediately before the signal. An observation
  83. * taken earlier in the same round cannot stand in for it: the observation
  84. * preserves the original PID-to-start-time pairing, so a recycled PID would
  85. * still match and take a signal meant for the process that exited.
  86. *
  87. * @param identity - PID plus start identity to signal.
  88. * @param signal - termination signal to deliver.
  89. */
  90. signalProcess(identity: ProcessIdentity, signal: 'SIGTERM' | 'SIGKILL'): void
  91. }
  92. /** Testable boundary around filesystem, process-table, and signal syscalls. */
  93. export interface ProcessInspectorInternals {
  94. readFile(path: string): string
  95. readDir(path: string): string[]
  96. readLink(path: string): string
  97. stat(path: string): FileStatus
  98. open(path: string): number
  99. read(fd: number, buffer: Buffer, length: number, position: number): number
  100. close(fd: number): void
  101. exec(file: string, args: string[]): string
  102. kill(pid: number, signal: NodeJS.Signals): void
  103. }
  104. /* v8 ignore start -- thin OS bindings; injected logic is unit-tested and real platform composition exercises them. */
  105. const DEFAULT_INTERNALS: ProcessInspectorInternals = {
  106. readFile: path => readFileSync(path, 'utf8'),
  107. readDir: path => readdirSync(path),
  108. readLink: path => readlinkSync(path, 'utf8'),
  109. stat: path => statSync(path),
  110. open: path => openSync(path, 'r'),
  111. read: (fd, buffer, length, position) => readSync(fd, buffer, 0, length, position),
  112. close: closeSync,
  113. exec: (file, args) => execFileSync(file, args, { encoding: 'utf8' }),
  114. kill: (pid, signal) => process.kill(pid, signal),
  115. }
  116. /* v8 ignore stop */
  117. interface ProcStat {
  118. pid: number
  119. parentPid: number
  120. pgrp: number
  121. session: number
  122. state: string
  123. ttyDevice: number
  124. tpgid: number
  125. started: string
  126. }
  127. /**
  128. * Parse fields used from Linux `/proc/<pid>/stat`, including parenthesized comm text.
  129. * @param text - complete stat line.
  130. * @returns Parsed identity/group fields, or undefined for malformed input.
  131. */
  132. export function parseProcStat(text: string): ProcStat | undefined {
  133. const open = text.indexOf('(')
  134. const close = text.lastIndexOf(')')
  135. if (open <= 0 || close <= open) return undefined
  136. const pid = Number(text.slice(0, open).trim())
  137. const rest = text.slice(close + 2).trim().split(/\s+/)
  138. const state = rest[0] || ''
  139. const parentPid = Number(rest[1])
  140. const pgrp = Number(rest[2])
  141. const session = Number(rest[3])
  142. const ttyDevice = Number(rest[4])
  143. const tpgid = Number(rest[5])
  144. const started = rest[19]
  145. if (![pid, parentPid, pgrp, session, ttyDevice, tpgid].every(Number.isSafeInteger)
  146. || state.length !== 1 || started === undefined) return undefined
  147. return { pid, parentPid, pgrp, session, state, ttyDevice, tpgid, started }
  148. }
  149. function readLinuxStat(internals: ProcessInspectorInternals, pid: number): ProcStat | undefined {
  150. try {
  151. return parseProcStat(internals.readFile(`/proc/${pid}/stat`))
  152. } catch (_unreadableProcEntry) {
  153. return undefined
  154. }
  155. }
  156. // `/proc/<pid>/stat` renders tty_nr as a signed 32-bit device number, while
  157. // Node exposes the same st_rdev bits as a nonnegative number.
  158. function linuxDeviceNumber(value: number): number {
  159. return value >>> 0
  160. }
  161. // `/dev/tty` reports the alias device instead of the selected PTY through stat,
  162. // so its owning process's tty_nr is the only comparable terminal identity.
  163. function readLinuxTerminalDevice(
  164. internals: ProcessInspectorInternals,
  165. pid: number,
  166. ttyDevice: number,
  167. tid?: number,
  168. ): number | undefined {
  169. const terminalDevice = linuxDeviceNumber(ttyDevice)
  170. if (terminalDevice === 0) return undefined
  171. const path = tid === undefined ? `/proc/${pid}/fd/0` : `/proc/${pid}/task/${tid}/fd/0`
  172. try {
  173. const target = internals.readLink(path)
  174. if (target === '/dev/tty') return terminalDevice
  175. const status = internals.stat(path)
  176. return status.isCharacterDevice() && linuxDeviceNumber(status.rdev) === terminalDevice
  177. ? terminalDevice
  178. : undefined
  179. } catch (_unreadableStdinDevice) {
  180. return undefined
  181. }
  182. }
  183. /**
  184. * Report whether a Linux process group has an executing member. `false`
  185. * means the group contains only zombie/dead entries; `undefined` means the
  186. * process table could not prove either outcome.
  187. * @param processGroupId - POSIX process-group id to inspect.
  188. * @param internals - injectable process-table operations.
  189. * @returns Live-member presence, or `undefined` when unavailable/absent.
  190. */
  191. export function linuxProcessGroupHasLiveMembers(
  192. processGroupId: number,
  193. internals: ProcessInspectorInternals = DEFAULT_INTERNALS,
  194. ): boolean | undefined {
  195. let entries: string[]
  196. try {
  197. entries = internals.readDir('/proc')
  198. } catch (_unreadableProcDirectory) {
  199. return undefined
  200. }
  201. let matched = false
  202. for (const entry of entries) {
  203. if (!/^\d+$/.test(entry)) continue
  204. const stat = readLinuxStat(internals, Number(entry))
  205. if (stat?.pgrp !== processGroupId) continue
  206. matched = true
  207. if (!/^[ZXx]$/.test(stat.state)) return true
  208. }
  209. return matched ? false : undefined
  210. }
  211. function numericEntries(internals: ProcessInspectorInternals, path: string): number[] {
  212. try {
  213. return internals.readDir(path).filter(entry => /^\d+$/.test(entry)).map(Number)
  214. } catch (_unreadableProcDirectory) {
  215. return []
  216. }
  217. }
  218. interface SyscallInfo {
  219. number: number
  220. args: number[]
  221. }
  222. function readSyscall(internals: ProcessInspectorInternals, pid: number, tid: number): SyscallInfo | undefined {
  223. try {
  224. const text = internals.readFile(`/proc/${pid}/task/${tid}/syscall`).trim()
  225. if (text === 'running' || text.startsWith('-1 ')) return undefined
  226. const fields = text.split(/\s+/)
  227. const number = Number(fields[0])
  228. const args = fields.slice(1, 7).map(field => Number.parseInt(field, 16))
  229. if (!Number.isSafeInteger(number) || args.some(value => !Number.isSafeInteger(value))) return undefined
  230. return { number, args }
  231. } catch (_unreadableSyscall) {
  232. return undefined
  233. }
  234. }
  235. function readMemory(
  236. internals: ProcessInspectorInternals,
  237. pid: number,
  238. address: number,
  239. length: number,
  240. ): Buffer | undefined {
  241. let fd: number | undefined
  242. try {
  243. fd = internals.open(`/proc/${pid}/mem`)
  244. const buffer = Buffer.alloc(length)
  245. const count = internals.read(fd, buffer, length, address)
  246. return buffer.subarray(0, count)
  247. } catch (_unreadableProcessMemory) {
  248. return undefined
  249. } finally {
  250. if (fd !== undefined) internals.close(fd)
  251. }
  252. }
  253. function fdSetHasStdin(internals: ProcessInspectorInternals, pid: number, address: number): boolean {
  254. return address !== 0 && (readMemory(internals, pid, address, 8)?.[0] ?? 0) % 2 === 1
  255. }
  256. function pollHasStdin(
  257. internals: ProcessInspectorInternals,
  258. pid: number,
  259. address: number,
  260. count: number,
  261. ): boolean {
  262. if (address === 0 || count <= 0) return false
  263. const memory = readMemory(internals, pid, address, Math.min(count, 1024) * 8)
  264. if (memory === undefined) return false
  265. for (let offset = 0; offset + 8 <= memory.length; offset += 8) {
  266. if (memory.readInt32LE(offset) === 0 && (memory.readInt16LE(offset + 4) & 0x001) !== 0) return true
  267. }
  268. return false
  269. }
  270. function epollHasStdin(internals: ProcessInspectorInternals, pid: number, tid: number, epfd: number): boolean {
  271. try {
  272. return internals.readFile(`/proc/${pid}/task/${tid}/fdinfo/${epfd}`)
  273. .split('\n')
  274. .some(line => /^tfd:\s+0\b/.test(line.trim()))
  275. } catch (_unreadableFdInfo) {
  276. return false
  277. }
  278. }
  279. interface SyscallTable {
  280. read: number
  281. select?: number
  282. pselect: number
  283. poll?: number
  284. ppoll: number
  285. epollWait?: number
  286. epollPwait: number
  287. }
  288. const SYSCALLS: Partial<Record<NodeJS.Architecture, SyscallTable>> = {
  289. x64: { read: 0, select: 23, pselect: 270, poll: 7, ppoll: 271, epollWait: 232, epollPwait: 281 },
  290. arm64: { read: 63, pselect: 72, ppoll: 73, epollPwait: 22 },
  291. }
  292. const SUPPORTED_SYSCALL_TABLES = Object.values(SYSCALLS)
  293. // `/proc/<pid>/task/<tid>/syscall` uses the kernel ABI's numbers. User-mode
  294. // emulation can therefore expose a supported table different from process.arch.
  295. function linuxSyscallTables(arch: NodeJS.Architecture): readonly SyscallTable[] | undefined {
  296. const primary = SYSCALLS[arch]
  297. if (primary === undefined) return undefined
  298. return [primary, ...SUPPORTED_SYSCALL_TABLES.filter(table => table !== primary)]
  299. }
  300. function syscallWaitsOnStdin(
  301. internals: ProcessInspectorInternals,
  302. pid: number,
  303. tid: number,
  304. syscall: SyscallInfo,
  305. tables: readonly SyscallTable[],
  306. ): boolean {
  307. const [a0 = 0, a1 = 0, a2 = 0] = syscall.args
  308. for (const table of tables) {
  309. if (syscall.number === table.read) return a0 === 0
  310. if (syscall.number === table.select || syscall.number === table.pselect) {
  311. return a0 >= 1 && fdSetHasStdin(internals, pid, a1)
  312. }
  313. if (syscall.number === table.poll || syscall.number === table.ppoll) {
  314. return a1 >= 1 && pollHasStdin(internals, pid, a0, a1)
  315. }
  316. if (syscall.number === table.epollWait || syscall.number === table.epollPwait) {
  317. return a2 >= 1 && epollHasStdin(internals, pid, tid, a0)
  318. }
  319. }
  320. return false
  321. }
  322. abstract class PosixProcessInspector implements ProcessInspector {
  323. constructor(protected readonly internals: ProcessInspectorInternals) {}
  324. abstract foregroundPgid(shellPid: number): number | undefined
  325. abstract isStdinWaiting(pgid: number, shellPid: number): boolean
  326. abstract snapshot(): ProcessSnapshot
  327. abstract isAlive(identity: ProcessIdentity): boolean
  328. signalGroup(pgid: number, signal: SubprocessTerminalSignal): void {
  329. this.internals.kill(-pgid, signal)
  330. }
  331. signalProcess(identity: ProcessIdentity, signal: 'SIGTERM' | 'SIGKILL'): void {
  332. if (this.isAlive(identity)) this.internals.kill(identity.pid, signal)
  333. }
  334. }
  335. interface ProcessTreeEntry extends ProcessIdentity {
  336. parentPid: number
  337. }
  338. /** One process-table row, carrying the fields a platform's table exposes. */
  339. interface ProcessRow extends ProcessTreeEntry {
  340. /** POSIX session identifier, or undefined where the table omits it. */
  341. session: number | undefined
  342. /** Single-letter process state, or undefined where the table omits it. */
  343. state: string | undefined
  344. }
  345. // Zombie and dead states answer "present in the table" but never "still
  346. // running"; a table without a state column can only report presence.
  347. function quiescent(state: string | undefined): boolean {
  348. return state !== undefined && /^[ZXx]$/.test(state)
  349. }
  350. class PosixProcessSnapshot implements ProcessSnapshot {
  351. private readonly byPid: Map<number, ProcessRow>
  352. constructor(private readonly rows: ProcessRow[]) {
  353. this.byPid = new Map(rows.map(row => [row.pid, row]))
  354. }
  355. tree(rootPid: number): ProcessIdentity[] {
  356. return processTree(this.rows, rootPid)
  357. }
  358. session(sessionId: number): ProcessIdentity[] {
  359. return this.rows.flatMap(row =>
  360. row.session === sessionId ? [{ pid: row.pid, started: row.started }] : [])
  361. }
  362. alive(identity: ProcessIdentity): boolean {
  363. const row = this.byPid.get(identity.pid)
  364. return row?.started === identity.started && !quiescent(row.state)
  365. }
  366. }
  367. function processTree(entries: ProcessTreeEntry[], rootPid: number): ProcessIdentity[] {
  368. const byPid = new Map(entries.map(entry => [entry.pid, entry]))
  369. const root = byPid.get(rootPid)
  370. if (root === undefined) return []
  371. const byParent = new Map<number, ProcessTreeEntry[]>()
  372. for (const entry of entries) {
  373. const children = byParent.get(entry.parentPid) ?? []
  374. children.push(entry)
  375. byParent.set(entry.parentPid, children)
  376. }
  377. const visited = new Set<number>()
  378. const result: ProcessIdentity[] = []
  379. const visit = (entry: ProcessTreeEntry): void => {
  380. if (visited.has(entry.pid)) return
  381. visited.add(entry.pid)
  382. for (const child of byParent.get(entry.pid) ?? []) visit(child)
  383. result.push({ pid: entry.pid, started: entry.started })
  384. }
  385. visit(root)
  386. return result
  387. }
  388. class LinuxProcessInspector extends PosixProcessInspector {
  389. constructor(
  390. private readonly arch: NodeJS.Architecture,
  391. internals: ProcessInspectorInternals,
  392. ) {
  393. super(internals)
  394. }
  395. foregroundPgid(shellPid: number): number | undefined {
  396. const tpgid = readLinuxStat(this.internals, shellPid)?.tpgid
  397. return tpgid !== undefined && tpgid > 0 ? tpgid : undefined
  398. }
  399. isStdinWaiting(pgid: number, shellPid: number): boolean {
  400. const tables = linuxSyscallTables(this.arch)
  401. if (tables === undefined) return false
  402. const shell = readLinuxStat(this.internals, shellPid)
  403. if (shell === undefined) return false
  404. const terminalDevice = readLinuxTerminalDevice(this.internals, shellPid, shell.ttyDevice)
  405. if (terminalDevice === undefined) return false
  406. for (const pid of numericEntries(this.internals, '/proc')) {
  407. const process = readLinuxStat(this.internals, pid)
  408. if (process?.pgrp !== pgid) continue
  409. for (const tid of numericEntries(this.internals, `/proc/${pid}/task`)) {
  410. const syscall = readSyscall(this.internals, pid, tid)
  411. if (syscall !== undefined
  412. && syscallWaitsOnStdin(this.internals, pid, tid, syscall, tables)
  413. && readLinuxTerminalDevice(this.internals, pid, process.ttyDevice, tid) === terminalDevice) return true
  414. }
  415. }
  416. return false
  417. }
  418. isAlive(identity: ProcessIdentity): boolean {
  419. const stat = readLinuxStat(this.internals, identity.pid)
  420. return stat?.started === identity.started && !quiescent(stat.state)
  421. }
  422. snapshot(): ProcessSnapshot {
  423. return new PosixProcessSnapshot(numericEntries(this.internals, '/proc').flatMap((pid) => {
  424. const stat = readLinuxStat(this.internals, pid)
  425. return stat === undefined ? [] : [{
  426. pid,
  427. parentPid: stat.parentPid,
  428. started: stat.started,
  429. session: stat.session,
  430. state: stat.state,
  431. }]
  432. }))
  433. }
  434. }
  435. // `ps` exposes neither the session id nor a state column in this format, so a
  436. // macOS row can answer presence and parentage but never session membership.
  437. function macProcessTable(internals: ProcessInspectorInternals): ProcessRow[] {
  438. return internals.exec('/bin/ps', ['-axo', 'pid=,ppid=,lstart=']).split('\n').flatMap((line) => {
  439. const match = /^\s*(\d+)\s+(\d+)\s+(.+?)\s*$/.exec(line)
  440. if (match?.[1] === undefined || match[2] === undefined || match[3] === undefined) return []
  441. return [{
  442. pid: Number(match[1]),
  443. parentPid: Number(match[2]),
  444. started: match[3],
  445. session: undefined,
  446. state: undefined,
  447. }]
  448. })
  449. }
  450. class MacProcessInspector extends PosixProcessInspector {
  451. foregroundPgid(shellPid: number): number | undefined {
  452. try {
  453. const value = Number(this.internals.exec('/bin/ps', ['-o', 'tpgid=', '-p', String(shellPid)]).trim())
  454. return Number.isSafeInteger(value) && value > 0 ? value : undefined
  455. } catch (_missingProcess) {
  456. return undefined
  457. }
  458. }
  459. isStdinWaiting(_pgid: number, _shellPid: number): boolean {
  460. return false
  461. }
  462. isAlive(identity: ProcessIdentity): boolean {
  463. return macProcessTable(this.internals)
  464. .some(entry => entry.pid === identity.pid && entry.started === identity.started)
  465. }
  466. snapshot(): ProcessSnapshot {
  467. return new PosixProcessSnapshot(macProcessTable(this.internals))
  468. }
  469. }
  470. /**
  471. * Create the supported platform inspector or fail at plugin load.
  472. * @param platform - target Node platform.
  473. * @param arch - target CPU architecture for Linux syscall numbers.
  474. * @param internals - filesystem/process boundary, injectable for deterministic tests.
  475. * @returns Platform process inspector.
  476. */
  477. export function createProcessInspector(
  478. platform: NodeJS.Platform = process.platform,
  479. arch: NodeJS.Architecture = process.arch,
  480. internals: ProcessInspectorInternals = DEFAULT_INTERNALS,
  481. ): ProcessInspector {
  482. if (platform === 'linux') return new LinuxProcessInspector(arch, internals)
  483. if (platform === 'darwin') return new MacProcessInspector(internals)
  484. if (platform === 'win32') return createWindowsProcessInspector()
  485. throw new Error(`subprocess-local: terminal inspection is unsupported on platform ${platform}`)
  486. }