Proper PE base relocation

344 Views Asked by At

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.

0

There are 0 best solutions below