Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 43 additions & 4 deletions ParallelKit.Harness.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -1119,6 +1119,35 @@ $d = Invoke-PkProcessDispatch -MaxConcurrent 1 -MaxQueueAhead 1 -AbortTimeoutSec
-JobBuilder { param($g) if ($late.Aborting) { $late.LateBuilds++ }; return @(@{ FilePath = $cmdExe; Arguments = '/c exit 0' }) }.GetNewClosure() `
-JobFinalize { param($job, $pending) $null = Complete-PkProcess -Job $job; if (-not $late.Aborting) { $late.Aborting = $true; Request-PkAbort } }.GetNewClosure()
Test-Assert ($d.Aborted -and $late.Groups -eq 1 -and $late.LateBuilds -eq 0) ("dispatch: a -JobFinalize that requests an abort gets no more groups from -GroupProvider (asked for " + $late.Groups + " group(s), " + $late.LateBuilds + " built after the abort)")
# The same for an abort from the callbacks that run while groups are fetched,
# with room to queue 3 groups ahead: -GroupProvider isn't asked again, and no
# group asked for after the abort is built. -GroupCompleteCallback and
# -GroupReleaseCheck run there for groups with no jobs.
foreach ($fetchCase in 'GroupProvider', 'JobBuilder', 'GroupCompleteCallback', 'GroupReleaseCheck') {
Reset-Harness
$fetch = @{ Asked = 0; AbortedAt = -1; AskedAfter = 0; LateBuilds = 0; Case = $fetchCase }
$fetchAbort = { if ($fetch.AbortedAt -lt 0) { $fetch.AbortedAt = $fetch.Asked; Request-PkAbort } }.GetNewClosure()
$fetchParams = @{
MaxConcurrent = 1; MaxQueueAhead = 3; AbortTimeoutSeconds = 5
GroupProvider = {
if ($fetch.Asked -ge 10) { return $null }
$fetch.Asked++
if ($fetch.AbortedAt -ge 0) { $fetch.AskedAfter++ }
if ($fetch.Case -eq 'GroupProvider') { & $fetchAbort }
return $fetch.Asked
}.GetNewClosure()
JobBuilder = {
param($g)
if ($fetch.AbortedAt -ge 0 -and $g -gt $fetch.AbortedAt) { $fetch.LateBuilds++ }
if ($fetch.Case -eq 'JobBuilder') { & $fetchAbort; return @(@{ FilePath = $cmdExe; Arguments = '/c exit 0' }) }
}.GetNewClosure()
JobFinalize = { param($job, $pending) $null = Complete-PkProcess -Job $job }
}
if ($fetchCase -eq 'GroupCompleteCallback') { $fetchParams.GroupCompleteCallback = { param($g) & $fetchAbort }.GetNewClosure() }
if ($fetchCase -eq 'GroupReleaseCheck') { $fetchParams.GroupReleaseCheck = { param($g) & $fetchAbort; return $true }.GetNewClosure() }
$d = Invoke-PkProcessDispatch @fetchParams
Test-Assert ($d.Aborted -and $fetch.AbortedAt -ge 1 -and $fetch.AskedAfter -eq 0 -and $fetch.LateBuilds -eq 0) ("dispatch: a -" + $fetchCase + " that requests an abort while groups are fetched gets no more groups (asked " + $fetch.AskedAfter + " more time(s) after the abort, " + $fetch.LateBuilds + " built)")
}

# Your own long step inside Invoke-PkRun has to poll.
Reset-Harness
Expand Down Expand Up @@ -5600,17 +5629,27 @@ $beR = Get-HarnessCapRun -Arguments '/d /c 1>&2 echo 0123456789ABCDEFGHIJ' -Cap
Test-Assert ($beR.Stderr -ceq "01234HIJ`r`n" -and $beR.StderrDroppedChars -eq 12 -and $beR.StdoutDroppedChars -eq 0) ("stderr is capped the same way, on its own ('" + ([string]$beR.Stderr -replace "`r", '\r' -replace "`n", '\n') + "', dropped " + $beR.StderrDroppedChars + ")")

# A cut never splits a surrogate pair. cmd /u writes UTF-16: four emoji are
# 8 characters, plus CRLF. A cap of 6 puts the head's end and the tail's
# start inside pairs.
# 8 characters, plus CRLF. A cap of 7 puts the head's end inside a pair (its
# first half, and the slot, go to the tail) and the tail's start inside
# another.
$beEmoji = [char]::ConvertFromUtf32(0x1F600)
$beR = Get-HarnessCapRun -Arguments ('/d /u /c echo ' + $beEmoji * 4) -Cap 6 -Encoding 'unicode'
$beR = Get-HarnessCapRun -Arguments ('/d /u /c echo ' + $beEmoji * 4) -Cap 7 -Encoding 'unicode'
$beText = [string]$beR.Stdout
$beLone = 0
for ($i = 0; $i -lt $beText.Length; $i++) {
if ([char]::IsHighSurrogate($beText[$i])) { if ($i + 1 -lt $beText.Length -and [char]::IsLowSurrogate($beText[$i + 1])) { $i++ } else { $beLone++ } }
elseif ([char]::IsLowSurrogate($beText[$i])) { $beLone++ }
}
Test-Assert ($beText -ceq ($beEmoji + "`r`n") -and $beLone -eq 0 -and $beR.StdoutDroppedChars -eq 6) ("a cut inside a surrogate pair drops the whole pair, never half (" + $beText.Length + " characters kept, " + $beLone + " half pairs, dropped " + $beR.StdoutDroppedChars + ")")
Test-Assert ($beText -ceq ($beEmoji * 2 + "`r`n") -and $beLone -eq 0 -and $beR.StdoutDroppedChars -eq 4) ("a cut inside a surrogate pair drops the whole pair, never half (" + $beText.Length + " characters kept, " + $beLone + " half pairs, dropped " + $beR.StdoutDroppedChars + ")")
# Output exactly as long as the cap is kept whole, even with a pair where the
# head would end: the tail takes the slot the head turns away.
$beR = Get-HarnessCapRun -Arguments ('/d /u /c echo ab' + $beEmoji + 'c') -Cap 7 -Encoding 'unicode'
Test-Assert ($beR.Stdout -ceq ('ab' + $beEmoji + "c`r`n") -and $beR.StdoutDroppedChars -eq 0) ("output exactly at the cap, with a surrogate pair at the head's end, comes back whole (" + ((Format-HarnessCapRun $beR) -replace [regex]::Escape($beEmoji), '<emoji>') + ")")
$beText = foreach ($beCase in @(@{ Text = $beEmoji; Cap = 2 }, @{ Text = 'a' + $beEmoji + 'b'; Cap = 4 }, @{ Text = 'ab' + $beEmoji + 'cd'; Cap = 6 })) {
$beTask = [PkStreamReadTask]::Run([System.IO.StringReader]::new($beCase.Text), $beCase.Cap)
if ($beTask.Result -cne $beCase.Text -or $beTask.DroppedChars -ne 0) { ($beCase.Text -replace [regex]::Escape($beEmoji), '<emoji>') + ' cap ' + $beCase.Cap + ": kept '" + ($beTask.Result -replace [regex]::Escape($beEmoji), '<emoji>') + "', dropped " + $beTask.DroppedChars }
}
Test-Assert ($null -eq $beText) ("the same for an emoji under a cap of 2, a<emoji>b under 4 and ab<emoji>cd under 6" + $(if ($beText) { " (" + ($beText -join '; ') + ")" }))

# Long output: what's held stays within the cap while the program writes,
# and the count adds up to the whole.
Expand Down
23 changes: 16 additions & 7 deletions ParallelKit.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -292,8 +292,11 @@ public sealed class PkStreamReadTask : Task<string>
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;
// it. _tailCap is 0 with no cap. A head that turns away a pair's
// first half gives the tail its slot, before the tail is allocated,
// so output that fits the cap is kept whole.
private readonly int _headCap;
private int _tailCap;
private bool _headFull;
private char[] _tail;
private int _tailStart, _tailCount;
Expand Down Expand Up @@ -334,8 +337,9 @@ public sealed class PkStreamReadTask : Task<string>
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--; }
// The head never ends on the first half of a surrogate
// pair: that half goes to the tail, and its slot too.
if (take > 0 && Char.IsHighSurrogate(chunk[take - 1])) { take--; _tailCap++; }
}
_text.Append(chunk, 0, take);
i = take;
Expand Down Expand Up @@ -1535,8 +1539,10 @@ function ConvertTo-PkArgumentString {
# batch-file program they also write a quote as "" instead of \", which
# cmd.exe can't be tricked by. This function's own output uses \": for
# those, give the kit the list instead. Not covered for those programs
# either way: cmd expands %NAME% inside quotes, and splits batch arguments
# at = (left unquoted, since some programs read NAME=value themselves).
# either way: cmd expands %NAME% inside quotes (and, with delayed expansion
# on, !NAME!, dropping a ^ from an argument that holds a !), and splits
# batch arguments at = (left unquoted, since some programs read NAME=value
# themselves).
# .PARAMETER Arguments
# The arguments, in order. A $null one is left out; an empty string is passed
# as "". A file or folder object (from Get-ChildItem or Get-Item) is its full
Expand Down Expand Up @@ -2864,7 +2870,10 @@ function Invoke-PkProcessDispatchCore {
}
}

while ((-not $pkProviderExhausted) -and $pkActiveGroupCount -lt $pkMaxQueueAhead -and (-not $pkCancelToken.IsCancellationRequested)) {
# The abort flag per group too, so an abort raised by -GroupProvider,
# -JobBuilder, -GroupReleaseCheck or -GroupCompleteCallback asks for
# no more groups on this pass.
while ((-not $pkProviderExhausted) -and $pkActiveGroupCount -lt $pkMaxQueueAhead -and (-not $pkCancelToken.IsCancellationRequested) -and (-not [PkConsoleCtrl]::AbortRequested)) {
# Invoke-PkCallback inlined, to count the values the provider
# output. Collected by plain assignment, `return ,@('a', 'b')` (one
# value, a list) and two values output separately are the same
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,7 @@ Each command is a hashtable with `FilePath`, `Arguments` and optionally `Working
- The program gets exactly that list back, spaces, quotes and trailing backslashes included. Don't pre-quote elements: a quote inside one is passed on as a quote character.
- `$null` elements are left out, a file or folder object from `Get-ChildItem` or `Get-Item` is its full path, and an element that's itself a list is an error.
- The quoting follows the rules most Windows programs use. `cmd.exe` itself (`FilePath = 'cmd.exe'`, `Arguments = @('/d', '/c', 'tool.exe', $file)`) gets the batch-file quoting described next, and the program after `/c` gets the rest of the list as given, with the same exception as for `%*` there (a `"` in an element, and a program built against `msvcrt.dll`). `cmd.exe` strips the quotes from a program path with spaces, though, so for one of those give it one string: `'/d /s /c ""C:\My Tools\tool.exe" "a b""'`.
- A `.bat` or `.cmd` program runs through `cmd.exe`, and the list is quoted for it: an element holding `&`, `|`, `<`, `>`, `^`, `(`, `)`, `,`, `;` or `"` reaches it as one argument and can't make `cmd.exe` run anything else. A `"` is written `""` for it, so the batch file itself sees the quote doubled in `%1` or `%~1`. A program it passes `%*` on to gets the list back as given if it was built with Microsoft's C runtime from 2008 on, as most are. One built against the older `msvcrt.dll`, as most MinGW builds are, reads a `"` in an element differently and can split it or run it into the next; elements without a `"` are fine. An element with a line break is an error. What quoting can't stop: `cmd.exe` expands `%NAME%` when a variable by that name exists, and splits batch arguments at `=` (left unquoted, since some programs read `NAME=value` themselves). The batch file can also undo the quoting: `%~1` strips the quotes, so a line like `echo %~1` runs the `& echo INJECTED` in an element `a & echo INJECTED`. Keep it quoted in the batch file (`"%~1"`), or use `%1`.
- A `.bat` or `.cmd` program runs through `cmd.exe`, and the list is quoted for it: an element holding `&`, `|`, `<`, `>`, `^`, `(`, `)`, `,`, `;` or `"` reaches it as one argument and can't make `cmd.exe` run anything else. A `"` is written `""` for it, so the batch file itself sees the quote doubled in `%1` or `%~1`. A program it passes `%*` on to gets the list back as given if it was built with Microsoft's C runtime from 2008 on, as most are. One built against the older `msvcrt.dll`, as most MinGW builds are, reads a `"` in an element differently and can split it or run it into the next; elements without a `"` are fine. An element with a line break is an error. What quoting can't stop: `cmd.exe` expands `%NAME%` when a variable by that name exists, and splits batch arguments at `=` (left unquoted, since some programs read `NAME=value` themselves). With delayed expansion on (`cmd /v:on`, `setlocal EnableDelayedExpansion` in the batch file, or the registry setting `cmd /?` describes), `!NAME!` is expanded inside quotes too, and a `^` in an element that holds a `!` is dropped. In a batch file, an unset `!NAME!` or a lone `!` is dropped as well. The batch file can also undo the quoting: `%~1` strips the quotes, so a line like `echo %~1` runs the `& echo INJECTED` in an element `a & echo INJECTED`. Keep it quoted in the batch file (`"%~1"`), or use `%1`.

Only the list form gets this quoting. A string, including one built with `ConvertTo-PkArgumentString`, is passed as written.

Expand Down
12 changes: 8 additions & 4 deletions Source/PkChildProcessJob.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,11 @@ private sealed class Buffer
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;
// it. _tailCap is 0 with no cap. A head that turns away a pair's
// first half gives the tail its slot, before the tail is allocated,
// so output that fits the cap is kept whole.
private readonly int _headCap;
private int _tailCap;
private bool _headFull;
private char[] _tail;
private int _tailStart, _tailCount;
Expand Down Expand Up @@ -92,8 +95,9 @@ private void Append(char[] chunk, int 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--; }
// The head never ends on the first half of a surrogate
// pair: that half goes to the tail, and its slot too.
if (take > 0 && Char.IsHighSurrogate(chunk[take - 1])) { take--; _tailCap++; }
}
_text.Append(chunk, 0, take);
i = take;
Expand Down