Difference between WinMain,main and DllMain in C++ - c++

What is the difference between the three functions and when to use them??

main() means your program is a console application.
WinMain() means the program is a GUI application -- that is, it displays windows and dialog boxes instead of showing console.
DllMain() means the program is a DLL. A DLL cannot be run directly but is used by the above two kinds of applications.
Therefore:
Use WinMain when you are writing a program that is going to display windows etc.
Use DLLMain when you write a DLL.
Use main in all other cases.

WinMain is used for an application (ending .exe) to indicate the process is starting. It will provide command line arguments for the process and serves as the user code entry point for a process. WinMain (or a different version of main) is also a required function. The OS needs a function to call in order to start a process running.
DllMain is used for a DLL to signify a lot of different scenarios. Most notably, it will be called when
The DLL is loaded into the process: DLL_PROCESS_ATTACH
The DLL is unloaded from the process: DLL_PROCESS_DETACH
A thread is started in the process: DLL_THREAD_ATTACH
A thread is ended in the process: DLL_THREAD_DETACH
DllMain is an optional construct and has a lot of implicit contracts associated with it. For instance, you should not be calling code that will force another DLL to load. In general it's fairly difficult function to get right and should be avoided unless you have a very specific need for it.

[Addendum to your question]
Also don't forget the DllEntryPoint:
When loading time is involved the entry point is DllMain.
(Ex. COM in-process server DLL).
When running time is involved the entry point is DllEntryPoint.
(Ex. LoadLibrary get called).

Related

C++ Injecting a dll, do you need threads?

I'm a little new to it and I don't understand the threading term completely yet, Allthough I know how to make a thread and run programs with multiple threads. What I'm wondering about is that when you create a dll file (c++) and inject it into a process (lets say gamehacking) for instance. Would you need to create threads in the dll file, or is that not going to work? After my understanding the main thread will be running from the host process right? Or how does it work?
Well it depends on what you are planning to achieve using the DLL. If that particular DLL has some static functions / utility class, that just takes an input, doing some calculations / processing and produce an output, then there is no need of threading here.
But if that DLL is going to listen on a socket or write to a file or do the actual work that going to need some parallelism, then you might want to create threads inside that DLL.
Basically you must need to understand, what is that task, that is accomplished by this DLL. A DLL can be linked during compile time as a normal library or it can be loaded dynamically in run-time based on your need / use-case.
To answer your question,
Would you need to create threads in the dll file, or is that not going to work?
Ans : Not always. You need to create thread to accomplish some task. That being said, this is not the case always. It is perfectly feasible to run a DLL inside a process, without having any threads.
After my understanding the main thread will be running from the host process right? Or how does it work?
Ans : That's right. Any process you run, there will be one thread by default. If your application is simple enough to be processed by a single thread, then it is a blessing. Keep up with it :)
Since you are specifically refering to injecting the DLL, I have some input for you additionally to what has already been said.
First, let's make sure that the concepts of threads, processes and modules are clear.
A thread is basically the immediate environment in which code runs. Things like the current state of processor registers and stack variables (e.g. your local variables in functions, in most cases, but also where in the code the execution currently stands) belong to a thread. There are also other resources which often have thread-affinity, such as windows. It depends a lot on the resource in question whether and what kind of thread affinity they have.
Let's assume you write a simple hello world program. It will run in one thread which goes through your program from the beginning to the end and print "Hello World". Now let's assume you would want to write a program which slowly writes "Hello World", one character per second, but in the meantime download a file. Then you could create a second thread and have one thread output "Hello World" slowly, and one thread download the file. This means execution can happen in parallel, with different local state - one thread is currently inside your printHelloWorld function and one thread is inside downloadFile.
A process is basically a container for one or more threads. It bundles them together in a shared environment which uses the same virtual memory (this means that for example global variables in your code would be accessible from all threads, but this would require careful synchronization to avoid race conditions) and shares resources such as file handles the threads in the process create. So, your hello-world-and-download program from before would have 2 threads in 1 process, sharing the console for example, and being seen in the task manager as one entity.
A module is a file which contains executable code (in most cases, that is) and is loaded into a process. Usually, in a process there are one EXE file and several DLL files loaded as modules. DLL files and EXE files are technically almost the same, but EXE files are meant to be the basis from which a processes starts, and DLL files are meant to be libraries exporting certain functions which can be used by other modules. Since I said modules are loaded into processes, it means that a module is accessible by all threads in the process, and it doesn't have thread-affinity by its own - in our previous example, when the second thread downloads the file, it may be calling into a HTTP-networking DLL, whose code would then run in the second thread. There is a number of modules which is loaded automatically into each process by Windows, and others are probably loaded by certain features of your compiler.
OK, so, back to your question:
Would you need to create threads in the dll file[...]?
Per se, using a DLL has nothing to do with whether you need to create new threads or not. It depends on what you want to do - if you need to do some time-consuming task in parallel to whatever other code is running, then you would need to create a new thread for it, otherwise there is no need.
[...]or is that not going to work?
As said, you can create new threads if you want (it will work), but it's not a necessity coming with using a DLL.
After my understanding the main thread will be running from the host process right?
The main thread of the host process will of course be in the host process. (Although there is technically no "main thread", since it's perfectly valid to have the first thread in a process create a second one and then terminate, so only the second one would be running anymore, you usually do have the first thread live through the whole lifetime of the process, and you can probably call it the "main thread" in this case.) In which module the currently-running code is located, though, will depend on what the thread is currently doing.
Let me get back to the matter of "injecting": The previous answers appear to have assumed a more "normal" environment where your DLL is just linked to the program and meant to be loaded by it. In this case, your DLL's initialization routine (which is automatically run when a module is loaded into a process) would just be run in the "main thread", probably before the actual work of the process begins.
However, things are a bit different when you inject a DLL. It depends on how you do the injection:
If you inject the DLL by modifying the imports table of the host EXE, then your DLL will be loaded the "normal" way I just said. So you can expect your initialization routine to run during the process' startup, in the main thread.
If you inject the DLL by using the AppInit_DLLs registry key, it would be the same.
Same thing if you inject the DLL by starting the host process suspended, then writing a stub to load the DLL into the processes' memory and using SetThreadContext to point the instruction pointer to it.
If you inject the DLL through means of remotely calling LoadLibrary inside the target process, using CreateRemoteThread, then however, as the name suggests, you are creating a new thread inside the process. In this thread, LoadLibrary will load your DLL and also call your initialization routine, so in this case, your initialization routine would indeed run in a new thread other than the "main thread".
Every process has at least one thread. When that process starts, it's possible to link a bunch of functions, or a library, to the memory space of that process. That's what a dll is. The advantage compared to linking directly to the binary is the library only has to exist in one place in the file system and one place in memory while being used by multiple processes. It's a linking technique, similar to how .so files are used in Linux. It has nothing to do with threading.
Would you need to create threads in the dll file, or is that not going to work?
There wouldn't be any point loading a DLL that didn't contain code that would be run. That said, there are several ways the DLL code might get run:
when the DLL is loaded it gets a chance to run some initialisation code
during initialisation, it might:
start one or more threads, which can keep running - perhaps watching for some event that triggers some action on their part
register for callbacks from the OS or application, such as setting up signal handlers, keystroke handlers, any type of event handler....
it might contain functions that the program will look for dynamically and run, mistaking your DLL code for the original versions of those functions that the program came with
Which of these suits your needs depends entirely on what your DLL is trying to achieve, and what's technically necessary to achieve it. For example, if watching for some memory to have specific content, then modifying it further, it might suffice to have a function in your DLL called by an OS alarm service, resetting itself to go off again later if the triggering memory content is not found. But, the trigger might be existence of a file, or shared memory service, a socket being created etc..
After my understanding the main thread will be running from the host process right? Or how does it work?
Yes - threads started within a process - including any DLL initialisation routines - are also within the process. There are some library functions that may create other processes - such as fork, popen, system - that may contain their own threads.

LoadLibrary and SetWindowsHookEx inquiry

I wanted to make sure i fully understand those API functions. If I have an application and a dll where i created a thread. I load this dll inside the application with LoadLibrary function. Does it mean that this dll thread is now a thread of that application?
P.S The thread in the dll created via exported function if that matters.
Thanks.
Understand that threads are an element of an executing process - there's no real notion of a DLL "owning" a thread. The code that starts the thread may well have originated from a function call in code contained in a DLL, but the process that loaded the library is the one that owns the thread. Loading the library merely makes the code in that library available to the calling process dynamically (at runtime).

Injecting a hook DLL into a process before its imports get called?

I have a target process which loads a DLL before its main code gets called. It accomplishes this through a DLL whose name was added to the file's ImportsTable (using StudPE). My goal is to create a hook DLL that will be injected into this process and intercept its calls before it loads its imports. So the target process will load my hook dll before its security DLL. I tried using the conventional method but I hadn't success because the security DLL always gets called before my hook DLL's DllMain is called. Can anybody tell me a method to solve this issue?
You can create the target process suspended and use CreateRemoteThread() for injection, but mind the following limitations:
You should copy the thread main routine for the remote thread to the address space of the target process.
This code cannot contain any external references (e.g. CRTL or direct WinApi calls). I would usually limit this code to loading of the DLL and either executing function from it, or relying on the DllMain to do the job you need. In order to call LoadLibrary and GetProcAddress methods, I obtain their addresses and copy structure containing this information to the target process and pass the address of the remote structure as an argument for the thread main routine in CreateRemoteThread(). You can use VirtualAllocEx() to allocate memory in the remote process.
Remote thread in this situation will be executed before main thread, including process and some Win32/64 initialization. Therefore, not every Win32 API is safe to call in this condition.
If the target process is spawned by someone else, you have to intercept its creation before it is initialized. There are some ways to do that, all of them are undocumented and therefore not future proof.
The DLL are loaded sequentially in the same order as the imports entries in the PE header. Most PE editors will let you reorder the imports. You should also note that if another DLL X has dependencies on the security DLL, then it will be loaded at the same time as DLL X. Also, if security DLL is using static loading, hooking by modifying the import tables at runtime should still be effective even if your DLL is loaded later, though you will miss the calls done in the meantime (but there shouldn't be any).

Detecting whether the CRT initialization was done in an injected process

I'm working on an application that injects a dll when a process starts (Suspend --> Inject --> Resume)
The very first call in DllMain with DLL_PROCESS_ATTACH (in the dll I injected) is a call to MessageBox() (just for debugging purpose).
However, this call to MessageBox() sometimes pops an error and crashes the injected process.
Runtime Error!Program: C:\Program Files\Microsoft
Office\Office14\OUTLOOK.EXER6030- CRT not initialized
This is reproducible with Outlook and Winword for example. Though Notepad, IE, CMD, Calc and many others - print the message box and continue normally.
Printing a message box is not a must-have for me, so I just want to be able to check whether CRT has done initialization or not, so I can continue normally like this:
case DLL_PROCESS_ATTACH:
if (IsCRTInitialized())
MessageBox(...);
Please let me know if some information is missing.
Thanks!
Kernel32.dll is guaranteed to be loaded in the process address space when the entry-point function DLLMain is called. MessageBox resides in user32.dll and as per Best practices for creating DLL calling functions from user32.dll is a strict no-no.
You can either
Call OutputDebugString for any debugger tracing. This function resides in kernel32.dll and should be safe to call.
Before your application loads any other dlls, call MessageBox yourself. This will ensure that user32.dll and its dependencies are
already loaded. This way calling MessageBox in DllMain may have
a better chance of succeeding. But your mileage may vary.
The problem isn't the CRT. You're not allowed to call MessageBox or any other non-trivial function from DllMain

is it possible to inject multiple Dlls with MS detours?

In c++ ,I want to hook more than one dll to a process. Right now I use CreateProcesswithdll() which can hook only one api at a time. What can I do to inject multiple dlls?
I came across this problem because MS detours requires us to name our custom dll the same as original dll in order to properly detour the api calls. So even though i could have different api calls handled in the same detour dll I created I need to have different names to hook calls from different apis, which means I need different detour Dlls. This also means I need to inject different DLLs. Am I right?
If I am unclear about something I will try to present it more clearly :D
Thanks!
P.S: Just to make my problem more lucid. I need to inject more than 1 dll onto the same process. CreateProcesswithdll() creates a new process with its thread in sleep state. It is woken up after the detours has finished injecting the dll and setting up the hooks. If I want to inject more than one dll I obviously cant repeatedly call CreateProcesswithdll()
so what do i do?? or Is my understanding about some aspect of this wrong?
Calling LoadLibrary() and FreeLibrary() is NOT SAFE from DLLMain(). From TFA:
"The entry-point function should
perform only simple initialization or
termination tasks. It must not call
the LoadLibrary or LoadLibraryEx
function (or a function that calls
these functions), because this may
create dependency loops in the DLL
load order. This can result in a DLL
being used before the system has
executed its initialization code.
Similarly, the entry-point function
must not call the FreeLibrary function
(or a function that calls FreeLibrary)
during process termination, because
this can result in a DLL being used
after the system has executed its
termination code."
EDIT: Apologies - this was meant as a comment for Serge's answer above.
Seems like detourattach and detourdetach will do the trick for me. Thanks everyone!
I found this blog useful!
Obviously you can load any number of DLLs from the first DLL you inject with detours.
EDIT.
When DLL is loaded system runs DllMain of your DLL (with fdwReason==DLL_PROCESS_ATTACH) and then within that function you can do whatever you like, e.g. you can call LoadLibrary to load other DLLs.
ADD:
I totally agree with comments that calling LoadLibrary from DllMain is unsafe. So you can call LoadLibrary (and all the other tricky things) from thread created in DllMain.