Previous step is here. By the way, there was a bug in the code, I fixed it. It appeared when PE file had more than one callback.
Let’s turn to the next important part of many PE files – relocations. They are used, when it is impossible to load an image to the base address indicated in its header. Mainly this is a typical behavior for DLL files (basically they can’t work properly without relocations). Imagine that EXE file is being loaded to 0x400000 address. This EXE file loads the DLL, which is also loaded to this address. The addresses are the same, and the loader will look for DLL file relocations, because the DLL is loaded after the EXE. If there will be no relocations, loading will fail.
The relocations themselves are just the set of the tables with pointers to DWORDs, which should be calculated by the loader, if the image is loaded by an address other than base. There are many types of relocations, but actually only two are used in x86 (PE): IMAGE_REL_BASED_HIGHLOW = 3 and IMAGE_REL_BASED_ABSOLUTE = 0, and the second one does nothing, it is required only for relocation tables alignment.
I will just say, that loader loads EXE files to base address almost always, without using relocation. Our packer is unable to pack DLL yet, so to test relocation packing we should create an EXE file with incorrect base address, and then the loader will have to change it and apply relocations. I will not provide the test project source code here, you will find it in solution at the end of the article. I set 0x7F000000 as a base address (Linker – Advanced – Base Address).
We have to process relocations manually, like everything else, after unpacking a file. We should notify the loader in advance, that the file has relocations. Also, we need to know a new address, to which the loader moved the file.
We don’t have to do anything to notify the loader, that our file has relocations – we still have necessary flags set in PE file headers left from original file. However, we need to know at which address the file was loaded.
Continue reading “Developing PE file packer step-by-step. Step 7. Relocations”