private static void Release(IProtectedMemoryAllocator pm, ref IntPtr ptr, ulong len) { #pragma warning disable 162 if (Debug.On) { // TODO Add/uncomment this when we refactor logging to use static creation // log.LogDebug("closing: {pointer}", ptr); } #pragma warning restore 162 IntPtr oldPtr = Interlocked.Exchange(ref ptr, IntPtr.Zero); if (oldPtr != IntPtr.Zero) { try { pm.SetReadWriteAccess(oldPtr, len); pm.ZeroMemory(oldPtr, len); } finally { pm.Free(oldPtr, len); } } }
protected virtual void Dispose(bool disposing) { if (!disposing) { if (pointer == IntPtr.Zero) { return; } if (requireSecretDisposal) { const string exceptionMessage = "FATAL: Reached finalizer for ProtectedMemorySecret (missing Dispose())"; throw new Exception(exceptionMessage + ((creationStackTrace == null) ? string.Empty : Environment.NewLine + creationStackTrace)); } const string warningMessage = "WARN: Reached finalizer for ProtectedMemorySecret (missing Dispose())"; Debug.WriteLine(warningMessage + ((creationStackTrace == null) ? string.Empty : Environment.NewLine + creationStackTrace)); } else { pointerLock.EnterWriteLock(); try { if (pointer == IntPtr.Zero) { return; } #if DEBUG // TODO Add/uncomment this when we refactor logging to use static creation // log.LogDebug("closing: {pointer}", ptr); #endif // accessLock isn't needed here since we are holding the pointer lock in write try { allocator.SetReadWriteAccess(pointer, length); } finally { allocator.Free(pointer, length); pointer = IntPtr.Zero; } } finally { pointerLock.ExitWriteLock(); } } }
private void TestSetReadWriteAccess() { IntPtr pointer = protectedMemoryAllocator.Alloc(1); try { protectedMemoryAllocator.SetReadWriteAccess(pointer, 1); CheckIntPtr(pointer, "IProtectedMemoryAllocator.Alloc"); // Verifies we can write and read back Marshal.WriteByte(pointer, 0, 42); Assert.Equal(42, Marshal.ReadByte(pointer, 0)); } finally { protectedMemoryAllocator.Free(pointer, 1); } }
private static void Release(IProtectedMemoryAllocator pm, ref IntPtr ptr, ulong len) { #if DEBUG // TODO Add/uncomment this when we refactor logging to use static creation // log.LogDebug("closing: {pointer}", ptr); #endif IntPtr oldPtr = Interlocked.Exchange(ref ptr, IntPtr.Zero); if (oldPtr != IntPtr.Zero) { try { pm.SetReadWriteAccess(oldPtr, len); } finally { pm.Free(oldPtr, len); } } }