Static libraries - c++

When I want to call some Windows function, like MessageBox I can import it from user32.dll and call (with LoadLibrary and GetProcAddress). But there is also a static library that Visual C++ uses, so I don't need to manually load DLLs and functions. How do they work? Do they contain wrappers that call LoadLibrary/GetProcAddress every time I call a function?

The "static library" that you're referring to is actually an import library. This type of library contains records that tell the linker which library each function actually exists in, and doesn't contain any code itself. The linker creates import records in the executable, which the loader resolves at load time. This fixes up the addresses used at runtime so your code doesn't need to explicitly call LoadLibrary and GetProcAddress.

No, they just allow you to use static linking with DLLs. The executable file contain a list of functions that it needs from other DLL files, so when the executable file is loaded the loader parses this list and resolves each function with LoadLibrary and GetProcAddress, saving result to a static table (IAT, Imported Address Table). This is done only once. There is also the notion of "delayed load" of DLL, that will resolve the address only when the function is call for the first time, but it's rarely used.
In this way the lib file for a DLL contains just information needed to build that list (names of exported functions).

Related

clean way to explicitly load library

I am looking for a clean way to explicitly load library. Most often, I have a LIB and DLL pair so the LIB will handle all the "load stuff" and I can directly call the function in the dll. When doing this explicitly, I need to do sort of the following:
HMODULE libA = LoadLibrary("dllA.dll"); // NULL if load failed
HMODULE libB = LoadLibrary("dllB.dll"); // NULL if load failed
void (*functionA)(void) = libA ? GetProcAddress(libA,"functionA"):NULL;
void (*functionB)(void) = libB ? GetProcAddress(libB,"functionB"):NULL;
It will be messy if the LoadLibrary() and GetProcAddress() are found all over my code when I need to call function in DLL. I would like to know if there is a clean way such that I can write all the handling within 1-2 files and call the functions as if I am loading the library implicitly through LIB and DLL pair.
Indeed there is a way to get all the implicit linking convenience, while still being able to gracefully handle both library load as well as symbol lookup failures. Visual Studio offers Linker Support for Delay-Loaded DLLs, that give user code the ability to hook into the loader, and implement arbitrary recovery strategies for unavailable symbols (e.g. by returning a no-op stub). This makes it possible to consolidate all failure handling into a single place.
Write a pure interface to the external functions you need. (Platform dependent)
Provide an implementation class (for you platform). For your Windows implementation load the DLL, get the procedure address initially.
Than when the interface function need to be called, the class routes the call into the loaded DLL.
Use an similar way for other platforms.
This is nothing else than using of delay-loaded DLLs. It is just a manual solution. But the approach of using an interface allows you a real platform dependent solution.

How to build with required `.dll` in Windows 10 Visual Studio

I'm trying to build a project. I have a.lib file that I need to use in my project. I know that there are two ways to use this lib:
add it using #pragma comment(lib, "a.lib")
add it to linker dependencies Configuration Properties -> Linker -> Input -> Additional Dependencies
Now, a.lib uses StackWalk64 function DbgHelp. This library is supplied as DbgHelp.lib and DbgHelp.dll. I know that I can use it as a lib using two ways listed above. But what if I don't want to include it into my project and want to use DbgHelp.dll, how can I do that in Visual Studio?
If you want to call a function that is within a DLL, but don't want to link to the LIB file that imports these functions for you, then you can use LoadLibrary and GetProcAddress. (Though if you have the import library and can link to it, why do you want to load these functions manually?)
IF YOU HAVE THE DbgHelp.lib IMPORT LIBRARY, USE IT! LOADING FUNCTIONS MAUNALLY IS ERROR-PRONE IF NOT DONE RESPONSIBLY. USE WITH CAUTION!
// Type definition for a function pointer that can call the function
typedef BOOL (WINAPI *StackWalk64_func)
(
DWORD,
HANDLE,
HANDLE,
LPSTACKFRAME64,
PVOID,
PREAD_PROCESS_MEMORY_ROUTINE64,
PFUNCTION_TABLE_ACCESS_ROUTINE64,
PGET_MODULE_BASE_ROUTINE64,
PTRANSLATE_ADDRESS_ROUTINE64
);
// Within a function . . .
HMODULE hDbgHelpDll = LoadLibrary(TEXT("DbgHelp.dll"));
if (hDbgHelpDll == NULL)
{
// handle error and return
}
StackWalk64_func funStackWalk64
= (StackWalk64_func)GetProcAddress(hDbgHelpDll, "StackWalk64");
if (funStackWalk64 == NULL)
{
// handle error and return
}
// funStackWalk64 is valid and ready to use
Now you can call funStackWalk64 like the function StackWalk64, and pass the function pointer around the place. When you're done using the library, you should free the module handle:
FreeLibrary(hDbgHelpDll);
Please read up: http://www.learncpp.com/cpp-tutorial/a1-static-and-dynamic-libraries/
Implicit Linkage with an import library (using .lib)
In this case the static-library is an "import library", which automates the process of determining the effective functions in the DLL. This is called implicit dynamic linkage.
Explicit Linkage
If you don't want to use the import library you have to determine all functions by yourself, create corresponding pointers to the addresses of the procedures and use them after that.
Usually there's some InitDLL() function in your client code, which does this.
See: https://msdn.microsoft.com/de-de/library/64tkc9y5.aspx
The "GetProcAddress"-function can be used to obtain a handle to the function and call it.
This is called explicit dynamic linkage and requires also the calls to LoadLibrary() and FreeLibrary() on Windows.
More Info: http://www.equestionanswers.com/dll/what-is-implicit-and-explicit-linking-in-dynamic-loading.php
Explicit Linkage on Linux
For linux/unix things work differently. If you want to read up: http://www.yolinux.com/TUTORIALS/LibraryArchives-StaticAndDynamic.html
Usually (and in Visual C++ specifically,) the lib file that comes with a dll is what is called an "import library". It means that the library has no actual function bodies in it; it is just there to appease the linker and instruct it to generate an EXE (or DLL) that would use the first dll at load time.
It is so in this case too. Since you don't have access to the source code for DbgHelp so that you can build it as a real static library, you need to make do with the small import library at link time and the dll file at load/run time.
Note: the whole linking and dynamic linking concepts and mechanisms are obviously a lot more complex than what I have room here to discuss. So, the explanation above is quite narrow and specific to your question.

Create a dll that changes a few functions of another dll

I want to create a dll, that will reference any function that is not defined in the dll to another dll.
How do i get the dll to change the behavior of a few functions of another dll, but keep the other functions the same.
What is the syntax to my dll "for every function that is not a, b, c import the function from shell32.dll. for function a b c do ......"
I want to do so without reverse engineering the dll. and without copying the entire set of function in shell32.dll
DLLs can contain forwarders, but this is a limitative list. Anything not listed is not forwarded. Wouldn't matter much, anyway: your import lib declares the same list of functions, so RandomWindows9Function(HWND) will not be in your import lib. The linker therefore will not put in a dependency to your DLL for it. The function will simply be found in the Windows 9 SDK, and the linker will add a dependency to Kernel32.dll.

When building a dll, can the lib be used for linking?

I wanted to create a C++ dll (to be used in a dot net application). Some functionality I needed was already implemented in another C++ dll.
The dll I was referencing was set up like this (including the comment):
extern "C"
{
__declspec(dllexport) BOOL SomeFunctionToBeUsedExternally();
}
// internal functions
BOOL OtherFunctions();
I need to use one of the OtherFunctions in my code.
So, I added the proper include in my own code, added dependencies on the lib created by the dll above, and used the method I needed. As a result, of course, I got another __declspec(dllexport)... function.
It refused to link though, I got an error about the OtherFunction.
I verified everything, looked online - nothing seems to solve my problem.
Then, I added a __declspec(dllexport) in front of the function I needed, and it works.
I don't understand though. I thought, the dllexport marked functions will be exported to the dll, but aren't all functions sent to the lib ?
Why do I have to export functions to the dll, if I am not linking against the dll but against the lib ?
No, the linker does not automatically export all identifiers. The dllexport attribute tells the linker which identifiers are exported. Without this you would be forced to either export every identifier in the DLL or specify which identifiers should not be exported. When the linker creates the DLL it also creates an import library and includes information about which identifiers are exported based on that attribute.
When you want to use a DLL you need link with the appropriate .lib file for good reason. The .lib file tells the linker which identifiers are exported, the name of the DLL they are in and other information. It is also possible to export identifiers from the DLL by ordinal instead of by name. In this case the linker still needs to match the identifier with the appropriate ordinal. This is only possible by having an accompanying library file that contains that information since it is not present in DLL's export table.
No, only exported functions end up in the .lib. As you can tell.
It is not a static link library, it the import library for the DLL. It is a very simple and very small file since it contains no code at all. Just a list of the exported functions. The linker needs it to resolve the external in the client code, it needs to know the name of the DLL and the actual exported function name or ordinal (could be different) so it can add the entry to client's import table. Import libraries having the same filename extension as static libraries was perhaps a bit unfortunate.

utilizing a static library to create an import library

I am interested in using my static lib to create a dll (implicitly linking). which means I need to (in vs2008)
create a dll project that should generate the following:
header file (which have export function declarations. These are simple wrappers to actual functions in the static lib using __declspec(dllexport) which are in the .cpp )
import lib which will be made as a result of creating the dll
the actual dll which is created.
I have made a test program that will utilize the above dll(including the import lib/header files) to test it.
in this I have included all the three items. now the exe compiles/links without issue.
however in the main.cpp when i call the exported functions (with the associated __declspec(dllimport) call it never seems to execute. I am uncertain why this is?
Its almost like the even though the exe can see the exported function in in the dll...the dll cannot call on the code that is in the static lib?
i just cannot answer why my exe can't see the code in the static lib? do i need an archiver/librarian for vs2008 to include all those obj files as part of the import lib?
I am at a loss and am not sure how to test this?
other than just making my static lib directly into a dll. I wanted to try this method. I know i am missing something...i have read all over the place and i am just stuck. There were some threads here that had some people posting something similar but i can't seem to get it. please be as detailed as possible as I am new to this. thanks again.
update 1:
ok so currently i added the extern line to the function prototype and now it sees the exported function from the dll. however, now the only issue left is that:
i can't invoke the function that this exported function (aka wrapper) is trying to call. which happens to be in the static library. how should my exe get visibility to that static library function. I know it can be done because I think there was one other person on this board who was able to make this work.
update 2: my setup is exactly like this questioner...
How to force inclusion of an object file in a static library when linking into executable?
but i am not using explicit linking. i am using implicit linking. my real issue is how to call a static lib function in my dll wrapper which is exported to the exe?
If the app and DLLs are MFC app/dlls, then make sure that the application and all dlls are either "Debug" versions or "release" versions and not a mix.