DEV Community

loading...

Getting a Handle to a Dynamically Linked Library [Windows PE Internals]

wireless90 profile image wireless90 Updated on ・2 min read

Previous Windows PE Internals Writeups

Let's Begin

This writeup is going to be on loading our PE File's DLL at runtime.

We are going to use the function GetModuleHandleA.

HMODULE GetModuleHandleA(
  LPCSTR lpModuleName
);
Enter fullscreen mode Exit fullscreen mode

Retrieves a module handle for the specified module. The module must have been loaded by the calling process.
We can either pass in an executable or a dll as the name.

We want to load user32.dll from our own executable.

The important thing is that the dll must already be loaded by the executable.

By default in Visual Studio windows project, some dlls are already configured to be loaded. We can double check it in the Project Properties.

image

We can see that user32.dll is already configured to be loaded. If it is not loaded, we can either configure it to be loaded or use any functions within user32.dll which causes the linker to load it.

The signature for the function would thus look like,

HMODULE peBase = GetModuleHandleA("user32.dll");
Enter fullscreen mode Exit fullscreen mode

After loading the module, a pointer (HMODULE) to the start of the user32.dll is returned which is stored in the variable peBase.

In general, our windows program looks like,

#include <Windows.h>

int  WinMain(
     HINSTANCE hInstance,
     HINSTANCE hPrevInstance,
     LPSTR     lpCmdLine,
     int       nCmdShow
)
{
    HMODULE peBase = GetModuleHandleA("user32.dll");

    if (peBase == NULL)
    {
        MessageBoxA(0, "Can't load user32.dll", "Error", MB_OK | MB_ICONERROR);
        return 1;
    }

    MessageBoxA(0, "user32.dll loaded successfully!", "Success", MB_OK | MB_ICONINFORMATION);

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

In this exercise, I learnt how to get a handle to an already loaded dynamic link library (dll).

Next

Validating the MZ Signature

Discussion (0)

Forem Open with the Forem app