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.
5 /*============================================================
7 ** Purpose: Unsafe code that uses pointers should use
8 ** SafePointer to fix subtle lifetime problems with the
9 ** underlying resource.
11 ===========================================================*/
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.
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).
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)
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.
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.
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.
57 // *) This class could benefit from a constraint saying T is a value type
58 // containing no GC references.
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.
69 using System.Diagnostics;
70 using System.Runtime.CompilerServices;
71 using Internal.Runtime.CompilerServices;
72 using Microsoft.Win32.SafeHandles;
74 namespace System.Runtime.InteropServices
76 public abstract unsafe class SafeBuffer : SafeHandleZeroOrMinusOneIsInvalid
78 // Steal UIntPtr.MaxValue as our uninitialized value.
79 private static readonly UIntPtr Uninitialized = (UIntPtr.Size == 4) ?
80 ((UIntPtr)UInt32.MaxValue) : ((UIntPtr)UInt64.MaxValue);
82 private UIntPtr _numBytes;
84 protected SafeBuffer(bool ownsHandle) : base(ownsHandle)
86 _numBytes = Uninitialized;
90 /// Specifies the size of the region of memory, in bytes. Must be
91 /// called before using the SafeBuffer.
93 /// <param name="numBytes">Number of valid bytes in memory.</param>
95 public void Initialize(ulong numBytes)
97 if (IntPtr.Size == 4 && numBytes > UInt32.MaxValue)
98 throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_AddressSpace);
100 if (numBytes >= (ulong)Uninitialized)
101 throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_UIntPtrMax);
103 _numBytes = (UIntPtr)numBytes;
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.
110 [CLSCompliant(false)]
111 public void Initialize(uint numElements, uint sizeOfEachElement)
113 if (IntPtr.Size == 4 && numElements * sizeOfEachElement > UInt32.MaxValue)
114 throw new ArgumentOutOfRangeException("numBytes", SR.ArgumentOutOfRange_AddressSpace);
116 if (numElements * sizeOfEachElement >= (ulong)Uninitialized)
117 throw new ArgumentOutOfRangeException(nameof(numElements), SR.ArgumentOutOfRange_UIntPtrMax);
119 _numBytes = checked((UIntPtr)(numElements * sizeOfEachElement));
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.
126 [CLSCompliant(false)]
127 public void Initialize<T>(uint numElements) where T : struct
129 Initialize(numElements, AlignedSizeOf<T>());
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:
138 // byte* pointer = null;
140 // safeBuffer.AcquirePointer(ref pointer);
141 // // Use pointer here, with your own bounds checking
144 // if (pointer != null)
145 // safeBuffer.ReleasePointer();
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.
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.
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)
164 if (_numBytes == Uninitialized)
165 throw NotInitialized();
170 DangerousAddRef(ref junk);
171 pointer = (byte*)handle;
174 public void ReleasePointer()
176 if (_numBytes == Uninitialized)
177 throw NotInitialized();
183 /// Read a value type from memory at the given offset. This is
184 /// equivalent to: return *(T*)(bytePtr + byteOffset);
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
193 if (_numBytes == Uninitialized)
194 throw NotInitialized();
196 uint sizeofT = SizeOf<T>();
197 byte* ptr = (byte*)handle + byteOffset;
198 SpaceCheck(ptr, sizeofT);
200 // return *(T*) (_ptr + byteOffset);
201 T value = default(T);
202 bool mustCallRelease = false;
205 DangerousAddRef(ref mustCallRelease);
207 fixed (byte* pStructure = &Unsafe.As<T, byte>(ref value))
208 Buffer.Memmove(pStructure, ptr, sizeofT);
218 [CLSCompliant(false)]
219 public void ReadArray<T>(ulong byteOffset, T[] array, int index, int count)
223 throw new ArgumentNullException(nameof(array), SR.ArgumentNull_Buffer);
225 throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
227 throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
228 if (array.Length - index < count)
229 throw new ArgumentException(SR.Argument_InvalidOffLen);
231 if (_numBytes == Uninitialized)
232 throw NotInitialized();
234 uint sizeofT = SizeOf<T>();
235 uint alignedSizeofT = AlignedSizeOf<T>();
236 byte* ptr = (byte*)handle + byteOffset;
237 SpaceCheck(ptr, checked((ulong)(alignedSizeofT * count)));
239 bool mustCallRelease = false;
242 DangerousAddRef(ref mustCallRelease);
248 fixed (byte* pStructure = &Unsafe.As<T, byte>(ref array[index]))
250 for (int i = 0; i < count; i++)
251 Buffer.Memmove(pStructure + sizeofT * i, ptr + alignedSizeofT * i, sizeofT);
264 /// Write a value type to memory at the given offset. This is
265 /// equivalent to: *(T*)(bytePtr + byteOffset) = value;
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
274 if (_numBytes == Uninitialized)
275 throw NotInitialized();
277 uint sizeofT = SizeOf<T>();
278 byte* ptr = (byte*)handle + byteOffset;
279 SpaceCheck(ptr, sizeofT);
281 // *((T*) (_ptr + byteOffset)) = value;
282 bool mustCallRelease = false;
285 DangerousAddRef(ref mustCallRelease);
287 fixed (byte* pStructure = &Unsafe.As<T, byte>(ref value))
288 Buffer.Memmove(ptr, pStructure, sizeofT);
297 [CLSCompliant(false)]
298 public void WriteArray<T>(ulong byteOffset, T[] array, int index, int count)
302 throw new ArgumentNullException(nameof(array), SR.ArgumentNull_Buffer);
304 throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
306 throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
307 if (array.Length - index < count)
308 throw new ArgumentException(SR.Argument_InvalidOffLen);
310 if (_numBytes == Uninitialized)
311 throw NotInitialized();
313 uint sizeofT = SizeOf<T>();
314 uint alignedSizeofT = AlignedSizeOf<T>();
315 byte* ptr = (byte*)handle + byteOffset;
316 SpaceCheck(ptr, checked((ulong)(alignedSizeofT * count)));
318 bool mustCallRelease = false;
321 DangerousAddRef(ref mustCallRelease);
327 fixed (byte* pStructure = &Unsafe.As<T, byte>(ref array[index]))
329 for (int i = 0; i < count; i++)
330 Buffer.Memmove(ptr + alignedSizeofT * i, pStructure + sizeofT * i, sizeofT);
343 /// Returns the number of bytes in the memory region.
345 [CLSCompliant(false)]
346 public ulong ByteLength
350 if (_numBytes == Uninitialized)
351 throw NotInitialized();
353 return (ulong)_numBytes;
357 /* No indexer. The perf would be misleadingly bad. People should use
358 * AcquirePointer and ReleasePointer instead. */
360 private void SpaceCheck(byte* ptr, ulong sizeInBytes)
362 if ((ulong)_numBytes < sizeInBytes)
364 if ((ulong)(ptr - (byte*)handle) > ((ulong)_numBytes) - sizeInBytes)
368 private static void NotEnoughRoom()
370 throw new ArgumentException(SR.Arg_BufferTooSmall);
373 private static InvalidOperationException NotInitialized()
375 return new InvalidOperationException(SR.InvalidOperation_MustCallInitialize);
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.
383 internal static uint AlignedSizeOf<T>() where T : struct
385 uint size = SizeOf<T>();
386 if (size == 1 || size == 2)
391 return (uint)(((size + 3) & (~3)));
395 /// Returns same value as sizeof(T) but throws if T contains GC references.
397 internal static uint SizeOf<T>() where T : struct
399 if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
400 throw new ArgumentException(SR.Argument_NeedStructWithNoRefs);
402 return (uint)Unsafe.SizeOf<T>();