4

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
  • Although there are various safeguards I think the short answer is that it doesn't. It's up to you to provide the correct DLL. In fact some hacks work by using a technique called DLL Injection which substitutes the correct DLL with a different one under the control of the hackers. Commented Jul 30, 2020 at 5:24
  • @john so how would you specify it exactly i see everyone using just __declspec(dllimport) and that's it . it works but i don't understand how? Commented Jul 30, 2020 at 5:45

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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).

1 Comment

I think you might be able to do this automatically using dll manifests and #pragma comment(linker... to set a dependency on that manifest

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.