views:

107

answers:

2

I have a simple small question which someone who knows will be able to answer easily, I searched google but couldn't find the answer.

There are many programs running at once on a computer, and my question is: when a program loads a DLL, does it actually load the DLL file or does it find the memory in which the DLL is already loaded? For example, is ws2_32.dll (winsock 2) loaded for every program that uses winsock, or is it loaded once and all programs that use it use the same memory addresses to call the functions?

+6  A: 

It's loaded once and all programs share the same in-memory copy of code. It's kind of complicated, but for the read-only sections of the DLL (that is, code) the operating system loader uses a technique called "memory mapping" to map the DLL into the process's address space. The pages are only loaded into physical memory once for all processes, even though they may have the page mapped to different address in their virtual address space.

However, each process has a separate data section (so that global variables are not shared - unless you explicitly ask them to be) and they obviously also have a separate heap so that dynamically-allocated memory is not shared.

Dean Harding
Ok thank you, this makes sense. I just needed to know if a pointer to a function from a DLL would point to the same address that is used by all the programs that used the function.
Nilbert
The answer to that question is "no". Function pointers are addresses in the processes *virtual address space*, and that is definitely not shared between processes. A DLL can be loaded at different addresses in different processes, and therefore the address of a function pointer will be different - even though the same physical page is used.
Dean Harding
In fact, it would be highly unlikely for the function to have the same address in two different programs. The DLL's code will be mapped into the next available address space after all the code segment contributions preceding it. In Secure Linux, load address randomizing is used (to prevent viri from using hardcoded addresses in attacks). You're not writing a virus, are you? :-)
wallyk
So is it possible to get the actual memory address of the function in the dll?Edit: No wallyk I'm not writing a virus, I'm just trying to expand my limited knowledge of how windows works.
Nilbert
Nilbert: not it's possible. In fact, the physical address will change *as your program is running* and the operating system pages the code in and out of physical memory.
Dean Harding
+4  A: 

It depends on what you mean by "loaded". The DLL is prepared for code and data shared use, and most Windows environments will honor that (by mapping the same memory copy of the code into each process's memory space) to conserve memory. However, part of the "load" is running the DLL's initialization: that is done separately in each process with distinct data copies of the data which are kept private to each process.

wallyk