From f6ecb9964e41dfc1c46c3c701f25feccff935b3d Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Wed, 2 Dec 2026 01:38:52 -0500 Subject: [PATCH 1/2] Keep the kit's C# in Source/*.cs, with a script that copies it into ParallelKit.ps1 The C# in ParallelKit.ps1's three Add-Type blocks now lives in Source/.cs, one file per block. Build/Update-ParallelKitCSharp.ps1 copies them into the .ps1, which stays committed and stays the release asset: -Check fails if they differ, and -Compile builds each file with the .NET Framework's csc.exe as C# 5 and with the .NET SDK for pwsh's .NET, with warnings as errors and a short list of analyzer rules. The C# itself is unchanged. A new CI job, C#, runs both. Harness section BN checks the copy matches and tests the script's checks. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/tests.yml | 17 + Build/Update-ParallelKitCSharp.ps1 | 147 +++++ ParallelKit.Harness.ps1 | 49 ++ ParallelKit.ps1 | 2 + Source/PkChildProcessJob.cs | 829 +++++++++++++++++++++++++++++ Source/PkConsoleCtrl.cs | 147 +++++ Source/PkConsoleQuickEdit.cs | 41 ++ 7 files changed, 1232 insertions(+) create mode 100644 Build/Update-ParallelKitCSharp.ps1 create mode 100644 Source/PkChildProcessJob.cs create mode 100644 Source/PkConsoleCtrl.cs create mode 100644 Source/PkConsoleQuickEdit.cs diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 3d0510c..7a77ec7 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -57,3 +57,20 @@ jobs: run: | & pwsh -NoProfile -ExecutionPolicy Bypass -File .\ParallelKit.Harness.ps1 -AsModule -Section MODULE exit $LASTEXITCODE + + # The C# in Source/: ParallelKit.ps1 carries the same code, and it compiles + # with no warnings as C# 5 with the .NET Framework's compiler (Add-Type's on + # Windows PowerShell 5.1), and with the .NET SDK for the .NET pwsh runs on, + # with the analyzer rules the script lists. + csharp: + name: C# + runs-on: windows-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + + - name: Check and compile Source/*.cs + shell: powershell + run: | + & powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\Build\Update-ParallelKitCSharp.ps1 -Check -Compile + exit $LASTEXITCODE diff --git a/Build/Update-ParallelKitCSharp.ps1 b/Build/Update-ParallelKitCSharp.ps1 new file mode 100644 index 0000000..8a7f645 --- /dev/null +++ b/Build/Update-ParallelKitCSharp.ps1 @@ -0,0 +1,147 @@ +# Copies the kit's C# from Source/*.cs into ParallelKit.ps1, whose Add-Type +# blocks carry it, so the .ps1 stays one self-contained file. Edit the .cs +# files, then run this: never edit the C# inside ParallelKit.ps1. +# +# powershell -NoProfile -File .\Build\Update-ParallelKitCSharp.ps1 # update ParallelKit.ps1 +# powershell -NoProfile -File .\Build\Update-ParallelKitCSharp.ps1 -Check # exit 1 if it isn't up to date +# powershell -NoProfile -File .\Build\Update-ParallelKitCSharp.ps1 -Compile # and compile the C# +# +# Each Source/.cs is the block guarded by in ParallelKit.ps1: +# if (-not ([System.Management.Automation.PSTypeName]'').Type) { +# Add-Type -TypeDefinition @' +# ... +# '@ -Language CSharp +# } +# Every block needs its file and every file its block. Nothing else in the +# .ps1 changes. Runs on Windows PowerShell 5.1 and PowerShell 7. +# +# -Compile builds each file on its own, as Add-Type does, twice: with the +# .NET Framework's csc.exe, the compiler Add-Type uses on 5.1 (C# 5), and +# with the .NET SDK at LangVersion 5 for the .NET that pwsh runs on, with the +# analyzer rules listed below. Warnings are errors in both. It needs pwsh and +# a .NET SDK that can target pwsh's .NET. +param( + [switch]$Check, + [switch]$Compile, + # The repository root, for testing on a copy. + [string]$Root = (Split-Path -Parent $PSScriptRoot) +) +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' + +$kitPath = Join-Path $Root 'ParallelKit.ps1' +$sourceDir = Join-Path $Root 'Source' +if (-not (Test-Path -LiteralPath $kitPath -PathType Leaf)) { throw "Update-ParallelKitCSharp: '$kitPath' doesn't exist. Pass -Root with the repository's folder." } +$sources = @(Get-ChildItem -LiteralPath $sourceDir -Filter '*.cs' -File -ErrorAction SilentlyContinue | Sort-Object Name) +if ($sources.Count -eq 0) { throw "Update-ParallelKitCSharp: no .cs files in '$sourceDir'." } + +# Read and written as bytes decoded as UTF-8, keeping a byte-order mark only +# if the file had one, so a run that changes nothing writes nothing. +$kitBytes = [System.IO.File]::ReadAllBytes($kitPath) +$hasBom = $kitBytes.Length -ge 3 -and $kitBytes[0] -eq 0xEF -and $kitBytes[1] -eq 0xBB -and $kitBytes[2] -eq 0xBF +$utf8 = [System.Text.UTF8Encoding]::new($false, $true) +$kitText = $utf8.GetString($kitBytes, [int]$hasBom * 3, $kitBytes.Length - [int]$hasBom * 3) +$newline = if ($kitText.Contains("`r`n")) { "`r`n" } else { "`n" } + +$blockCount = [regex]::Matches($kitText, "(?m)^ Add-Type -TypeDefinition @'\r?$").Count +if ($blockCount -ne $sources.Count) { + throw ("Update-ParallelKitCSharp: ParallelKit.ps1 has " + $blockCount + " Add-Type block(s) and Source has " + $sources.Count + " .cs file(s) (" + (($sources | ForEach-Object Name) -join ', ') + "). Each block needs a file named after the type that guards it, and each file a block.") +} + +$updated = $kitText +$stale = [System.Collections.Generic.List[string]]::new() +foreach ($source in $sources) { + $type = [System.IO.Path]::GetFileNameWithoutExtension($source.Name) + $pattern = "(?s)(if \(-not \(\[System\.Management\.Automation\.PSTypeName\]'" + [regex]::Escape($type) + "'\)\.Type\) \{\r?\n Add-Type -TypeDefinition @'\r?\n)(.*?)(\r?\n'@ -Language CSharp\r?\n\})" + $found = [regex]::Matches($updated, $pattern) + if ($found.Count -ne 1) { throw ("Update-ParallelKitCSharp: expected one Add-Type block guarded by '" + $type + "' in ParallelKit.ps1 (for " + $source.Name + "), found " + $found.Count + ". The guard and the Add-Type line must keep the form shown at the top of this script.") } + $code = [System.IO.File]::ReadAllText($source.FullName, $utf8) + if ($code.Length -gt 0 -and $code[0] -eq [char]0xFEFF) { $code = $code.Substring(1) } + $code = ($code -replace "\r\n", "`n") -replace "\n\z", '' + # A line starting with '@ would end the here-string early. + if ($code -match "(?m)^'@") { throw ("Update-ParallelKitCSharp: " + $source.Name + " has a line starting with '@, which would end ParallelKit.ps1's here-string there. Indent it or rewrite it.") } + $code = $code.Replace("`n", $newline) + $match = $found[0] + if ($match.Groups[2].Value -cne $code) { $stale.Add($source.Name) } + $updated = $updated.Substring(0, $match.Groups[2].Index) + $code + $updated.Substring($match.Groups[2].Index + $match.Groups[2].Length) +} + +if ($Check) { + if ($stale.Count -gt 0) { + Write-Host ("ParallelKit.ps1 doesn't match " + ($stale -join ', ') + ". Run Build/Update-ParallelKitCSharp.ps1 and commit both.") -ForegroundColor Red + exit 1 + } + Write-Host ("ParallelKit.ps1 matches Source/ (" + $sources.Count + " files).") +} elseif ($stale.Count -gt 0) { + $bom = if ($hasBom) { [byte[]](0xEF, 0xBB, 0xBF) } else { [byte[]]@() } + [System.IO.File]::WriteAllBytes($kitPath, [byte[]]($bom + $utf8.GetBytes($updated))) + Write-Host ("Updated ParallelKit.ps1 from " + ($stale -join ', ') + ".") +} else { + Write-Host "ParallelKit.ps1 already matches Source/." +} + +if (-not $Compile) { exit 0 } + +$work = Join-Path ([System.IO.Path]::GetTempPath()) ("pk-csharp-" + [System.Guid]::NewGuid().ToString('N')) +$null = New-Item -ItemType Directory -Path $work +$failed = [System.Collections.Generic.List[string]]::new() +try { + # The .NET Framework 4.x compiler, as Add-Type on 5.1 uses it. + $framework = if ([Environment]::Is64BitOperatingSystem) { 'Framework64' } else { 'Framework' } + $csc = Join-Path $env:SystemRoot ("Microsoft.NET\" + $framework + "\v4.0.30319\csc.exe") + if (-not (Test-Path -LiteralPath $csc -PathType Leaf)) { throw "Update-ParallelKitCSharp: the .NET Framework compiler isn't at '$csc'. -Compile needs Windows with .NET Framework 4.x." } + foreach ($source in $sources) { + $out = & $csc /nologo /target:library /langversion:5 /warn:4 /warnaserror+ ("/out:" + (Join-Path $work ($source.BaseName + '.framework.dll'))) $source.FullName 2>&1 + if ($LASTEXITCODE -ne 0) { $failed.Add('csc.exe ' + $source.Name); $out | ForEach-Object { Write-Host (" " + $_) } } + else { Write-Host ("csc.exe (C# 5): " + $source.Name + " compiles with no warnings.") } + } + + # The .NET SDK, for the .NET that pwsh runs on. + $pwsh = Get-Command pwsh -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 + if ($null -eq $pwsh) { throw "Update-ParallelKitCSharp: -Compile needs pwsh (PowerShell 7) on PATH, to target the .NET it runs on." } + $dotnet = Get-Command dotnet -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 + if ($null -eq $dotnet) { throw "Update-ParallelKitCSharp: -Compile needs the .NET SDK (dotnet) on PATH." } + $runtime = (& $pwsh.Source -NoProfile -Command '[Environment]::Version.ToString(2)').Trim() + $framework = 'net' + $runtime + # Analyzer rules checked on top of the compiler's own warnings: ones about + # real faults, all clean today. Left out on purpose: style rules, and ones + # this code breaks deliberately (catch-all handlers that report the + # failure; DllImport of kernel32, a KnownDLL; handles a catch block + # releases, which the dispose rule can't follow). + $rules = @('CA1069', 'CA2002', 'CA2011', 'CA2013', 'CA2101', 'CA2200', 'CA2201', 'CA2208', 'CA2213', 'CA2216', 'CA2219', 'CA2241') + $config = @('is_global = true') + @($rules | ForEach-Object { 'dotnet_diagnostic.' + $_ + '.severity = warning' }) + foreach ($source in $sources) { + $project = Join-Path $work $source.BaseName + $null = New-Item -ItemType Directory -Path $project + [System.IO.File]::WriteAllLines((Join-Path $project 'rules.globalconfig'), [string[]]$config) + [System.IO.File]::WriteAllText((Join-Path $project 'check.csproj'), (@' + + + FRAMEWORK + 5 + disable + disable + false + 4 + true + true + None + + + + + + +'@).Replace('FRAMEWORK', $framework).Replace('SOURCE', [System.Security.SecurityElement]::Escape($source.FullName))) + $out = & $dotnet.Source build (Join-Path $project 'check.csproj') -nologo -v:q --disable-build-servers 2>&1 + if ($LASTEXITCODE -ne 0) { $failed.Add('dotnet ' + $source.Name); $out | ForEach-Object { Write-Host (" " + $_) } } + else { Write-Host ("dotnet (" + $framework + ", LangVersion 5): " + $source.Name + " compiles with no warnings.") } + } +} finally { + Remove-Item -LiteralPath $work -Recurse -Force -ErrorAction SilentlyContinue +} +if ($failed.Count -gt 0) { + Write-Host ("Didn't compile cleanly: " + ($failed -join ', ') + ".") -ForegroundColor Red + exit 1 +} +exit 0 diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index 4e257d1..8d94001 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -6077,6 +6077,55 @@ Test-Assert ($bmOtherBuild.Results[0].ExitCode -eq 0 -and $bmStaleOut -like '*re Write-Host "" } +# ============================================================================== +if (Test-HarnessSection 'BN' "the C# in Source/ and in ParallelKit.ps1 match") { +# The C# is edited in Source/*.cs, and Build/Update-ParallelKitCSharp.ps1 +# copies it into ParallelKit.ps1's Add-Type blocks. Its checks are tested on a +# copy of the kit and its sources in %TEMP%. Compiling (-Compile) needs the +# .NET SDK, so it's checked by CI's C# job, not here. +$bnScript = Join-Path $PSScriptRoot 'Build\Update-ParallelKitCSharp.ps1' +$null = & $bnScript -Check 6>$null +Test-Assert ($LASTEXITCODE -eq 0) "ParallelKit.ps1's C# matches Source/*.cs (Build/Update-ParallelKitCSharp.ps1 -Check)" + +$bnDir = Join-Path $env:TEMP ("pk-harness-bn-" + $PID) +try { + $null = New-Item -ItemType Directory -Force -Path (Join-Path $bnDir 'Source') + Copy-Item -LiteralPath $kitPs1 -Destination $bnDir + Copy-Item -Path (Join-Path $PSScriptRoot 'Source\*.cs') -Destination (Join-Path $bnDir 'Source') + $bnKit = Join-Path $bnDir 'ParallelKit.ps1' + $bnCs = Join-Path $bnDir 'Source\PkConsoleQuickEdit.cs' + $bnKitText = [System.IO.File]::ReadAllText($bnKit) + $bnCsText = [System.IO.File]::ReadAllText($bnCs) + + # An edit to one .cs file: -Check fails, the update copies that one line + # into its own block and nothing else, and -Check passes again. + [System.IO.File]::WriteAllText($bnCs, $bnCsText.Replace('using System;', 'using System; // pk-harness-bn')) + $null = & $bnScript -Root $bnDir -Check 6>$null + $bnStale = $LASTEXITCODE + $null = & $bnScript -Root $bnDir 6>$null + $bnUpdated = [System.IO.File]::ReadAllText($bnKit) + $null = & $bnScript -Root $bnDir -Check 6>$null + $bnFresh = $LASTEXITCODE + $bnAt = $bnKitText.IndexOf('using System;', $bnKitText.IndexOf("'PkConsoleQuickEdit'")) + $bnExpected = $bnKitText.Substring(0, $bnAt) + 'using System; // pk-harness-bn' + $bnKitText.Substring($bnAt + 'using System;'.Length) + Test-Assert ($bnStale -eq 1 -and $bnFresh -eq 0 -and $bnUpdated -ceq $bnExpected) ("an edited .cs file: -Check fails (exit " + $bnStale + "), the update changes only that line in its block (" + ($bnUpdated -ceq $bnExpected) + "), then -Check passes (exit " + $bnFresh + ")") + + # Refused, with a message: a line starting with '@, which would end the + # here-string, and a block left without its file. + [System.IO.File]::WriteAllText($bnCs, $bnCsText + "'@`r`n") + $bnTerminator = '' + try { $null = & $bnScript -Root $bnDir 6>$null } catch { $bnTerminator = [string]$_ } + [System.IO.File]::WriteAllText($bnCs, $bnCsText) + Rename-Item -LiteralPath $bnCs -NewName 'PkConsoleQuickEdit.txt' + $bnMissing = '' + try { $null = & $bnScript -Root $bnDir 6>$null } catch { $bnMissing = [string]$_ } + Test-Assert ($bnTerminator -like "*line starting with '@*" -and $bnMissing -like '*has 3 Add-Type block(s) and Source has 2 .cs file(s)*' -and [System.IO.File]::ReadAllText($bnKit) -ceq $bnUpdated) ("the update refuses a line starting with '@ and a block without its file, and leaves ParallelKit.ps1 alone (" + $bnTerminator + " / " + $bnMissing + ")") +} finally { + Remove-Item -LiteralPath $bnDir -Recurse -Force -ErrorAction SilentlyContinue +} +Write-Host "" +} + Set-PkMessageHandler -Handler $null Reset-PkAbortState if ($null -ne $moduleDir) { diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 235dc7d..d1b8e81 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -37,6 +37,8 @@ New-Module -Name ParallelKit -ErrorAction Stop -ScriptBlock { # ============================================================================== # Native types (guarded so the kit can be loaded more than once) # ============================================================================== +# The C# below is copied from Source/.cs by +# Build/Update-ParallelKitCSharp.ps1: edit it there, then run that script. if (-not ([System.Management.Automation.PSTypeName]'PkConsoleCtrl').Type) { Add-Type -TypeDefinition @' diff --git a/Source/PkChildProcessJob.cs b/Source/PkChildProcessJob.cs new file mode 100644 index 0000000..96602cf --- /dev/null +++ b/Source/PkChildProcessJob.cs @@ -0,0 +1,829 @@ +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): something 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, and the task's result; +// without one, the result is the whole text. The read goes on to the end +// either way, dropping what it no longer needs, so nothing that writes to the +// stream blocks on a full pipe. The reader is closed there. +// +// No text ends in half a character: the decoder carries one split across two +// reads over to the next, and a snapshot leaves out a surrogate pair's first +// half whose second hasn't arrived. With a cap (maxChars), only the first half +// and the last half of a longer stream are kept, never split inside a pair, +// and DroppedChars counts the rest. +// +// Each read has a thread of its own (LongRunning), not a pool thread: it +// 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). Leftover programs +// holding their output would otherwise use up the pool, and a new program's +// reads would wait for it to grow and hit their stream timeout. +public sealed class PkStreamReadTask : Task +{ + 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(buffer.Pump), TaskCreationOptions.LongRunning) { _buffer = buffer; } + + // 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. + private sealed class TreeJob : SafeHandleZeroOrMinusOneIsInvalid + { + public TreeJob(IntPtr h) : base(true) { SetHandle(h); } + protected override bool ReleaseHandle() { return CloseHandle(handle); } + } + private static readonly ConditionalWeakTable _treeJobs = new ConditionalWeakTable(); + + // 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: a second Assign of the same 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; } + + // Harness only: make Initialize, or Assign, fail as if Windows refused + // (error 5), to test their warnings. + public static bool TestFailInit = false; + public static bool TestFailAssign = false; + + public static bool Initialize() + { + lock (_lock) + { + if (_job != IntPtr.Zero) { return true; } + if (TestFailInit) { LastError = 5; return false; } + 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. reason says + // why it failed ("Win32 error 5", or what was thrown), null when it + // worked. Per call: LastError is shared, and another thread's start can + // change it before the caller reads it. + public static bool Assign(System.Diagnostics.Process process, out string reason) + { + reason = null; + if (_job == IntPtr.Zero || process == null) { reason = "no Job Object"; return false; } + if (TestFailAssign) { LastError = 5; reason = "Win32 error 5"; return false; } + try + { + if (!AssignProcessToJobObject(_job, process.Handle)) + { + int e = Marshal.GetLastWin32Error(); + LastError = e; + reason = "Win32 error " + e; + 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 (Exception ex) { reason = ex.Message; return false; } // a process whose handle can't be read: say what was thrown + } + + // ---- 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, + // redirected stdout/stderr, and the default encoding. stdin is NUL, or + // PowerShell's own as Process.Start passes it. + // + // 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 const uint GENERIC_READ = 0x80000000; + private const uint FILE_SHARE_READ_WRITE = 3; + private const uint OPEN_EXISTING = 3; + 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", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern IntPtr CreateFile(string lpFileName, uint dwDesiredAccess, uint dwShareMode, + ref SECURITY_ATTRIBUTES lpSecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile); + + [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; + + // Harness only: act as if .NET's start lock weren't found, to test the + // warning a .NET that moved it would bring. + public static bool TestNoStartLock = false; + + private static StartLock GetStartLock() + { + lock (_lock) + { + if (TestNoStartLock) { return null; } + 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:" or + // "Lock:"), 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); } + // The same, once each, for a Job Object that couldn't be set up when + // first needed, and for a running program Windows wouldn't add to it. + private static int _initWarned = 0, _assignWarned = 0; + public static bool ClaimInitWarning() { return Interlocked.Exchange(ref _initWarned, 1) == 0; } + public static bool ClaimAssignWarning() { return Interlocked.Exchange(ref _assignWarned, 1) == 0; } + public static void TestResetJobWarnings() { Interlocked.Exchange(ref _initWarned, 0); Interlocked.Exchange(ref _assignWarned, 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); + } + } + + private static IntPtr OpenNulForRead() + { + SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES(); + sa.nLength = Marshal.SizeOf(typeof(SECURITY_ATTRIBUTES)); + sa.bInheritHandle = 1; + IntPtr nul = CreateFile("NUL", GENERIC_READ, FILE_SHARE_READ_WRITE, ref sa, OPEN_EXISTING, 0, IntPtr.Zero); + if (nul == new IntPtr(-1)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } + return nul; + } + + // 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, bool inheritStdin, 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, nul = IntPtr.Zero; + PROCESS_INFORMATION pi = new PROCESS_INFORMATION(); + + startLock.Enter(); + try + { + try + { + // Setup: a failure here falls back to Process.Start and Assign + // 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); + + // NUL, so a program that reads its input gets the end of it + // at once. Or, asked for, PowerShell's own as Process.Start + // passes it: listed only if inheritable, the only case the + // child could use it. + bool stdinInherit = true; + if (inheritStdin) + { + stdin = GetStdHandle(STD_INPUT_HANDLE); + uint hflags; + stdinInherit = stdin != IntPtr.Zero && stdin != new IntPtr(-1) + && GetHandleInformation(stdin, out hflags) && (hflags & HANDLE_FLAG_INHERIT) != 0; + } + else + { + nul = OpenNulForRead(); + stdin = nul; + } + 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 (nul != IntPtr.Zero) { CloseHandle(nul); } + 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; + } +} diff --git a/Source/PkConsoleCtrl.cs b/Source/PkConsoleCtrl.cs new file mode 100644 index 0000000..5c587f3 --- /dev/null +++ b/Source/PkConsoleCtrl.cs @@ -0,0 +1,147 @@ +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 this +// file. +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 = 14; + + // Locked: Register-/Unregister-PkCancellationSource are callable from + // worker runspaces, and List is not safe for concurrent writers. + private static readonly List _sources = new List(); + 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; } } } + + // Get-PkCommandKind's answers for this session: whether Get-Module finds a + // module by name, under "|". + public static readonly System.Collections.Concurrent.ConcurrentDictionary ModuleFound = + new System.Collections.Concurrent.ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); + + // Get-PkPredefinedVariable's answer for this session. + public static HashSet PredefinedVariables = null; +} diff --git a/Source/PkConsoleQuickEdit.cs b/Source/PkConsoleQuickEdit.cs new file mode 100644 index 0000000..6ee2811 --- /dev/null +++ b/Source/PkConsoleQuickEdit.cs @@ -0,0 +1,41 @@ +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); + } +} From da0c7b5a6bb32447ba45e061c563d9533469961b Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Wed, 2 Dec 2026 01:54:11 -0500 Subject: [PATCH 2/2] Update-ParallelKitCSharp: name the file that isn't UTF-8, and compile a copy of each .cs file Co-Authored-By: Claude Opus 5.5 --- Build/Update-ParallelKitCSharp.ps1 | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/Build/Update-ParallelKitCSharp.ps1 b/Build/Update-ParallelKitCSharp.ps1 index 8a7f645..c9abf7c 100644 --- a/Build/Update-ParallelKitCSharp.ps1 +++ b/Build/Update-ParallelKitCSharp.ps1 @@ -40,7 +40,14 @@ if ($sources.Count -eq 0) { throw "Update-ParallelKitCSharp: no .cs files in '$s $kitBytes = [System.IO.File]::ReadAllBytes($kitPath) $hasBom = $kitBytes.Length -ge 3 -and $kitBytes[0] -eq 0xEF -and $kitBytes[1] -eq 0xBB -and $kitBytes[2] -eq 0xBF $utf8 = [System.Text.UTF8Encoding]::new($false, $true) -$kitText = $utf8.GetString($kitBytes, [int]$hasBom * 3, $kitBytes.Length - [int]$hasBom * 3) +function Read-CSharpSourceText { + # Strict UTF-8, so a file saved in another encoding stops the run rather + # than being copied wrong. + param([byte[]]$Bytes, [int]$Skip, [string]$Name) + try { return $utf8.GetString($Bytes, $Skip, $Bytes.Length - $Skip) } + catch [System.Text.DecoderFallbackException] { throw ("Update-ParallelKitCSharp: " + $Name + " isn't valid UTF-8. Save it as UTF-8 and run this again.") } +} +$kitText = Read-CSharpSourceText -Bytes $kitBytes -Skip ([int]$hasBom * 3) -Name 'ParallelKit.ps1' $newline = if ($kitText.Contains("`r`n")) { "`r`n" } else { "`n" } $blockCount = [regex]::Matches($kitText, "(?m)^ Add-Type -TypeDefinition @'\r?$").Count @@ -55,7 +62,7 @@ foreach ($source in $sources) { $pattern = "(?s)(if \(-not \(\[System\.Management\.Automation\.PSTypeName\]'" + [regex]::Escape($type) + "'\)\.Type\) \{\r?\n Add-Type -TypeDefinition @'\r?\n)(.*?)(\r?\n'@ -Language CSharp\r?\n\})" $found = [regex]::Matches($updated, $pattern) if ($found.Count -ne 1) { throw ("Update-ParallelKitCSharp: expected one Add-Type block guarded by '" + $type + "' in ParallelKit.ps1 (for " + $source.Name + "), found " + $found.Count + ". The guard and the Add-Type line must keep the form shown at the top of this script.") } - $code = [System.IO.File]::ReadAllText($source.FullName, $utf8) + $code = Read-CSharpSourceText -Bytes ([System.IO.File]::ReadAllBytes($source.FullName)) -Skip 0 -Name $source.Name if ($code.Length -gt 0 -and $code[0] -eq [char]0xFEFF) { $code = $code.Substring(1) } $code = ($code -replace "\r\n", "`n") -replace "\n\z", '' # A line starting with '@ would end the here-string early. @@ -87,8 +94,8 @@ $null = New-Item -ItemType Directory -Path $work $failed = [System.Collections.Generic.List[string]]::new() try { # The .NET Framework 4.x compiler, as Add-Type on 5.1 uses it. - $framework = if ([Environment]::Is64BitOperatingSystem) { 'Framework64' } else { 'Framework' } - $csc = Join-Path $env:SystemRoot ("Microsoft.NET\" + $framework + "\v4.0.30319\csc.exe") + $frameworkDir = if ([Environment]::Is64BitOperatingSystem) { 'Framework64' } else { 'Framework' } + $csc = Join-Path $env:SystemRoot ("Microsoft.NET\" + $frameworkDir + "\v4.0.30319\csc.exe") if (-not (Test-Path -LiteralPath $csc -PathType Leaf)) { throw "Update-ParallelKitCSharp: the .NET Framework compiler isn't at '$csc'. -Compile needs Windows with .NET Framework 4.x." } foreach ($source in $sources) { $out = & $csc /nologo /target:library /langversion:5 /warn:4 /warnaserror+ ("/out:" + (Join-Path $work ($source.BaseName + '.framework.dll'))) $source.FullName 2>&1 @@ -102,7 +109,7 @@ try { $dotnet = Get-Command dotnet -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 if ($null -eq $dotnet) { throw "Update-ParallelKitCSharp: -Compile needs the .NET SDK (dotnet) on PATH." } $runtime = (& $pwsh.Source -NoProfile -Command '[Environment]::Version.ToString(2)').Trim() - $framework = 'net' + $runtime + $targetFramework = 'net' + $runtime # Analyzer rules checked on top of the compiler's own warnings: ones about # real faults, all clean today. Left out on purpose: style rules, and ones # this code breaks deliberately (catch-all handlers that report the @@ -132,10 +139,13 @@ try { -'@).Replace('FRAMEWORK', $framework).Replace('SOURCE', [System.Security.SecurityElement]::Escape($source.FullName))) +'@).Replace('FRAMEWORK', $targetFramework).Replace('SOURCE', $source.Name)) + # A copy next to the project, included by its bare name: MSBuild reads + # characters such as % ; * $ in an item's path as its own syntax. + Copy-Item -LiteralPath $source.FullName -Destination $project $out = & $dotnet.Source build (Join-Path $project 'check.csproj') -nologo -v:q --disable-build-servers 2>&1 if ($LASTEXITCODE -ne 0) { $failed.Add('dotnet ' + $source.Name); $out | ForEach-Object { Write-Host (" " + $_) } } - else { Write-Host ("dotnet (" + $framework + ", LangVersion 5): " + $source.Name + " compiles with no warnings.") } + else { Write-Host ("dotnet (" + $targetFramework + ", LangVersion 5): " + $source.Name + " compiles with no warnings.") } } } finally { Remove-Item -LiteralPath $work -Recurse -Force -ErrorAction SilentlyContinue