user2899050
user2899050

Reputation: 159

Why does this C program infinitely loop?

I wrote a DLL file that I can inject into another process. Once injected, it is supposed to create a message box. It seems to create an infinite number of messageboxes and my computer crashes. Any ideas? Also, what is the difference between DLLIMPORT and DWORD WINAPI? Should Main be DLLIMPORT or the other?

dllmain.c

/* Replace "dll.h" with the name of your header */
#include "dll.h"
#include <windows.h>

DLLIMPORT void HelloWorld() {
    MessageBox(0,"Hello World from DLL!\n","Hi",MB_ICONINFORMATION);
}

int main() {
    MessageBox(0,"Hello World from DLL!\n","Hi",MB_ICONINFORMATION);
}

DWORD WINAPI Main(LPVOID lpParam) {
    main();
    return S_OK;
}

BOOL WINAPI DllMain(
    HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) {
    switch(fdwReason) {
        case DLL_PROCESS_ATTACH:
        break;

        case DLL_PROCESS_DETACH:
        break;

        case DLL_THREAD_ATTACH:
        DisableThreadLibraryCalls(hinstDLL);
        CreateThread(NULL, 0, &Main, NULL, 0, NULL);
        break;

        case DLL_THREAD_DETACH:
        break;
    }

    return TRUE;
}

dll.h

#ifndef _DLL_H_
#define _DLL_H_

#if BUILDING_DLL
#define DLLIMPORT __declspec(dllexport)
#else
#define DLLIMPORT __declspec(dllimport)
#endif

DLLIMPORT void HelloWorld();

#endif

Upvotes: 2

Views: 201

Answers (1)

user1129665
user1129665

Reputation:

Execute the thread when the DLL is attached to the process not the thread:

...
        case DLL_PROCESS_ATTACH:
        DisableThreadLibraryCalls(hinstDLL);
        CreateThread(NULL, 0, Main, NULL, 0, NULL);
        break;

        case DLL_PROCESS_DETACH:
        break;

        case DLL_THREAD_ATTACH:
        break;

        case DLL_THREAD_DETACH:
        break;
...

and check the callback you pass to CreateThread, it should be Main not &Main, it's already pointer.

Upvotes: 2

Related Questions