Skip to content

Commit

Permalink
SerialPortStream: Don't let IsOpen throw a NullReferenceException
Browse files Browse the repository at this point in the history
Even though this commit protects the property IsOpen from throwing a NullReferenceException, other method calls are not protected for thread safety. Do not use any API except IsOpen on the class after it is Closed.

Issue: DOTNET-188
Issue: #90
  • Loading branch information
jcurl committed May 2, 2020
1 parent 6e81324 commit 2fabb7e
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 4 deletions.
2 changes: 2 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ Bugfixes
* DOTNET-180: Allow compilation of libnserial on Ubuntu 16.04.5.
* [Issue #104](https://github.com/jcurl/SerialPortStream/issues/104): Fix buffer
handling. `Write()` would sometimes corrupt data.
* [Issue #90](https://github.com/jcurl/SerialPortStream/issues/90): `IsOpen()`
might return `NullReferenceException` as it's not threadsafe with `Close()`.

Features:

Expand Down
8 changes: 5 additions & 3 deletions code/Native/WinNativeSerial.cs
Original file line number Diff line number Diff line change
Expand Up @@ -639,7 +639,8 @@ public bool IsOpen
get
{
if (m_IsDisposed) return false;
return m_ComPortHandle != null && !m_ComPortHandle.IsClosed && !m_ComPortHandle.IsInvalid;
SafeFileHandle handle = m_ComPortHandle;
return handle != null && !handle.IsClosed && !handle.IsInvalid;
}
}

Expand Down Expand Up @@ -887,12 +888,13 @@ public void Close()
{
if (m_IsDisposed) throw new ObjectDisposedException("WinNativeSerial");
if (IsOpen) {
SafeFileHandle handle = m_ComPortHandle;
m_ComPortHandle = null;
m_CommOverlappedIo.Dispose();
m_CommOverlappedIo = null;
m_CommState = null;
m_CommModemStatus = null;
m_ComPortHandle.Dispose();
m_ComPortHandle = null;
handle.Dispose();
}
}

Expand Down
2 changes: 1 addition & 1 deletion code/SerialPortStream.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright © Jason Curl 2012-2016
// Copyright © Jason Curl 2012-2020
// Sources at https://github.com/jcurl/SerialPortStream
// Licensed under the Microsoft Public License (Ms-PL)

Expand Down

0 comments on commit 2fabb7e

Please sign in to comment.