Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid crashing the process when Stream.Dispose throws #1085

Merged
merged 1 commit into from
Oct 1, 2024
Merged
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
17 changes: 15 additions & 2 deletions src/StreamJsonRpc/PipeMessageHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ public PipeMessageHandler(Stream? writer, Stream? reader, IJsonRpcMessageFormatt
{
Assumes.NotNull(this.Writer);
#pragma warning disable CS0618 // Type or member is obsolete (Nerdbank.Streams implements this, so it won't go away).
this.Writer.OnReaderCompleted((ex, state) => ((Stream)state!).Dispose(), writer);
this.Writer.OnReaderCompleted(static (ex, state) => DisposeStreamSafely(state), writer);
#pragma warning restore CS0618 // Type or member is obsolete
}

Expand All @@ -80,7 +80,20 @@ public PipeMessageHandler(Stream? writer, Stream? reader, IJsonRpcMessageFormatt
// We only need to do this if the read stream is distinct from the write stream, which is already handled above.
if (reader is not null && reader != writer)
{
this.DisposalToken.Register(state => ((Stream)state!).Dispose(), reader);
this.DisposalToken.Register(DisposeStreamSafely, reader);
}

static void DisposeStreamSafely(object? state)
{
// These callbacks are invoked on a worker thread with no exception handler underneath.
try
{
((Stream?)state)?.Dispose();
}
catch (Exception)
{
// Dispose should never throw, but if it does, we don't want the process to crash.
}
}
}

Expand Down