Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ How to control Image Base of LoadLibrary API

After Rebasing the main program very high up in it's own imagebase.

How do I guarantee that the dll that gets loaded will load in 0x400000

dllImageBase = LoadLibrary("test.dll");
printf("imagebase = 0x%x", dllImageBase);

I always get 0x460000 instead of 0x400000

I need my dll first instruction to start from 0x401000, it used to start at 0x600000 before rebasing

Command for linker to rebase is

#pragma comment( linker, "/BASE:8000000") 

So 0x400000 is actually free right now yet it doesn't use it by default.. so any way I can control it, where it should relocate. Some WIN32API maybe?

like image 563
SSpoke Avatar asked Sep 11 '11 18:09

SSpoke


People also ask

How do I find DLL base address?

To get the base address of a module(DLL or EXE) in memory you can enumerate the loaded modules using ToolHelp32Snapshot Windows API function. Microsoft provides documented source code to find the module. Basically you need 2 functions, one to grab the ProcessId and then one to get the base address.

How does LoadLibrary work?

LoadLibrary can be used to load a library module into the address space of the process and return a handle that can be used in GetProcAddress to get the address of a DLL function. LoadLibrary can also be used to load other executable modules.

Which DLL is LoadLibrary?

Kernel32. dll is loaded into every Windows process, and within it is a useful function called LoadLibrary .

What is Hmodule?

HMODULE. A handle to a module. The is the base address of the module in memory. HMODULE and HINSTANCE are the same in current versions of Windows, but represented different things in 16-bit Windows.


2 Answers

You are going to have to disable Address Space Layout Randomization to get the DLL loaded where you want it. A feature designed to stop you from what you are trying to do. /DYNAMICBASE linker option. Loading at 0x400000 worked when I tried it.

like image 184
Hans Passant Avatar answered Sep 22 '22 09:09

Hans Passant


Never rely on a DLL loading at a specific base. If you could force DLLs to load at a specific base then you are opening a potential security hole.

If you have a map file you know what the offset of a given function is. Therefore you can use GetProcAddress to work out what the base address of the DLL is. This is a far safer way to work even if it means that updating your DLL breaks the code loading the DLL.

like image 45
Goz Avatar answered Sep 21 '22 09:09

Goz