0

I'm trying to run a WIN32 PE executable from memory (not for malware just for software protection purposes). When I allocate at the desired image base address (0x00400000) it works perfectly. But this is not ideal since this address is not always available, sometimes even already in use by the current process depending on ASLR.

Instead I have to relocate the image with the new address obtained from VirtualAlloc() using this generic code.

    while (pIBR->VirtualAddress)
    {
        if (pIBR->SizeOfBlock >= sizeof(IMAGE_BASE_RELOCATION))
        {
            count = (pIBR->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / sizeof(WORD);
            list = (PWORD)(pIBR + 1);

            for (i = 0; i < count; i++)
            {
                if (list[i])
                {
                    ptr = (PDWORD)((LPBYTE)image + (pIBR->VirtualAddress + (list[i] & 0xFFF)));
                    *ptr += delta;
                }
            }
        }

        pIBR = (PIMAGE_BASE_RELOCATION)((LPBYTE)pIBR + pIBR->SizeOfBlock);
    }

which works fine for simple executable's, but more complex executable's with resources, TLS, and various other things, don't load correctly or at all.

My question, is there a better way of doing image relocation, or how can I always reserve the address 0x00400000 for my new PE image.

Thanks.

  • If you absolutely want the 0x400000 base address and it's already mapped, you won't be able to do anything (it could be anything from a module, heap base, heap allocations, private bytes, internal OS structures, etc.). On the other hand you can use [VirtualQuery](https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualquery) to check if you have enough room anywhere in the process address space if the pages in a range are all marked as `MEM_FREE`. – Neitsa Apr 06 '20 at 08:30
  • Ok i'll leave it aside for now then. The problem with using any other base address is I have to relocate the image, which i'm trying to avoid. – DanielWashington Apr 06 '20 at 09:53
  • The upper 4 bits of `list[i]` is the base relocation type, which you ignore. See [Base Relocation Types](https://learn.microsoft.com/en-us/windows/win32/debug/pe-format#base-relocation-types). – ssbssa Jun 06 '20 at 16:23

0 Answers0