process-inspector.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. /** Platform process-table inspection for terminal readiness, signals, and teardown. */
  2. import { closeSync, openSync, readFileSync, readdirSync, readSync } from 'node:fs'
  3. import { execFileSync } from 'node:child_process'
  4. import type { SubprocessTerminalSignal } from '@deepseek-ai/dsh-subprocess'
  5. /** PID plus start identity, preventing teardown escalation after PID reuse. */
  6. export interface ProcessIdentity {
  7. pid: number
  8. started: string
  9. }
  10. /** Injectable OS process operations used by one local PTY session. */
  11. export interface ProcessInspector {
  12. foregroundPgid(shellPid: number): number | undefined
  13. isStdinWaiting(pgid: number): boolean
  14. /** Return the root and its current transitive descendants, children first. */
  15. processTree(rootPid: number): ProcessIdentity[]
  16. /** Return current members of one POSIX process session when the platform exposes them. */
  17. processSession(sessionId: number): ProcessIdentity[]
  18. /** Return whether the exact identity remains a non-quiescent process. */
  19. isAlive(identity: ProcessIdentity): boolean
  20. signalGroup(pgid: number, signal: SubprocessTerminalSignal): void
  21. signalProcess(identity: ProcessIdentity, signal: 'SIGTERM' | 'SIGKILL'): void
  22. }
  23. /** Testable boundary around filesystem, process-table, and signal syscalls. */
  24. export interface ProcessInspectorInternals {
  25. readFile(path: string): string
  26. readDir(path: string): string[]
  27. open(path: string): number
  28. read(fd: number, buffer: Buffer, length: number, position: number): number
  29. close(fd: number): void
  30. exec(file: string, args: string[]): string
  31. kill(pid: number, signal: NodeJS.Signals): void
  32. }
  33. /* v8 ignore start -- thin OS bindings; injected logic is unit-tested and real platform composition exercises them. */
  34. const DEFAULT_INTERNALS: ProcessInspectorInternals = {
  35. readFile: path => readFileSync(path, 'utf8'),
  36. readDir: path => readdirSync(path),
  37. open: path => openSync(path, 'r'),
  38. read: (fd, buffer, length, position) => readSync(fd, buffer, 0, length, position),
  39. close: closeSync,
  40. exec: (file, args) => execFileSync(file, args, { encoding: 'utf8' }),
  41. kill: (pid, signal) => process.kill(pid, signal),
  42. }
  43. /* v8 ignore stop */
  44. interface ProcStat {
  45. pid: number
  46. parentPid: number
  47. pgrp: number
  48. session: number
  49. state: string
  50. tpgid: number
  51. started: string
  52. }
  53. /**
  54. * Parse fields used from Linux `/proc/<pid>/stat`, including parenthesized comm text.
  55. * @param text - complete stat line.
  56. * @returns Parsed identity/group fields, or undefined for malformed input.
  57. */
  58. export function parseProcStat(text: string): ProcStat | undefined {
  59. const open = text.indexOf('(')
  60. const close = text.lastIndexOf(')')
  61. if (open <= 0 || close <= open) return undefined
  62. const pid = Number(text.slice(0, open).trim())
  63. const rest = text.slice(close + 2).trim().split(/\s+/)
  64. const state = rest[0] || ''
  65. const parentPid = Number(rest[1])
  66. const pgrp = Number(rest[2])
  67. const session = Number(rest[3])
  68. const tpgid = Number(rest[5])
  69. const started = rest[19]
  70. if (![pid, parentPid, pgrp, session, tpgid].every(Number.isSafeInteger)
  71. || state.length !== 1 || started === undefined) return undefined
  72. return { pid, parentPid, pgrp, session, state, tpgid, started }
  73. }
  74. function readLinuxStat(internals: ProcessInspectorInternals, pid: number): ProcStat | undefined {
  75. try {
  76. return parseProcStat(internals.readFile(`/proc/${pid}/stat`))
  77. } catch (_unreadableProcEntry) {
  78. return undefined
  79. }
  80. }
  81. /**
  82. * Report whether a Linux process group has an executing member. `false`
  83. * means the group contains only zombie/dead entries; `undefined` means the
  84. * process table could not prove either outcome.
  85. * @param processGroupId - POSIX process-group id to inspect.
  86. * @param internals - injectable process-table operations.
  87. * @returns Live-member presence, or `undefined` when unavailable/absent.
  88. */
  89. export function linuxProcessGroupHasLiveMembers(
  90. processGroupId: number,
  91. internals: ProcessInspectorInternals = DEFAULT_INTERNALS,
  92. ): boolean | undefined {
  93. let entries: string[]
  94. try {
  95. entries = internals.readDir('/proc')
  96. } catch (_unreadableProcDirectory) {
  97. return undefined
  98. }
  99. let matched = false
  100. for (const entry of entries) {
  101. if (!/^\d+$/.test(entry)) continue
  102. const stat = readLinuxStat(internals, Number(entry))
  103. if (stat?.pgrp !== processGroupId) continue
  104. matched = true
  105. if (!/^[ZXx]$/.test(stat.state)) return true
  106. }
  107. return matched ? false : undefined
  108. }
  109. function numericEntries(internals: ProcessInspectorInternals, path: string): number[] {
  110. try {
  111. return internals.readDir(path).filter(entry => /^\d+$/.test(entry)).map(Number)
  112. } catch (_unreadableProcDirectory) {
  113. return []
  114. }
  115. }
  116. interface SyscallInfo {
  117. number: number
  118. args: number[]
  119. }
  120. function readSyscall(internals: ProcessInspectorInternals, pid: number, tid: number): SyscallInfo | undefined {
  121. try {
  122. const text = internals.readFile(`/proc/${pid}/task/${tid}/syscall`).trim()
  123. if (text === 'running' || text.startsWith('-1 ')) return undefined
  124. const fields = text.split(/\s+/)
  125. const number = Number(fields[0])
  126. const args = fields.slice(1, 7).map(field => Number.parseInt(field, 16))
  127. if (!Number.isSafeInteger(number) || args.some(value => !Number.isSafeInteger(value))) return undefined
  128. return { number, args }
  129. } catch (_unreadableSyscall) {
  130. return undefined
  131. }
  132. }
  133. function readMemory(
  134. internals: ProcessInspectorInternals,
  135. pid: number,
  136. address: number,
  137. length: number,
  138. ): Buffer | undefined {
  139. let fd: number | undefined
  140. try {
  141. fd = internals.open(`/proc/${pid}/mem`)
  142. const buffer = Buffer.alloc(length)
  143. const count = internals.read(fd, buffer, length, address)
  144. return buffer.subarray(0, count)
  145. } catch (_unreadableProcessMemory) {
  146. return undefined
  147. } finally {
  148. if (fd !== undefined) internals.close(fd)
  149. }
  150. }
  151. function fdSetHasStdin(internals: ProcessInspectorInternals, pid: number, address: number): boolean {
  152. return address !== 0 && (readMemory(internals, pid, address, 8)?.[0] ?? 0) % 2 === 1
  153. }
  154. function pollHasStdin(
  155. internals: ProcessInspectorInternals,
  156. pid: number,
  157. address: number,
  158. count: number,
  159. ): boolean {
  160. if (address === 0 || count <= 0) return false
  161. const memory = readMemory(internals, pid, address, Math.min(count, 1024) * 8)
  162. if (memory === undefined) return false
  163. for (let offset = 0; offset + 8 <= memory.length; offset += 8) {
  164. if (memory.readInt32LE(offset) === 0 && (memory.readInt16LE(offset + 4) & 0x001) !== 0) return true
  165. }
  166. return false
  167. }
  168. function epollHasStdin(internals: ProcessInspectorInternals, pid: number, epfd: number): boolean {
  169. try {
  170. return internals.readFile(`/proc/${pid}/fdinfo/${epfd}`)
  171. .split('\n')
  172. .some(line => /^tfd:\s+0\b/.test(line.trim()))
  173. } catch (_unreadableFdInfo) {
  174. return false
  175. }
  176. }
  177. interface SyscallTable {
  178. read: number
  179. select?: number
  180. pselect: number
  181. poll?: number
  182. ppoll: number
  183. epollWait?: number
  184. epollPwait: number
  185. }
  186. const SYSCALLS: Partial<Record<NodeJS.Architecture, SyscallTable>> = {
  187. x64: { read: 0, select: 23, pselect: 270, poll: 7, ppoll: 271, epollWait: 232, epollPwait: 281 },
  188. arm64: { read: 63, pselect: 72, ppoll: 73, epollPwait: 22 },
  189. }
  190. function syscallWaitsOnStdin(
  191. internals: ProcessInspectorInternals,
  192. pid: number,
  193. syscall: SyscallInfo,
  194. table: SyscallTable,
  195. ): boolean {
  196. const [a0 = 0, a1 = 0, a2 = 0] = syscall.args
  197. if (syscall.number === table.read) return a0 === 0
  198. if (syscall.number === table.select || syscall.number === table.pselect) {
  199. return a0 >= 1 && fdSetHasStdin(internals, pid, a1)
  200. }
  201. if (syscall.number === table.poll || syscall.number === table.ppoll) {
  202. return a1 >= 1 && pollHasStdin(internals, pid, a0, a1)
  203. }
  204. if (syscall.number === table.epollWait || syscall.number === table.epollPwait) {
  205. return a2 >= 1 && epollHasStdin(internals, pid, a0)
  206. }
  207. return false
  208. }
  209. abstract class PosixProcessInspector implements ProcessInspector {
  210. constructor(protected readonly internals: ProcessInspectorInternals) {}
  211. abstract foregroundPgid(shellPid: number): number | undefined
  212. abstract isStdinWaiting(pgid: number): boolean
  213. abstract processTree(rootPid: number): ProcessIdentity[]
  214. abstract processSession(sessionId: number): ProcessIdentity[]
  215. abstract isAlive(identity: ProcessIdentity): boolean
  216. signalGroup(pgid: number, signal: SubprocessTerminalSignal): void {
  217. this.internals.kill(-pgid, signal)
  218. }
  219. signalProcess(identity: ProcessIdentity, signal: 'SIGTERM' | 'SIGKILL'): void {
  220. if (this.isAlive(identity)) this.internals.kill(identity.pid, signal)
  221. }
  222. }
  223. interface ProcessTreeEntry extends ProcessIdentity {
  224. parentPid: number
  225. }
  226. function processTree(entries: ProcessTreeEntry[], rootPid: number): ProcessIdentity[] {
  227. const byPid = new Map(entries.map(entry => [entry.pid, entry]))
  228. const root = byPid.get(rootPid)
  229. if (root === undefined) return []
  230. const byParent = new Map<number, ProcessTreeEntry[]>()
  231. for (const entry of entries) {
  232. const children = byParent.get(entry.parentPid) ?? []
  233. children.push(entry)
  234. byParent.set(entry.parentPid, children)
  235. }
  236. const visited = new Set<number>()
  237. const result: ProcessIdentity[] = []
  238. const visit = (entry: ProcessTreeEntry): void => {
  239. if (visited.has(entry.pid)) return
  240. visited.add(entry.pid)
  241. for (const child of byParent.get(entry.pid) ?? []) visit(child)
  242. result.push({ pid: entry.pid, started: entry.started })
  243. }
  244. visit(root)
  245. return result
  246. }
  247. class LinuxProcessInspector extends PosixProcessInspector {
  248. constructor(
  249. private readonly arch: NodeJS.Architecture,
  250. internals: ProcessInspectorInternals,
  251. ) {
  252. super(internals)
  253. }
  254. foregroundPgid(shellPid: number): number | undefined {
  255. const tpgid = readLinuxStat(this.internals, shellPid)?.tpgid
  256. return tpgid !== undefined && tpgid > 0 ? tpgid : undefined
  257. }
  258. isStdinWaiting(pgid: number): boolean {
  259. const table = SYSCALLS[this.arch]
  260. if (table === undefined) return false
  261. for (const pid of numericEntries(this.internals, '/proc')) {
  262. if (readLinuxStat(this.internals, pid)?.pgrp !== pgid) continue
  263. for (const tid of numericEntries(this.internals, `/proc/${pid}/task`)) {
  264. const syscall = readSyscall(this.internals, pid, tid)
  265. if (syscall !== undefined && syscallWaitsOnStdin(this.internals, pid, syscall, table)) return true
  266. }
  267. }
  268. return false
  269. }
  270. processTree(rootPid: number): ProcessIdentity[] {
  271. const entries = numericEntries(this.internals, '/proc').flatMap((pid) => {
  272. const stat = readLinuxStat(this.internals, pid)
  273. return stat === undefined ? [] : [{ pid, parentPid: stat.parentPid, started: stat.started }]
  274. })
  275. return processTree(entries, rootPid)
  276. }
  277. processSession(sessionId: number): ProcessIdentity[] {
  278. return numericEntries(this.internals, '/proc').flatMap((pid) => {
  279. const stat = readLinuxStat(this.internals, pid)
  280. return stat?.session === sessionId ? [{ pid, started: stat.started }] : []
  281. })
  282. }
  283. isAlive(identity: ProcessIdentity): boolean {
  284. const stat = readLinuxStat(this.internals, identity.pid)
  285. return stat?.started === identity.started && !/^[ZXx]$/.test(stat.state)
  286. }
  287. }
  288. interface PsEntry extends ProcessTreeEntry {}
  289. function macProcessTable(internals: ProcessInspectorInternals): PsEntry[] {
  290. return internals.exec('/bin/ps', ['-axo', 'pid=,ppid=,lstart=']).split('\n').flatMap((line) => {
  291. const match = /^\s*(\d+)\s+(\d+)\s+(.+?)\s*$/.exec(line)
  292. if (match?.[1] === undefined || match[2] === undefined || match[3] === undefined) return []
  293. return [{ pid: Number(match[1]), parentPid: Number(match[2]), started: match[3] }]
  294. })
  295. }
  296. class MacProcessInspector extends PosixProcessInspector {
  297. foregroundPgid(shellPid: number): number | undefined {
  298. try {
  299. const value = Number(this.internals.exec('/bin/ps', ['-o', 'tpgid=', '-p', String(shellPid)]).trim())
  300. return Number.isSafeInteger(value) && value > 0 ? value : undefined
  301. } catch (_missingProcess) {
  302. return undefined
  303. }
  304. }
  305. isStdinWaiting(_pgid: number): boolean {
  306. return false
  307. }
  308. processTree(rootPid: number): ProcessIdentity[] {
  309. return processTree(macProcessTable(this.internals), rootPid)
  310. }
  311. processSession(_sessionId: number): ProcessIdentity[] {
  312. return []
  313. }
  314. isAlive(identity: ProcessIdentity): boolean {
  315. return macProcessTable(this.internals).some(entry => entry.pid === identity.pid && entry.started === identity.started)
  316. }
  317. }
  318. /**
  319. * Create the supported platform inspector or fail at plugin load.
  320. * @param platform - target Node platform.
  321. * @param arch - target CPU architecture for Linux syscall numbers.
  322. * @param internals - filesystem/process boundary, injectable for deterministic tests.
  323. * @returns Platform process inspector.
  324. */
  325. export function createProcessInspector(
  326. platform: NodeJS.Platform = process.platform,
  327. arch: NodeJS.Architecture = process.arch,
  328. internals: ProcessInspectorInternals = DEFAULT_INTERNALS,
  329. ): ProcessInspector {
  330. if (platform === 'linux') return new LinuxProcessInspector(arch, internals)
  331. if (platform === 'darwin') return new MacProcessInspector(internals)
  332. throw new Error(`subprocess-local: terminal inspection is unsupported on platform ${platform}`)
  333. }