I'm trying to impletement a C++ dll named (let's say) name.dll, which loads another dll (not mine) that is also named name.dll.
In my name.dll implementation I'm loading the real name.dll using this line :
driver_library = LoadLibrary(_T("c:\\windows\\system32\\name.dll"));
My dll is in a program.exe.local folder so that the program load mine before the real one in System32.
Depending on which program.exe uses my dll, LoadLibrary either works fine or returns my own name.dll handle as driver_library, with GetLastError() returning "file not found".
In https://msdn.microsoft.com/en-us/library/windows/desktop/ms684175(v=vs.85).aspx it is explicit stated that "If the string specifies a full path, the function searches only that path for the module." Why and how does it load itself for some applications ?
What in the program.exe application could affect LoadLibrary's behavior ?
#Franck Boyne commented :
"You have two programs - let's call them fine.exe and own.exe. The fine.exe program loads your own name.dll and then loads the other name.dll from System32. The own.exe program loads your own name.dll but when it calls LoadLibrary you get back another handle to your own name.dll instead of a handle to the one from System32."
About own.exe (which is not at all my "own" application) :
-> name.dll is located in an own.exe.local folder I created, which is located in own.exe directory.
-> own.exe had an application.manifest file that I deleted (the application still launches correctled without it if not using my dll). own.exe does not have an embedded manifest (checked using sigcheck).
-> name.dll is not one of Windows "known dlls" from HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\KnownDLLs
-> own.exe does not load name.dll using LoadLibrary() (checked by setting a breakpoint into LoadLibrary/A/W/Ex functions)
-> own.exe and name.dll are both 64 bits.
About fine.exe (it's a sample, I have access to the code):
-> name.dll is located in the fine.exe application directory.
-> No manifest file (either embedded or text).
Is it possible your problem program is using DLL Redirection?
From the LoadLibrary documentation (emphasis added) ...
If a path is specified and there is a redirection file for the application, the function searches for the module in the application's directory. If the module exists in the application's directory, LoadLibrary ignores the specified path and loads the module from the application's directory. If the module does not exist in the application's directory, LoadLibrary loads the module from the specified directory. For more information, see Dynamic Link Library Redirection.
Update 6/4/2018
Here's what I think is happening.
Both of your programs are using load-time dynamic linking (sometimes called implicit linking) to link to a DLL called name.dll. I'm assuming both programs just specify name.dll without a full path name. If you want to check I think you can run dumpbin /imports against fine.exe and own.exe to examine the DLL name.
fine.exe
In the case of the program that does what you expect (loads the second name.dll from \Windows\System32) there's no DLL redirection involved so the standard DLL Search Order is followed during the implicit link. The application directory is searched before the system directory so your copy of name.dll gets loaded.
Then your name.dll executes a LoadLibrary call specifying a full path to the file C:\Windows\System32\name.dll. Since there's no redirection going on, the system directory version of name.dll gets loaded as you expect.
own.exe
In the case of the program that doesn't do what you expect (gets a handle to your own version of name.dll twice) there is DLL redirection going on because you have a directory called own.exe.local in the application folder. Since there's redirection going on, during the implicit link the standard search order is ignored and name.dll is loaded from own.exe.local.
Then your name.dll executes a loadlibrary call specifying a full path to the file C:\Windows\System32\name.dll. But this time there is redirection going on. The full path specified in the LoadLibrary call is ignored and the module is loaded from the redirection folder own.exe.local.
Since that copy of name.dll has already been loaded by the implicit linking you just get another handle to the module.
As was pointed out in the comments, the GetLastError result is misleading. The LoadLibrary call didn't return NULL (it returned a handle to your own name.dll) so the value returned by GetLastError doesn't apply to the LoadLibrary call.
Related
as we all know when we start a CMD.exe it will appear a console window and start with lines like:
Microsoft Windows [版本 6.1.7601]
版权所有 (c) 2009 Microsoft Corporation。保留所有权利。
C:\Users\hey>
but when i crate a windows console project in VS and my code like this:
int _tmain(int argc, _TCHAR* argv[])
{
auto h = LoadLibrary(__TEXT("cmd.exe"));
Sleep(99999);
}
just turns out a black window.no lines out!
as i expect,i can load this PE(windows executable format) file in my process so i do not have to start a new cmd.exe and redirect its stdIO to the process which start cmd.exe.(i know Loadlibrary with an exe file could start a exe in calling process without creating a new process)
and why is Loadlibrary not working?(it did not appear any words in the console window)
(i know Loadlibrary with an exe file could start a exe in calling process without creating a new process)
No, it can't.
You can pass the name of an EXE file to LoadLibraryEx if you use the LOAD_LIBRARY_AS_DATAFILE flag, in order to access its resources, but LoadLibrary neither runs the code in an EXE nor prepares the code for being run.
The entry point for an EXE is designed for having its own process. (I'm talking about the real entry point, which is usually provided by a language support library. It may have a name such as wmainCRT and its address, not the address of user-provided main(), appears in the PE header). Typically it exits by calling ExitProcess(), which will have catastrophic effects on your host EXE even if you do manage to map it into your memory space and call it.
The requirements for the entry point of a dynamically loadable library and an executable file are very, very different.
You can't run an executable via LoadLibrary. Use CreateProcess (or one of its siblings) instead.
From the LoadLibrary function docs (highlight in bold is mine):
LoadLibrary can also be used to load other executable modules. For example, the function can specify an .exe file to get a handle that can be used in FindResource or LoadResource. However, do not use LoadLibrary to run an .exe file. Instead, use the CreateProcess function.
I'm trying to load a dll (through LoadLibraryA) from another dll.
This is the problem:
c:\**EXE_DIR**\myExe.exe // this exe load the MY_DLL_N1.dll
c:\**DLLS_DIR**\MY_DLL_N1.dll // this dll load the MY_DLL_N2.dll
c:\**DLLS_DIR**\MY_DLL_N2.dll
the exe load the MY_DLL_N1.dll ... fine.
MY_DLL_N1.dll try to load (below the code) the MY_DLL_N2.dll (same dir) ... and here is my problem!
int LoadMyDLL()
{
// ...
// same path of the MY_DLL_N1.dll ... right?
handle = LoadLibraryA ("MY_DLL_N2.dll");
// ...
}
that's all .... any help is welcome!
Everything you need to know is located here: Dynamic-Link Library Search Order.
Consider using SetDllDirectory to add your DLL path to the LoadLibrary search path.
handle = LoadLibraryA ("MY_DLL_N2.dll");
Because you do not supply a path, the DLL search order is used. This will look in the executable's directory, but will not search in the directories of any DLLS that are loaded. Hence the failure to find the DLL.
You have a number of options:
Put all the DLLS in the same directory as the executable.
Pass the full path to the DLL when calling LoadLibrary.
Call SetDllDirectory to add the DLL directory to the search path. Make this call from the executable before loading the first DLL. Once you do this you won't need to use the full path when loading the first DLL.
Unless you have a need to share the DLLS between different applications, option 1 is always preferred. This makes it easy for you to be sure that the DLLs you load are the right ones. That's because the executable directory is always searched first.
We are trying to load a dll-library from inside a 64-bit dll using LoadLibraryA function. It returns 126 error - mod not found. The dll file path given to the function is correct, we are sure.
We have tried a dummy dll to test and it worked, it is loaded.
We also tried adding the dll (which is a dependcy of the first dll that we want to load) to the dummy dll. It also worked. So the problem seems not about the dependency dlls, but the original dll that we want to load in the first place.
We also tried converting the dl to 64-bit, and tried that, still no good.
We also checked the dependencies with Dependency Walker. Everything is OK.
The operating system that we are using is Windows 8, 64bit. If it makes any difference..
Does anyone have any idea about this poblem?
EDIT:
We also tried this code:
hModule = LoadLibraryW(L"C:\\temp\\dllToLoad.dll");
and received this error code:
"First-chance exception at 0x00000000 in C_Test_TSMPPKCS11.exe: 0xC0000005: Access violation at location 0x0000000000000000."
EDIT 2:
The code that we used in the first place is:
hModule = LoadLibraryA((char*)aDLLFile);
EDIT 3:
We are using complete path to load the dll. In order to test this we tried this code:
FILE *fp;
int size = 0;
fp=fopen("C:\\temp\\dllToLoad.dll", "r");
size = fgetc(fp);
printf("size:%d\n",size);
fclose(fp);
There was no problem, we received the file size which is 77.
We also tried converting the dl to 64-bit, and tried that, still no good.
There's no way you can load a 32-bit dll as executable code into a 64-bit process (and since you're using LoadLibraryA() that's all you can be trying to do).
Assuming the dll that you are trying to load and the process that you're loading it into are the same type then are you passing a complete path to LoadLibraryA() or a relative path or just a dll name? If you're not using a complete path then consider using LoadLibraryEx() if possible as this gives you much more control over the search path used. If you are using a complete path try opening the file using normal file operations if you fail to load the dll, does this work? If that works then try LoadLibraryEX() with LOAD_LIBRARY_AS_DATAFILE and see if that will load the dll as a simple data file (which proves that it's finding the file).
Run up Sysinternal's ProcMon and watch the code open the DLL, that may show you dependent DLL load failures.
I have a process which calls CreateProcess. It appears that CreateProcess returns nonzero indicating success. However, the HANDLE to the process then gets immediately set, indicating the process has exited. When I call GetExitCodeProcess, STATUS_DLL_NOT_FOUND is then returned.
I understand that a DLL is missing. I even know exactly which one. However, what I don't understand is how to figure that out programmatically.
I noticed that Windows will present a dialog saying that the process failed to start because it couldn't find the specified DLL (screenshot: http://www.mediafire.com/view/?kd9ddq0e2dlvlb9 ). In the dialog, Windows specifies which DLL is missing. However, I find no way to get that information myself programmatically.
If a process fails to start and would return STATUS_DLL_NOT_FOUND, how do I programmatically retrieve the library name to which the target process was linked which couldn't be found? That way I can automatically record in an error report what DLL appears to be missing or corrupt in a given installation.
CreateProcess returns 0 indicating success.
CreateProcess() returns a BOOL, where 0 is FALSE, aka failure not success.
If a process fails to start and would return STATUS_DLL_NOT_FOUND, how do I programmatically retrieve the library name to which the target process was linked which couldn't be found?
Unfortunately, there is no API for that. Your only option would be to manually access and enumerate the executable's IMPORTS table to find out what DLLs it uses, and then recursively access and enumerate their IMPORTS tables, manually checking every DLL reference you find to see whether that DLL file exists on the OS's search path or not.
If the dll is statically linked you can walk the iat and see if the dll exists. If the dll is dynamically loaded then starting the process suspended and hooking LoadLibrary (or instead of hooking emulate a debugger) is the only way I see.
The best way is to use loader snaps. Basically you use gflags.exe (which is included with windbg) to enable loader snaps; then, run the process with the debugger attached. Loader snaps will enable the loader to print out dbg messages of the process and it will print the failures.
gflags.exe -i yourcode.exe +sls
windbg yourcode.exe
I know this is not a "programmatic" way to find out the problem, but what the loader does is complicated, and you don't really want to be redoing its logic to find the failure. That is why loader snaps were invented.
The very hard way would be: Parsing the .EXE and .DLL files and create the dependency tree of .DLL files.
I don't think there is a way to get a list of DLL files that are missing: When Windows finds one missing DLL file it stops loading so if one DLL file is missing you won't find out if more DLL files are missing.
Another problem you could have is that old DLL versions could have missing "exports" (functions). This is even harder to detect than the dependency tree.
Just since this is somehow the top stackoverflow result on Google for "STATUS_DLL_NOT_FOUND". How to trace and solve any random occurence:
Download SysInternals procmon64.exe (or just the entire set). After startup immediately hit the looking glass 'Stop capture' button (Ctrl+E). And 'Clear' (Ctrl+X).
Set filters for:
'Process name' is to whatever the mentioned process name was (for me it was 'build-script-build.exe') [Add]
'Result' is not 'SUCCESS' [Add]
'Path' ends with '.dll' [Add] [OK]
Start capture again (Ctrl+E).
Run the thing that had a problem again (for me: build cargo). Google for the last listed DLL file.
For me that was VCRUNTIME140.dll, so I installed the VC++ 2015 to 2019 redistributable.
ProcMon is kind of like unix strace.
I'm including python.h in my Visual C++ DLL file project which causes an implicit linking with python25.dll. However, I want to load a specific python25.dll (several can be present on the computer), so I created a very simple manifest file named test.manifest:
<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'>
<file name="python25.dll" />
</assembly>
And I'm merging it with the automatically embedded manifest file generated by Visual Studio thanks to:
Configuration Properties -> Manifest Tool -> Input and Output -> Additional Manifest Files
-->$(ProjectDir)\src\test.manifest
python25.dll is now loaded twice: the one requested by the manifest, and the one that Windows should find through its search order.
Screendump of Process Explorer http://dl.dropbox.com/u/3545118/python25_dll.png
Why is that happening and how can I just load the DLL file pointed by the manifest?
After exhaustive battle with WinSxS and DLL redirection, here's my advice for you:
Some background
Various things can cause a DLL file to be loaded under Windows:
Explicit linking (LoadLibrary) -- the loader uses the current activation context of the running EXE file. This is intuitive.
Implicit linking ("load time linkage", the "auto" ones) -- the loader uses the default activation context of the depending DLL file. If A.exe depends on B.dll depends on C.dll (all implicit linkage), the loader will use B.dll's activation context when loading C.dll. IIRC, it means if B's DllMain loads C.dll, it can be using B.dll's activation context -- most of the time it means the system-wide default activation context. So you get your Python DLL from %SystemRoot%.
COM (CoCreateInstance) -- this is the nasty one. Extremely subtle. It turns out the loader can look up the full path of a DLL file from the registry using COM (under HKCR\CLSID). LoadLibrary will not do any searching if the user gives it a full path, so the activation context can't affect the DLL file resolution. Those can be redirected with the comClass element and friends, see [reference][msdn_assembly_ref].
Even though you have the correct manifest, sometimes someone can still change the activation context at run time using the Activation Context API. If this is the case, there is usually not much you can do about it (see the ultimate solution below); this is just here for completeness. If you want to find out who is messing with the activation context, WinDbg bp kernel32!ActivateActCtx.
Now on to finding the culprit
The easiest way to find out what causes a DLL file to load is to use Process Monitor. You can watch for "Path containing python25.dll" or "Detail containing python25.dll" (for COM lookups). Double clicking an entry will actually show you a stack trace (you need to set the symbol search paths first, and also set Microsoft's PDB server). This should be enough for most of your needs.
Sometimes the stack trace obtained from above could be spawned from a new thread. For this purpose you need WinDbg. That can be another topic, but suffice to say you can sxe ld python25 and look at what other threads are doing (!findstack MyExeModuleName or ~*k) that causes a DLL file to load.
Real world solution
Instead of fiddling with this WinSxS thing, try hooking LoadLibraryW using Mhook or EasyHook. You can just totally replace that call with your custom logic. You can finish this before lunch and find the meaning of life again.
[msdn_assembly_ref]: Assembly Manifests
I made some progress for the understanding of the issue.
First let me clarify the scenario:
I'm building a DLL file that both embeds and extends Python, using the Python C API and Boost.Python.
Thus, I'm providing a python25.dll in the same folder as my DLL file, as well as a boost_python-vc90-mt-1_39.dll.
Then I have an EXE file which is a demo to show how to link to my DLL file: this EXE file doesn't have to be in the same folder as my DLL file, as long as the DLL file can be found in the PATH (I'm assuming that the end user may or may not put it in the same folder).
Then, when running the EXE file, the current directory is not the one containing python25.dll, and that's why the search order is used and some other python25.dll can be found before mine.
Now I figured out that the manifest technique was the good approach: I managed to redirect the loading to "my" python25.dll.
The problem is that this is the Boost DLL file boost_python-vc90-mt-1_39.dll that's responsible for the "double" loading!
If I don't load this one, then python25.dll is correctly redirected. Now I somehow have to figure out how to tell the Boost DLL file not to load another python25.dll...
Dependency Walker is usually the best tool for resolving this kind of problem. I'm not too sure how well it handles manifests though...
Where in this entangled mess is the actual process executable file?
Two possibilities come to mind:
You are writing a Python extension DLL file. So the Python process is loading your DLL file, and it would already have its own python25.dll dependency.
The EXE file loading your DLL file is being built with header files and libraries provided by the DLL file project. So it is inheriting the #pragma comment(lib,"python25.lib") from your header file and as a result is loading the DLL file itself.
My problem with the second scenario is, I'd expect the EXE file, and your DLL file, to be in the same folder in the case that the EXE file is implicitly loading your DLL file. In which case the EXE file, your DLL file and the python25.dll are all already in the same folder. Why then would the system32 version ever be loaded? The search order for implicitly loaded DLL files is always in the application EXE file's folder.
So the actual interesting question implicit in your query is: How is the system32 python26.dll being loaded at all?
Recently, I hit a very similar problem:
My application embedding Python loads the python32.dll from a known location, that is a side-by-side assembly (WinSxS) with Python.manifest
Attempt to import tkinter inside the embedded Python interpreter caused second loading of the very same python32.dll, but under a different non-default address.
The initialisation function of tkinter module (specifically, _tkinter.pyd) was failing because to invalid Python interpreter thread state (_PyThreadState_Current == NULL). Obviously, Py_Initialize() was never called for the second Python interpreter loaded from the duplicate python32.dll.
Why was the python32.dll loaded twice? As I explained in my post on python-capi, this was caused by the fact the application was loading python32.dll from WinSxS, but _tkinter.pyd did not recognise the assembly, so python32.dll was loaded using the regular DLL search path.
The Python.manifest + python32.dll assembly was recognised by the DLL loading machinery as a different module (under different activation context), than the python32.dll requested by _tkinter.pyd.
Removing the reference to Python.manifest from the application embedding Python and allowing the DLL search path to look for the DLLs solved the problem.