| | | 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 | | internal sealed class PinnedObject : CriticalDisposableObject |
| | | 11 | | { |
| | | 12 | | // can't be read-only since GCHandle is a mutable struct |
| | | 13 | | private GCHandle _handle; |
| | | 14 | | |
| | | 15 | | // non-zero indicates a valid handle |
| | | 16 | | private int _isValid; |
| | | 17 | | |
| | 0 | 18 | | public PinnedObject(object obj) |
| | 0 | 19 | | { |
| | | 20 | | #if FEATURE_CER |
| | | 21 | | // Make sure the current thread isn't aborted in between allocating the handle and storing it. |
| | | 22 | | RuntimeHelpers.PrepareConstrainedRegions(); |
| | | 23 | | try |
| | | 24 | | { /* intentionally left blank */ } |
| | | 25 | | finally |
| | | 26 | | #endif |
| | 0 | 27 | | { |
| | 0 | 28 | | _handle = GCHandle.Alloc(obj, GCHandleType.Pinned); |
| | 0 | 29 | | _isValid = 1; |
| | 0 | 30 | | } |
| | 0 | 31 | | } |
| | | 32 | | |
| | | 33 | | protected override void Release() |
| | 0 | 34 | | { |
| | | 35 | | #if FEATURE_CER |
| | | 36 | | // Make sure the current thread isn't aborted in between zeroing the handle and freeing it. |
| | | 37 | | RuntimeHelpers.PrepareConstrainedRegions(); |
| | | 38 | | try |
| | | 39 | | { /* intentionally left blank */ } |
| | | 40 | | finally |
| | | 41 | | #endif |
| | 0 | 42 | | { |
| | 0 | 43 | | if (Interlocked.Exchange(ref _isValid, 0) != 0) |
| | 0 | 44 | | { |
| | 0 | 45 | | _handle.Free(); |
| | 0 | 46 | | } |
| | 0 | 47 | | } |
| | 0 | 48 | | } |
| | | 49 | | |
| | 0 | 50 | | public unsafe byte* Pointer => (byte*)_handle.AddrOfPinnedObject(); |
| | | 51 | | } |
| | | 52 | | } |
| | | 53 | | |