Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LoadLibrary() an EXE?

I have an executable (that I created using Visual C++ 10), and I need to use its capabilities from another program I wrote (same environment). Due to complex deployment requirements which I won't go into, building a DLL from the required functionality and loading it in both programs is not something I can do.

So I thought that I can __declspec(dllexport) some functions in the EXE, and then LoadLibrary() will let me GetProcAddress() them.

Obviously this can't be done, though when I started looking at it - it looked feasible.

Specifically, when you __declspec(dllexport) functions in an EXE project, Visual C++ also generates a lib file for dynamic linking - so you don't even need to use LoadLibrary() - just link against the resulting lib and call the functions.

Unfortunately, the main problem is that when you declare the resulting file as an EXE, Visual C++ adds the "CRTmain" entry point into the resulting file, instead of the "CRTDLLmain" that a DLL gets. When Windows (automatically) LoadLibrary() the EXE from your main program, it doesn't call the the "CRTDLLmain" entry point (because it doesn't exist), the C runtime for the module doesn't get initialized, and as a result all interesting work (such as memory allocation) fails with interesting(*) runtime exceptions.

So as follows, my question is: is there a way to cause Visual C++ to build into the resulting file both the "CRTmain" entry point and the "CRTDLLmain" entry point?

(*) "Interesting" as in an old Chinese curse.

like image 991
Guss Avatar asked Oct 01 '13 07:10

Guss


1 Answers

Yes it is possible.

http://www.codeproject.com/Articles/1045674/Load-EXE-as-DLL-Mission-Possible

The idea is a) to patch the IAT and b) to call the CRT before calling your exports.

like image 81
Michael Chourdakis Avatar answered Oct 11 '22 14:10

Michael Chourdakis