From 0c288c367db3dc7c296e67a4bb2fff84f0f93c3f Mon Sep 17 00:00:00 2001 From: Jeremy Koritzinsky Date: Tue, 25 Sep 2018 14:54:26 -0700 Subject: [PATCH] Fix possible overflow in SafeBuffer.Initialize. Since a 0-length buffer is technically possible (though not very usable), have sizeOfEachElement==0 -> ByteLength == 0. --- .../shared/System/Runtime/InteropServices/SafeBuffer.cs | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/SafeBuffer.cs b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/SafeBuffer.cs index 661a7ed..66b500a 100644 --- a/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/SafeBuffer.cs +++ b/src/System.Private.CoreLib/shared/System/Runtime/InteropServices/SafeBuffer.cs @@ -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)); + } } /// -- 2.7.4