Skip to content

Commit

Permalink
Avoid crashing the process when Stream.Dispose throws
Browse files Browse the repository at this point in the history
Fixes #1084
  • Loading branch information
AArnott committed Oct 1, 2024
1 parent f9ff7cc commit b1f96fa
Showing 1 changed file with 15 additions and 2 deletions.
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

0 comments on commit b1f96fa

Please sign in to comment.