win-nice 0.1.0 → 0.2.0
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/CHANGELOG.md +141 -0
- package/README.md +309 -41
- package/bin/abovenormal +11 -11
- package/bin/abovenormal.bat +2 -2
- package/bin/abovenormal.ps1 +38 -10
- package/bin/admin +11 -11
- package/bin/admin.bat +2 -2
- package/bin/admin.ps1 +52 -13
- package/bin/belownormal +11 -11
- package/bin/belownormal.bat +2 -2
- package/bin/belownormal.ps1 +38 -10
- package/bin/{cap → capc} +11 -11
- package/bin/{cap.bat → capc.bat} +3 -3
- package/bin/capc.ps1 +432 -0
- package/bin/{pint → capm} +11 -11
- package/bin/capm.bat +12 -0
- package/bin/capm.ps1 +506 -0
- package/bin/capn +11 -0
- package/bin/capn.bat +8 -0
- package/bin/capn.ps1 +426 -0
- package/bin/caps +11 -0
- package/bin/caps.bat +10 -0
- package/bin/caps.ps1 +589 -0
- package/bin/capt +11 -0
- package/bin/capt.bat +8 -0
- package/bin/capt.ps1 +449 -0
- package/bin/cx +11 -11
- package/bin/cx.bat +1 -1
- package/bin/cx.ps1 +38 -10
- package/bin/cy +11 -11
- package/bin/cy.bat +1 -1
- package/bin/cy.ps1 +38 -10
- package/bin/high +11 -11
- package/bin/high.bat +2 -2
- package/bin/high.ps1 +38 -10
- package/bin/idle +11 -11
- package/bin/idle.bat +2 -2
- package/bin/idle.ps1 +38 -10
- package/bin/realtime +11 -11
- package/bin/realtime.bat +2 -2
- package/bin/realtime.ps1 +38 -10
- package/bin/uiup +11 -11
- package/bin/uiup.bat +1 -1
- package/bin/uiup.ps1 +2 -1
- package/install/install.js +30 -15
- package/install/paths.js +28 -2
- package/install/skill.js +25 -1
- package/install/uninstall.js +11 -0
- package/package.json +7 -3
- package/skills/win-nice/SKILL.md +107 -12
- package/bin/cap.ps1 +0 -269
- package/bin/pint.bat +0 -8
- package/bin/pint.ps1 +0 -270
package/bin/capn.ps1
ADDED
|
@@ -0,0 +1,426 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
2
|
+
# win-nice: managed-file
|
|
3
|
+
# Deliberately no param()/[CmdletBinding()]: a declared parameter name (even
|
|
4
|
+
# without a [Parameter()] attribute) can still be ambiguously prefix-matched by
|
|
5
|
+
# flags meant for the wrapped command (e.g. "-c" matching "-Count"). Reading
|
|
6
|
+
# everything from $args sidesteps PowerShell's parameter binder entirely.
|
|
7
|
+
$usage = "usage: capn <count> <command> [args...] (count: positive whole number, " +
|
|
8
|
+
"minimum 1; maximum 4294967295, because ActiveProcessLimit is a uint32 struct " +
|
|
9
|
+
"field - there is no smaller natural bound the way capt's thread-count has)"
|
|
10
|
+
|
|
11
|
+
if ($args.Count -lt 2) {
|
|
12
|
+
Write-Error $usage
|
|
13
|
+
exit 1
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
$countArg = $args[0]
|
|
17
|
+
# TryParse, not a raw [int]/[uint32] cast: an arbitrarily long digit string (a
|
|
18
|
+
# usage mistake, not an attack) overflows a plain cast with a raw, unhandled
|
|
19
|
+
# PowerShell conversion error (path/line number and all) - TryParse fails
|
|
20
|
+
# cleanly instead, so every invalid <count> hits the same single usage message
|
|
21
|
+
# regardless of why it's invalid. (Same reason capm.ps1/caps.ps1 document for
|
|
22
|
+
# their own arguments.) [uint32], not [int]: ActiveProcessLimit is a uint32
|
|
23
|
+
# struct field and there is no other natural maximum here, so the type's own
|
|
24
|
+
# range IS the validation - anything above 4294967295 (or negative, or
|
|
25
|
+
# non-numeric) must be rejected as the usage error it is, never silently
|
|
26
|
+
# wrapped/truncated into a different limit.
|
|
27
|
+
$countValue = [uint32]0
|
|
28
|
+
if (-not [uint32]::TryParse($countArg, [ref]$countValue) -or $countValue -lt 1) {
|
|
29
|
+
Write-Error $usage
|
|
30
|
+
exit 1
|
|
31
|
+
}
|
|
32
|
+
$Command = @($args[1..($args.Count - 1)])
|
|
33
|
+
|
|
34
|
+
# Fallback command line for when the target isn't a directly-launchable .exe (see
|
|
35
|
+
# CapnLauncher.Run below) - re-parsed by cmd.exe (via "cmd.exe /c"), so quoting must
|
|
36
|
+
# neutralize its operators (&|<>^) and not just whitespace - see capc.ps1 for the
|
|
37
|
+
# same logic and its documented "%" limitation.
|
|
38
|
+
$commandLine = ($Command | ForEach-Object {
|
|
39
|
+
$escaped = $_ -replace '"', '\"'
|
|
40
|
+
if ($escaped -eq '' -or $escaped -match '[\s"&|<>^]') { '"' + $escaped + '"' } else { $escaped }
|
|
41
|
+
}) -join ' '
|
|
42
|
+
|
|
43
|
+
$source = @"
|
|
44
|
+
using System;
|
|
45
|
+
using System.Runtime.InteropServices;
|
|
46
|
+
using System.Text;
|
|
47
|
+
|
|
48
|
+
public static class CapnLauncher
|
|
49
|
+
{
|
|
50
|
+
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
|
51
|
+
struct STARTUPINFO
|
|
52
|
+
{
|
|
53
|
+
public int cb;
|
|
54
|
+
public string lpReserved;
|
|
55
|
+
public string lpDesktop;
|
|
56
|
+
public string lpTitle;
|
|
57
|
+
public int dwX;
|
|
58
|
+
public int dwY;
|
|
59
|
+
public int dwXSize;
|
|
60
|
+
public int dwYSize;
|
|
61
|
+
public int dwXCountChars;
|
|
62
|
+
public int dwYCountChars;
|
|
63
|
+
public int dwFillAttribute;
|
|
64
|
+
public int dwFlags;
|
|
65
|
+
public short wShowWindow;
|
|
66
|
+
public short cbReserved2;
|
|
67
|
+
public IntPtr lpReserved2;
|
|
68
|
+
public IntPtr hStdInput;
|
|
69
|
+
public IntPtr hStdOutput;
|
|
70
|
+
public IntPtr hStdError;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
74
|
+
struct PROCESS_INFORMATION
|
|
75
|
+
{
|
|
76
|
+
public IntPtr hProcess;
|
|
77
|
+
public IntPtr hThread;
|
|
78
|
+
public int dwProcessId;
|
|
79
|
+
public int dwThreadId;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
83
|
+
struct JOBOBJECT_BASIC_LIMIT_INFORMATION
|
|
84
|
+
{
|
|
85
|
+
public long PerProcessUserTimeLimit;
|
|
86
|
+
public long PerJobUserTimeLimit;
|
|
87
|
+
public uint LimitFlags;
|
|
88
|
+
public UIntPtr MinimumWorkingSetSize;
|
|
89
|
+
public UIntPtr MaximumWorkingSetSize;
|
|
90
|
+
public uint ActiveProcessLimit;
|
|
91
|
+
public UIntPtr Affinity;
|
|
92
|
+
public uint PriorityClass;
|
|
93
|
+
public uint SchedulingClass;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
97
|
+
struct IO_COUNTERS
|
|
98
|
+
{
|
|
99
|
+
public ulong ReadOperationCount;
|
|
100
|
+
public ulong WriteOperationCount;
|
|
101
|
+
public ulong OtherOperationCount;
|
|
102
|
+
public ulong ReadTransferCount;
|
|
103
|
+
public ulong WriteTransferCount;
|
|
104
|
+
public ulong OtherTransferCount;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
108
|
+
struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION
|
|
109
|
+
{
|
|
110
|
+
public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation;
|
|
111
|
+
public IO_COUNTERS IoInfo;
|
|
112
|
+
public UIntPtr ProcessMemoryLimit;
|
|
113
|
+
public UIntPtr JobMemoryLimit;
|
|
114
|
+
public UIntPtr PeakProcessMemoryUsed;
|
|
115
|
+
public UIntPtr PeakJobMemoryUsed;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
|
|
119
|
+
static extern bool CreateProcess(string lpApplicationName, StringBuilder lpCommandLine,
|
|
120
|
+
IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool bInheritHandles,
|
|
121
|
+
uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory,
|
|
122
|
+
ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
|
|
123
|
+
|
|
124
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
125
|
+
static extern IntPtr CreateJobObject(IntPtr lpJobAttributes, string lpName);
|
|
126
|
+
|
|
127
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
128
|
+
static extern bool SetInformationJobObject(IntPtr hJob, int JobObjectInfoClass, IntPtr lpJobObjectInfo, uint cbJobObjectInfoLength);
|
|
129
|
+
|
|
130
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
131
|
+
static extern bool AssignProcessToJobObject(IntPtr hJob, IntPtr hProcess);
|
|
132
|
+
|
|
133
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
134
|
+
static extern uint ResumeThread(IntPtr hThread);
|
|
135
|
+
|
|
136
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
137
|
+
static extern uint WaitForSingleObject(IntPtr hHandle, uint dwMilliseconds);
|
|
138
|
+
|
|
139
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
140
|
+
static extern bool GetExitCodeProcess(IntPtr hProcess, out uint lpExitCode);
|
|
141
|
+
|
|
142
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
143
|
+
static extern bool TerminateProcess(IntPtr hProcess, uint uExitCode);
|
|
144
|
+
|
|
145
|
+
[DllImport("kernel32.dll")]
|
|
146
|
+
static extern bool CloseHandle(IntPtr hObject);
|
|
147
|
+
|
|
148
|
+
const uint CREATE_SUSPENDED = 0x00000004;
|
|
149
|
+
const int JobObjectExtendedLimitInformation = 9;
|
|
150
|
+
// JOB_OBJECT_LIMIT_ACTIVE_PROCESS: ceiling on the number of SIMULTANEOUSLY
|
|
151
|
+
// ACTIVE processes in the job. Hex value verified two ways: Microsoft
|
|
152
|
+
// Learn's JOBOBJECT_BASIC_LIMIT_INFORMATION page (winnt.h) documents
|
|
153
|
+
// 0x00000008, and empirically - with ONLY this flag set plus a plausible
|
|
154
|
+
// ActiveProcessLimit, an over-limit spawn attempt fails, while the same
|
|
155
|
+
// ActiveProcessLimit value with a different flag bit
|
|
156
|
+
// (JOB_OBJECT_LIMIT_AFFINITY, 0x00000010) does not restrict spawning.
|
|
157
|
+
const uint JOB_OBJECT_LIMIT_ACTIVE_PROCESS = 0x00000008;
|
|
158
|
+
const uint JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x00002000;
|
|
159
|
+
|
|
160
|
+
// Standard MSVCRT/CommandLineToArgvW quoting: safe for a directly-launched .exe's
|
|
161
|
+
// own argv parsing. No cmd.exe involved on this path, so none of its operator or
|
|
162
|
+
// "%" expansion semantics apply - this is the safe path, used whenever possible.
|
|
163
|
+
static string ArgvQuote(string arg)
|
|
164
|
+
{
|
|
165
|
+
if (arg.Length > 0 && arg.IndexOfAny(new char[] { ' ', '\t', '\n', '\v', '"' }) < 0)
|
|
166
|
+
return arg;
|
|
167
|
+
|
|
168
|
+
var result = new StringBuilder();
|
|
169
|
+
result.Append('"');
|
|
170
|
+
int backslashes = 0;
|
|
171
|
+
foreach (char c in arg)
|
|
172
|
+
{
|
|
173
|
+
if (c == '\\')
|
|
174
|
+
{
|
|
175
|
+
backslashes++;
|
|
176
|
+
}
|
|
177
|
+
else if (c == '"')
|
|
178
|
+
{
|
|
179
|
+
result.Append('\\', backslashes * 2 + 1);
|
|
180
|
+
result.Append('"');
|
|
181
|
+
backslashes = 0;
|
|
182
|
+
}
|
|
183
|
+
else
|
|
184
|
+
{
|
|
185
|
+
if (backslashes > 0) { result.Append('\\', backslashes); backslashes = 0; }
|
|
186
|
+
result.Append(c);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
if (backslashes > 0) result.Append('\\', backslashes * 2);
|
|
190
|
+
result.Append('"');
|
|
191
|
+
return result.ToString();
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
static string BuildArgvCommandLine(string[] argv)
|
|
195
|
+
{
|
|
196
|
+
var parts = new string[argv.Length];
|
|
197
|
+
for (int i = 0; i < argv.Length; i++) parts[i] = ArgvQuote(argv[i]);
|
|
198
|
+
return string.Join(" ", parts);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
public static int Run(uint activeProcessLimit, string[] argv, string cmdExeCommandLine)
|
|
202
|
+
{
|
|
203
|
+
IntPtr hJob = CreateJobObject(IntPtr.Zero, null);
|
|
204
|
+
if (hJob == IntPtr.Zero)
|
|
205
|
+
throw new InvalidOperationException("CreateJobObject failed: " + Marshal.GetLastWin32Error());
|
|
206
|
+
|
|
207
|
+
// Single owner for every handle this method acquires. The finally below closes
|
|
208
|
+
// hThread/hProcess/hJob - in that order - on EVERY way out: normal return, any
|
|
209
|
+
// of the InvalidOperationExceptions thrown here, and an unexpected managed
|
|
210
|
+
// exception (allocation/marshalling failure) between acquisition and use.
|
|
211
|
+
// hProcess/hThread stay IntPtr.Zero until CreateProcess has actually succeeded,
|
|
212
|
+
// so each handle is closed exactly once and only if it was really acquired.
|
|
213
|
+
IntPtr hProcess = IntPtr.Zero;
|
|
214
|
+
IntPtr hThread = IntPtr.Zero;
|
|
215
|
+
try
|
|
216
|
+
{
|
|
217
|
+
// KILL_ON_JOB_CLOSE: the cleanup in the finally below only runs if this
|
|
218
|
+
// launcher process survives to execute it. Killed from outside (taskkill
|
|
219
|
+
// without /T, a crash), nothing in-process ever runs - without this flag
|
|
220
|
+
// the last job handle dying with the process would leave every process
|
|
221
|
+
// still assigned to the job running on, untracked and unmanaged. With
|
|
222
|
+
// it, Windows itself terminates the whole job at that moment.
|
|
223
|
+
//
|
|
224
|
+
// A backstop only, never the normal exit mechanism: the last handle
|
|
225
|
+
// closing terminates every process still assigned to the job FOR ANY
|
|
226
|
+
// reason, including this wrapper's own orderly close in the finally -
|
|
227
|
+
// and the wait below only waits on the directly wrapped root process,
|
|
228
|
+
// so a daemon it spawned and left running can still be in the job at
|
|
229
|
+
// that point, the root long gone. Killing a daemon on a SUCCESSFUL
|
|
230
|
+
// exit would break the documented daemon-survival contract (README:
|
|
231
|
+
// the process-count ceiling sticks to any daemon the wrapped command
|
|
232
|
+
// leaves running, for that daemon's whole lifetime), so the success
|
|
233
|
+
// path below clears this flag first - see capc.ps1 for the full
|
|
234
|
+
// write-up.
|
|
235
|
+
// Set via the EXTENDED info class: JobObjectBasicLimitInformation
|
|
236
|
+
// rejects this flag with ERROR_INVALID_PARAMETER.
|
|
237
|
+
// ACTIVE_PROCESS: exceeding it is neither a kill nor a throttle -
|
|
238
|
+
// the offending spawn attempt itself is the thing that fails
|
|
239
|
+
// (CreateProcess returns failure for a child that would push the
|
|
240
|
+
// count past ActiveProcessLimit, in the same spirit as capm's
|
|
241
|
+
// failed allocation, not capc's silent throttling). The directly
|
|
242
|
+
// wrapped process occupies one slot on its own: it is assigned to
|
|
243
|
+
// the still-empty job before it can spawn anything, so "capn 1
|
|
244
|
+
// <command>" runs the command but makes its very first child-spawn
|
|
245
|
+
// attempt fail while the command itself keeps running (confirmed
|
|
246
|
+
// empirically: with limit 1, a wrapped PowerShell's Start-Process
|
|
247
|
+
// failed with "Not enough quota is available to process this
|
|
248
|
+
// command." and the parent went on to run and exit 0).
|
|
249
|
+
var extInfo = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION
|
|
250
|
+
{
|
|
251
|
+
BasicLimitInformation = new JOBOBJECT_BASIC_LIMIT_INFORMATION
|
|
252
|
+
{
|
|
253
|
+
LimitFlags = JOB_OBJECT_LIMIT_ACTIVE_PROCESS | JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
|
|
254
|
+
ActiveProcessLimit = activeProcessLimit
|
|
255
|
+
}
|
|
256
|
+
};
|
|
257
|
+
int size = Marshal.SizeOf(extInfo);
|
|
258
|
+
IntPtr ptr = Marshal.AllocHGlobal(size);
|
|
259
|
+
bool ok;
|
|
260
|
+
try
|
|
261
|
+
{
|
|
262
|
+
Marshal.StructureToPtr(extInfo, ptr, false);
|
|
263
|
+
ok = SetInformationJobObject(hJob, JobObjectExtendedLimitInformation, ptr, (uint)size);
|
|
264
|
+
}
|
|
265
|
+
finally
|
|
266
|
+
{
|
|
267
|
+
Marshal.FreeHGlobal(ptr);
|
|
268
|
+
}
|
|
269
|
+
if (!ok)
|
|
270
|
+
throw new InvalidOperationException("SetInformationJobObject failed: " + Marshal.GetLastWin32Error());
|
|
271
|
+
|
|
272
|
+
var si = new STARTUPINFO();
|
|
273
|
+
si.cb = Marshal.SizeOf(si);
|
|
274
|
+
PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
|
|
275
|
+
|
|
276
|
+
// See capc.ps1 for why .bat/.cmd targets skip the direct attempt entirely:
|
|
277
|
+
// CreateProcess silently re-invokes them through cmd.exe on its own, using
|
|
278
|
+
// unescaped text, instead of failing the way a genuinely missing exe would.
|
|
279
|
+
bool isBatOrCmd = argv.Length > 0 && (
|
|
280
|
+
argv[0].EndsWith(".bat", StringComparison.OrdinalIgnoreCase) ||
|
|
281
|
+
argv[0].EndsWith(".cmd", StringComparison.OrdinalIgnoreCase));
|
|
282
|
+
|
|
283
|
+
bool created = false;
|
|
284
|
+
if (!isBatOrCmd)
|
|
285
|
+
{
|
|
286
|
+
var directCommandLine = new StringBuilder(BuildArgvCommandLine(argv));
|
|
287
|
+
created = CreateProcess(null, directCommandLine, IntPtr.Zero, IntPtr.Zero, true,
|
|
288
|
+
CREATE_SUSPENDED, IntPtr.Zero, null, ref si, out pi);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
if (!created)
|
|
292
|
+
{
|
|
293
|
+
// Falling back to cmd.exe /c: a literal "%" in any argument could now
|
|
294
|
+
// trigger environment-variable expansion (cmd.exe pairs up "%" characters
|
|
295
|
+
// across the whole command line, even across separate arguments) and
|
|
296
|
+
// change what actually runs. Fail loudly here instead of silently risking
|
|
297
|
+
// that - there's no reliable per-character escape for "%" at this level.
|
|
298
|
+
foreach (var a in argv)
|
|
299
|
+
{
|
|
300
|
+
if (a.IndexOf('%') >= 0)
|
|
301
|
+
throw new InvalidOperationException(
|
|
302
|
+
"Refusing to run: argument contains '%' and the target needs the cmd.exe " +
|
|
303
|
+
"fallback (not a directly-launchable .exe), where '%' can trigger unintended " +
|
|
304
|
+
"environment-variable expansion. See README's Argument handling section.");
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
string cmdExe = Environment.SystemDirectory + "\\cmd.exe";
|
|
308
|
+
// /d: skip HKCU AutoRun (user-writable registry key). /v:off: disable delayed
|
|
309
|
+
// expansion so "!var!" in an argument can't be expanded. /s plus the extra outer
|
|
310
|
+
// quote pair: cmd's /S rule strips exactly that outer pair and leaves the rest of
|
|
311
|
+
// the string untouched - without /S, cmd strips the first and last quote of the
|
|
312
|
+
// whole line instead, which breaks quoting whenever the target path itself needs
|
|
313
|
+
// quotes AND another argument is also quoted.
|
|
314
|
+
var shellCommandLine = new StringBuilder("\"" + cmdExe + "\" /d /v:off /s /c \"" + cmdExeCommandLine + "\"");
|
|
315
|
+
created = CreateProcess(null, shellCommandLine, IntPtr.Zero, IntPtr.Zero, true,
|
|
316
|
+
CREATE_SUSPENDED, IntPtr.Zero, null, ref si, out pi);
|
|
317
|
+
if (!created)
|
|
318
|
+
throw new InvalidOperationException("CreateProcess failed: " + Marshal.GetLastWin32Error());
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
// Ownership of the child's handles transfers here, once CreateProcess has
|
|
322
|
+
// actually succeeded - from this point the finally below is what closes them.
|
|
323
|
+
hProcess = pi.hProcess;
|
|
324
|
+
hThread = pi.hThread;
|
|
325
|
+
|
|
326
|
+
if (!AssignProcessToJobObject(hJob, hProcess))
|
|
327
|
+
{
|
|
328
|
+
// Can't guarantee the limit - kill instead of letting it run uncapped and orphaned.
|
|
329
|
+
int err = Marshal.GetLastWin32Error();
|
|
330
|
+
string message = "AssignProcessToJobObject failed: " + err;
|
|
331
|
+
// Report if the best-effort kill itself also failed.
|
|
332
|
+
if (!TerminateProcess(hProcess, 1))
|
|
333
|
+
message += "; TerminateProcess also failed: " + Marshal.GetLastWin32Error();
|
|
334
|
+
throw new InvalidOperationException(message);
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
if (ResumeThread(hThread) == 0xFFFFFFFF)
|
|
338
|
+
{
|
|
339
|
+
// Still suspended - an unbounded wait below would hang forever. Kill
|
|
340
|
+
// it instead of leaving an orphaned, permanently-suspended process.
|
|
341
|
+
int resumeErr = Marshal.GetLastWin32Error();
|
|
342
|
+
string message = "ResumeThread failed: " + resumeErr;
|
|
343
|
+
// Report if the best-effort kill itself also failed.
|
|
344
|
+
if (!TerminateProcess(hProcess, 1))
|
|
345
|
+
message += "; TerminateProcess also failed: " + Marshal.GetLastWin32Error();
|
|
346
|
+
throw new InvalidOperationException(message);
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
if (WaitForSingleObject(hProcess, 0xFFFFFFFF) == 0xFFFFFFFF)
|
|
350
|
+
{
|
|
351
|
+
// The child's actual state is unknown here - don't just report
|
|
352
|
+
// failure and potentially leave it running unmanaged in the
|
|
353
|
+
// background. Best-effort kill before giving up.
|
|
354
|
+
int waitErr = Marshal.GetLastWin32Error();
|
|
355
|
+
string message = "WaitForSingleObject failed: " + waitErr;
|
|
356
|
+
// Report if the best-effort kill itself also failed.
|
|
357
|
+
if (!TerminateProcess(hProcess, 1))
|
|
358
|
+
message += "; TerminateProcess also failed: " + Marshal.GetLastWin32Error();
|
|
359
|
+
throw new InvalidOperationException(message);
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
uint exitCode;
|
|
363
|
+
if (!GetExitCodeProcess(hProcess, out exitCode))
|
|
364
|
+
throw new InvalidOperationException("GetExitCodeProcess failed: " + Marshal.GetLastWin32Error());
|
|
365
|
+
|
|
366
|
+
// Normal success: the root process finished - release the
|
|
367
|
+
// kill-on-close backstop so the finally below closes hJob WITHOUT
|
|
368
|
+
// terminating anything still assigned to the job (the documented
|
|
369
|
+
// daemon-survival contract: the process-count ceiling keeps
|
|
370
|
+
// applying to whatever the command left running, it just outlives
|
|
371
|
+
// this wrapper's handle). Deliberately best-effort, not a throw:
|
|
372
|
+
// the wrapped command succeeded, and a failed cleanup syscall must
|
|
373
|
+
// not turn its real exit code below into a wrapper error - warn on
|
|
374
|
+
// stderr instead. Same struct and field values as the original set
|
|
375
|
+
// above, minus the kill-on-close bit, so the daemon keeps its
|
|
376
|
+
// process-count ceiling.
|
|
377
|
+
var releaseInfo = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION
|
|
378
|
+
{
|
|
379
|
+
BasicLimitInformation = new JOBOBJECT_BASIC_LIMIT_INFORMATION
|
|
380
|
+
{
|
|
381
|
+
LimitFlags = JOB_OBJECT_LIMIT_ACTIVE_PROCESS,
|
|
382
|
+
ActiveProcessLimit = activeProcessLimit
|
|
383
|
+
}
|
|
384
|
+
};
|
|
385
|
+
int releaseSize = Marshal.SizeOf(releaseInfo);
|
|
386
|
+
IntPtr releasePtr = Marshal.AllocHGlobal(releaseSize);
|
|
387
|
+
bool releaseOk;
|
|
388
|
+
int releaseErr = 0;
|
|
389
|
+
try
|
|
390
|
+
{
|
|
391
|
+
Marshal.StructureToPtr(releaseInfo, releasePtr, false);
|
|
392
|
+
releaseOk = SetInformationJobObject(hJob, JobObjectExtendedLimitInformation, releasePtr, (uint)releaseSize);
|
|
393
|
+
// Capture the Win32 error immediately, before any other call can
|
|
394
|
+
// overwrite it - every other native failure branch in this file
|
|
395
|
+
// reports the code for the same diagnosability reason.
|
|
396
|
+
if (!releaseOk)
|
|
397
|
+
releaseErr = Marshal.GetLastWin32Error();
|
|
398
|
+
}
|
|
399
|
+
finally
|
|
400
|
+
{
|
|
401
|
+
Marshal.FreeHGlobal(releasePtr);
|
|
402
|
+
}
|
|
403
|
+
if (!releaseOk)
|
|
404
|
+
Console.Error.WriteLine("warning: could not release the job's kill-on-close guard (SetInformationJobObject failed with Win32 error " + releaseErr + ") - a still-running background process left by the wrapped command may be terminated when this wrapper exits");
|
|
405
|
+
|
|
406
|
+
return (int)exitCode;
|
|
407
|
+
}
|
|
408
|
+
finally
|
|
409
|
+
{
|
|
410
|
+
// Same order as the code this replaces: thread handle, process handle, job handle.
|
|
411
|
+
if (hThread != IntPtr.Zero) CloseHandle(hThread);
|
|
412
|
+
if (hProcess != IntPtr.Zero) CloseHandle(hProcess);
|
|
413
|
+
if (hJob != IntPtr.Zero) CloseHandle(hJob);
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
"@
|
|
418
|
+
|
|
419
|
+
Add-Type -TypeDefinition $source -Language CSharp
|
|
420
|
+
|
|
421
|
+
try {
|
|
422
|
+
exit ([CapnLauncher]::Run($countValue, [string[]]$Command, $commandLine))
|
|
423
|
+
} catch {
|
|
424
|
+
Write-Error $_.Exception.InnerException.Message
|
|
425
|
+
exit 1
|
|
426
|
+
}
|
package/bin/caps
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
#!/bin/sh
|
|
2
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
3
|
+
# win-nice: managed-file
|
|
4
|
+
# Git Bash ignores PATHEXT for bare-name resolution; this shim covers that shell.
|
|
5
|
+
# MSYS2_ARG_CONV_EXCL='*' stops Git Bash/MSYS from rewriting user arguments
|
|
6
|
+
# (e.g. /c, /d, C:\...) into Windows paths before the exec; the shim's own
|
|
7
|
+
# .ps1 path is converted explicitly with cygpath -w so -File gets a Windows path.
|
|
8
|
+
MSYS2_ARG_CONV_EXCL='*'
|
|
9
|
+
export MSYS2_ARG_CONV_EXCL
|
|
10
|
+
script=$(cygpath -w "$(dirname "$0")/caps.ps1" 2>/dev/null) || script="$(dirname "$0")/caps.ps1"
|
|
11
|
+
exec powershell -NoProfile -ExecutionPolicy Bypass -File "$script" "$@"
|
package/bin/caps.bat
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
@echo off
|
|
2
|
+
:: SPDX-License-Identifier: MIT OR Apache-2.0
|
|
3
|
+
:: win-nice: managed-file
|
|
4
|
+
:: A literal "%" in any argument gets corrupted here (cmd.exe rescans %1/%* for
|
|
5
|
+
:: %...% patterns the moment a batch file reads them - confirmed with nothing more
|
|
6
|
+
:: than a bare "echo %1", no forwarding involved; there's no per-character escape
|
|
7
|
+
:: for this from inside a .bat). Every other cmd.exe metacharacter (&|<>^) survives
|
|
8
|
+
:: this hop untouched. Invoking "caps" bare from an actual PowerShell session skips
|
|
9
|
+
:: this file entirely (PowerShell prefers caps.ps1) and has no "%" problem at all.
|
|
10
|
+
"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -ExecutionPolicy Bypass -File "%~dp0caps.ps1" %*
|