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
23 changes: 21 additions & 2 deletions Tools/windows/ShellOwnedProcess.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@
using System.Threading.Tasks;

public sealed class ShellOwnedLaunch {
[DllImport("kernel32.dll")]
static extern uint GetOEMCP();
public static int OemCodePage() { return checked((int)GetOEMCP()); }

public static string SelectWorkingDirectory(ProcessStartInfo info) {
return String.IsNullOrEmpty(info.WorkingDirectory) ? null : info.WorkingDirectory;
}
Expand Down Expand Up @@ -141,6 +145,12 @@ static string Quote(string value) {
}

public static ShellOwnedLaunch Suspended(ProcessStartInfo info) {
return Suspended(info, null, null);
}

public static ShellOwnedLaunch Suspended(ProcessStartInfo info, TextWriter standardOutputWriter,
TextWriter standardErrorWriter) {
// Supplied writers remain caller-owned until verified teardown and pipe EOF.
if (info.UseShellExecute || !String.IsNullOrEmpty(info.Arguments))
throw new InvalidOperationException("Owned launch requires UseShellExecute=false and ArgumentList.");
var security = new Security { Length = Marshal.SizeOf<Security>(), Inherit = 1 };
Expand Down Expand Up @@ -202,8 +212,10 @@ public static ShellOwnedLaunch Suspended(ProcessStartInfo info) {
run.errorReader = new StreamReader(new FileStream(
new Microsoft.Win32.SafeHandles.SafeFileHandle(errRead, true), FileAccess.Read));
errRead = IntPtr.Zero;
run.outputCapture = new OutputCapture(run.outputReader, ForwardWriter(info.RedirectStandardOutput, Console.Out));
run.errorCapture = new OutputCapture(run.errorReader, ForwardWriter(info.RedirectStandardError, Console.Error));
run.outputCapture = new OutputCapture(run.outputReader,
standardOutputWriter ?? ForwardWriter(info.RedirectStandardOutput, Console.Out));
run.errorCapture = new OutputCapture(run.errorReader,
standardErrorWriter ?? ForwardWriter(info.RedirectStandardError, Console.Error));
run.Output = run.outputCapture.Completion;
run.Error = run.errorCapture.Completion;
return run;
Expand Down Expand Up @@ -271,6 +283,13 @@ public void Drain() {
foreach (var task in new[] { Output, Error })
if (task != null && !task.Wait(5000)) throw new InvalidOperationException("Owned output EOF is unproved.");
}
public void Drain(int timeoutMilliseconds) {
if (timeoutMilliseconds < 0) throw new ArgumentOutOfRangeException(nameof(timeoutMilliseconds));
var clock = Stopwatch.StartNew();
foreach (var task in new[] { Output, Error })
if (task != null && !task.Wait(Math.Max(0, timeoutMilliseconds - (int)clock.ElapsedMilliseconds)))
throw new InvalidOperationException("Owned output EOF is unproved.");
}
public void Close() {
if (Handle != IntPtr.Zero) RequireExited();
Drain();
Expand Down
32 changes: 21 additions & 11 deletions Tools/windows/ShellProcessOwnership.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,9 @@ function Invoke-ShellJob([string] $Operation, [IntPtr] $Job = [IntPtr]::Zero,
}
}

function New-ShellSuspendedLaunch([Diagnostics.ProcessStartInfo] $StartInfo) {
[ShellOwnedLaunch]::Suspended($StartInfo)
function New-ShellSuspendedLaunch([Diagnostics.ProcessStartInfo] $StartInfo,
[IO.TextWriter] $StandardOutputWriter, [IO.TextWriter] $StandardErrorWriter) {
[ShellOwnedLaunch]::Suspended($StartInfo, $StandardOutputWriter, $StandardErrorWriter)
}

function Test-ShellOwnershipUnproven($Failure) {
Expand Down Expand Up @@ -219,9 +220,13 @@ function New-ShellProcessScope {
}
}

function Start-ShellOwnedProcess($Scope, [Diagnostics.ProcessStartInfo] $StartInfo) {
function Start-ShellOwnedProcess($Scope, [Diagnostics.ProcessStartInfo] $StartInfo,
[IO.TextWriter] $StandardOutputWriter, [IO.TextWriter] $StandardErrorWriter) {
if ($Scope.Closed) { throw "Owned shell scope is closed" }
try { $run = New-ShellSuspendedLaunch $StartInfo } catch {
try {
$run = New-ShellSuspendedLaunch $StartInfo `
-StandardOutputWriter $StandardOutputWriter -StandardErrorWriter $StandardErrorWriter
} catch {
if (Test-ShellOwnershipUnproven $_) {
throw (Set-ShellOwnershipUnproven $_.Exception -FailureRecord $_)
}
Expand Down Expand Up @@ -310,18 +315,23 @@ function Receive-ShellOwnedOutput($Scope, [Diagnostics.Process] $Process,
}
}

function Complete-ShellLaunch($Run) {
function Complete-ShellLaunch($Run, [Nullable[int]] $TimeoutMilliseconds) {
if ($Run.Finalized) { return }
$clock = [Diagnostics.Stopwatch]::StartNew()
try {
$Run.RequireExited()
if ($Run.LaunchJob -ne [IntPtr]::Zero -and -not $Run.LaunchJobClosed) {
Invoke-ShellJob "Terminate" $Run.LaunchJob
Invoke-ShellJob "Wait" $Run.LaunchJob
$remaining = if ($null -eq $TimeoutMilliseconds) { 5000 } else {
[Math]::Max(0, [int]$TimeoutMilliseconds - [int]$clock.ElapsedMilliseconds)
}
Invoke-ShellJob "Wait" $Run.LaunchJob -TimeoutMilliseconds $remaining
if ((Invoke-ShellJob "Active" $Run.LaunchJob) -ne 0) {
throw "OWNED_CLEANUP_UNPROVEN: private launch job not empty"
}
}
$Run.Drain()
if ($null -eq $TimeoutMilliseconds) { $Run.Drain() }
else { $Run.Drain([Math]::Max(0, [int]$TimeoutMilliseconds - [int]$clock.ElapsedMilliseconds)) }
if ($Run.LaunchJob -ne [IntPtr]::Zero -and -not $Run.LaunchJobClosed) {
Invoke-ShellJob "Close" $Run.LaunchJob
$Run.LaunchJobClosed = $true
Expand All @@ -346,22 +356,22 @@ function Complete-ShellOwnedProcess($Scope, [Diagnostics.Process] $Process) {
Complete-ShellLaunch $runs[0]
}

function Close-ShellProcessScope($Scope) {
function Close-ShellProcessScope($Scope, [ValidateRange(0, 5000)][int] $TimeoutMilliseconds = 5000) {
if ($Scope.Closed) { return }
$exitClock = [Diagnostics.Stopwatch]::StartNew()
try {
Invoke-ShellJob "Terminate" $Scope.Job
Invoke-ShellJob "Wait" $Scope.Job -TimeoutMilliseconds ([Math]::Max(0, 5000 - [int]$exitClock.ElapsedMilliseconds))
Invoke-ShellJob "Wait" $Scope.Job -TimeoutMilliseconds ([Math]::Max(0, $TimeoutMilliseconds - [int]$exitClock.ElapsedMilliseconds))
if ((Invoke-ShellJob "Active" $Scope.Job) -ne 0) { throw "OWNED_CLEANUP_UNPROVEN: job not empty" }
# Job accounting can reach zero before the original process objects signal.
# Prove every held root within the same termination deadline before closing any.
foreach ($run in $Scope.Runs) {
if ($run.Finalized) { continue }
if (-not $run.ScopeAssigned) { $run.Stop() }
$run.RequireExited([Math]::Max(0, 5000 - [int]$exitClock.ElapsedMilliseconds))
$run.RequireExited([Math]::Max(0, $TimeoutMilliseconds - [int]$exitClock.ElapsedMilliseconds))
}
foreach ($run in $Scope.Runs) {
Complete-ShellLaunch $run
Complete-ShellLaunch $run -TimeoutMilliseconds ([Math]::Max(0, $TimeoutMilliseconds - [int]$exitClock.ElapsedMilliseconds))
$run.Close()
}
foreach ($member in $Scope.Members) { $member.Dispose() }
Expand Down
Loading
Loading