user2073973
user2073973

Reputation: 584

How does code know the addresses of API functions?

Once again, sorry for the bad title.

So I've been researching the PE format the last week, and I didn't quite get something. When a process loads, all the DLL's get mapped into memory. What I don't understand is, because a DLL can get loaded at a random base address, how is the code of the .exe file able to know the addresses of the API functions? Is there some "startup code" that looks for Kernel32.dll or something? I understand that is easy for the process to find functions with GetProcAddress, but how does it obtain the address of GetProcAddress?

Upvotes: 2

Views: 466

Answers (1)

Martin Rosenau
Martin Rosenau

Reputation: 18493

All Windows .EXE files (and all .DLL files depending on other .DLL files) have a so-called imports table.

This table contains a list of DLLs and functions required and arrays of function addresses.

When the .EXE file is loaded into memory Windows will internally call LoadLibrary for all DLLs and GetProcAddress for all API functions required by that .EXE file. It will fill the arrays in the imports table with the values returned by GetProcAddress.

If GetProcAddress returns NULL that value is not written to the array but loading the .EXE file will fail!

Upvotes: 4

Related Questions