dotnet / dotnet/runtime

[Analyzer Proposal]: Avoid deadlocking patterns for System.Diagnostics.Process

Open
#119,650 2 comments 4 reactions 1 assignee Claimed by @adamsitnik View on GitHub
api-suggestion area-System.Diagnostics.Process code-analyzer
Dominant language
C#
Stars
18.3k
Forks
5.6k
PR merge metrics
PR metrics pending

Description

### Background and motivation

I was investigating System.Diagnostics.Process issues today, and found out along the way some common patterns that can easily lead to deadlocks.

1. Calling `process.[StandardOutput|StandardError].ReadToEnd()` (or awaiting the async variant) after waiting for process exit. This can lead to deadlock if the child process attempts to write to stdout/stderr more than 4kb (the current buffer size). The child process will only be able to write the first 4kb of data, then it cannot write more data unless the written data is consumed by the parent process. But the parent process is waiting for process exit first before consuming the stream. So this will cause a deadlock.
2. Even with the order swapped, deadlocks can happen when both StdOut and StdErr are waited on sequentially.

### API Proposal

Analyzer the warns when such patterns are detected.

### API Usage

Example violations from real-world repos today:

https://github.com/microsoft/azure-pipelines-agent/blob/349341c78bf275c22cb6e0df888c84589f4b29c9/src/Agent.Worker/VsoTaskLibManager.cs#L121

https://github.com/dotnet/aspire/blob/05226437076bb5755e8a382a65bf027bc80e616c/src/Aspire.Cli/DotNet/DotNetSdkInstaller.cs#L47-L62 (I assume because stderr is redirected and is never read, this can deadlock if more than 4kb are attempted to be written to stderr.

https://github.com/dotnet/sdk/blob/f099c198ca7d9faa092a41df85c1861754fba000/src/Cli/Microsoft.TemplateEngine.Cli/PostActionProcessors/ProcessStartPostActionProcessor.cs#L71

### Alternative Designs

_No response_

### Risks

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.