[SafeHandle] Avoid handle leakage in case of ThreadAbortException
authorLudovic Henry <ludovic@xamarin.com>
Mon, 22 Feb 2016 12:56:23 +0000 (12:56 +0000)
committerLudovic Henry <ludovic@xamarin.com>
Mon, 22 Feb 2016 16:54:57 +0000 (16:54 +0000)
commit942bd2b8b22a8725ed10a31d9e92876d79d704c7
tree15c73e4993181293109d24c04affab3b672a6789
parentf558ee9034335b252395a87ef87b8b39cc81e2df
[SafeHandle] Avoid handle leakage in case of ThreadAbortException

If we get a ThreadAbortException while at SafeHandle.cs:124 (before this commit), we would not set release to true, even after incrementing the internal reference count of the SafeHandle. That could lead to potential leak, as the caller (following the common following pattern) would never call DangerousRelase, thus never calling PerformRelease. The finalizer or Dispose would not lead to the call of PerformRelease either, as the DangerousAddRef / DangerousRelase calls are unbalanced.

The common pattern for DangerousAddRef / DangerousRelease is the following:

bool release = false;
try {
  safeHandle.DangerousAddRef (ref release);
  /* do something with safeHandle.DangerousGetHandle () */
} finally {
  if (release)
    safeHandle.DangerousRelease ();
}
mcs/class/corlib/System.Runtime.InteropServices/SafeHandle.cs