elishacloud / dxwrapper

Fixes compatibility issues with older games running on Windows 10/11 by wrapping DirectX dlls. Also allows loading custom libraries with the file extension .asi into game processes.
zlib License
1.16k stars 83 forks source link

LoadLibrary in DLLMain is expressly forbidden #56

Open bo3b opened 4 years ago

bo3b commented 4 years ago

Just noting a fairly serious problem with your code structure.

In Dllmain.cpp, during Attach, you call LoadLibrary. This is expressly forbidden by Microsoft:

https://docs.microsoft.com/en-us/windows/win32/dlls/dllmain

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.

This can cause the wrapper to crash or hang. I see that you try to work around the problem by increasing the thread priority, but this is not a good idea. You'll still have scenarios where it will crash or hang.

Best strategy is to do a minimalist DLLMain code, not even logging there, to avoid the limited runtime. Since you are using Detours, you can make a later init at first code instruction. Or you can do what we do in 3Dmigoto, which is to only init upon first active API call. (late-binding)

elishacloud commented 3 years ago

Agreed. So far I have not run into any issues doing this. Fixing this would not be very easy, but I have a few ideas how to fix this. Probably won't happen very soon.