Fix possible overflow in SafeBuffer.Initialize.
authorJeremy Koritzinsky <jekoritz@microsoft.com>
Tue, 25 Sep 2018 21:54:26 +0000 (14:54 -0700)
committerJeremy Koritzinsky <jekoritz@microsoft.com>
Tue, 25 Sep 2018 21:54:26 +0000 (14:54 -0700)
Since a 0-length buffer is technically possible (though not very usable), have sizeOfEachElement==0 -> ByteLength == 0.

src/System.Private.CoreLib/shared/System/Runtime/InteropServices/SafeBuffer.cs

index 661a7ed..66b500a 100644 (file)
@@ -110,13 +110,20 @@ namespace System.Runtime.InteropServices
         [CLSCompliant(false)]
         public void Initialize(uint numElements, uint sizeOfEachElement)
         {
-            if (IntPtr.Size == 4 && numElements * sizeOfEachElement > uint.MaxValue)
-                throw new ArgumentOutOfRangeException("numBytes", SR.ArgumentOutOfRange_AddressSpace);
+            if (sizeOfEachElement == 0)
+            {
+                _numBytes = (UIntPtr)0;
+            }
+            else
+            {
+                if (IntPtr.Size == 4 && numElements > uint.MaxValue / sizeOfEachElement)
+                    throw new ArgumentOutOfRangeException("numBytes", SR.ArgumentOutOfRange_AddressSpace);
 
-            if (numElements * sizeOfEachElement >= (ulong)Uninitialized)
-                throw new ArgumentOutOfRangeException(nameof(numElements), SR.ArgumentOutOfRange_UIntPtrMax);
+                if (numElements >= (ulong)Uninitialized / sizeOfEachElement)
+                    throw new ArgumentOutOfRangeException(nameof(numElements), SR.ArgumentOutOfRange_UIntPtrMax);
 
-            _numBytes = checked((UIntPtr)(numElements * sizeOfEachElement));
+                _numBytes = checked((UIntPtr)(numElements * sizeOfEachElement)); 
+            }
         }
 
         /// <summary>