how does __declspec(dllimport) actually work?

Viewed 116

I am trying to understand how dynamic linking works and I understand most of it but now how does the compiler or the linker know which dll exactly I am importing from?

For example I have test_program.dll that exports a function called test(); and I used __declspec(dllimport) in my program to import that function there could be thousands of functions in my system that have the same name and are also exported how does the compiler differentiate between them?

2 Answers

When you use test() in your code the resulting object file is marked as requiring the symbol for test.

You then supply the .lib file for your dll to the linker, the lib contains the symbol for test and contains the required code for loading your dll which includes the name of the dll.

You could supply a different .lib file which also contains the test symbol which would load a different dll.

The closest means you could get to testing that the library you loaded is the library you expect would require that you cryptographically sign both the executable and DLL.

You sign the executable to ensure that it has not been tampered with, you sign the library to be able to ensure that the library you find is the one you created.

If you need to go to this level of paranoia you likely won't be using __declspec(dllimport), instead you would locate the DLL, test its cryptographic signature then run-time load it (LoadLibrary/GetProcAddress).

I suppose you could do __declspec(dllimport) with delay-loading as long as you provide a custom delay-loader helper but you would then need some way of telling that helper which files need extra processing (simply checking signatures wouldn't be enough because an attacker could provide a DLL that was signed with some other certificate, you need to make sure that the library in question was signed with your certificate).

Related