| | | 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 | | |
| | | 4 | | using System.Runtime.CompilerServices; |
| | | 5 | | using System.Runtime.InteropServices; |
| | | 6 | | using System.Threading; |
| | | 7 | | |
| | | 8 | | namespace System.Reflection.Internal |
| | | 9 | | { |
| | | 10 | | /// <summary> |
| | | 11 | | /// Represents memory block allocated on native heap. |
| | | 12 | | /// </summary> |
| | | 13 | | /// <remarks> |
| | | 14 | | /// Owns the native memory resource. |
| | | 15 | | /// </remarks> |
| | | 16 | | internal sealed class NativeHeapMemoryBlock : AbstractMemoryBlock |
| | | 17 | | { |
| | | 18 | | private sealed unsafe class DisposableData : CriticalDisposableObject |
| | | 19 | | { |
| | | 20 | | private IntPtr _pointer; |
| | | 21 | | |
| | 0 | 22 | | public DisposableData(int size) |
| | 0 | 23 | | { |
| | | 24 | | #if FEATURE_CER |
| | | 25 | | // make sure the current thread isn't aborted in between allocating and storing the pointer |
| | | 26 | | RuntimeHelpers.PrepareConstrainedRegions(); |
| | | 27 | | try |
| | | 28 | | { /* intentionally left blank */ } |
| | | 29 | | finally |
| | | 30 | | #endif |
| | 0 | 31 | | { |
| | 0 | 32 | | _pointer = Marshal.AllocHGlobal(size); |
| | 0 | 33 | | } |
| | 0 | 34 | | } |
| | | 35 | | |
| | | 36 | | protected override void Release() |
| | 0 | 37 | | { |
| | | 38 | | #if FEATURE_CER |
| | | 39 | | // make sure the current thread isn't aborted in between zeroing the pointer and freeing the memory |
| | | 40 | | RuntimeHelpers.PrepareConstrainedRegions(); |
| | | 41 | | try |
| | | 42 | | { /* intentionally left blank */ } |
| | | 43 | | finally |
| | | 44 | | #endif |
| | 0 | 45 | | { |
| | 0 | 46 | | IntPtr ptr = Interlocked.Exchange(ref _pointer, IntPtr.Zero); |
| | 0 | 47 | | if (ptr != IntPtr.Zero) |
| | 0 | 48 | | { |
| | 0 | 49 | | Marshal.FreeHGlobal(ptr); |
| | 0 | 50 | | } |
| | 0 | 51 | | } |
| | 0 | 52 | | } |
| | | 53 | | |
| | 0 | 54 | | public byte* Pointer => (byte*)_pointer; |
| | | 55 | | } |
| | | 56 | | |
| | | 57 | | private readonly DisposableData _data; |
| | | 58 | | private readonly int _size; |
| | | 59 | | |
| | 0 | 60 | | internal NativeHeapMemoryBlock(int size) |
| | 0 | 61 | | { |
| | 0 | 62 | | _data = new DisposableData(size); |
| | 0 | 63 | | _size = size; |
| | 0 | 64 | | } |
| | | 65 | | |
| | 0 | 66 | | public override void Dispose() => _data.Dispose(); |
| | 0 | 67 | | public override unsafe byte* Pointer => _data.Pointer; |
| | 0 | 68 | | public override int Size => _size; |
| | | 69 | | } |
| | | 70 | | } |
| | | 71 | | |