如何通过HANDLE来判断堆是否被序列化?

时间:2017-06-03 01:24:42

标签: c++ windows multithreading winapi heap-memory

说,如果我在我的流程中调用GetProcessHeaps来获取它使用的堆列表。有一个堆HANDLE如何判断这个堆是否是用HEAP_NO_SERIALIZE flag创建的?

1 个答案:

答案 0 :(得分:1)

虽然不是一个明确的答案,但您可以调用HeapQueryInformation(HeapCompatibilityInformation),如果它返回2则会被序列化,因为MSDN说这是关于HEAP_NO_SERIALIZE:

  

无法为使用此选项创建的堆启用低碎片堆(LFH)

我不知道是否有一个未记录的API来获取标志,但出于调试目的,您可以直接访问内部堆结构:

void DumpHeapType_Win8_x86(HANDLE hHeap)
{
    typedef struct {
        UINT32 Unknown1[2];
        UINT32 Sig;
        UINT32 Unknown2[1];
        void*Unknown3[2]; //LIST_ENTRY?
        void*Unknown4[1+1+1+1+2];
        UINT32 Unknown5[1+1+1+1];
        UINT32 Flags;
    } HEAP_HDR;
    typedef struct {
        UINT32 Unknown1[2];
        UINT32 Sig;
        UINT32 Unknown2[1];
        void*Unknown3[2]; //LIST_ENTRY?
        HEAP_HDR*pHdr;
    } HEAP_THING;
    HEAP_THING *pThing = (HEAP_THING*) hHeap;
    if (hHeap && pThing->Sig == 0xffeeffee)
    {
        HEAP_HDR *pHdr = (HEAP_HDR*) pThing->pHdr;
        if (pHdr->Sig == 0xffeeffee)
        {
            printf("Flags=%#x Serialized=%d\n", pHdr->Flags, !(pHdr->Flags & HEAP_NO_SERIALIZE));
        }
    }
}

void playwithheaps()
{
    HANDLE hHeap;
    DumpHeapType_Win8_x86(hHeap = GetProcessHeap());
    DumpHeapType_Win8_x86(hHeap = HeapCreate(0, 0, 0)); if (hHeap) HeapDestroy(hHeap);
    DumpHeapType_Win8_x86(hHeap = HeapCreate(HEAP_NO_SERIALIZE, 0, 0)); if (hHeap) HeapDestroy(hHeap);
    DumpHeapType_Win8_x86(hHeap = HeapCreate(HEAP_NO_SERIALIZE|HEAP_GENERATE_EXCEPTIONS, 0, 0)); if (hHeap) HeapDestroy(hHeap);
}

在我的Windows 8机器上,这给了我以下输出:

Flags=0x2 Serialized=1
Flags=0x1002 Serialized=1
Flags=0x1003 Serialized=0
Flags=0x1007 Serialized=0

但是堆结构布局在其他版本上可能会有所不同,所以你只需要仔细测试......