views:

211

answers:

1

Hey guys,

So I've got an application that starts another application with my DLL injected (with Detours). The entry point is DllMain. I can't do much from DllMain, and certainly cannot loop. So how do I call my DLL monitor functions every x seconds? I read you cannot create a thread from DllMain (at least until it returns) and its true because it crashed me. So I tried creating it in the attach thread event and it crashed me. So now what I'm trying to do is inject it again (incase Detours fails) so I can get the module handle. Then I get the address of an initializer function which creates my thread. I get the module handle fine, but I don't think I can get the function address. I made the function empty, and it still crashed me. So it doesn't even get as far as calling the function. Visual Studio said I have no read access.

So what am I suppose to do? What do you do to loop your DLL functions when you don't own the attached program (exe).

//Application.exe
STARTUPINFO si = {sizeof(STARTUPINFO)};
     PROCESS_INFORMATION pi = {0};

     DetourCreateProcessWithDll(filename, NULL, NULL, NULL, TRUE, 
            CREATE_DEFAULT_ERROR_MODE | CREATE_SUSPENDED, NULL, path,
            &si, &pi, detoured, hook, NULL);

     processID = pi.dwProcessId;

     hDll = InjectDLL(processID, hook);


if(hDll != NULL)
{
STARTER Starter = (STARTER)GetProcAddress(hDll, "Starter");

if(Starter != NULL)
    Starter();
}

     ResumeThread(pi.hThread);

The function Starter is extern C exported and looks fine inspected (it's ordinal 1).

I have no idea what could possibly be wrong, and merely hope someone out there has had experience with this topic and crashing.

Here's the DLL code:

//Hook.h
extern "C"
{
    void __declspec(dllexport) Starter(void);
}

//Hook.cpp
void Starter(void)
{

}

Thanks

A: 

You can't do it that way because the DLL is injected into a different process and you're trying to execute the function in the address space of your hooking process.

What you'll have to do is call CreateRemoteThread, passing in the address that you get from GetProcAddress in the lpStartAddress parameter. This will create a new thread on the remote process, and execute the function in the address space of that process, in the context of the new thread.

BTW, technically you should be able to create a new thread in DllMain/DLL_PROCESS_ATTACH, as long as you're not doing any synchronizing with other threads, though it's not recommended. I'm not sure what issues might exist if doing this when the DLL is being injected though.

Gerald