Repository navigation
Expand file tree
/
Copy pathParallelKit.ps1
More file actions
4043 lines (3800 loc) · 214 KB
/
Copy pathParallelKit.ps1
File metadata and controls
4043 lines (3800 loc) · 214 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
# ParallelKit - parallel runspace jobs, bounded external-process dispatch, and
# graceful Ctrl+C/window-close handling for Windows PowerShell 5.1 and
# PowerShell 7.
#
# Version 3.4 - https://github.com/HalRiveria/PowerShell-ParallelKit
# (Initialize-ParallelKit reports the version too: change both together.)
# Copyright (c) 2026 HalRiveria. MIT License: keep this notice with any copy;
# the full text is in LICENSE in the repository.
#
# Use: . "<path>\ParallelKit.ps1" (dot-source it; it loads itself as an in-memory module)
# Read README.md first: its two worker-code rules are what keep this from
# hanging or crashing.
#
# Works under Set-StrictMode: read job hashtables as $job['Name'], never
# $job.Name, which throws there for a key that isn't set yet. State lives in
# the static [PkState] class, never in $script: variables: a function called
# from a .GetNewClosure() block can see an empty $script: scope.
# Add-Type needs FullLanguage: say so, rather than fail on Add-Type's error.
if ($ExecutionContext.SessionState.LanguageMode -ne 'FullLanguage') {
throw ("ParallelKit: this PowerShell session runs in " + $ExecutionContext.SessionState.LanguageMode + " mode, but the kit needs FullLanguage " +
"(it compiles C# with Add-Type). This is usually set by AppLocker or Windows Defender Application Control policy. " +
"Ask whoever manages the machine to allow this script, or run it where that policy doesn't apply.")
}
# Loads as an in-memory module, so a callback you pass in sees your
# variables, never the kit's, and the private helpers stay out of your
# session. A copy loaded earlier is removed first. -ErrorAction Stop makes a
# throw in here (the stale-types check) stop the script that loads the kit.
Get-Module -Name ParallelKit | Remove-Module
New-Module -Name ParallelKit -ErrorAction Stop -ScriptBlock {
# ==============================================================================
# Native types (guarded so the file can be dot-sourced more than once)
# ==============================================================================
if (-not ([System.Management.Automation.PSTypeName]'PkConsoleCtrl').Type) {
Add-Type -TypeDefinition @'
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
public static class PkConsoleCtrl
{
public delegate bool HandlerRoutine(uint ctrlType);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool SetConsoleCtrlHandler(HandlerRoutine handler, bool add);
// Set by the handler (or Request-PkAbort); polled by PowerShell code.
public static volatile bool AbortRequested = false;
public static volatile bool IsCloseEvent = false; // true = window close/logoff/shutdown, false = Ctrl+C
// The handler only acts while a run is active.
public static volatile bool RunActive = false;
// On a window close, logoff or shutdown the handler parks on this until
// the run ends, since the process dies as soon as the handler returns.
// Ctrl+C never parks.
public static readonly ManualResetEventSlim DrainComplete = new ManualResetEventSlim(false);
public static int DrainWaitMs = 65000;
// Ctrl+C presses: the first starts the abort, the next skips the drain
// (force-stops running jobs now), the one after that is let through to
// PowerShell, which stops the script. A press within SkipDebounceMs of
// the last counted one is a double tap or key repeat, and is ignored.
public static volatile bool SkipDrain = false;
public static volatile string PressedKey = null; // "Ctrl+C" / "Ctrl+Break" once a press started the abort
public static int SkipDebounceMs = 1000;
private static long _lastPressTimestamp = 0;
private static readonly object _pressLock = new object();
private static HandlerRoutine _handler; // strong ref so the GC can't collect it
public static bool LastRegisterSucceeded = false;
public static void Register()
{
// SetConsoleCtrlHandler is additive - drop the previous delegate
// first so a second Register() can't leave an unrooted one behind.
if (_handler != null) { SetConsoleCtrlHandler(_handler, false); }
_handler = new HandlerRoutine(Handler);
LastRegisterSucceeded = SetConsoleCtrlHandler(_handler, true);
}
private static bool Handler(uint ctrlType)
{
// 0=CTRL_C, 1=CTRL_BREAK, 2=CTRL_CLOSE, 5=CTRL_LOGOFF, 6=CTRL_SHUTDOWN
if (!RunActive) { return false; }
if (ctrlType == 0 || ctrlType == 1)
{
// Never park here: Windows delivers one console event at a time, so
// a parked Ctrl+C would hold back the next press and a window close.
return OnInterrupt(ctrlType == 1 ? "Ctrl+Break" : "Ctrl+C");
}
if (ctrlType == 2 || ctrlType == 5 || ctrlType == 6)
{
// IsCloseEvent BEFORE AbortRequested: a poller that sees
// AbortRequested must already see the right IsCloseEvent.
IsCloseEvent = true;
AbortRequested = true;
DrainComplete.Wait(DrainWaitMs);
return true; // suppress the default OS action
}
return false;
}
// One Ctrl+C/Ctrl+Break press during a run. Public so tests can press it.
// true = handled here; false = let PowerShell's own Ctrl+C stop the script.
public static bool OnInterrupt(string key)
{
lock (_pressLock)
{
long now = System.Diagnostics.Stopwatch.GetTimestamp();
if (!AbortRequested)
{
PressedKey = key;
_lastPressTimestamp = now;
AbortRequested = true;
return true;
}
// An abort is already under way (this press, Request-PkAbort or a
// close). A press that follows a counted one too closely is ignored.
if (_lastPressTimestamp != 0)
{
double sinceLastMs = (now - _lastPressTimestamp) * 1000.0 / System.Diagnostics.Stopwatch.Frequency;
if (sinceLastMs < SkipDebounceMs) { return true; }
}
_lastPressTimestamp = now;
if (!SkipDrain) { SkipDrain = true; return true; }
return false;
}
}
public static void ResetPresses()
{
lock (_pressLock)
{
SkipDrain = false;
PressedKey = null;
_lastPressTimestamp = 0;
}
}
}
// Keeps the PC from idle-sleeping while a run is going. Per-thread: lifted
// by the same thread that set it, and dropped by Windows if the process ends.
public static class PkSleepBlock
{
[DllImport("kernel32.dll")]
private static extern uint SetThreadExecutionState(uint esFlags);
public static bool Block() { return SetThreadExecutionState(0x80000000u | 0x00000001u) != 0; }
public static bool Unblock() { return SetThreadExecutionState(0x80000000u) != 0; }
}
// Main-thread bookkeeping. Static on purpose - see the note at the top of
// ParallelKit.ps1.
public static class PkState
{
public static bool AbortLatched = false;
public static bool CloseAbort = false;
public static object MessageHandler = null; // a PowerShell scriptblock, or null for the default
// Bump this, and the check after the type definitions, whenever any C#
// in this file changes: a session keeps the types it compiled first.
public const int TypesVersion = 11;
// Locked: Register-/Unregister-PkCancellationSource are callable from
// worker runspaces, and List<T> is not safe for concurrent writers.
private static readonly List<CancellationTokenSource> _sources = new List<CancellationTokenSource>();
private static readonly object _sourcesLock = new object();
public static void AddSource(CancellationTokenSource cts) { lock (_sourcesLock) { _sources.Add(cts); } }
public static bool RemoveSource(CancellationTokenSource cts) { lock (_sourcesLock) { return _sources.Remove(cts); } }
public static CancellationTokenSource[] SnapshotSources() { lock (_sourcesLock) { return _sources.ToArray(); } }
public static int SourceCount { get { lock (_sourcesLock) { return _sources.Count; } } }
}
'@ -Language CSharp
}
if (-not ([System.Management.Automation.PSTypeName]'PkConsoleQuickEdit').Type) {
Add-Type -TypeDefinition @'
using System;
using System.Runtime.InteropServices;
// Console QuickEdit mode freezes the whole process while the user has text
// selected. Invoke-PkRun turns it off for the length of a run.
public static class PkConsoleQuickEdit
{
private const int STD_INPUT_HANDLE = -10;
private const uint ENABLE_QUICK_EDIT_MODE = 0x0040;
private const uint ENABLE_EXTENDED_FLAGS = 0x0080;
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr GetStdHandle(int nStdHandle);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool GetConsoleMode(IntPtr hConsoleHandle, out uint lpMode);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool SetConsoleMode(IntPtr hConsoleHandle, uint dwMode);
// 1 = on, 0 = off, -1 = can't tell (no real console).
public static int GetEnabled()
{
IntPtr handle = GetStdHandle(STD_INPUT_HANDLE);
if (handle == IntPtr.Zero || handle == new IntPtr(-1)) { return -1; }
uint mode;
if (!GetConsoleMode(handle, out mode)) { return -1; }
return (mode & ENABLE_QUICK_EDIT_MODE) != 0 ? 1 : 0;
}
public static bool SetEnabled(bool enabled)
{
IntPtr handle = GetStdHandle(STD_INPUT_HANDLE);
if (handle == IntPtr.Zero || handle == new IntPtr(-1)) { return false; }
uint mode;
if (!GetConsoleMode(handle, out mode)) { return false; }
if (enabled) { mode |= ENABLE_QUICK_EDIT_MODE; } else { mode &= ~ENABLE_QUICK_EDIT_MODE; }
mode |= ENABLE_EXTENDED_FLAGS;
return SetConsoleMode(handle, mode);
}
}
'@ -Language CSharp
}
if (-not ([System.Management.Automation.PSTypeName]'PkChildProcessJob').Type) {
Add-Type -TypeDefinition @'
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Runtime.CompilerServices;
using Microsoft.Win32.SafeHandles;
public sealed class PkStartedProcess
{
public Process Process;
public StreamReader Stdout;
public StreamReader Stderr;
}
// Reads one of a program's output streams to its end, in chunks, so what has
// arrived can be taken at any time (Snapshot): a program the program started
// can hold the stream open long after it exits. The first snapshot taken
// before the end is the stream's text from then on: the read carries on to
// the end, so the program holding the stream never blocks on a full pipe,
// but drops what it reads, which nobody can get any more. The task's result
// is that snapshot, or the whole text if none was taken. The reader is
// closed at the end of the stream. The reader's decoder carries a
// character split across two reads over to the next, and a snapshot leaves
// out a surrogate pair's first half whose second half hasn't arrived, so a
// snapshot never ends in half a character. Each read runs on a thread of its own
// (LongRunning), not a thread-pool thread: a read blocks until every holder
// of the stream's write end has let go (at the latest when PowerShell exits:
// they're in the Job Object), and leftover programs holding their output
// would otherwise use up the pool, so a new program's reads would wait for
// the pool to grow and hit their stream timeout. With a cap (maxChars), only
// the first half and the last half of a longer stream are kept, never split
// inside a surrogate pair; DroppedChars counts the rest. The read still goes
// to the end, so the program never blocks on a full pipe.
public sealed class PkStreamReadTask : Task<string>
{
private sealed class Buffer
{
private readonly TextReader _reader;
// Null once the text is kept: at a snapshot or at the end of the
// stream, whichever comes first. The builder goes then, so the text
// isn't held twice. With a cap, it holds the head (the first half).
private StringBuilder _text = new StringBuilder();
private string _kept;
private readonly object _gate = new object();
public volatile bool ReaderClosed;
// The cap's tail: the last chars read, a ring once it's full. It
// grows with the output, so a cap costs nothing until output reaches
// it. _tailCap is 0 with no cap.
private readonly int _headCap, _tailCap;
private bool _headFull;
private char[] _tail;
private int _tailStart, _tailCount;
private long _total, _dropped;
public Buffer(TextReader reader, int maxChars)
{
_reader = reader;
if (maxChars > 0) { _headCap = maxChars / 2; _tailCap = maxChars - _headCap; }
}
public string Pump()
{
try
{
char[] chunk = new char[4096];
int n;
while ((n = _reader.Read(chunk, 0, chunk.Length)) > 0)
{
lock (_gate) { if (_text != null) { Append(chunk, n); } }
}
return Keep(false);
}
finally
{
// Closes the pipe now rather than at the next garbage collection.
try { _reader.Dispose(); ReaderClosed = true; }
catch (Exception) { } // a close that fails must not hide the read's own result or error
}
}
// Under _gate.
private void Append(char[] chunk, int n)
{
_total += n;
if (_tailCap == 0) { _text.Append(chunk, 0, n); return; }
int i = 0;
if (!_headFull)
{
int take = Math.Min(_headCap - _text.Length, n);
if (take == _headCap - _text.Length)
{
_headFull = true;
// The head never ends on the first half of a surrogate pair.
if (take > 0 && Char.IsHighSurrogate(chunk[take - 1])) { take--; }
}
_text.Append(chunk, 0, take);
i = take;
}
if (i < n) { AppendTail(chunk, i, n - i); }
}
// Under _gate. Until the ring is full it's filled in order from 0;
// after, _tailStart is the oldest char.
private void AppendTail(char[] src, int offset, int count)
{
if (_tailCount < _tailCap)
{
int take = Math.Min(_tailCap - _tailCount, count);
int need = _tailCount + take;
if (_tail == null || _tail.Length < need)
{
long size = _tail == null ? 4096 : _tail.Length;
while (size < need) { size *= 2; }
Array.Resize(ref _tail, (int)Math.Min(size, _tailCap));
}
Array.Copy(src, offset, _tail, _tailCount, take);
_tailCount += take; offset += take; count -= take;
}
if (count == 0) { return; }
if (count >= _tailCap)
{
Array.Copy(src, offset + count - _tailCap, _tail, 0, _tailCap);
_tailStart = 0;
return;
}
int first = Math.Min(count, _tailCap - _tailStart);
Array.Copy(src, offset, _tail, _tailStart, first);
Array.Copy(src, offset + first, _tail, 0, count - first);
_tailStart = (_tailStart + count) % _tailCap;
}
// Locked: the reader may be appending while Complete-PkProcess takes
// it. A snapshot (the stream still open) leaves out a last char that
// is the first half of a pair whose second half hasn't been read.
public string Keep(bool snapshot)
{
lock (_gate)
{
if (_text != null)
{
if (_tailCount > 0)
{
int skip = 0;
// Once the ring has wrapped, it can start on the second half of a pair.
if (_total > _text.Length + _tailCount && Char.IsLowSurrogate(_tail[_tailStart])) { skip = 1; }
for (int k = skip; k < _tailCount; k++) { _text.Append(_tail[(_tailStart + k) % _tailCap]); }
_tail = null; _tailCount = 0;
}
if (snapshot && _text.Length > 0 && Char.IsHighSurrogate(_text[_text.Length - 1])) { _text.Length--; }
_kept = _text.ToString();
_dropped = _total - _kept.Length;
_text = null;
}
return _kept;
}
}
public int HeldLength { get { lock (_gate) { return _text != null ? _text.Length + _tailCount : _kept.Length; } } }
public long DroppedChars { get { lock (_gate) { return _dropped; } } }
}
private readonly Buffer _buffer;
private PkStreamReadTask(Buffer buffer) : base(new Func<string>(buffer.Pump), TaskCreationOptions.LongRunning) { _buffer = buffer; }
public static PkStreamReadTask Run(TextReader reader) { return Run(reader, 0); }
// maxChars: 0 for no cap.
public static PkStreamReadTask Run(TextReader reader, int maxChars)
{
PkStreamReadTask task = new PkStreamReadTask(new Buffer(reader, maxChars));
task.Start(TaskScheduler.Default);
return task;
}
// The text that has arrived so far, kept as the stream's text from then
// on; all of it if the stream has already ended.
public string Snapshot() { return _buffer.Keep(true); }
// How many characters the cap left out of the kept text: 0 with no cap,
// and until the text is kept (the end of the stream or a snapshot).
public long DroppedChars { get { return _buffer.DroppedChars; } }
// Test-only reads: how many characters the buffer holds, and whether the
// reader has been closed.
public int TestHeldLength { get { return _buffer.HeldLength; } }
public bool TestReaderClosed { get { return _buffer.ReaderClosed; } }
}
// A Windows Job Object with KILL_ON_JOB_CLOSE: every child process assigned
// to it dies when this process exits for ANY reason, force-kill included.
// Each program the kit starts also gets a job of its own (its tree job),
// nested in that one, so the program and everything it started can be
// killed at once (KillTree), including a child whose parent has already
// exited, which taskkill /T can't find.
public static class PkChildProcessJob
{
private const int JobObjectExtendedLimitInformation = 9;
private const uint JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x2000;
[StructLayout(LayoutKind.Sequential)]
private struct JOBOBJECT_BASIC_LIMIT_INFORMATION
{
public long PerProcessUserTimeLimit;
public long PerJobUserTimeLimit;
public uint LimitFlags;
public UIntPtr MinimumWorkingSetSize;
public UIntPtr MaximumWorkingSetSize;
public uint ActiveProcessLimit;
public UIntPtr Affinity;
public uint PriorityClass;
public uint SchedulingClass;
}
[StructLayout(LayoutKind.Sequential)]
private struct IO_COUNTERS
{
public ulong ReadOperationCount, WriteOperationCount, OtherOperationCount;
public ulong ReadTransferCount, WriteTransferCount, OtherTransferCount;
}
[StructLayout(LayoutKind.Sequential)]
private struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION
{
public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation;
public IO_COUNTERS IoInfo;
public UIntPtr ProcessMemoryLimit;
public UIntPtr JobMemoryLimit;
public UIntPtr PeakProcessMemoryUsed;
public UIntPtr PeakJobMemoryUsed;
}
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr CreateJobObject(IntPtr lpJobAttributes, string lpName);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool SetInformationJobObject(IntPtr hJob, int infoClass, IntPtr lpInfo, uint cbInfoLength);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool AssignProcessToJobObject(IntPtr hJob, IntPtr hProcess);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool CloseHandle(IntPtr hObject);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool TerminateJobObject(IntPtr hJob, uint uExitCode);
// A program's tree job, closed by ReleaseTree or, failing that, when its
// Process object is collected. Without KILL_ON_JOB_CLOSE: closing it
// leaves whatever is still running in the kit's job, as before.
private sealed class TreeJob : SafeHandleZeroOrMinusOneIsInvalid
{
public TreeJob(IntPtr h) : base(true) { SetHandle(h); }
protected override bool ReleaseHandle() { return CloseHandle(handle); }
}
private static readonly ConditionalWeakTable<Process, TreeJob> _treeJobs = new ConditionalWeakTable<Process, TreeJob>();
// Harness only: start programs without a tree job, to test the taskkill
// path; or have TryStart's first CreateProcess, with the tree job, count
// as refused, to test its retry without one.
public static bool TestNoTreeJob = false;
public static bool TestRefuseTreeJob = false;
private static void AddTree(Process process, IntPtr treeJob)
{
try { _treeJobs.Add(process, new TreeJob(treeJob)); }
catch (ArgumentException) { CloseHandle(treeJob); } // already has one (can't happen: each start is a new Process)
}
// Kills every process in the program's tree job. False if it has none,
// or Windows refused: the caller then uses taskkill.
public static bool KillTree(Process process)
{
if (process == null) { return false; }
TreeJob j;
if (!_treeJobs.TryGetValue(process, out j)) { return false; }
bool added = false, ended = false;
try
{
j.DangerousAddRef(ref added);
ended = TerminateJobObject(j.DangerousGetHandle(), 1);
}
catch (ObjectDisposedException) { return false; } // released meanwhile: taskkill instead
finally { if (added) { j.DangerousRelease(); } }
// The tree is gone: its job's handle can go now rather than with the Process.
if (ended) { ReleaseTree(process); }
return ended;
}
// Closes the program's tree job: KillTree can't reach its tree after this.
public static void ReleaseTree(Process process)
{
if (process == null) { return; }
TreeJob j;
if (_treeJobs.TryGetValue(process, out j)) { _treeJobs.Remove(process); j.Dispose(); }
}
// Harness only: whether the program has a tree job.
public static bool TestHasTree(Process process)
{
TreeJob j;
return process != null && _treeJobs.TryGetValue(process, out j);
}
// Never closed: Windows closes it when this process exits, and that is
// what kills the children.
private static IntPtr _job = IntPtr.Zero;
private static readonly object _lock = new object();
public static bool IsInitialized { get { return _job != IntPtr.Zero; } }
public static int LastError { get; private set; }
public static bool Initialize()
{
lock (_lock)
{
if (_job != IntPtr.Zero) { return true; }
IntPtr job = CreateJobObject(IntPtr.Zero, null);
if (job == IntPtr.Zero) { LastError = Marshal.GetLastWin32Error(); return false; }
JOBOBJECT_EXTENDED_LIMIT_INFORMATION info = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION();
info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
int size = Marshal.SizeOf(typeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
IntPtr buffer = Marshal.AllocHGlobal(size);
try
{
Marshal.StructureToPtr(info, buffer, false);
if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation, buffer, (uint)size))
{
LastError = Marshal.GetLastWin32Error();
CloseHandle(job);
return false;
}
}
finally { Marshal.FreeHGlobal(buffer); }
_job = job;
return true;
}
}
// Never throws: a failed assignment only loses the force-kill cleanup
// for that one process. Once it's in the kit's job, it also gets a tree
// job (Windows nests it); without one, a kill uses taskkill.
public static bool Assign(System.Diagnostics.Process process)
{
if (_job == IntPtr.Zero || process == null) { return false; }
try
{
if (!AssignProcessToJobObject(_job, process.Handle)) { LastError = Marshal.GetLastWin32Error(); return false; }
if (!TestNoTreeJob)
{
IntPtr treeJob = CreateJobObject(IntPtr.Zero, null);
if (treeJob != IntPtr.Zero)
{
if (AssignProcessToJobObject(treeJob, process.Handle)) { AddTree(process, treeJob); } else { CloseHandle(treeJob); }
}
}
return true;
}
catch { return false; }
}
// ---- Starting a program inside the job from its first instruction ----
//
// Process.Start can only be followed by Assign, so a program that starts a
// child straight away (cmd /c tool.exe) can do so before it's in the job,
// and that child survives a force-kill. TryStart has Windows put the
// program in the job as it creates it (PROC_THREAD_ATTRIBUTE_JOB_LIST,
// Windows 10 / Server 2016+), so its children join too.
//
// Everything else copies Process.Start with UseShellExecute = false:
// command line, Windows' own search for a bare name, CREATE_NO_WINDOW,
// stdin, redirected stdout/stderr, and the default encoding.
//
// The pipe ends the child writes to must be inheritable while it's
// created, and a plain Process.Start elsewhere in PowerShell inherits
// every inheritable handle: it would hold our output open until it exits.
// .NET's own start lock keeps those apart, so TryStart takes it (found by
// reflection) and returns null, for Process.Start plus Assign, when it
// isn't there in a form it knows. The handle list keeps our child from
// inheriting anyone else's handles.
private const uint CREATE_SUSPENDED = 0x4;
private const uint CREATE_UNICODE_ENVIRONMENT = 0x400;
private const uint EXTENDED_STARTUPINFO_PRESENT = 0x80000;
private const uint CREATE_NO_WINDOW = 0x08000000;
private const int STARTF_USESTDHANDLES = 0x100;
private const int STD_INPUT_HANDLE = -10;
private const uint HANDLE_FLAG_INHERIT = 1;
private static readonly IntPtr PROC_THREAD_ATTRIBUTE_HANDLE_LIST = (IntPtr)0x20002;
private static readonly IntPtr PROC_THREAD_ATTRIBUTE_JOB_LIST = (IntPtr)0x2000D;
[StructLayout(LayoutKind.Sequential)]
private struct STARTUPINFO
{
public int cb;
public IntPtr lpReserved, lpDesktop, lpTitle;
public int dwX, dwY, dwXSize, dwYSize, dwXCountChars, dwYCountChars, dwFillAttribute, dwFlags;
public short wShowWindow, cbReserved2;
public IntPtr lpReserved2, hStdInput, hStdOutput, hStdError;
}
[StructLayout(LayoutKind.Sequential)]
private struct STARTUPINFOEX
{
public STARTUPINFO StartupInfo;
public IntPtr lpAttributeList;
}
[StructLayout(LayoutKind.Sequential)]
private struct PROCESS_INFORMATION
{
public IntPtr hProcess, hThread;
public int dwProcessId, dwThreadId;
}
[StructLayout(LayoutKind.Sequential)]
private struct SECURITY_ATTRIBUTES
{
public int nLength;
public IntPtr lpSecurityDescriptor;
public int bInheritHandle;
}
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool CreateProcess(string lpApplicationName, StringBuilder lpCommandLine,
IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool bInheritHandles, uint dwCreationFlags,
IntPtr lpEnvironment, string lpCurrentDirectory, ref STARTUPINFOEX lpStartupInfo,
out PROCESS_INFORMATION lpProcessInformation);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool CreatePipe(out IntPtr hReadPipe, out IntPtr hWritePipe, ref SECURITY_ATTRIBUTES lpPipeAttributes, int nSize);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool SetHandleInformation(IntPtr hObject, uint dwMask, uint dwFlags);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool GetHandleInformation(IntPtr hObject, out uint lpdwFlags);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr GetStdHandle(int nStdHandle);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool InitializeProcThreadAttributeList(IntPtr lpAttributeList, int dwAttributeCount, int dwFlags, ref IntPtr lpSize);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool UpdateProcThreadAttribute(IntPtr lpAttributeList, uint dwFlags, IntPtr Attribute,
IntPtr lpValue, IntPtr cbSize, IntPtr lpPreviousValue, IntPtr lpReturnSize);
[DllImport("kernel32.dll")]
private static extern void DeleteProcThreadAttributeList(IntPtr lpAttributeList);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern uint ResumeThread(IntPtr hThread);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool TerminateProcess(IntPtr hProcess, uint uExitCode);
[DllImport("kernel32.dll")]
private static extern uint GetConsoleOutputCP();
// .NET's process-start lock: a plain object (5.1, 7.6) is held with
// Monitor; a System.Threading.Lock (where newer .NET is moving its locks)
// through its own Enter/Exit, by reflection since 5.1 has no such type.
// Monitor on a Lock wouldn't keep out its Enter, hence the type check.
private sealed class StartLock
{
public readonly string Kind;
private readonly object _obj;
private readonly MethodInfo _enter, _exit;
private StartLock(string kind, object obj, MethodInfo enter, MethodInfo exit)
{
Kind = kind; _obj = obj; _enter = enter; _exit = exit;
}
public static StartLock From(object candidate, string fieldName)
{
if (candidate == null) { return null; }
Type t = candidate.GetType();
if (t == typeof(object)) { return new StartLock("Monitor:" + fieldName, candidate, null, null); }
if (t.FullName == "System.Threading.Lock")
{
BindingFlags bf = BindingFlags.Public | BindingFlags.Instance;
MethodInfo enter = t.GetMethod("Enter", bf, null, Type.EmptyTypes, null);
MethodInfo exit = t.GetMethod("Exit", bf, null, Type.EmptyTypes, null);
if (enter != null && exit != null && enter.ReturnType == typeof(void) && exit.ReturnType == typeof(void))
{
return new StartLock("Lock:" + fieldName, candidate, enter, exit);
}
}
return null;
}
public void Enter()
{
if (_enter == null) { Monitor.Enter(_obj); return; }
try { _enter.Invoke(_obj, null); }
catch (TargetInvocationException e) { throw e.InnerException; }
}
public void Exit()
{
if (_exit == null) { Monitor.Exit(_obj); return; }
try { _exit.Invoke(_obj, null); }
catch (TargetInvocationException e) { throw e.InnerException; }
}
}
private static StartLock _startLock;
private static bool _startLockLooked;
private static StartLock GetStartLock()
{
lock (_lock)
{
if (_startLockLooked) { return _startLock; }
_startLockLooked = true;
// .NET Framework: s_CreateProcessLock. .NET (Core) on Windows: s_createProcessLock.
string[] names = new string[] { "s_CreateProcessLock", "s_createProcessLock" };
foreach (string n in names)
{
try
{
FieldInfo f = typeof(Process).GetField(n, BindingFlags.NonPublic | BindingFlags.Static);
if (f == null) { continue; }
StartLock l = StartLock.From(f.GetValue(null), n);
if (l != null) { _startLock = l; break; }
}
catch { } // reflection refused or the field changed: try the next name, else Process.Start
}
return _startLock;
}
}
// The start's two attributes: the handles the child inherits and its
// jobs. 0, or the Win32 error (the list is then left uninitialized).
private static int SetStartAttributes(IntPtr attrList, IntPtr attrSize, IntPtr handleArr, int handleCount, IntPtr jobArr, int jobCount)
{
IntPtr size = attrSize;
if (!InitializeProcThreadAttributeList(attrList, 2, 0, ref size)) { return Marshal.GetLastWin32Error(); }
if (UpdateProcThreadAttribute(attrList, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, handleArr, (IntPtr)(IntPtr.Size * handleCount), IntPtr.Zero, IntPtr.Zero)
&& UpdateProcThreadAttribute(attrList, 0, PROC_THREAD_ATTRIBUTE_JOB_LIST, jobArr, (IntPtr)(IntPtr.Size * jobCount), IntPtr.Zero, IntPtr.Zero))
{
return 0;
}
int e = Marshal.GetLastWin32Error();
DeleteProcThreadAttributeList(attrList);
return e;
}
// How TryStart holds .NET's start lock ("Monitor:<field>" or
// "Lock:<field>"), or null when it can't and the kit uses Process.Start.
public static string StartLockKind { get { StartLock l = GetStartLock(); return l == null ? null : l.Kind; } }
// Harness only: makes TryStart return null, to test the Process.Start path.
public static bool TestUseProcessStart = false;
// Harness only: make a start's setup fail, or building its output readers.
public static bool TestFailSetup = false;
public static bool TestFailReaders = false;
// How programs start here, for Initialize-ParallelKit: "CreatedInJob"
// (TryStart), "AddedToJob" (Process.Start, then the job: no usable start
// lock, or the harness switch), or "NoJob" (the job couldn't be set up,
// so nothing is cleaned up on a kill). A single start can still fall back
// from CreatedInJob when its setup fails; that warns.
public static string StartMode
{
get
{
if (_job == IntPtr.Zero) { return "NoJob"; }
if (TestUseProcessStart || GetStartLock() == null) { return "AddedToJob"; }
return "CreatedInJob";
}
}
// The fallback warning is shown once per process: true for the first caller.
private static int _fallbackWarned = 0;
public static bool ClaimFallbackWarning() { return Interlocked.Exchange(ref _fallbackWarned, 1) == 0; }
public static void TestResetFallbackWarning() { Interlocked.Exchange(ref _fallbackWarned, 0); }
private static StringBuilder BuildCommandLine(string fileName, string arguments)
{
// As Process.Start builds it: the program quoted unless it already is.
StringBuilder sb = new StringBuilder();
string f = fileName.Trim();
bool quoted = f.Length > 1 && f.StartsWith("\"", StringComparison.Ordinal) && f.EndsWith("\"", StringComparison.Ordinal);
if (!quoted) { sb.Append('"'); }
sb.Append(f);
if (!quoted) { sb.Append('"'); }
if (!String.IsNullOrEmpty(arguments)) { sb.Append(' '); sb.Append(arguments); }
return sb;
}
private static void CreateOutputPipe(out IntPtr read, out IntPtr write)
{
SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
sa.nLength = Marshal.SizeOf(typeof(SECURITY_ATTRIBUTES));
sa.bInheritHandle = 1;
if (!CreatePipe(out read, out write, ref sa, 0)) { throw new Win32Exception(Marshal.GetLastWin32Error()); }
if (!SetHandleInformation(read, HANDLE_FLAG_INHERIT, 0))
{
int e = Marshal.GetLastWin32Error();
CloseHandle(read); CloseHandle(write);
read = IntPtr.Zero; write = IntPtr.Zero;
throw new Win32Exception(e);
}
}
// Starts the program in the job, or returns null when it can't do that
// safely: the caller then uses Process.Start and Assign. fallbackReason
// says why, for the caller's one-time warning; it stays null where no
// warning is due (no job, which has its own; the harness switch). Throws
// Win32Exception when Windows refuses to create the program, as
// Process.Start does. encoding null: the console's output code page.
public static PkStartedProcess TryStart(string fileName, string arguments, string workingDirectory, Encoding encoding, out string fallbackReason)
{
fallbackReason = null;
if (TestUseProcessStart || _job == IntPtr.Zero) { return null; }
StartLock startLock = GetStartLock();
if (startLock == null) { fallbackReason = ".NET's process-start lock isn't where the kit expects it on this .NET version"; return null; }
if (encoding == null)
{
try { encoding = Encoding.GetEncoding((int)GetConsoleOutputCP()); }
catch { encoding = Console.OutputEncoding; } // a code page this runtime can't decode: what PowerShell itself uses
}
StringBuilder commandLine = BuildCommandLine(fileName, arguments);
IntPtr outRead = IntPtr.Zero, outWrite = IntPtr.Zero, errRead = IntPtr.Zero, errWrite = IntPtr.Zero;
IntPtr attrList = IntPtr.Zero, handleArr = IntPtr.Zero, jobArr = IntPtr.Zero, treeJob = IntPtr.Zero;
IntPtr attrSize = IntPtr.Zero;
int handleCount = 0, jobCount = 0;
bool attrReady = false, created = false, setupFailed = false;
IntPtr stdin = IntPtr.Zero;
PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
startLock.Enter();
try
{
try
{
// Setup: a failure here falls back to Process.Start and Assign
// (3.1's way) instead of failing the start. Only CreateProcess
// itself, below, reports that the program couldn't start.
try
{
CreateOutputPipe(out outRead, out outWrite);
CreateOutputPipe(out errRead, out errWrite);
// stdin as Process.Start passes it: PowerShell's own. Listed
// only if inheritable, the only case the child could use it.
stdin = GetStdHandle(STD_INPUT_HANDLE);
uint hflags;
bool stdinInherit = stdin != IntPtr.Zero && stdin != new IntPtr(-1)
&& GetHandleInformation(stdin, out hflags) && (hflags & HANDLE_FLAG_INHERIT) != 0;
handleCount = stdinInherit ? 3 : 2;
handleArr = Marshal.AllocHGlobal(IntPtr.Size * handleCount);
Marshal.WriteIntPtr(handleArr, 0, outWrite);
Marshal.WriteIntPtr(handleArr, IntPtr.Size, errWrite);
if (stdinInherit) { Marshal.WriteIntPtr(handleArr, 2 * IntPtr.Size, stdin); }
// The kit's job, then the program's tree job, which Windows
// nests in it. No tree job if it can't be made: a kill
// then uses taskkill.
if (!TestNoTreeJob) { treeJob = CreateJobObject(IntPtr.Zero, null); }
jobCount = treeJob != IntPtr.Zero ? 2 : 1;
jobArr = Marshal.AllocHGlobal(IntPtr.Size * 2);
Marshal.WriteIntPtr(jobArr, _job);
if (jobCount == 2) { Marshal.WriteIntPtr(jobArr, IntPtr.Size, treeJob); }
InitializeProcThreadAttributeList(IntPtr.Zero, 2, 0, ref attrSize); // fails by design: returns the size
attrList = Marshal.AllocHGlobal(attrSize);
int attrError = SetStartAttributes(attrList, attrSize, handleArr, handleCount, jobArr, jobCount);
if (attrError != 0) { throw new Win32Exception(attrError); }
attrReady = true;
if (TestFailSetup) { throw new Win32Exception(5); }
}
catch (Win32Exception e)
{
setupFailed = true;
fallbackReason = "setting up a start inside the Job Object failed (" + e.Message + ")";
}
if (setupFailed) { return null; } // the finally blocks below clean up and release the lock
STARTUPINFOEX si = new STARTUPINFOEX();
si.StartupInfo.cb = Marshal.SizeOf(typeof(STARTUPINFOEX));
si.StartupInfo.dwFlags = STARTF_USESTDHANDLES;
si.StartupInfo.hStdInput = stdin;
si.StartupInfo.hStdOutput = outWrite;
si.StartupInfo.hStdError = errWrite;
si.lpAttributeList = attrList;
// Suspended only until the Process object below has its handle:
// the program is in the job already, so nothing can escape.
uint flags = CREATE_NO_WINDOW | CREATE_SUSPENDED | EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT;
string dir = String.IsNullOrEmpty(workingDirectory) ? null : workingDirectory;
bool started = !TestRefuseTreeJob || jobCount == 1;
if (started) { started = CreateProcess(null, commandLine, IntPtr.Zero, IntPtr.Zero, true, flags, IntPtr.Zero, dir, ref si, out pi); }
if (!started && jobCount == 2)
{
// Once more without the tree job, in case that's what Windows
// refused (nesting it): the program still starts, and a kill
// then uses taskkill. A program that can't start at all fails
// again, with its own error.
DeleteProcThreadAttributeList(attrList); attrReady = false;
CloseHandle(treeJob); treeJob = IntPtr.Zero; jobCount = 1;
int retryError = SetStartAttributes(attrList, attrSize, handleArr, handleCount, jobArr, jobCount);
if (retryError != 0) { throw new Win32Exception(retryError); }
attrReady = true;
started = CreateProcess(null, commandLine, IntPtr.Zero, IntPtr.Zero, true, flags, IntPtr.Zero, dir, ref si, out pi);
}
if (!started) { throw new Win32Exception(Marshal.GetLastWin32Error()); }
created = true;
}
finally
{
if (attrReady) { DeleteProcThreadAttributeList(attrList); }
if (attrList != IntPtr.Zero) { Marshal.FreeHGlobal(attrList); }
if (handleArr != IntPtr.Zero) { Marshal.FreeHGlobal(handleArr); }
if (jobArr != IntPtr.Zero) { Marshal.FreeHGlobal(jobArr); }
// The child has its own copies; ours must go, or reading its
// output never reaches the end.
if (outWrite != IntPtr.Zero) { CloseHandle(outWrite); }
if (errWrite != IntPtr.Zero) { CloseHandle(errWrite); }
if (!created)
{
if (outRead != IntPtr.Zero) { CloseHandle(outRead); }
if (errRead != IntPtr.Zero) { CloseHandle(errRead); }
if (treeJob != IntPtr.Zero) { CloseHandle(treeJob); treeJob = IntPtr.Zero; }
}
}
}
finally { startLock.Exit(); }
// Everything up to the resume is guarded, the output readers included:
// if any step fails, the program (still suspended) is ended and every
// handle released, so nothing is left running untracked.
Process proc = null;
SafeFileHandle outSafe = null, errSafe = null;
StreamReader stdoutReader = null, stderrReader = null;
try
{
proc = Process.GetProcessById(pi.dwProcessId);
IntPtr opened = proc.Handle; // taken while it's suspended, so ExitCode stays readable however fast it exits
outSafe = new SafeFileHandle(outRead, true);
errSafe = new SafeFileHandle(errRead, true);
if (TestFailReaders) { throw new IOException("Test: building the output readers failed."); }
stdoutReader = new StreamReader(new FileStream(outSafe, FileAccess.Read, 4096, false), encoding, true, 4096);
stderrReader = new StreamReader(new FileStream(errSafe, FileAccess.Read, 4096, false), encoding, true, 4096);
if (ResumeThread(pi.hThread) == 0xFFFFFFFF) { throw new Win32Exception(Marshal.GetLastWin32Error()); }
}
catch
{
TerminateProcess(pi.hProcess, 1);
// A reader owns its handle; a SafeFileHandle not yet in a reader
// owns its own; before either, the raw handle is closed directly.
if (stdoutReader != null) { stdoutReader.Dispose(); }
if (outSafe != null) { outSafe.Dispose(); } else { CloseHandle(outRead); }
if (stderrReader != null) { stderrReader.Dispose(); }
if (errSafe != null) { errSafe.Dispose(); } else { CloseHandle(errRead); }
CloseHandle(pi.hThread); CloseHandle(pi.hProcess);
if (treeJob != IntPtr.Zero) { CloseHandle(treeJob); }
if (proc != null) { proc.Dispose(); }
throw;
}
if (treeJob != IntPtr.Zero) { AddTree(proc, treeJob); }
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
PkStartedProcess r = new PkStartedProcess();
r.Process = proc;
r.Stdout = stdoutReader;
r.Stderr = stderrReader;
return r;
}