Code cleanup and formatting for System.Memory files. (#17451)
[platform/upstream/coreclr.git] / src / System.Private.CoreLib / shared / System / Runtime / InteropServices / SafeBuffer.cs
1 // Licensed to the .NET Foundation under one or more agreements.
2 // The .NET Foundation licenses this file to you under the MIT license.
3 // See the LICENSE file in the project root for more information.
4
5 /*============================================================
6 **
7 ** Purpose: Unsafe code that uses pointers should use
8 ** SafePointer to fix subtle lifetime problems with the
9 ** underlying resource.
10 **
11 ===========================================================*/
12
13 // Design points:
14 // *) Avoid handle-recycling problems (including ones triggered via
15 // resurrection attacks) for all accesses via pointers.  This requires tying
16 // together the lifetime of the unmanaged resource with the code that reads
17 // from that resource, in a package that uses synchronization to enforce
18 // the correct semantics during finalization.  We're using SafeHandle's
19 // ref count as a gate on whether the pointer can be dereferenced because that
20 // controls the lifetime of the resource.
21 //
22 // *) Keep the penalties for using this class small, both in terms of space
23 // and time.  Having multiple threads reading from a memory mapped file
24 // will already require 2 additional interlocked operations.  If we add in
25 // a "current position" concept, that requires additional space in memory and
26 // synchronization.  Since the position in memory is often (but not always)
27 // something that can be stored on the stack, we can save some memory by
28 // excluding it from this object.  However, avoiding the need for
29 // synchronization is a more significant win.  This design allows multiple
30 // threads to read and write memory simultaneously without locks (as long as
31 // you don't write to a region of memory that overlaps with what another
32 // thread is accessing).
33 //
34 // *) Space-wise, we use the following memory, including SafeHandle's fields:
35 // Object Header  MT*  handle  int bool bool <2 pad bytes> length
36 // On 32 bit platforms: 24 bytes.  On 64 bit platforms: 40 bytes.
37 // (We can safe 4 bytes on x86 only by shrinking SafeHandle)
38 //
39 // *) Wrapping a SafeHandle would have been a nice solution, but without an
40 // ordering between critical finalizable objects, it would have required
41 // changes to each SafeHandle subclass to opt in to being usable from a
42 // SafeBuffer (or some clever exposure of SafeHandle's state fields and a
43 // way of forcing ReleaseHandle to run even after the SafeHandle has been
44 // finalized with a ref count > 1).  We can use less memory and create fewer
45 // objects by simply inserting a SafeBuffer into the class hierarchy.
46 //
47 // *) In an ideal world, we could get marshaling support for SafeBuffer that
48 // would allow us to annotate a P/Invoke declaration, saying this parameter
49 // specifies the length of the buffer, and the units of that length are X.
50 // P/Invoke would then pass that size parameter to SafeBuffer.
51 //     [DllImport(...)]
52 //     static extern SafeMemoryHandle AllocCharBuffer(int numChars);
53 // If we could put an attribute on the SafeMemoryHandle saying numChars is
54 // the element length, and it must be multiplied by 2 to get to the byte
55 // length, we can simplify the usage model for SafeBuffer.
56 //
57 // *) This class could benefit from a constraint saying T is a value type
58 // containing no GC references.
59
60 // Implementation notes:
61 // *) The Initialize method must be called before you use any instance of
62 // a SafeBuffer.  To avoid race conditions when storing SafeBuffers in statics,
63 // you either need to take a lock when publishing the SafeBuffer, or you
64 // need to create a local, initialize the SafeBuffer, then assign to the
65 // static variable (perhaps using Interlocked.CompareExchange).  Of course,
66 // assignments in a static class constructor are under a lock implicitly.
67
68 using System;
69 using System.Diagnostics;
70 using System.Runtime.CompilerServices;
71 using Internal.Runtime.CompilerServices;
72 using Microsoft.Win32.SafeHandles;
73
74 namespace System.Runtime.InteropServices
75 {
76     public abstract unsafe class SafeBuffer : SafeHandleZeroOrMinusOneIsInvalid
77     {
78         // Steal UIntPtr.MaxValue as our uninitialized value.
79         private static readonly UIntPtr Uninitialized = (UIntPtr.Size == 4) ?
80             ((UIntPtr)UInt32.MaxValue) : ((UIntPtr)UInt64.MaxValue);
81
82         private UIntPtr _numBytes;
83
84         protected SafeBuffer(bool ownsHandle) : base(ownsHandle)
85         {
86             _numBytes = Uninitialized;
87         }
88
89         /// <summary>
90         /// Specifies the size of the region of memory, in bytes.  Must be
91         /// called before using the SafeBuffer.
92         /// </summary>
93         /// <param name="numBytes">Number of valid bytes in memory.</param>
94         [CLSCompliant(false)]
95         public void Initialize(ulong numBytes)
96         {
97             if (IntPtr.Size == 4 && numBytes > UInt32.MaxValue)
98                 throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_AddressSpace);
99
100             if (numBytes >= (ulong)Uninitialized)
101                 throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_UIntPtrMax);
102
103             _numBytes = (UIntPtr)numBytes;
104         }
105
106         /// <summary>
107         /// Specifies the size of the region in memory, as the number of
108         /// elements in an array.  Must be called before using the SafeBuffer.
109         /// </summary>
110         [CLSCompliant(false)]
111         public void Initialize(uint numElements, uint sizeOfEachElement)
112         {
113             if (IntPtr.Size == 4 && numElements * sizeOfEachElement > UInt32.MaxValue)
114                 throw new ArgumentOutOfRangeException("numBytes", SR.ArgumentOutOfRange_AddressSpace);
115
116             if (numElements * sizeOfEachElement >= (ulong)Uninitialized)
117                 throw new ArgumentOutOfRangeException(nameof(numElements), SR.ArgumentOutOfRange_UIntPtrMax);
118
119             _numBytes = checked((UIntPtr)(numElements * sizeOfEachElement));
120         }
121
122         /// <summary>
123         /// Specifies the size of the region in memory, as the number of
124         /// elements in an array.  Must be called before using the SafeBuffer.
125         /// </summary>
126         [CLSCompliant(false)]
127         public void Initialize<T>(uint numElements) where T : struct
128         {
129             Initialize(numElements, AlignedSizeOf<T>());
130         }
131
132         // Callers should ensure that they check whether the pointer ref param
133         // is null when AcquirePointer returns.  If it is not null, they must
134         // call ReleasePointer.  This method calls DangerousAddRef
135         // & exposes the pointer. Unlike Read, it does not alter the "current
136         // position" of the pointer.  Here's how to use it:
137         //
138         // byte* pointer = null;
139         // try {
140         //     safeBuffer.AcquirePointer(ref pointer);
141         //     // Use pointer here, with your own bounds checking
142         // }
143         // finally {
144         //     if (pointer != null)
145         //         safeBuffer.ReleasePointer();
146         // }
147         //
148         // Note: If you cast this byte* to a T*, you have to worry about
149         // whether your pointer is aligned.  Additionally, you must take
150         // responsibility for all bounds checking with this pointer.
151         /// <summary>
152         /// Obtain the pointer from a SafeBuffer for a block of code,
153         /// with the express responsibility for bounds checking and calling
154         /// ReleasePointer later to ensure the pointer can be freed later.
155         /// This method either completes successfully or throws an exception 
156         /// and returns with pointer set to null.
157         /// </summary>
158         /// <param name="pointer">A byte*, passed by reference, to receive
159         /// the pointer from within the SafeBuffer.  You must set
160         /// pointer to null before calling this method.</param>
161         [CLSCompliant(false)]
162         public void AcquirePointer(ref byte* pointer)
163         {
164             if (_numBytes == Uninitialized)
165                 throw NotInitialized();
166
167             pointer = null;
168
169             bool junk = false;
170             DangerousAddRef(ref junk);
171             pointer = (byte*)handle;
172         }
173
174         public void ReleasePointer()
175         {
176             if (_numBytes == Uninitialized)
177                 throw NotInitialized();
178
179             DangerousRelease();
180         }
181
182         /// <summary>
183         /// Read a value type from memory at the given offset.  This is
184         /// equivalent to:  return *(T*)(bytePtr + byteOffset);
185         /// </summary>
186         /// <typeparam name="T">The value type to read</typeparam>
187         /// <param name="byteOffset">Where to start reading from memory.  You
188         /// may have to consider alignment.</param>
189         /// <returns>An instance of T read from memory.</returns>
190         [CLSCompliant(false)]
191         public T Read<T>(ulong byteOffset) where T : struct
192         {
193             if (_numBytes == Uninitialized)
194                 throw NotInitialized();
195
196             uint sizeofT = SizeOf<T>();
197             byte* ptr = (byte*)handle + byteOffset;
198             SpaceCheck(ptr, sizeofT);
199
200             // return *(T*) (_ptr + byteOffset);
201             T value = default;
202             bool mustCallRelease = false;
203             try
204             {
205                 DangerousAddRef(ref mustCallRelease);
206
207                 fixed (byte* pStructure = &Unsafe.As<T, byte>(ref value))
208                     Buffer.Memmove(pStructure, ptr, sizeofT);
209             }
210             finally
211             {
212                 if (mustCallRelease)
213                     DangerousRelease();
214             }
215             return value;
216         }
217
218         [CLSCompliant(false)]
219         public void ReadArray<T>(ulong byteOffset, T[] array, int index, int count)
220             where T : struct
221         {
222             if (array == null)
223                 throw new ArgumentNullException(nameof(array), SR.ArgumentNull_Buffer);
224             if (index < 0)
225                 throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
226             if (count < 0)
227                 throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
228             if (array.Length - index < count)
229                 throw new ArgumentException(SR.Argument_InvalidOffLen);
230
231             if (_numBytes == Uninitialized)
232                 throw NotInitialized();
233
234             uint sizeofT = SizeOf<T>();
235             uint alignedSizeofT = AlignedSizeOf<T>();
236             byte* ptr = (byte*)handle + byteOffset;
237             SpaceCheck(ptr, checked((ulong)(alignedSizeofT * count)));
238
239             bool mustCallRelease = false;
240             try
241             {
242                 DangerousAddRef(ref mustCallRelease);
243
244                 if (count > 0)
245                 {
246                     unsafe
247                     {
248                         fixed (byte* pStructure = &Unsafe.As<T, byte>(ref array[index]))
249                         {
250                             for (int i = 0; i < count; i++)
251                                 Buffer.Memmove(pStructure + sizeofT * i, ptr + alignedSizeofT * i, sizeofT);
252                         }
253                     }
254                 }
255             }
256             finally
257             {
258                 if (mustCallRelease)
259                     DangerousRelease();
260             }
261         }
262
263         /// <summary>
264         /// Write a value type to memory at the given offset.  This is
265         /// equivalent to:  *(T*)(bytePtr + byteOffset) = value;
266         /// </summary>
267         /// <typeparam name="T">The type of the value type to write to memory.</typeparam>
268         /// <param name="byteOffset">The location in memory to write to.  You
269         /// may have to consider alignment.</param>
270         /// <param name="value">The value type to write to memory.</param>
271         [CLSCompliant(false)]
272         public void Write<T>(ulong byteOffset, T value) where T : struct
273         {
274             if (_numBytes == Uninitialized)
275                 throw NotInitialized();
276
277             uint sizeofT = SizeOf<T>();
278             byte* ptr = (byte*)handle + byteOffset;
279             SpaceCheck(ptr, sizeofT);
280
281             // *((T*) (_ptr + byteOffset)) = value;
282             bool mustCallRelease = false;
283             try
284             {
285                 DangerousAddRef(ref mustCallRelease);
286
287                 fixed (byte* pStructure = &Unsafe.As<T, byte>(ref value))
288                     Buffer.Memmove(ptr, pStructure, sizeofT);
289             }
290             finally
291             {
292                 if (mustCallRelease)
293                     DangerousRelease();
294             }
295         }
296
297         [CLSCompliant(false)]
298         public void WriteArray<T>(ulong byteOffset, T[] array, int index, int count)
299             where T : struct
300         {
301             if (array == null)
302                 throw new ArgumentNullException(nameof(array), SR.ArgumentNull_Buffer);
303             if (index < 0)
304                 throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
305             if (count < 0)
306                 throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
307             if (array.Length - index < count)
308                 throw new ArgumentException(SR.Argument_InvalidOffLen);
309
310             if (_numBytes == Uninitialized)
311                 throw NotInitialized();
312
313             uint sizeofT = SizeOf<T>();
314             uint alignedSizeofT = AlignedSizeOf<T>();
315             byte* ptr = (byte*)handle + byteOffset;
316             SpaceCheck(ptr, checked((ulong)(alignedSizeofT * count)));
317
318             bool mustCallRelease = false;
319             try
320             {
321                 DangerousAddRef(ref mustCallRelease);
322
323                 if (count > 0)
324                 {
325                     unsafe
326                     {
327                         fixed (byte* pStructure = &Unsafe.As<T, byte>(ref array[index]))
328                         {
329                             for (int i = 0; i < count; i++)
330                                 Buffer.Memmove(ptr + alignedSizeofT * i, pStructure + sizeofT * i, sizeofT);
331                         }
332                     }
333                 }
334             }
335             finally
336             {
337                 if (mustCallRelease)
338                     DangerousRelease();
339             }
340         }
341
342         /// <summary>
343         /// Returns the number of bytes in the memory region.
344         /// </summary>
345         [CLSCompliant(false)]
346         public ulong ByteLength
347         {
348             get
349             {
350                 if (_numBytes == Uninitialized)
351                     throw NotInitialized();
352
353                 return (ulong)_numBytes;
354             }
355         }
356
357         /* No indexer.  The perf would be misleadingly bad.  People should use
358          * AcquirePointer and ReleasePointer instead.  */
359
360         private void SpaceCheck(byte* ptr, ulong sizeInBytes)
361         {
362             if ((ulong)_numBytes < sizeInBytes)
363                 NotEnoughRoom();
364             if ((ulong)(ptr - (byte*)handle) > ((ulong)_numBytes) - sizeInBytes)
365                 NotEnoughRoom();
366         }
367
368         private static void NotEnoughRoom()
369         {
370             throw new ArgumentException(SR.Arg_BufferTooSmall);
371         }
372
373         private static InvalidOperationException NotInitialized()
374         {
375             return new InvalidOperationException(SR.InvalidOperation_MustCallInitialize);
376         }
377
378         /// <summary>
379         /// Returns the size that SafeBuffer (and hence, UnmanagedMemoryAccessor) reserves in the unmanaged buffer for each element of an array of T. This is not the same
380         /// value that sizeof(T) returns! Since the primary use case is to parse memory mapped files, we cannot change this algorithm as this defines a de-facto serialization format.
381         /// Throws if T contains GC references.
382         /// </summary>
383         internal static uint AlignedSizeOf<T>() where T : struct
384         {
385             uint size = SizeOf<T>();
386             if (size == 1 || size == 2)
387             {
388                 return size;
389             }
390
391             return (uint)(((size + 3) & (~3)));
392         }
393
394         /// <summary>
395         /// Returns same value as sizeof(T) but throws if T contains GC references.
396         /// </summary>
397         internal static uint SizeOf<T>() where T : struct
398         {
399             if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
400                 throw new ArgumentException(SR.Argument_NeedStructWithNoRefs);
401
402             return (uint)Unsafe.SizeOf<T>();
403         }
404     }
405 }