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
78 changes: 78 additions & 0 deletions ParallelKit.Harness.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -6492,6 +6492,84 @@ try {
Write-Host ""
}

# ==============================================================================
if (Test-HarnessSection 'BO' "a program or working folder past 260 characters starts by its short name") {
# Windows refuses a program path of 260 characters or more, and a working
# folder of 259 or more, even with long paths enabled; the kit tries once more
# with their 8.3 short names. Those exist only where the volume makes them, so
# the cases that need them skip without.
Reset-Harness
$boPrefix = [string][char]92 + [char]92 + '?' + [char]92
$boRoot = Join-Path $env:TEMP ("pk-harness-bo-" + $PID)
$boDir = $boRoot
foreach ($c in 'a', 'b', 'c', 'd', 'e') { $boDir = Join-Path $boDir ([string]$c * 60) }
$boExe = Join-Path $boDir 'pk-bo-cmd.exe'
$boText = Join-Path $boDir 'pk-bo-text.exe'
$boMissing = Join-Path $boDir 'pk-bo-missing.exe'
try {
$null = [System.IO.Directory]::CreateDirectory($boPrefix + $boDir)
[System.IO.File]::Copy($cmdExe, $boPrefix + $boExe)
# Short name or not, Windows can't run this one: not a program.
[System.IO.File]::WriteAllText($boPrefix + $boText, 'not a program')
$boShortNames = [bool](@(& $cmdExe /d /c ('dir /x /ad "' + $boRoot + '"')) -match '\sAAAAAA~\d+\s')
Test-Assert ($boExe.Length -ge 260 -and $boDir.Length -ge 259) ("the test program's path is " + $boExe.Length + " characters, its folder " + $boDir.Length)

$boCommandLine = '/d /c echo %CMDCMDLINE%& exit 7'
$boCommands = @(
@{ Name = 'program'; FilePath = $boExe; Arguments = $boCommandLine }
@{ Name = 'folder'; FilePath = $cmdExe; Arguments = '/d /c cd& exit 7'; WorkingDirectory = $boDir }
@{ Name = 'both'; FilePath = $boExe; Arguments = '/d /c cd& exit 7'; WorkingDirectory = $boDir }
@{ Name = 'missing'; FilePath = $boMissing; Arguments = '/d /c exit 7' }
@{ Name = 'not a program'; FilePath = $boText; Arguments = '/d /c exit 7' }
@{ Name = 'missing folder'; FilePath = $cmdExe; Arguments = '/d /c exit 7'; WorkingDirectory = (Join-Path $boDir 'pk-bo-missing') }
)
foreach ($boPath in 'job', 'fallback') {
[PkChildProcessJob]::TestUseProcessStart = ($boPath -eq 'fallback')
try { $boBatch = Invoke-PkProcessBatch -Commands $boCommands -MaxConcurrent 2 }
finally { [PkChildProcessJob]::TestUseProcessStart = $false }
$boRows = @{}
foreach ($br in $boBatch.Results) { $boRows[$br.Command['Name']] = $br }
$boLabel = $(if ($boPath -eq 'job') { 'CreatedInJob' } else { 'Process.Start' })

if ($boShortNames) {
# The program runs by its short name, with nothing added to its
# command line: no long path in front of the arguments.
$r = $boRows['program']
$boLine = ([string]$r.Stdout).Trim()
Test-Assert ($null -eq $r.StartError -and $r.ExitCode -eq 7 -and $boLine -match '^"[^"]*\\EEEEEE~\d\\PK-BO-~\d\.EXE" /d /c echo ') ("a program past 260 characters runs by its short name, its arguments as given, " + $boLabel + " (exit " + $r.ExitCode + ", " + $(if ($r.StartError) { $r.StartError } else { $boLine }) + ")")
$r = $boRows['folder']
$boCd = ([string]$r.Stdout).Trim()
Test-Assert ($null -eq $r.StartError -and $r.ExitCode -eq 7 -and $boCd -like '*\EEEEEE~*') ("a working folder past 259 characters is used by its short name, " + $boLabel + " (exit " + $r.ExitCode + ", " + $(if ($r.StartError) { $r.StartError } else { $boCd }) + ")")
$r = $boRows['both']
Test-Assert ($null -eq $r.StartError -and $r.ExitCode -eq 7 -and ([string]$r.Stdout).Trim() -ceq $boCd) ("and both at once, " + $boLabel + " (exit " + $r.ExitCode + ", " + $(if ($r.StartError) { $r.StartError } else { ([string]$r.Stdout).Trim() }) + ")")
} else {
Test-Skip ("a program and a working folder past 260 characters, by their short names, " + $boLabel + ": " + $env:TEMP + "'s volume doesn't make 8.3 short names")
}

# No short name (the file doesn't exist), or the short name fails
# too (not a program): the error is the first try's, for the path
# given. Without a short name it also says the length is why.
foreach ($boCase in @(@{ N = 'missing'; Note = "*The program's path is * characters: Windows won't start a program by a path of 260 or more*Use a shorter path." }, @{ N = 'not a program'; Note = $null }, @{ N = 'missing folder'; Note = "*The working folder's path is * characters: Windows won't start a program in a folder of 259 or more*Use a shorter path." })) {
$r = $boRows[$boCase.N]
$boGiven = $r.Command['FilePath']
$boNoteRight = $(if ($null -ne $boCase.Note) { $r.StartError -like $boCase.Note } else { $r.StartError -notlike '*Use a shorter path*' })
Test-Assert ($null -ne $r.StartError -and $r.StartError -like ("Start-PkProcess: could not start '" + $boGiven + "': *") -and $r.StartError -notlike '*\EEEEEE~*' -and $r.StartError -notlike '*PK-BO-~*' -and $boNoteRight -and $null -eq $r.ExitCode) ("a " + $boCase.N + " past 260 characters fails with the error for the path given" + $(if ($null -ne $boCase.Note) { ", saying the length is why" } else { "" }) + ", " + $boLabel + " (" + $r.StartError + ")")
}
}
if ($boShortNames) {
# The other entry points start through the same code.
$boTimeout = $null
$boTimeoutError = ''
try { $boTimeout = Invoke-PkProcessWithTimeout -FilePath $boExe -Arguments '/d /c cd& exit 7' -WorkingDirectory $boDir } catch { $boTimeoutError = [string]$_ }
Test-Assert ($null -ne $boTimeout -and $boTimeout.ExitCode -eq 7 -and ([string]$boTimeout.Stdout).Trim() -like '*\EEEEEE~*') ("Invoke-PkProcessWithTimeout too (" + $(if ($null -ne $boTimeout) { "exit " + $boTimeout.ExitCode } else { $boTimeoutError }) + ")")
}
} finally {
[PkChildProcessJob]::TestUseProcessStart = $false
Remove-Item -LiteralPath $boRoot -Recurse -Force -ErrorAction SilentlyContinue
}
Write-Host ""
}

Set-PkMessageHandler -Handler $null
Reset-PkAbortState
if ($null -ne $moduleDir) {
Expand Down
91 changes: 82 additions & 9 deletions ParallelKit.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -875,6 +875,44 @@ public static class PkChildProcessJob
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); }

[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern uint GetShortPathName(string lpszLongPath, StringBuilder lpszShortPath, uint cchBuffer);

// The 8.3 short form of a full path, or null when it has none that differs:
// the path doesn't exist, isn't rooted, or the volume doesn't make short
// names. Asked with the \\?\ prefix, which works past 260 characters on
// both runtimes (without it, PowerShell 7 fails there); the answer comes
// back without it, since CreateProcess refuses a prefixed program path.
public static string GetShortPath(string path)
{
if (string.IsNullOrEmpty(path)) { return null; }
// .NET Framework throws here on characters like " and |; it's asked
// after a start has failed, and mustn't replace that error.
try { if (!Path.IsPathRooted(path)) { return null; } }
catch (ArgumentException) { return null; }
string full = path.Replace('/', '\\');
if (!full.StartsWith(@"\\?\", StringComparison.Ordinal))
{
if (full.StartsWith(@"\\", StringComparison.Ordinal)) { full = @"\\?\UNC\" + full.Substring(2); }
else if (full.Length > 1 && full[1] == ':' && full.Length > 2 && full[2] == '\\') { full = @"\\?\" + full; }
else { return null; } // \folder or C:folder: relative to a current drive or folder
}
StringBuilder sb = new StringBuilder(full.Length + 1);
uint n = GetShortPathName(full, sb, (uint)sb.Capacity);
if (n == 0) { return null; }
if (n > sb.Capacity)
{
sb = new StringBuilder((int)n);
n = GetShortPathName(full, sb, (uint)sb.Capacity);
if (n == 0 || n > sb.Capacity) { return null; }
}
string s = sb.ToString();
if (s.StartsWith(@"\\?\UNC\", StringComparison.Ordinal)) { s = @"\\" + s.Substring(8); }
else if (s.StartsWith(@"\\?\", StringComparison.Ordinal)) { s = s.Substring(4); }
if (string.Equals(s, path, StringComparison.OrdinalIgnoreCase)) { return null; }
return s;
}

private static StringBuilder BuildCommandLine(string fileName, string arguments)
{
// As Process.Start builds it: the program quoted unless it already is.
Expand Down Expand Up @@ -1786,6 +1824,7 @@ function Start-PkProcessCore {
# script, and a $null process would be polled forever. The path handling
# is in here too: it throws on characters Windows doesn't allow.
$started = $null
$lengthNote = ""
try {
if ($WorkingDirectory) {
if ($null -ne $here) { $WorkingDirectory = Resolve-PkFileSystemPath -Path $WorkingDirectory -Here $here -CallerState $CallerState }
Expand All @@ -1802,15 +1841,48 @@ function Start-PkProcessCore {
# Process.Start, and the job just after (a child it starts at once
# can miss it then).
$fallbackReason = $null
$started = [PkChildProcessJob]::TryStart($psi.FileName, $psi.Arguments, $psi.WorkingDirectory, $encoding, $InheritStdin, [ref]$fallbackReason)
if ($null -eq $started) {
# Once per process: the cost is the same for every program after.
if ($null -ne $fallbackReason -and [PkChildProcessJob]::ClaimFallbackWarning()) {
Write-PkMessage ("[WARNING] Starting programs with Process.Start and adding them to the Job Object just after, because " + $fallbackReason + ". A child a program starts straight away (cmd /c tool.exe) can escape the cleanup if PowerShell is killed outright. Shown once.") -Level Warn
}
$proc = [System.Diagnostics.Process]::Start($psi)
if (-not $InheritStdin) {
try { $proc.StandardInput.Close() } catch { } # nothing is written, so a failed close is a pipe whose program has already gone
$firstError = $null
while ($true) {
try {
$started = [PkChildProcessJob]::TryStart($psi.FileName, $psi.Arguments, $psi.WorkingDirectory, $encoding, $InheritStdin, [ref]$fallbackReason)
if ($null -eq $started) {
# Once per process: the cost is the same for every program after.
if ($null -ne $fallbackReason -and [PkChildProcessJob]::ClaimFallbackWarning()) {
Write-PkMessage ("[WARNING] Starting programs with Process.Start and adding them to the Job Object just after, because " + $fallbackReason + ". A child a program starts straight away (cmd /c tool.exe) can escape the cleanup if PowerShell is killed outright. Shown once.") -Level Warn
}
$proc = [System.Diagnostics.Process]::Start($psi)
if (-not $InheritStdin) {
try { $proc.StandardInput.Close() } catch { } # nothing is written, so a failed close is a pipe whose program has already gone
}
}
break
} catch {
if ($null -ne $firstError) {
# The short names failed too: the first error, for the paths given.
$psi.FileName = $longFile
$psi.WorkingDirectory = $longDir
throw $firstError
}
$firstError = $_
# Windows refuses a program path of 260 characters or more and
# a working folder of 259 or more (it adds a backslash), on both
# start paths and even with long paths enabled. The 8.3 short
# names, where the volume has them, start fine: one more try
# with those.
$longFile = $psi.FileName
$longDir = $psi.WorkingDirectory
$shortFile = $null
$shortDir = $null
if ($longFile.Length -ge 260) { $shortFile = [PkChildProcessJob]::GetShortPath($longFile) }
if ($longDir.Length -ge 259) { $shortDir = [PkChildProcessJob]::GetShortPath($longDir) }
if ($null -eq $shortFile -and $null -eq $shortDir) {
# Windows' own error doesn't say the length is why.
if ($longFile.Length -ge 260) { $lengthNote = "The program's path is " + $longFile.Length + " characters: Windows won't start a program by a path of 260 or more, and the kit found no 8.3 short name to try instead. Use a shorter path." }
elseif ($longDir.Length -ge 259) { $lengthNote = "The working folder's path is " + $longDir.Length + " characters: Windows won't start a program in a folder of 259 or more, and the kit found no 8.3 short name to try instead. Use a shorter path." }
throw
}
if ($null -ne $shortFile) { $psi.FileName = $shortFile }
if ($null -ne $shortDir) { $psi.WorkingDirectory = $shortDir }
}
}
} catch {
Expand All @@ -1819,6 +1891,7 @@ function Start-PkProcessCore {
# Windows' reason, without PowerShell's "Exception calling <method>" wrapper.
$reason = [string]$_
if ($_.Exception -is [System.Management.Automation.MethodInvocationException] -and $null -ne $_.Exception.InnerException) { $reason = $_.Exception.InnerException.Message }
if ($lengthNote) { $reason = $reason.TrimEnd('.') + ". " + $lengthNote }
# The original goes along as the inner exception: the batch reads Windows' error code from it.
throw [System.Management.Automation.RuntimeException]::new("Start-PkProcess: could not start '" + $FilePath + "'" + $tried + ": " + $reason, $_.Exception)
}
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -683,7 +683,7 @@ Other pieces: `Request-PkAbort` triggers the same abort from code. `Test-PkAbort
- If a program can't be started inside the Job Object (`Initialize-ParallelKit`'s `StartMode` isn't `CreatedInJob`, or the one-time warning says so), then on Windows PowerShell with a UTF-8 console its stdin isn't quite empty: .NET Framework puts a byte-order mark in it.
- A program's output is collected in memory and handed over when it exits; there's no live line-by-line output. A program that prints gigabytes will use that much memory, unless `-MaxOutputChars` caps what's kept. A batch keeps every result, output included, until it returns, which adds up over thousands of chatty programs. If you only need the output in `-OnComplete`, drop it there with `$result.Stdout = $null; $result.Stderr = $null` and it's freed as the batch goes.
- A program can't start a child outside the kit's Job Object. One that tries (`CREATE_BREAKAWAY_FROM_JOB`) gets "access denied" from Windows, which can look like a bug in the program. The kit doesn't allow it on purpose, since that child would escape the cleanup.
- A program whose path is longer than 260 characters can't be started, even with long paths enabled and in the `\\?\` form: Windows refuses it, and the start fails with "The filename or extension is too long" (or, for a plain path on PowerShell 7, "The system cannot find the file specified").
- Windows won't start a program whose path is 260 characters or longer, or in a working folder of 259 or longer, even with long paths enabled and in the `\\?\` form. The kit then tries once more with their 8.3 short names (`C:\PROGRA~1\...`), which works where the volume makes short names: usually the system drive, often not others. A program started that way sees its own path in that short form. Without short names the start fails with Windows' error ("The filename or extension is too long", "The directory name is invalid", or, for a plain program path on PowerShell 7, "The system cannot find the file specified"), followed by a sentence saying the path's length is why.
- Child-process cleanup has the gaps listed under [Process-tree cleanup limitations](#process-tree-cleanup-limitations).

## Testing
Expand Down
38 changes: 38 additions & 0 deletions Source/PkChildProcessJob.cs
Original file line number Diff line number Diff line change
Expand Up @@ -633,6 +633,44 @@ public static string StartMode
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); }

[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern uint GetShortPathName(string lpszLongPath, StringBuilder lpszShortPath, uint cchBuffer);

// The 8.3 short form of a full path, or null when it has none that differs:
// the path doesn't exist, isn't rooted, or the volume doesn't make short
// names. Asked with the \\?\ prefix, which works past 260 characters on
// both runtimes (without it, PowerShell 7 fails there); the answer comes
// back without it, since CreateProcess refuses a prefixed program path.
public static string GetShortPath(string path)
{
if (string.IsNullOrEmpty(path)) { return null; }
// .NET Framework throws here on characters like " and |; it's asked
// after a start has failed, and mustn't replace that error.
try { if (!Path.IsPathRooted(path)) { return null; } }
catch (ArgumentException) { return null; }
string full = path.Replace('/', '\\');
if (!full.StartsWith(@"\\?\", StringComparison.Ordinal))
{
if (full.StartsWith(@"\\", StringComparison.Ordinal)) { full = @"\\?\UNC\" + full.Substring(2); }
else if (full.Length > 1 && full[1] == ':' && full.Length > 2 && full[2] == '\\') { full = @"\\?\" + full; }
else { return null; } // \folder or C:folder: relative to a current drive or folder
}
StringBuilder sb = new StringBuilder(full.Length + 1);
uint n = GetShortPathName(full, sb, (uint)sb.Capacity);
if (n == 0) { return null; }
if (n > sb.Capacity)
{
sb = new StringBuilder((int)n);
n = GetShortPathName(full, sb, (uint)sb.Capacity);
if (n == 0 || n > sb.Capacity) { return null; }
}
string s = sb.ToString();
if (s.StartsWith(@"\\?\UNC\", StringComparison.Ordinal)) { s = @"\\" + s.Substring(8); }
else if (s.StartsWith(@"\\?\", StringComparison.Ordinal)) { s = s.Substring(4); }
if (string.Equals(s, path, StringComparison.OrdinalIgnoreCase)) { return null; }
return s;
}

private static StringBuilder BuildCommandLine(string fileName, string arguments)
{
// As Process.Start builds it: the program quoted unless it already is.
Expand Down