From 2fabb7ea7f4683b91c0b7466352454b85afeafcb Mon Sep 17 00:00:00 2001 From: Jason Curl Date: Sat, 2 May 2020 22:40:10 +0200 Subject: [PATCH] SerialPortStream: Don't let IsOpen throw a NullReferenceException 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: https://github.com/jcurl/SerialPortStream/issues/90 --- CHANGES.md | 2 ++ code/Native/WinNativeSerial.cs | 8 +++++--- code/SerialPortStream.cs | 2 +- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 1bcf1f88..da3f2c0c 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -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: diff --git a/code/Native/WinNativeSerial.cs b/code/Native/WinNativeSerial.cs index 9563de56..d443eda5 100644 --- a/code/Native/WinNativeSerial.cs +++ b/code/Native/WinNativeSerial.cs @@ -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; } } @@ -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(); } } diff --git a/code/SerialPortStream.cs b/code/SerialPortStream.cs index 431211ff..37a7a88e 100644 --- a/code/SerialPortStream.cs +++ b/code/SerialPortStream.cs @@ -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)