简体   繁体   中英

How to find out to what process my dll is attached?

Before my dll file gets injected to a process, I want to check if it actually is the process I want it to inject. Is there a way to achieve this, so I could abort the injection process if its the wrong process? Thank you in advance for any help!

int APIENTRY DllMain(HMODULE hModule, DWORD reason, LPVOID reserved)
{
    if (reason == DLL_PROCESS_ATTACH)
    {
        if (process == theprocessiwant)
        {
            //call my stuff....
        }
    }
        return true;
}

GetModuleFileNameA will give you the complete path of the executable of whose process you have injected into. Compare this path against your predefined executable path.

Okay thank you for your suggestions, I found a working way!

DWORD targetProcessId;
int APIENTRY DllMain(HMODULE hModule, DWORD reason, LPVOID reserved)
{
    PROCESSENTRY32 entry;
    entry.dwSize = sizeof(PROCESSENTRY32);

    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);

    if (Process32First(snapshot, &entry) == TRUE)
    {
        while (Process32Next(snapshot, &entry) == TRUE)
        {
            if (_stricmp(entry.szExeFile, "target.exe") == 0)
            {
                targetProcessId = entry.th32ProcessID;
            }
        }
    }
    CloseHandle(snapshot);

    if (reason == DLL_PROCESS_ATTACH)
    {
        if (GetCurrentProcessId() == targetProcessId)
        {
           //MY Code
        }
    }

    return true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM