toolscript-mcp 1.0.3 → 1.0.5

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "toolscript-mcp",
3
- "version": "1.0.3",
3
+ "version": "1.0.5",
4
4
  "description": "Standalone MCP server for code mode: the model writes one JavaScript program that calls your MCP tools in a sandbox.",
5
5
  "keywords": [
6
6
  "mcp",
@@ -0,0 +1,132 @@
1
+ // The child guard of Windows (opt-in with TOOLSCRIPT_CHILD_GUARD=1). toolscript-mcp compiles this file one time with the
2
+ // csc.exe of .NET Framework, keeps the program under ~/.toolscript-mcp/guard (named by a hash of this text) and starts it
3
+ // once for each host or broker: child-guard.exe <pid of the host>
4
+ //
5
+ // It makes one Job Object (KILL_ON_JOB_CLOSE, breakaway allowed). For each line `guard <pid>` on its standard input it
6
+ // puts that process in the job, but only a process that the host started: its parent is the host and it is not older than
7
+ // the host. Then it puts in the job every descendant of the processes that it holds (a `cmd /c` wrapper can start its
8
+ // server before the assign), by parent pid, until a pass finds none. Windows never updates the parent pid of a process
9
+ // and reuses pids within seconds, so a descendant counts only when it is not older than its parent, and a member whose
10
+ // process has exited is dropped at once, with its handle. A process that a member starts is a member. When the host is
11
+ // gone (its process handle is signalled, or the standard input ends) this program exits, the last handle of the job
12
+ // closes, and the kernel ends every process in it. It is not in its own job. It reads and writes only pids and the
13
+ // words ready and guarded: no command, argument or environment value ever reaches it.
14
+
15
+ using System;
16
+ using System.Collections.Generic;
17
+ using System.IO;
18
+ using System.Runtime.InteropServices;
19
+ using System.Threading;
20
+
21
+ public static class ChildGuard {
22
+ [StructLayout(LayoutKind.Sequential)] struct BASIC { public long a, b; public uint LimitFlags; public UIntPtr c, d; public uint e; public UIntPtr f; public uint g, h; }
23
+ [StructLayout(LayoutKind.Sequential)] struct IOC { public ulong a, b, c, d, e, f; }
24
+ [StructLayout(LayoutKind.Sequential)] struct EXT { public BASIC Basic; public IOC Io; public UIntPtr p1, p2, p3, p4; }
25
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
26
+ struct PE { public uint size, usage, pid; public IntPtr heap; public uint modid, threads, ppid; public int pri; public uint flags;
27
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string exe; }
28
+ [DllImport("kernel32.dll", SetLastError = true)] static extern IntPtr CreateJobObjectW(IntPtr a, IntPtr n);
29
+ [DllImport("kernel32.dll", SetLastError = true)] static extern bool SetInformationJobObject(IntPtr j, int c, ref EXT i, uint l);
30
+ [DllImport("kernel32.dll", SetLastError = true)] static extern bool AssignProcessToJobObject(IntPtr j, IntPtr p);
31
+ [DllImport("kernel32.dll")] static extern IntPtr OpenProcess(uint access, bool inherit, int pid);
32
+ [DllImport("kernel32.dll")] static extern uint WaitForSingleObject(IntPtr h, uint ms);
33
+ [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr h);
34
+ [DllImport("kernel32.dll")] static extern bool GetProcessTimes(IntPtr h, out long created, out long exited, out long kernel, out long user);
35
+ [DllImport("kernel32.dll")] static extern IntPtr CreateToolhelp32Snapshot(uint flags, uint pid);
36
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] static extern bool Process32FirstW(IntPtr s, ref PE e);
37
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] static extern bool Process32NextW(IntPtr s, ref PE e);
38
+
39
+ // PROCESS_TERMINATE | PROCESS_SET_QUOTA | PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE
40
+ const uint ACCESS = 0x1 | 0x100 | 0x1000 | 0x100000;
41
+
42
+ class Member { public IntPtr Handle; public long Created; }
43
+
44
+ static IntPtr job;
45
+ static int hostPid;
46
+ static long hostCreated;
47
+ static readonly Dictionary<int, Member> members = new Dictionary<int, Member>();
48
+
49
+ // The processes of the system now: pid and parent pid.
50
+ static List<int[]> Snapshot() {
51
+ List<int[]> rows = new List<int[]>();
52
+ IntPtr snap = CreateToolhelp32Snapshot(2, 0);
53
+ PE e = new PE();
54
+ e.size = (uint)Marshal.SizeOf(typeof(PE));
55
+ if (Process32FirstW(snap, ref e)) { do { rows.Add(new int[] { (int)e.pid, (int)e.ppid }); } while (Process32NextW(snap, ref e)); }
56
+ CloseHandle(snap);
57
+ return rows;
58
+ }
59
+
60
+ // Puts the process in the job, if it is not older than `notBefore` (the creation time of its parent). It keeps the handle.
61
+ static bool Adopt(int pid, long notBefore) {
62
+ IntPtr h = OpenProcess(ACCESS, false, pid);
63
+ if (h == IntPtr.Zero) return false;
64
+ long created, exited, kernel, user;
65
+ if (!GetProcessTimes(h, out created, out exited, out kernel, out user) || created < notBefore || WaitForSingleObject(h, 0) == 0 || !AssignProcessToJobObject(job, h)) {
66
+ CloseHandle(h);
67
+ return false;
68
+ }
69
+ Member m = new Member();
70
+ m.Handle = h;
71
+ m.Created = created;
72
+ members[pid] = m;
73
+ return true;
74
+ }
75
+
76
+ // A member whose process has exited is dropped, so its pid can never match a later process that reuses it.
77
+ static void Prune() {
78
+ List<int> gone = new List<int>();
79
+ foreach (KeyValuePair<int, Member> pair in members) if (WaitForSingleObject(pair.Value.Handle, 0) == 0) gone.Add(pair.Key);
80
+ foreach (int pid in gone) { CloseHandle(members[pid].Handle); members.Remove(pid); }
81
+ }
82
+
83
+ // The descendants of the members, by parent pid, each not older than its parent, until a pass finds none.
84
+ static int Sweep() {
85
+ int found = 0;
86
+ for (int pass = 0; pass < 8; pass++) {
87
+ Prune();
88
+ int before = found;
89
+ foreach (int[] r in Snapshot()) {
90
+ Member parent;
91
+ if (members.ContainsKey(r[0]) || !members.TryGetValue(r[1], out parent)) continue;
92
+ if (Adopt(r[0], parent.Created)) found++;
93
+ }
94
+ if (found == before) break;
95
+ }
96
+ return found;
97
+ }
98
+
99
+ // `guard <pid>`: only a process that the host started, which is its child by parent pid and not older than the host.
100
+ static bool Guard(int pid) {
101
+ foreach (int[] r in Snapshot()) if (r[0] == pid) return r[1] == hostPid && Adopt(pid, hostCreated);
102
+ return false;
103
+ }
104
+
105
+ public static int Main(string[] args) {
106
+ if (args.Length != 1 || !int.TryParse(args[0], out hostPid)) return 2;
107
+ job = CreateJobObjectW(IntPtr.Zero, IntPtr.Zero);
108
+ EXT limits = new EXT();
109
+ limits.Basic.LimitFlags = 0x2000 | 0x800; // KILL_ON_JOB_CLOSE, breakaway allowed
110
+ if (job == IntPtr.Zero || !SetInformationJobObject(job, 9, ref limits, (uint)Marshal.SizeOf(typeof(EXT)))) return 3;
111
+ IntPtr host = OpenProcess(0x100000 | 0x1000, false, hostPid);
112
+ long exited, kernel, user;
113
+ if (host == IntPtr.Zero || !GetProcessTimes(host, out hostCreated, out exited, out kernel, out user)) return 4;
114
+ Thread watch = new Thread(() => { WaitForSingleObject(host, 0xFFFFFFFF); Environment.Exit(0); });
115
+ watch.IsBackground = true;
116
+ watch.Start();
117
+ TextWriter output = Console.Out;
118
+ output.WriteLine("ready");
119
+ output.Flush();
120
+ string line;
121
+ while ((line = Console.In.ReadLine()) != null) {
122
+ int pid;
123
+ if (!line.StartsWith("guard ") || !int.TryParse(line.Substring(6), out pid) || pid <= 0) continue;
124
+ Prune();
125
+ bool ok = members.ContainsKey(pid) || Guard(pid);
126
+ int more = Sweep();
127
+ output.WriteLine("guarded:" + pid + ":" + ok + ":" + more);
128
+ output.Flush();
129
+ }
130
+ return 0; // the host closed our standard input: the job closes with this process
131
+ }
132
+ }
@@ -0,0 +1,184 @@
1
+ # The warm job helper of the Workspace tasks on Windows (issue #149). toolscript-mcp starts it with Windows PowerShell 5.1:
2
+ # powershell.exe -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -File task-job.ps1 <report pipe name>
3
+ # One helper serves many tasks. It compiles its C# class one time, then only hosts it. For each task the class makes a new
4
+ # Job Object (KILL_ON_JOB_CLOSE, no breakaway flag), starts the task suspended, puts it in the job, then resumes it. The
5
+ # helper is not in the job and holds the only handle of it, so the job ends when the helper dies, with every process in it.
6
+ #
7
+ # The values of a task never are in this file or in a command line. They come as frames on the standard input of the
8
+ # helper (4-byte length, UTF-8, fields with a NUL between them): file, command line, folder, the named pipe of stdout, the
9
+ # named pipe of stderr, then the environment as name and value pairs, used as they are. The helper reports on the named
10
+ # pipe of its argument, one line each: ready, begin, started:<pid>, error:<win32 code>, left:<n>, exit:<code>,
11
+ # failed:<step> (before `begin` only). A frame of length 0 ends the job of the running task. The helper writes nothing to
12
+ # its own streams, which are closed, and nothing to the task.
13
+
14
+ param([string]$Pipe)
15
+ $ErrorActionPreference = 'Stop'
16
+ $ProgressPreference = 'SilentlyContinue'
17
+ # No cmdlet runs in this file: the first one makes Windows PowerShell look up the command and load its module, which took
18
+ # 20 to 30 s on a runner that starts several PowerShell processes at once. Every step is a .NET call, also the compile.
19
+ # The pipe is connected first, so the host tells a slow compile from no start at all.
20
+ try {
21
+ $channel = [System.IO.Pipes.NamedPipeClientStream]::new('.', $Pipe, [System.IO.Pipes.PipeDirection]::Out)
22
+ $channel.Connect(5000)
23
+ $writer = [System.IO.StreamWriter]::new($channel, [System.Text.UTF8Encoding]::new($false))
24
+ $writer.AutoFlush = $true
25
+ } catch { exit 3 }
26
+ if ([IntPtr]::Size -ne 8) { $writer.Write("failed:bits`n"); exit 4 }
27
+ $source = @'
28
+ using System;
29
+ using System.Collections.Concurrent;
30
+ using System.IO.Pipes;
31
+ using System.Runtime.InteropServices;
32
+ using System.Text;
33
+ using System.Threading;
34
+
35
+ public static class TsHost {
36
+ [StructLayout(LayoutKind.Sequential)]
37
+ struct STARTUPINFO {
38
+ public int cb; public IntPtr r1, desktop, title; public int x, y, xs, ys, xc, yc, fill, flags;
39
+ public short show, r2; public IntPtr r3, hIn, hOut, hErr;
40
+ }
41
+ [StructLayout(LayoutKind.Sequential)] struct PROCESS_INFORMATION { public IntPtr hProcess, hThread; public int pid, tid; }
42
+ [StructLayout(LayoutKind.Sequential)] struct SECURITY_ATTRIBUTES { public int length; public IntPtr descriptor; public int inherit; }
43
+ [StructLayout(LayoutKind.Sequential)] struct BASIC { public long a, b; public uint LimitFlags; public UIntPtr c, d; public uint e; public UIntPtr f; public uint g, h; }
44
+ [StructLayout(LayoutKind.Sequential)] struct IOC { public ulong a, b, c, d, e, f; }
45
+ [StructLayout(LayoutKind.Sequential)] struct EXT { public BASIC Basic; public IOC Io; public UIntPtr p1, p2, p3, p4; }
46
+
47
+ [DllImport("kernel32.dll", SetLastError = true)] static extern IntPtr CreateJobObjectW(IntPtr a, IntPtr n);
48
+ [DllImport("kernel32.dll", SetLastError = true)] static extern bool SetInformationJobObject(IntPtr j, int c, ref EXT i, uint l);
49
+ [DllImport("kernel32.dll", SetLastError = true)] static extern bool AssignProcessToJobObject(IntPtr j, IntPtr p);
50
+ [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
51
+ static extern IntPtr CreateFileW(string name, uint access, uint share, ref SECURITY_ATTRIBUTES sa, uint disposition, uint flags, IntPtr template);
52
+ [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
53
+ static extern bool CreateProcessW(string app, StringBuilder line, IntPtr pa, IntPtr ta, bool inherit, uint flags,
54
+ byte[] env, string cwd, ref STARTUPINFO si, out PROCESS_INFORMATION pi);
55
+ [DllImport("kernel32.dll")] static extern uint ResumeThread(IntPtr t);
56
+ [DllImport("kernel32.dll")] static extern uint WaitForSingleObject(IntPtr h, uint ms);
57
+ [DllImport("kernel32.dll")] static extern bool GetExitCodeProcess(IntPtr h, out uint code);
58
+ [DllImport("kernel32.dll")] static extern bool TerminateProcess(IntPtr h, uint code);
59
+ [DllImport("kernel32.dll")] static extern bool TerminateJobObject(IntPtr j, uint code);
60
+ [StructLayout(LayoutKind.Sequential)] struct ACCOUNTING { public long a, b, c, d; public uint faults, total, active, terminated; }
61
+ [DllImport("kernel32.dll")] static extern bool QueryInformationJobObject(IntPtr j, int c, out ACCOUNTING i, uint l, IntPtr r);
62
+ [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr h);
63
+ [DllImport("kernel32.dll")] static extern IntPtr GetStdHandle(int which);
64
+ [DllImport("kernel32.dll", SetLastError = true)] static extern bool SetHandleInformation(IntPtr h, uint mask, uint flags);
65
+
66
+ static NamedPipeClientStream pipe;
67
+ static System.IO.Stream input;
68
+ static void Say(string line) { byte[] b = Encoding.UTF8.GetBytes(line + "\n"); pipe.Write(b, 0, b.Length); pipe.Flush(); }
69
+ static byte[] Take(int count) {
70
+ byte[] buffer = new byte[count];
71
+ for (int have = 0; have < count;) {
72
+ int n = input.Read(buffer, have, count - have);
73
+ if (n <= 0) Environment.Exit(6); // the host is gone
74
+ have += n;
75
+ }
76
+ return buffer;
77
+ }
78
+ static IntPtr Open(string name, uint access) {
79
+ SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
80
+ sa.length = Marshal.SizeOf(typeof(SECURITY_ATTRIBUTES));
81
+ sa.inherit = 1;
82
+ return CreateFileW(name, access, 3, ref sa, 3, 0, IntPtr.Zero);
83
+ }
84
+
85
+ // One thread reads the frames for the life of the helper, so a stop frame (length 0) reaches it while a task runs.
86
+ static readonly BlockingCollection<string[]> frames = new BlockingCollection<string[]>();
87
+ static readonly object gate = new object();
88
+ static IntPtr live = IntPtr.Zero; // the job of the running task
89
+ static int enqueued = 0, pendingFor = -1;
90
+ // Ends every process of the job and waits until none is alive (2 s at most): a report of the end means a tree that is
91
+ // gone. It gives the number of processes still alive.
92
+ static uint Reap(IntPtr job) {
93
+ ACCOUNTING info;
94
+ uint size = (uint)Marshal.SizeOf(typeof(ACCOUNTING));
95
+ bool killed = QueryInformationJobObject(job, 1, out info, size, IntPtr.Zero) && info.active > 0;
96
+ TerminateJobObject(job, 1);
97
+ for (int waited = 0; waited < 2000; waited += 10) {
98
+ if (!QueryInformationJobObject(job, 1, out info, size, IntPtr.Zero) || info.active == 0) break;
99
+ Thread.Sleep(10);
100
+ }
101
+ // A process that is gone can still hold its folder as its cwd for a few ms while Windows closes its handles (8 ms measured).
102
+ if (killed) Thread.Sleep(50);
103
+ return info.active;
104
+ }
105
+ static void Reader() {
106
+ for (;;) {
107
+ int size = BitConverter.ToInt32(Take(4), 0);
108
+ if (size == 0) {
109
+ lock (gate) { if (live != IntPtr.Zero) Reap(live); else pendingFor = enqueued; }
110
+ continue;
111
+ }
112
+ if (size < 0 || size > 4194304) Environment.Exit(6);
113
+ string[] fields = Encoding.UTF8.GetString(Take(size)).Split('\0');
114
+ lock (gate) { enqueued++; }
115
+ frames.Add(fields);
116
+ }
117
+ }
118
+
119
+ public static void Serve(NamedPipeClientStream connected) {
120
+ // No handle of the helper is inherited by a task: not the frame pipe on standard input, and not the other two.
121
+ foreach (int which in new int[] { -10, -11, -12 }) {
122
+ IntPtr h = GetStdHandle(which);
123
+ if (h != IntPtr.Zero && h != new IntPtr(-1)) SetHandleInformation(h, 1, 0);
124
+ }
125
+ input = Console.OpenStandardInput();
126
+ pipe = connected;
127
+ IntPtr bad = new IntPtr(-1);
128
+ Thread reader = new Thread(Reader);
129
+ reader.IsBackground = true;
130
+ reader.Start();
131
+ Say("ready");
132
+ for (int number = 1; ; number++) {
133
+ string[] parts = frames.Take();
134
+ if (parts.Length < 5) { Say("failed:frame"); Environment.Exit(4); }
135
+ IntPtr job = CreateJobObjectW(IntPtr.Zero, IntPtr.Zero);
136
+ EXT limits = new EXT();
137
+ limits.Basic.LimitFlags = 0x2000; // KILL_ON_JOB_CLOSE, and no breakaway flag
138
+ if (job == IntPtr.Zero || !SetInformationJobObject(job, 9, ref limits, (uint)Marshal.SizeOf(typeof(EXT)))) { Say("failed:job"); Environment.Exit(4); }
139
+ IntPtr nul = Open("NUL", 0x80000000), output = Open("\\\\.\\pipe\\" + parts[3], 0x40000000), error = Open("\\\\.\\pipe\\" + parts[4], 0x40000000);
140
+ if (nul == bad || output == bad || error == bad) { Say("failed:streams"); Environment.Exit(4); }
141
+ StringBuilder block = new StringBuilder();
142
+ for (int i = 5; i + 1 < parts.Length; i += 2) block.Append(parts[i]).Append('=').Append(parts[i + 1]).Append('\0');
143
+ block.Append('\0');
144
+ STARTUPINFO si = new STARTUPINFO();
145
+ si.cb = Marshal.SizeOf(typeof(STARTUPINFO));
146
+ si.flags = 0x100; // STARTF_USESTDHANDLES
147
+ si.hIn = nul; si.hOut = output; si.hErr = error;
148
+ PROCESS_INFORMATION pi;
149
+ // CREATE_SUSPENDED | CREATE_UNICODE_ENVIRONMENT | CREATE_NO_WINDOW: the task runs no code before it is in the job.
150
+ bool made = CreateProcessW(parts[0], new StringBuilder("\"" + parts[0] + "\" " + parts[1]), IntPtr.Zero, IntPtr.Zero, true, 0x08000404,
151
+ Encoding.Unicode.GetBytes(block.ToString()), parts[2], ref si, out pi);
152
+ int problem = Marshal.GetLastWin32Error();
153
+ CloseHandle(nul); CloseHandle(output); CloseHandle(error);
154
+ if (!made) { CloseHandle(job); Say("error:" + problem); continue; }
155
+ if (!AssignProcessToJobObject(job, pi.hProcess)) { TerminateProcess(pi.hProcess, 1); Say("failed:assign"); Environment.Exit(4); }
156
+ // A stop frame that came before the task was in the job ends it now; it ran no code yet.
157
+ lock (gate) { live = job; if (pendingFor == number) Reap(job); }
158
+ Say("begin");
159
+ ResumeThread(pi.hThread);
160
+ CloseHandle(pi.hThread);
161
+ Say("started:" + pi.pid);
162
+ WaitForSingleObject(pi.hProcess, 0xFFFFFFFF);
163
+ uint code;
164
+ GetExitCodeProcess(pi.hProcess, out code);
165
+ CloseHandle(pi.hProcess);
166
+ // Ends what the task left behind and waits until it is gone, so no process holds the streams or the folder of the task.
167
+ uint left;
168
+ lock (gate) { left = Reap(job); live = IntPtr.Zero; CloseHandle(job); }
169
+ if (left > 0) Say("left:" + left); // before exit: the exit report ends the channel
170
+ Say("exit:" + code);
171
+ }
172
+ }
173
+ }
174
+ '@
175
+ # The same csc compile that the Add-Type cmdlet runs, called as .NET.
176
+ try {
177
+ $options = [System.CodeDom.Compiler.CompilerParameters]::new()
178
+ $options.GenerateInMemory = $true
179
+ [void]$options.ReferencedAssemblies.Add('System.dll')
180
+ [void]$options.ReferencedAssemblies.Add('System.Core.dll')
181
+ $results = [Microsoft.CSharp.CSharpCodeProvider]::new().CompileAssemblyFromSource($options, $source)
182
+ if ($results.Errors.HasErrors) { throw 'compile' }
183
+ } catch { $writer.Write("failed:compile`n"); exit 4 }
184
+ try { [TsHost]::Serve($channel) } catch { exit 5 }
@@ -0,0 +1,141 @@
1
+ #!/usr/bin/perl
2
+ # The POSIX task helper (issue #149): /usr/bin/perl task-reap.pl <prctl number> <file> <arg>...
3
+ # No module is loaded on the path of a task: strict, warnings and Config cost 5 to 6 ms of the start (measured).
4
+ #
5
+ # fd 3 is a duplex socket to the host. In: one frame (4-byte big-endian length, then NAME=VALUE entries with NUL between
6
+ # them), the whole environment of the task. After it, the end of the socket or any byte is the order to stop (so are
7
+ # SIGTERM, SIGINT and SIGHUP). Out: one report on each line: begin, started:<pid> or error:<errno>, then exit:<code>,
8
+ # signal:<number> or stopped, and left:<count> when processes stayed. failed:<step> comes before begin only.
9
+ # Linux: the helper is the child subreaper, so no descendant can leave. macOS: the tree is the process group, the live
10
+ # ppid chain, and each process whose environment holds the marker TOOLSCRIPT_TASK. Nothing goes to the task streams.
11
+
12
+ my $linux = $^O eq 'linux';
13
+ open(my $ctl, '+<&=', 3) or exit 70;
14
+ $SIG{PIPE} = 'IGNORE';
15
+ sub report { syswrite($ctl, "$_[0]\n") }
16
+ sub failed { report("failed:$_[0]"); exit 0 }
17
+
18
+ # The helper never writes to the streams of the task: its own stderr goes nowhere, and the task gets the real one back.
19
+ open(my $stderr, '>&', \*STDERR) or failed('streams');
20
+ open(STDERR, '>', '/dev/null') or failed('streams');
21
+
22
+ my ($nr, $file, @args) = @ARGV;
23
+ defined $file or failed('usage');
24
+
25
+ sub need {
26
+ my ($want, $got) = ($_[0], '');
27
+ while (length($got) < $want) {
28
+ sysread($ctl, $got, $want - length($got), length($got)) or failed('frame');
29
+ }
30
+ return $got;
31
+ }
32
+ my $size = unpack('N', need(4));
33
+ $size <= 4 * 1024 * 1024 or failed('frame');
34
+ %ENV = ();
35
+ for my $entry (split /\0/, $size ? need($size) : '') {
36
+ my ($name, $value) = split /=/, $entry, 2;
37
+ $ENV{$name} = $value;
38
+ }
39
+
40
+ if ($linux) {
41
+ # prctl has no perl name without the kernel headers. The host sends its number: 157 on x86_64, 167 on aarch64.
42
+ $nr =~ /^(157|167)$/ or failed('arch');
43
+ # 36 is PR_SET_CHILD_SUBREAPER, 37 reads it back into an int.
44
+ syscall($nr, 36, 1, 0, 0, 0) == 0 or failed('subreaper');
45
+ my $got = "\0" x 8;
46
+ (syscall($nr, 37, $got, 0, 0, 0) == 0 && unpack('i', $got) == 1) or failed('subreaper');
47
+ }
48
+ my $mark = $ENV{TOOLSCRIPT_TASK};
49
+ !$linux && !defined $mark and failed('marker');
50
+
51
+ pipe(my $sr, my $sw) or failed('pipe');
52
+ pipe(my $er, my $ew) or failed('pipe');
53
+ $SIG{CHLD} = sub { syswrite($sw, 'c') };
54
+ $SIG{TERM} = $SIG{INT} = $SIG{HUP} = sub { syswrite($sw, 't') };
55
+
56
+ report('begin');
57
+ my $pid = fork();
58
+ if (!defined $pid) { report('error:' . ($! + 0)); exit 0 }
59
+ if ($pid == 0) {
60
+ # The task leads its own process group, as with a direct spawn: a signal to its group never reaches the helper.
61
+ setpgrp(0, 0);
62
+ $SIG{$_} = 'DEFAULT' for qw(CHLD TERM INT HUP PIPE);
63
+ close $ctl; close $er; close $sr; close $sw;
64
+ open(STDERR, '>&', $stderr);
65
+ exec { $file } $file, @args;
66
+ syswrite($ew, $! + 0);
67
+ require POSIX;
68
+ POSIX::_exit(127);
69
+ }
70
+ close $ew;
71
+ my $errno = '';
72
+ sysread($er, $errno, 16);
73
+ close $er;
74
+ if ($errno ne '') { waitpid($pid, 0); report("error:$errno"); exit 0 }
75
+ report("started:$pid");
76
+
77
+ my ($status, $stop);
78
+ until (defined $status || $stop) {
79
+ my $rin = '';
80
+ vec($rin, fileno($ctl), 1) = 1;
81
+ vec($rin, fileno($sr), 1) = 1;
82
+ my $n = select(my $rout = $rin, undef, undef, undef);
83
+ next if $n < 0;
84
+ if (vec($rout, fileno($sr), 1)) {
85
+ sysread($sr, my $woke, 4096);
86
+ $stop = 1 if $woke =~ /t/;
87
+ while ((my $p = waitpid(-1, 1)) > 0) { $status = $? if $p == $pid }
88
+ }
89
+ $stop = 1 if vec($rout, fileno($ctl), 1);
90
+ }
91
+
92
+ # The pids of the tree that still run, without this process.
93
+ sub tree {
94
+ my (%kids, %state, @out);
95
+ if ($linux) {
96
+ opendir(my $d, '/proc') or return;
97
+ for my $p (grep { /^\d+$/ } readdir $d) {
98
+ open(my $f, '<', "/proc/$p/stat") or next;
99
+ my $line = <$f>;
100
+ close $f;
101
+ defined $line && $line =~ /^\d+ \(.*\) (\S) (\d+) /s or next;
102
+ $state{$p} = $1;
103
+ push @{ $kids{$2} }, $p;
104
+ }
105
+ my @todo = @{ $kids{$$} || [] };
106
+ while (defined(my $p = shift @todo)) {
107
+ push @out, $p if $state{$p} ne 'Z';
108
+ push @todo, @{ $kids{$p} || [] };
109
+ }
110
+ return @out;
111
+ }
112
+ my $ps = open(my $f, '-|', '/bin/ps', '-axEww', '-o', 'pid=,ppid=,pgid=,command=') or return;
113
+ my (%hit, %all);
114
+ while (my $line = <$f>) {
115
+ $line =~ /^\s*(\d+)\s+(\d+)\s+(\d+)\s(.*)$/s or next;
116
+ next if $1 == $$ || $1 == $ps;
117
+ $all{$1} = 1;
118
+ push @{ $kids{$2} }, $1;
119
+ $hit{$1} = 1 if $3 == $pid || index($4, " TOOLSCRIPT_TASK=$mark") >= 0;
120
+ }
121
+ close $f;
122
+ my @todo = @{ $kids{$$} || [] };
123
+ while (defined(my $p = shift @todo)) { $hit{$p} = 1; push @todo, @{ $kids{$p} || [] } }
124
+ return grep { $all{$_} } keys %hit;
125
+ }
126
+
127
+ my $left = 0;
128
+ for my $round (1 .. 400) {
129
+ my $w;
130
+ while (($w = waitpid(-1, 1)) > 0) { $status = $? if $w == $pid && !$stop }
131
+ # Linux: each process that is left is a child of this one, or under one. No child means that nothing is left.
132
+ if ($linux && $w < 0) { $left = 0; last }
133
+ my @pids = tree();
134
+ $left = @pids;
135
+ last if !$left;
136
+ kill 'KILL', @pids;
137
+ select(undef, undef, undef, 0.005);
138
+ }
139
+ report(!defined $status ? 'stopped' : $status & 127 ? 'signal:' . ($status & 127) : 'exit:' . ($status >> 8));
140
+ report("left:$left") if $left;
141
+ exit 0;