Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why CreateProcess must not be called from a DllMain function?

I've read in several sources that CreateProcess must not be called from a DllMain function.

CreateProcess :

Do not call CreateProcess from a DllMain function. This causes the application to stop responding.

Dynamic-Link Library Best Practices:

You should never perform the following tasks from within DllMain: Call CreateProcess. Creating a process can load another DLL.

Question

Why is that? it states that it causes the application to stop responding but this is just a symptom. what is the real reason?

The reason I'm asking is that I tried creating a process from a DllMain function and it sees to work just fine.

like image 370
idanshmu Avatar asked Dec 14 '25 06:12

idanshmu


2 Answers

DllMain executes whilst the loader lock is held. As explained by the documentation you referenced, CreateProcess may result in a DLL being loaded. And that can lead to dead lock on the loader lock. The dead lock occurs because the loader lock is already held.

The documentation is clear. Don't call CreateProcess from DllMain. The standard way to get things done from DllMain is to create a thread to do the work. Although you must not wait on that thread because that leads to exactly the same dead lock.

like image 197
David Heffernan Avatar answered Dec 16 '25 22:12

David Heffernan


MSDN says:

Therefore, the entry-point function can call functions in Kernel32.dll that do not load other DLLs. [...] Unfortunately, there is not a comprehensive list of safe functions in Kernel32.dll.

Then it expands the statement explaining that more complicated APIs (CreateProcess included) might involve usafe API calling:

Calling functions that require DLLs other than Kernel32.dll may result in problems that are difficult to diagnose. For example, calling User, Shell, and COM functions can cause access violation errors, because some functions load other system components. Conversely, calling functions such as these during termination can cause access violation errors because the corresponding component may already have been unloaded or uninitialized.

This is what stands behind best practices advise to not call CreateProcess. It is out of your control whether CreateProcess will or will not load other DLLs. In your control is to avoid unsafe API call and create process later.

like image 42
Roman R. Avatar answered Dec 16 '25 23:12

Roman R.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!