WinAPI中的SafeHandle与IntPtr和C#中的CloseHandle

时间:2018-11-08 09:26:05

标签: c# intptr safehandle

我阅读了许多有关SafeHandleIDiposable的文章,但我仍然不明白我是否应该在C#中使用SafeHandle和CloseHandle。

MSDN SafeHandle example

IntPtr, SafeHandle and HandleRef - Explained

https://blog.benoitblanchon.fr/safehandle/

第一个来源与我的问题类似,但是没有回答我的问题。

比方说,我有以下3个来自互联网的示例:

// Example 1
byte[] temp = new byte[IntPtr.Size];
fixed (byte* p = temp)
{
    IntPtr SectionHandle = new IntPtr(p);
    LARGE_INTEGER MaximumSize = new LARGE_INTEGER();
    MaximumSize.LowPart = pNTHeader->OptionalHeader.SizeOfImage;
    status = NtCreateSection(
        SectionHandle,
        SectionAccess.SECTION_MAP_EXECUTE | SectionAccess.SECTION_MAP_READ | SectionAccess.SECTION_MAP_WRITE,
        IntPtr.Zero,
        ref MaximumSize,
        MemoryProtectionConstants.PAGE_EXECUTE_READWRITE,
        AllocationTypes.SEC_COMMIT,
        IntPtr.Zero);
}

// Example 2
IntPtr hFile = CreateFile(
    path, 
    GenericRights.GENERIC_READ, 
    FileFlags.FILE_SHARE_DELETE | FileFlags.FILE_SHARE_READ | FileFlags.FILE_SHARE_WRITE, 
    IntPtr.Zero, 
    FileCreationFlags.OPEN_EXISTING, 
    FileFlags.FILE_ATTRIBUTE_NORMAL, 
    IntPtr.Zero);

if (hFile == INVALID_HANDLE_VALUE)
    return false;

// Example 3
IntPtr hMap = CreateFileMapping(
    hFile, 
    IntPtr.Zero, 
    MemoryProtectionConstants.PAGE_READONLY, 
    0, 
    0, 
    IntPtr.Zero);

if (hMap == IntPtr.Zero)
    return false;

这些示例是Windows API,因此不受管理。我不明白的是:

1)所有3个示例都应使用IntPtr上的SafeHandle,因为它们是不受管理的,如果其中之一不应该使用,为什么?

2)我发现CloseHandle是C / C ++中的一种好习惯,但是在C#中,我不知道垃圾收集器是否最终自动关闭了句柄?上面的示例中应该使用CloseHandle吗?为什么?

3)第一个示例使用非托管的byte*在堆上分配内存。可以通过不使用非托管指针来完成此过程吗?下面的代码是我的猜测,您对此有何看法?

IntPtr SectionHandle = Marshal.AllocateHGlobal(sizeof(int));
... code ...
Marshal.FreeHGlobal(SectionHandle);

编辑: 发布我编辑的代码:

[SecurityCritical]
public sealed class SafeHandleBuffer : SafeBuffer
{
    public SafeHandleBuffer()
        : base(true)
    {
        handle = Marshal.AllocHGlobal(IntPtr.Size);
    }

    public int GetValue() =>
        Marshal.ReadInt32(handle);

    [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
    protected override bool ReleaseHandle()
    {
        Marshal.FreeHGlobal(handle);
        return true;
    }
}

public sealed class SafeHandleToken : SafeHandleZeroOrMinusOneIsInvalid
{
    private SafeHandleToken()
        : base(true)
    {
    }

    [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
    protected override bool ReleaseHandle() => 
        CloseHandle(handle);
}

// Including the IDisposable implementation in the class where the next example calls are found
private SafeHandleToken _fileHandle, _mappingHandle;
private SafeHandleBuffer _sectionHandle;

public void Dispose()
{
    Dispose(true);
    GC.SuppressFinalize(this);
}

[SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)]
protected virtual void Dispose(bool disposing)
{
    if (_fileHandle != null && !_fileHandle.IsInvalid)
    {
        _fileHandle.Dispose();
    }

    if (_mappingHandle != null && !_mappingHandle.IsInvalid)
    {
        _mappingHandle.Dispose();
    }

    if (_sectionHandle != null && !_sectionHandle.IsInvalid)
    {
        _sectionHandle.Dispose();
    }
}

// Example 1
SafeHandleBuffer tempHandle = new SafeHandleBuffer();
LARGE_INTEGER MaximumSize = new LARGE_INTEGER();
MaximumSize.LowPart = pNTHeader->OptionalHeader.SizeOfImage;
status = NtCreateSection(
    tempHandle,
    SectionAccess.SECTION_MAP_EXECUTE | SectionAccess.SECTION_MAP_READ | SectionAccess.SECTION_MAP_WRITE,
    IntPtr.Zero,
    ref MaximumSize,
    MemoryProtectionConstants.PAGE_EXECUTE_READWRITE,
    AllocationTypes.SEC_COMMIT,
    IntPtr.Zero);

// Example 2
SafeHandleToken tempHandle = CreateFile(
    path,
    GenericRights.GENERIC_READ,
    FileShare.ReadWrite | FileShare.Delete,
    IntPtr.Zero,
    FileMode.Open,
    FileAttributes.Normal,
    IntPtr.Zero);

Thread.Sleep(500);
_fileHandle = tempHandle;

if (_fileHandle.IsInvalid)
    throw new Win32Exception(Marshal.GetLastWin32Error());

// Example 3
tempHandle = CreateFileMapping(
    _fileHandle,
    IntPtr.Zero,
    (uint)MemoryProtectionConstants.PAGE_READONLY | (uint)AllocationTypes.SEC_IMAGE,
    0,
    0,
    IntPtr.Zero);

Thread.Sleep(500);
_mappingHandle = tempHandle;

if (_mappingHandle.IsInvalid)
    throw new Win32Exception(Marshal.GetLastWin32Error());

您认为我一切都很好吗? SafeHandle是否应在GetModuleHandleGetProcAddressMapViewOfFile之类的每个Windows API上使用,还有我现在不记得的其他一些API。其中一些返回LPVOID

0 个答案:

没有答案