diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index f26c018..2f00ceb 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -3149,6 +3149,23 @@ if ($compiled) { $nlBatch = (Invoke-PkProcessBatch -MaxConcurrent 1 -Commands @(@{ FilePath = $fwdBat; Arguments = @(("b" + "`r" + "c")) })).Results[0] Test-Assert ($nlError -like '*element 2*line break*' -and [string]$nlBatch.StartError -like '*line break*') ("a line break in a list element for a .cmd is refused with a clear error (" + $nlError + ")") Test-Assert ((Get-BatchArgvText @(("b" + "`n" + "c"))) -eq ("[b" + "`n" + "c]")) "and still reaches an ordinary program" + + # A NUL would end the command line there and drop the rest, later + # arguments included, for any program: refused before starting, in a list + # or a string, on each way in. + $nul = [string][char]0 + $nulList = '' + try { $null = Invoke-PkProcessWithTimeout -FilePath $argvExe -Arguments @('a', ('before' + $nul + 'after'), 'next') -TimeoutMs 10000 } catch { $nulList = [string]$_ } + $nulString = '' + try { $null = Invoke-PkProcessWithTimeout -FilePath $argvExe -Arguments ('before' + $nul + 'after next') -TimeoutMs 10000 } catch { $nulString = [string]$_ } + $nulBatch = (Invoke-PkProcessBatch -MaxConcurrent 1 -Commands @(@{ FilePath = $argvExe; Arguments = @(('before' + $nul + 'after'), 'next') }, @{ FilePath = $argvExe; Arguments = ('before' + $nul + 'after') })).Results + $nulStart = '' + try { $null = Start-PkProcess -FilePath $argvExe -Arguments ('x' + $nul) } catch { $nulStart = [string]$_ } + $nulJoin = '' + try { $null = ConvertTo-PkArgumentString @(('x' + $nul)) } catch { $nulJoin = [string]$_ } + Test-Assert ($nulList -like '*element 2*NUL*' -and $nulString -like '*NUL*' -and $nulStart -like '*NUL*') ("a NUL in an argument is refused before the program starts, in a list or a string (list: " + $nulList + "; string: " + $nulString + "; Start-PkProcess: " + $nulStart + ")") + Test-Assert ([string]$nulBatch[0].StartError -like '*NUL*' -and [string]$nulBatch[1].StartError -like '*NUL*') ("and is the command's StartError in a batch (" + $nulBatch[0].StartError + " | " + $nulBatch[1].StartError + ")") + Test-Assert ($nulJoin -like '*element 1*NUL*') ("and ConvertTo-PkArgumentString refuses it too (" + $nulJoin + ")") try { [System.IO.Directory]::Delete($injDir, $true) } catch { } # temp folder only; best effort # A string is still exactly as written. @@ -5277,6 +5294,35 @@ Test-Assert ($bcOut.Errors.Count -eq 0) ("a mandatory CancelToken and Mandatory $bcOut = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams @(@{ A = 1 }) -WorkerScript { param([Parameter(Mandatory, ParameterSetName = 'A')]$A, [Parameter(Mandatory, ParameterSetName = 'B')]$B) $A } Test-Assert ($bcOut.Errors.Count -eq 0) ("a worker with parameter sets isn't refused for the other set's mandatory parameter (" + $bcOut.Errors.Count + " errors)") +# A function's own scriptblock (${function:Name}) works as -WorkerScript, in +# both forms, function f { param(...) } and function f(...): its parameters +# are read, CancelToken is filled in, a missing mandatory one is refused up +# front, and the function's own top level may use $script:, as a { } block's +# may. +function Get-HarnessFnWorker { param([int]$Id, $CancelToken) return ([string]$Id + ':' + ($CancelToken -is [System.Threading.CancellationToken])) } +function Get-HarnessFnWorkerInline([int]$Id, [Parameter(Mandatory)][string]$Name) { return ([string]$Id + $Name) } +$bcFnResults = [System.Collections.Generic.List[object]]::new() +$bcError = $null +try { $null = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams @(@{ Id = 1 }, @{ Id = 2 }) -WorkerScript ${function:Get-HarnessFnWorker} -ResultHandler { param($r) $bcFnResults.Add($r) }.GetNewClosure() } catch { $bcError = [string]$_ } +$bcFnText = (@($bcFnResults | Sort-Object) -join ',') +Test-Assert ($null -eq $bcError -and $bcFnText -eq '1:True,2:True') ("-WorkerScript `${function:Name} with a param() block: its jobs bind and CancelToken is filled in (" + $bcFnText + ", error: " + $bcError + ")") +$bcFnResults = [System.Collections.Generic.List[object]]::new() +$bcError = $null +try { $null = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams @(@{ Id = 1; Name = 'a' }, @{ Id = 2; Name = 'b' }) -WorkerScript ${function:Get-HarnessFnWorkerInline} -ResultHandler { param($r) $bcFnResults.Add($r) }.GetNewClosure() } catch { $bcError = [string]$_ } +$bcFnText = (@($bcFnResults | Sort-Object) -join ',') +Test-Assert ($null -eq $bcError -and $bcFnText -eq '1a,2b') ("and declared as function f(...) (" + $bcFnText + ", error: " + $bcError + ")") +$bcError = $null +try { $null = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams @(@{ Id = 1; Name = 'a' }, @{ Id = 2 }) -WorkerScript ${function:Get-HarnessFnWorkerInline} } catch { $bcError = [string]$_ } +Test-Assert ($bcError -match "job 1 doesn't supply 'Name'") ("and its missing mandatory parameter is refused before anything starts (" + $bcError + ")") +function Get-HarnessFnScriptVar { param($Id) $script:bcFnCount = $Id; & { $script:bcFnNested } } +function Get-HarnessFnScriptVarInline($Id) { $script:bcFnCount = $Id } +$bcFindings = Test-PkWorkerSafety -WorkerScript ${function:Get-HarnessFnScriptVar} +$bcFindings = @($bcFindings | Where-Object { $_.Rule -eq 'ScriptVariable' }) +Test-Assert ($bcFindings.Count -eq 1 -and $bcFindings[0].Text -like '*bcFnNested*') ("`${function:Name}: `$script: at the function's top level isn't flagged, in a nested block it is (" + (@($bcFindings | ForEach-Object { $_.Text }) -join ' | ') + ")") +$bcFindings = Test-PkWorkerSafety -WorkerScript ${function:Get-HarnessFnScriptVarInline} +$bcFindings = @($bcFindings | Where-Object { $_.Rule -eq 'ScriptVariable' }) +Test-Assert ($bcFindings.Count -eq 0) ("and the same for function f(...) (" + (@($bcFindings | ForEach-Object { $_.Text }) -join ' | ') + ")") + # A code page read from a CSV or config file is a string. $bcResolve = { param($e) & (Get-Module ParallelKit) { param($x) try { (Resolve-PkEncoding -Encoding $x).CodePage } catch { 'refused' } } $e } $bcCodePages = @((& $bcResolve '65001'), (& $bcResolve ' 437 '), (& $bcResolve 65001), (& $bcResolve ([long]65001))) @@ -5969,6 +6015,26 @@ try { try { Test-HarnessKillTree 'no tree job, a second time' { Invoke-HarnessTreeBatch @{ KillTreeOnExit = $true; StreamTimeoutMs = 500 } @{} $bjHeld } -Left } finally { [PkChildProcessJob]::TestNoTreeJob = $false } Test-Assert (@($script:messages | Where-Object { $_.Message -like '*-KillTreeOnExit*' }).Count -eq 1) ("and only once per process (" + @($script:messages | Where-Object { $_.Message -like '*-KillTreeOnExit*' }).Count + " warning(s) after a second program)") + # A tree job Windows won't end (TerminateJobObject fails) leaves what the + # program started running too: one warning naming the process, once per + # process, in each engine. + $bjFailTerminate = @( + @{ Name = 'tree job not ended, batch'; Run = { Invoke-HarnessTreeBatch @{ KillTreeOnExit = $true; StreamTimeoutMs = 500 } @{} $bjHeld } } + @{ Name = 'tree job not ended, dispatcher'; Run = { Invoke-HarnessTreeDispatch @{ KillTreeOnExit = $true; StreamTimeoutMs = 500 } @{} $bjHeld } } + @{ Name = 'tree job not ended, one program'; Run = { Invoke-PkProcessWithTimeout -FilePath $cmdExe -Arguments $bjHeld -KillTreeOnExit -StreamTimeoutMs 500 } } + ) + foreach ($bjCase in $bjFailTerminate) { + Reset-Harness + [PkChildProcessJob]::TestResetJobWarnings() + [PkChildProcessJob]::TestFailTerminate = $true + try { Test-HarnessKillTree $bjCase.Name $bjCase.Run -Left } finally { [PkChildProcessJob]::TestFailTerminate = $false } + $bjWarned = @($script:messages | Where-Object { $_.Level -eq 'Warn' -and $_.Message -like '*-KillTreeOnExit*process *may still be running*' }) + Test-Assert ($script:messages.Count -eq 1 -and $bjWarned.Count -eq 1) ("and says so in one warning naming the process (" + $script:messages.Count + " message(s): " + (@($script:messages | ForEach-Object { $_.Message }) -join ' | ') + ")") + } + [PkChildProcessJob]::TestFailTerminate = $true + try { Test-HarnessKillTree 'tree job not ended, a second time' { Invoke-HarnessTreeBatch @{ KillTreeOnExit = $true; StreamTimeoutMs = 500 } @{} $bjHeld } -Left } finally { [PkChildProcessJob]::TestFailTerminate = $false } + Test-Assert (@($script:messages | Where-Object { $_.Message -like '*may still be running*' }).Count -eq 1) ("and only once per process (" + @($script:messages | Where-Object { $_.Message -like '*may still be running*' }).Count + " warning(s) after a second program)") + # A force-stop: the program has exited, but the caller's poll never says # done, so neither the poll nor Complete-PkProcess kills what it left. Reset-Harness diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 3783a54..6895836 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -507,9 +507,11 @@ public static class PkChildProcessJob // 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. + // as refused, to test its retry without one. TestFailTerminate makes + // KillTree's TerminateJobObject count as refused, leaving the tree running. public static bool TestNoTreeJob = false; public static bool TestRefuseTreeJob = false; + public static bool TestFailTerminate = false; private static void AddTree(Process process, IntPtr treeJob) { @@ -528,7 +530,7 @@ public static class PkChildProcessJob try { j.DangerousAddRef(ref added); - ended = TerminateJobObject(j.DangerousGetHandle(), 1); + ended = !TestFailTerminate && TerminateJobObject(j.DangerousGetHandle(), 1); } catch (ObjectDisposedException) { return false; } // released meanwhile: taskkill instead finally { if (added) { j.DangerousRelease(); } } @@ -863,12 +865,14 @@ public static class PkChildProcessJob 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, for a running program Windows wouldn't add to it, and for - // -KillTreeOnExit on a program without a tree job. - private static int _initWarned = 0, _assignWarned = 0, _noTreeWarned = 0; + // -KillTreeOnExit on a program without a tree job, or whose tree job + // Windows wouldn't end. + private static int _initWarned = 0, _assignWarned = 0, _noTreeWarned = 0, _killTreeWarned = 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 bool ClaimNoTreeWarning() { return Interlocked.Exchange(ref _noTreeWarned, 1) == 0; } - public static void TestResetJobWarnings() { Interlocked.Exchange(ref _initWarned, 0); Interlocked.Exchange(ref _assignWarned, 0); Interlocked.Exchange(ref _noTreeWarned, 0); } + public static bool ClaimKillTreeWarning() { return Interlocked.Exchange(ref _killTreeWarned, 1) == 0; } + public static void TestResetJobWarnings() { Interlocked.Exchange(ref _initWarned, 0); Interlocked.Exchange(ref _assignWarned, 0); Interlocked.Exchange(ref _noTreeWarned, 0); Interlocked.Exchange(ref _killTreeWarned, 0); } private static StringBuilder BuildCommandLine(string fileName, string arguments) { @@ -1547,6 +1551,11 @@ function ConvertTo-PkArgumentStringCore { if ($ForBatchFile -and $arg.IndexOfAny([char[]]@("`r", "`n")) -ge 0) { throw ("Arguments element " + $position + " contains a line break, which can't be passed to cmd.exe or a .bat or .cmd program: cmd.exe would end the command line there and drop the rest. Pass it another way (a file, an environment variable).") } + # Windows reads a command line up to its first NUL, for any program. + # Start-PkProcessCore checks a string -Arguments the same way. + if ($arg.IndexOf([char]0) -ge 0) { + throw ("Arguments element " + $position + " contains a NUL character, which can't be passed on a command line: Windows would end the command line there and drop the rest, later arguments included. Pass it another way (a file, an environment variable).") + } # The C runtime only needs whitespace and quotes quoted. The rest are for # cmd.exe, which runs a .bat/.cmd: it acts on & | < > ^ ( ) outside # quotes and splits batch arguments at , ; Quoting them is harmless @@ -1740,6 +1749,11 @@ function Start-PkProcessCore { ) $encoding = Resolve-PkEncoding -Encoding $OutputEncoding $commandLine = Resolve-PkArgumentList -Arguments $Arguments -FilePath $FilePath + # A list with a NUL is refused element by element in + # ConvertTo-PkArgumentStringCore; this catches a string. + if ($commandLine.IndexOf([char]0) -ge 0) { + throw "Arguments contains a NUL character, which can't be passed on a command line: Windows would end the command line there and drop the rest. Pass it another way (a file, an environment variable)." + } # For a caller who never ran Initialize-ParallelKit. No-ops once done; # a failure warns once, as Initialize-ParallelKit would. if (-not [PkChildProcessJob]::IsInitialized) { $null = Initialize-PkChildProcessJob -Once } @@ -2059,8 +2073,9 @@ function Stop-PkExitedJobTree { # running, through its tree job. Does nothing while it runs, or for a .Proc # that isn't a Process. A program without a tree job (Windows wouldn't # give it one, the kit has no Job Object, or a custom starter started it) - # can't be reached: that warns, once per process. One try only: the - # dispatcher's poll runs this every pass. + # can't be reached: that warns, once per process, and so does a tree job + # Windows won't end. One try only: the dispatcher's poll runs this every + # pass. param([hashtable]$Job) $proc = $Job['Proc'] if ($proc -isnot [System.Diagnostics.Process] -or $proc.HasExited -ne $true) { return } @@ -2071,7 +2086,11 @@ function Stop-PkExitedJobTree { } return } - $null = [PkChildProcessJob]::KillTree($proc) + # Windows refusing to end the tree job has no fallback: with the program + # gone, taskkill /T can't find its children. + if (-not [PkChildProcessJob]::KillTree($proc) -and [PkChildProcessJob]::ClaimKillTreeWarning()) { + Write-PkMessage ("[WARNING] -KillTreeOnExit couldn't stop what process " + $proc.Id + " left running: Windows wouldn't end the program's own Job Object, so anything it started may still be running. It still ends when PowerShell does. Shown once.") -Level Warn + } } function Wait-PkProcess { @@ -3437,7 +3456,8 @@ function Get-PkWorkerSafeFunctionName { function Get-PkHandlerParamCount { # How many parameters a callback declares, or -1 if it has no param() - # block (it takes whatever it's given, in $args). + # block (it takes whatever it's given, in $args). Invoke-PkRunspaceBatch + # reads a -WorkerScript's parameters the same way. param([Parameter(Mandatory)][scriptblock]$Callback) $ast = $Callback.Ast if ($ast -is [System.Management.Automation.Language.FunctionDefinitionAst]) { @@ -3725,8 +3745,18 @@ function Invoke-PkRunspaceBatch { # it out. $mandatoryParams = [System.Collections.Generic.List[string]]::new() $hasParameterSets = $false - if ($null -ne $WorkerScript.Ast.ParamBlock) { - foreach ($workerParam in $WorkerScript.Ast.ParamBlock.Parameters) { + # A function's own scriptblock (${function:Name}) has the function as its + # Ast: its parameters are in function f($a) or in its body's param() + # block, as Get-PkHandlerParamCount reads them. + $workerAst = $WorkerScript.Ast + $workerParamList = $null + if ($workerAst -is [System.Management.Automation.Language.FunctionDefinitionAst]) { + if ($null -ne $workerAst.Parameters) { $workerParamList = $workerAst.Parameters } + $workerAst = $workerAst.Body + } + if ($null -eq $workerParamList -and $null -ne $workerAst.ParamBlock) { $workerParamList = $workerAst.ParamBlock.Parameters } + if ($null -ne $workerParamList) { + foreach ($workerParam in $workerParamList) { $null = $declaredParams.Add($workerParam.Name.VariablePath.UserPath) $isMandatory = $false foreach ($paramAttr in $workerParam.Attributes) { @@ -4372,7 +4402,11 @@ function Test-PkWorkerSafetyCore { # A function defined inside the worker script is in the same # position as a shared one: called from a closure, its $script: # can read as empty. - foreach ($innerFn in $ast.FindAll({ param($node) $node -is [System.Management.Automation.Language.FunctionDefinitionAst] }, $true)) { $scriptVarScopes.Add($innerFn.Body) } + # Not the worker itself when it's a function (${function:Name}): + # its body is the worker's top level. + foreach ($innerFn in $ast.FindAll({ param($node) $node -is [System.Management.Automation.Language.FunctionDefinitionAst] }, $true)) { + if (-not [object]::ReferenceEquals($innerFn, $ast)) { $scriptVarScopes.Add($innerFn.Body) } + } } else { $scriptVarScopes.Add($ast) } diff --git a/README.md b/README.md index 73fc3ec..ba7ac7f 100644 --- a/README.md +++ b/README.md @@ -286,6 +286,8 @@ Each command is a hashtable with `FilePath`, `Arguments` and optionally `Working Only the list form gets this quoting. A string, including one built with `ConvertTo-PkArgumentString`, is passed as written. +A NUL character in an argument, in a list or a string, is an error for any program, raised before it starts: Windows would end the command line there and drop the rest. +
@@ -310,7 +312,7 @@ The per-command keys go on the command itself, for example one that keeps all of `-StreamTimeoutMs` (default 15000) is how long to wait for a program's output after it exits; see `StreamTimedOut` in [Process results](#process-results). -`-KillTreeOnExit` kills whatever a program started that's still running when the program itself exits, whether or not it holds the program's output open. It's off by default, since some tools leave a build server or a daemon running on purpose. A command's own `KillTreeOnExit` key, `$true` or `$false`, overrides it either way. `Invoke-PkProcessWithTimeout` and the dispatcher take it too; `Start-PkProcess` doesn't, since it returns before there's an exit to act on. It goes through the program's own Job Object, so for a program without one (`StartMode` `NoJob`, or Windows refused it) it can't kill anything; it warns once per session instead. `StartMode` `CreatedInJob` describes how programs start, not whether each one got its own Job Object. In `AddedToJob` mode it can miss a child the program started straight away. +`-KillTreeOnExit` kills whatever a program started that's still running when the program itself exits, whether or not it holds the program's output open. It's off by default, since some tools leave a build server or a daemon running on purpose. A command's own `KillTreeOnExit` key, `$true` or `$false`, overrides it either way. `Invoke-PkProcessWithTimeout` and the dispatcher take it too; `Start-PkProcess` doesn't, since it returns before there's an exit to act on. It goes through the program's own Job Object, so for a program without one (`StartMode` `NoJob`, or Windows refused it) it can't kill anything; it warns once per session instead. If Windows won't end a program's Job Object, what it started may still be running, and that warns once per session too. `StartMode` `CreatedInJob` describes how programs start, not whether each one got its own Job Object. In `AddedToJob` mode it can miss a child the program started straight away.
diff --git a/Source/PkChildProcessJob.cs b/Source/PkChildProcessJob.cs index 4150445..42ae14a 100644 --- a/Source/PkChildProcessJob.cs +++ b/Source/PkChildProcessJob.cs @@ -265,9 +265,11 @@ private sealed class TreeJob : SafeHandleZeroOrMinusOneIsInvalid // 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. + // as refused, to test its retry without one. TestFailTerminate makes + // KillTree's TerminateJobObject count as refused, leaving the tree running. public static bool TestNoTreeJob = false; public static bool TestRefuseTreeJob = false; + public static bool TestFailTerminate = false; private static void AddTree(Process process, IntPtr treeJob) { @@ -286,7 +288,7 @@ public static bool KillTree(Process process) try { j.DangerousAddRef(ref added); - ended = TerminateJobObject(j.DangerousGetHandle(), 1); + ended = !TestFailTerminate && TerminateJobObject(j.DangerousGetHandle(), 1); } catch (ObjectDisposedException) { return false; } // released meanwhile: taskkill instead finally { if (added) { j.DangerousRelease(); } } @@ -621,12 +623,14 @@ public static string StartMode 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, for a running program Windows wouldn't add to it, and for - // -KillTreeOnExit on a program without a tree job. - private static int _initWarned = 0, _assignWarned = 0, _noTreeWarned = 0; + // -KillTreeOnExit on a program without a tree job, or whose tree job + // Windows wouldn't end. + private static int _initWarned = 0, _assignWarned = 0, _noTreeWarned = 0, _killTreeWarned = 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 bool ClaimNoTreeWarning() { return Interlocked.Exchange(ref _noTreeWarned, 1) == 0; } - public static void TestResetJobWarnings() { Interlocked.Exchange(ref _initWarned, 0); Interlocked.Exchange(ref _assignWarned, 0); Interlocked.Exchange(ref _noTreeWarned, 0); } + public static bool ClaimKillTreeWarning() { return Interlocked.Exchange(ref _killTreeWarned, 1) == 0; } + public static void TestResetJobWarnings() { Interlocked.Exchange(ref _initWarned, 0); Interlocked.Exchange(ref _assignWarned, 0); Interlocked.Exchange(ref _noTreeWarned, 0); Interlocked.Exchange(ref _killTreeWarned, 0); } private static StringBuilder BuildCommandLine(string fileName, string arguments) {