Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent Windows from using the PATH env variable when resolving dll dependencies?

Tags:

c++

windows

dll

When loading a DLL (either dynamically with LoadLibrary/Ex or statically) is it somehow possible to prevent Windows from using the PATH environment variable to look up the DLL/other DLLs the DLL to be loaded depends upon?

The docs I could find for the Dynamic-Link Library Search Order seem to imply there is no way to prevent PATH from being searched, but maybe I'm missing something?

The reason I am asking this is that we would like to have a fail-fast scenario, when a (statically) linked DLL is missing from the application folder but is possibly present (different version) on the PATH.

like image 275
Martin Ba Avatar asked May 20 '26 01:05

Martin Ba


2 Answers

For dynamically loaded dlls: the easiest way to control which one is loaded is to not invoke the search logic. The search logic is only invoked if a partial path is supplied - provide a fully qualified path to the dll when calling LoadLibrary and the call will fail if the Dll doesn't exist in that location.

For statically loaded dlls: Dlls that are part of an assembly are searched for ONLY in WinSxS and the application's folder. So, create a "dummy" assembly to hold the dll. Which is as simple as creating a .manifest file with contents like this:

<!-- dummyassembly.manifest -->

<assembly manifestVersion="1.0">
    <assemblyIdentity type="Win32" name="dummyassembly" version="1.0.0.0" processorArchitecture="x86"/>
    <file name="thedll.dll"/>
</assembly>

Add this code to any project that needs to use the exact dll only:

#pragma comment(linker, "/manifestdependency:\"dummyassembly'"\
                       " processorArchitecture='*' version='1.0.0.0' type='win32'\"")

and it will fail to load if the dll doesn't exist in the same folder.

like image 105
Chris Becke Avatar answered May 21 '26 23:05

Chris Becke


You could change the PATH environment variable from code before loading your dlls. And then possibly restore it afterwords.

like image 36
jonaskje Avatar answered May 21 '26 23:05

jonaskje