runtime icon indicating copy to clipboard operation
runtime copied to clipboard

SerialPort: fAbortOnError not always cleared correctly when port is opened

Open willdean opened this issue 9 years ago • 25 comments

@daflame76 reported this in dotnet/runtime#14275.

There has been a long-standing problem with SerialPort where the DCB fAbortOnError flag can get set somehow (by past problems with the port, how it gets set doesn't really matter) and is then not cleared by SerialPort when the port is opened in a .NET application. This changes the behaviour of the port so that it doesn't work correctly with SerialPort, because it's not expecting the fAbortOnError flag.

There have been reports of this before here which have been closed as 'by design', which was, IMO, a mistake - or at least the reasoning given was incorrect.

This needs a test in the test suite, and to be investigated to see:

  1. Does the problem still exist
  2. Is it really a SerialPort bug or do some USB ports behave differently to real ports
  3. Regardless of '2', can the situation be improved by changes to SerialPort to be more defensive.

This can be assigned to me.

willdean avatar Mar 22 '17 19:03 willdean

@willdean that is exactly the issue. Thank you for digging up the related issue.

jcoder76 avatar Mar 22 '17 19:03 jcoder76

That report says we need to respect the setting if a program set it to on, which technically is correct, but the port tends to fail to close the serial port stream properly because the underlying windows file handle becomes invalid since it is closed by Windows directly.

I didn't want to pollute the main channel with this kind of detail.

It is possible that the fAbortOnError flag is valid in that state, but the port should at least handle it, and offer the ability for the developers to switch it off if desired.

jcoder76 avatar Mar 22 '17 19:03 jcoder76

I don't actually see that we need to 'respect the setting' at all - as someone else points out in that Connect report, all properties of a serial port are "global", and yet we don't say we have to use a particular baud rate or parity setting or timeout settings just because it's what's already set when we open the port. It's incumbent on the application opening the port to get it configured how it needs it.

If this wasn't the case it would imply that there is something special about fAbortOnError which put it aside from the other members of DCB, if that's so, it's undocumented.

willdean avatar Mar 22 '17 20:03 willdean

I've built a test here which does the following:

  1. Opens a port
  2. Uses the internal method SetDcbFlag to set fAbortOnError
  3. Uses GetDcbFlag to read fAbortOnError to verify it's set
  4. Closes the port
  5. Reopens the port
  6. Uses GetDcbFlag to read fAbortOnError

With both 'real' ports and FTDI USB-serial ports using current drivers, the fAbortOnError flag does not survive the close/reopen - i.e. it's set before closing, clear after reopening.

I'm not clear where to go next with this.

willdean avatar Mar 22 '17 20:03 willdean

I suppose turning off fAbortOnError is desirable either way. The fact that some programs leave it on is probably an oversight, since it has serious port handling implications and the default state is off.

The problem with testing is that unless you physically remove the port (hot plug), or cause the device (or driver) to fail in some uncomfortable way (hardware failure), I have never had this issue show up.

Cases to reproduce:

  1. Hot plug - it is the common failure case these days because of USB.
  2. Hardware failure - it is somewhat irrelevant, but graceful port failure should still happen.
  3. Driver failure - it is out of our control, so I understand if we don't bother to test this.

This means that in the true non-hotplug UART port situation, this almost never happens.

jcoder76 avatar Mar 23 '17 16:03 jcoder76

I guess it would be safe (and probably more correct) to always clear the flag on open, even if it's only buggy drivers which don't do this normally. It is of course unclear in my test last night whether the drivers (FTDI and MS) are clearing the flag on close or clearing it on open - if it's the former than that might account for the differences in the hot-unplug scenario.

I will have a bit of a play here with pulling out USB cables, but if you could come up with a clear step-by-step repro (ideally with an FTDI-based USB-serial port) then that would be great.

willdean avatar Mar 23 '17 16:03 willdean

I should be able to test it with an FTDI device since I have one sitting on my desk right now.

jcoder76 avatar Mar 23 '17 17:03 jcoder76

Cool. I have about 5 on my desk right now, but I'm not inspired to enrage the BSOD gods by plugging and unplugging them while I'm in the middle of something else...

willdean avatar Mar 23 '17 17:03 willdean

I just tried this with 4.6.1 and although the FTDI port doesn't explode with a blaze of glory like some of my other ports are prone to do, it does seem to leak resources and hold the port open until the program is restarted. It also seems to prevent the port from being removed (it lingers in the device manager).

jcoder76 avatar Mar 27 '17 21:03 jcoder76

Correction, it leaves the port present in device manager until the port is reinserted and removed again. That can be troublesome in production. It does prevent the close operation on the SerialPort from working though. I am going to put this is a tight loop to see how ugly it can get.

jcoder76 avatar Mar 27 '17 21:03 jcoder76

Spoke too soon. Reinserting the port before closing the application process causes a spurious ObjectDisposedException to pop up randomly on the old event loop runner thread which was stuck in WaitForCommEvent. Apparently reattaching the serial port must wake up that thread, but it notices (too late) that the handle was closed already. Since this happens on a thread outside our control it is sent straight to the AppDomain error handler.

jcoder76 avatar Mar 27 '17 21:03 jcoder76

I reinserted the port at "Press q to exit" and waited a couple seconds for the port to reregister. It caused an AppDomain unhandled exception and I doubt it can be avoided. Currently I construct a separate AppDomain to work around this issue, otherwise it tears down my entire application. Here is the trace from my tests:

Remove the port and press any key.
Access to the port is denied.
   at System.IO.Ports.InternalResources.WinIOError(Int32 errorCode, String str)
   at System.IO.Ports.SerialStream.Dispose(Boolean disposing)
   at System.IO.Stream.Close()
   at System.IO.Ports.SerialPort.Dispose(Boolean disposing)
   at System.ComponentModel.Component.Dispose()
   at SerialPortFailure.Program.Main(String[] args) in C:\Projects\Common\SerialPortFailure\SerialPortFailure\SerialPortFailure\Program.cs:line 20
What happened?  Press q to exit.
Safe handle has been closed
   at System.Runtime.InteropServices.SafeHandle.DangerousAddRef(Boolean& success)
   at System.StubHelpers.StubHelpers.SafeHandleAddRef(SafeHandle pHandle, Boolean& success)
   at Microsoft.Win32.UnsafeNativeMethods.GetOverlappedResult(SafeFileHandle hFile, NativeOverlapped* lpOverlapped, Int32& lpNumberOfBytesTransferred, Boolean bWait)
   at System.IO.Ports.SerialStream.EventLoopRunner.WaitForCommEvent()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()
Is Terminating: True
Press any key.

jcoder76 avatar Mar 27 '17 22:03 jcoder76

[This crossed with your latest post]

Thanks for this - there are some fundamental difficulties with writing USB-Serial drivers which come from the Windows driver PnP and serial port model. With drivers like the FTDI drivers, your COM port is the top end of a stack which goes all the way down to the USB device (this is the natural way to write a USB-Serial driver, as it's the same way the non-USB serial port drivers work). The driver loads when the device loads, and it creates a COMxx device. Unplugging yanks away the USB device, but the COMxx is still open, and the driver cannot force that closed because the application holds a handle to it.

If you then replug the device, the driver cannot mend the link between the orphaned COMxx port and the new USB device which has now appeared.

I absolutely believe that .NET SerialPort has weaknesses to do with this, and I'm sure we can improve that, but the unplug/replug-while-open situation is never going to work nicely with drivers written in the conventional fashion, because the Windows serial port stack just doesn't properly support hot-plugging of the port itself.

Having once written from scratch a USB serial driver that worked exactly like this (because it's how MS guide you to write USB drivers), if I ever had to do it again (I wouldn't take the job), I would arrange for the driver to load itself without being dependent on the USB device, and create COM ports completely independently of USB devices - this would fix the lifetime issues by decoupling the top and bottom of the stack. Unfortunately that's not how any USB-Serial drivers I know of actually work, so we're stuck with the reality of the way things are now.

But that doesn't excuse crashing on background threads in .NET, obviously.

willdean avatar Mar 27 '17 22:03 willdean

Re your last trace - we absolutely 100% shouldn't have a route out of a background thread within an unhandled exception, that's just madness and we should fix it.

There were tests in the test suite which had the same problem (unhandled exceptions in background threads) which I think must be becauseSerialPort hasn't had any serious attention since before .NET2 (when background exceptions were handled differently) - and of course before USB-Serial ports were ubiquitous too.

willdean avatar Mar 27 '17 22:03 willdean

I do understand the idea of the port failing to be removed from the device manager. I know .NET can't fix that. I also understand the idea of how the port is opened like a file with a windows file handle to the connection. It is just too bad that the connectivity design in Windows ports doesn't support dynamic connection routing (virtual patch bay style) with removal signalling so the application can respond to the file handle going away (we manually hook the device events to detect this currently), and that is part of the issue there, the application is NOT notified by Windows so it is oblivious to the change until it is too late.

As you said, it can be done, but:

  1. it isn't the default recommendation
  2. it isn't easy

So no one does it. Up until USB was invented, serial ports were only physical devices assumed to be permanently installed, so it isn't surprising that we are fighting with this issue now.

I agree that the background thread crash issue has been neglected somewhat since background exceptions were handled more gracefully with .NET 1.1 than .NET 2.0+ (Not that the behaviour of 2.0+ is wrong, a background thread crash should not be allowed to happen). The serial port code wasn't updated that much overall.

However with USB serial ports becoming all the more common and physical serial devices dwindling, this will probably only become worse for everyone. Almost all of our system console ports are USB serial devices now. Not all FTDI, but I put a push towards that direction a few years ago and now the new ones are. I generally can't expect the users and production workers to be graceful about disconnecting before unplugging them although we do our best.

As long as we ensure the fAbortOnError flag is off, and handle the background thread gracefully (emit a debug console error about file handle already being closed if necessary) then that should be enough.

jcoder76 avatar Mar 29 '17 17:03 jcoder76

Do you want me to submit pull requests?

jcoder76 avatar Mar 29 '17 17:03 jcoder76

@daflame76 It won't be me that approves PRs them, because that gets done by MS insiders, but if you want to put in a PR for the fAbortOnError thing against this issue, then we should be able to get it merged - reviewers are going to ask about test coverage, which is a bit difficult unless we can come up with a way of forcing it on before opening it. I think we can argue persuasively that it's an omission that it isn't explicitly assigned at Open anyway..

The background thread unhandled exception should be another issue - with a different PR to go with it. I'm sure we can argue persuasively for that one just on the basis of code inspection.

willdean avatar Mar 29 '17 17:03 willdean

Actually I just tested the fAbortOnError flag now. I turn it on and closed the port using P/Invoke. Then I checked the state, it was still on. Opened the SerialPort and closed it. Checked again, it was still on. Closed the application and restarted without setting it this time, and it was still on.

I am using Window 7, so it may be platform specific, UAC is off on my system and I have admin rights, I don't know if that may influence it.

jcoder76 avatar Mar 29 '17 18:03 jcoder76

@daflame76 I'll put up the code I tried with and you can test it on your machine

I'm also about to open an issue for the background thread exception problem, so don't worry about doing that yourself

willdean avatar Mar 29 '17 18:03 willdean

I did one more test. Removing the USB port physically and reinserting and this seems to toggle the fAbortOnError flag back to off.

jcoder76 avatar Mar 29 '17 18:03 jcoder76