[bcl] Add null reference checks to Interlocked.Exchange<T> (mono/mono#17400)
authorAleksey Kliger (λgeek) <alklig@microsoft.com>
Fri, 18 Oct 2019 23:11:22 +0000 (19:11 -0400)
committerZoltan Varga <vargaz@gmail.com>
Fri, 18 Oct 2019 23:11:22 +0000 (19:11 -0400)
* [bcl] Add null reference checks to Interlocked.Exchange<T>

and Interlocked.CompareExchange<T>

This is to mimic the old behavior in unmanaged when the intrinsic cannot be
used.

The issue was detected via the coreclr acceptance test:
https://github.com/mono/coreclr/blob/mono/tests/src/baseservices/threading/interlocked/exchange/exchangetneg.il

* and netcore

Commit migrated from https://github.com/mono/mono/commit/d8ae32a9ee7763c861bdc31831271d82aa8a4953

src/mono/netcore/System.Private.CoreLib/src/System.Threading/Interlocked.cs

index fe48ed4..0f99892 100644 (file)
@@ -80,6 +80,10 @@ namespace System.Threading
                [Intrinsic]
                public static T CompareExchange<T> (ref T location1, T value, T comparand) where T : class?
                {
+                       unsafe {
+                               if (Unsafe.AsPointer (ref location1) == null)
+                                       throw new NullReferenceException ();
+                       }
                        // Besides avoiding coop handles for efficiency,
                        // and correctness, this also appears needed to
                        // avoid an assertion failure in the runtime, related to
@@ -110,6 +114,10 @@ namespace System.Threading
                [Intrinsic]
                public static T Exchange<T> (ref T location1, T value) where T : class?
                {
+                       unsafe {
+                               if (Unsafe.AsPointer (ref location1) == null)
+                                       throw new NullReferenceException ();
+                       }
                        // See CompareExchange(T) for comments.
                        //
                        // This is not entirely convincing due to lack of volatile.