-1
#include <Windows.h>

int main(){
    printf("Enter name of program. \n");
    char prog[300];
    scanf("%s", prog);
    HMODULE hModule = GetModuleHandleW((LPCWSTR)prog);
    if (hModule){
        IMAGE_DOS_HEADER* pIDH = (IMAGE_DOS_HEADER*)hModule;
        IMAGE_NT_HEADERS* pNTH =(IMAGE_NT_HEADERS*)((BYTE*)pIDH + pIDH->e_lfanew);
        IMAGE_OPTIONAL_HEADER pOPH = (IMAGE_OPTIONAL_HEADER)pNTH->OptionalHeader;
        IMAGE_DATA_DIRECTORY* pIDD = (IMAGE_DATA_DIRECTORY*)pOPH.DataDirectory;
        printf("%x", pIDD->VirtualAddress);
    }
    else {
        printf("Error");
    }

    return 0;
}

That's my basic script for now only to check if I get into the IMAGE_DATA_DIRECTORY. My goal is to print every dll and all of it's imported functions of a certain running process - GetModuleHandleA / W. Every call its returning null - printing "Error" as I checked, excluding the empty call in which it prints '0' for some reason..

  • 3
    `prog` is not a wide string, casting it to one like `(LPCWSTR)prog` doesn't change that. – Retired Ninja Nov 06 '22 at 21:13
  • You would probably have more success doing something like [How can I get a process handle by its name in C++?](https://stackoverflow.com/questions/865152/how-can-i-get-a-process-handle-by-its-name-in-c) if you're trying to find a process that was not loaded by the current process. since the [socumentation](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulehandlea) does say "Retrieves a module handle for the specified module. The module must have been loaded by the calling process." – Retired Ninja Nov 06 '22 at 21:34
  • Your code does work using `GetModuleHandleA` and the name of the currently running executable. – Retired Ninja Nov 06 '22 at 21:36

1 Answers1

1

Besides the obvious (LPCWSTR)prog casting bug, GetModuleHandle is never going to work because it only handles modules in the current process.

Call CreateToolhelp32Snapshot to get a list of all processes and then call CreateToolhelp32Snapshot again to get the modules of a specific process. Note that you cannot read the DOS/NT headers of a remote process directly, you would have to use ReadProcessMemory.

DataDirectory is an array, you have to specify the directory you are interested in (resource, import, export etc.).

Anders
  • 97,548
  • 12
  • 110
  • 164