Dissecting Shared Libraries
By Peter Seebach2005-03-22
How shared libraries work
The concept is easy enough to understand. You have a library; you share the library. But what actually happens when your program tries to call printf() -- the real way this works -- is a bit more complex.
It is a simpler process in a static linking system than in a dynamically linked system. In a static linked system, the generated code possesses a reference to a function. The linker replaces that reference with the actual address at which it had loaded the function, so that the resulting binary code has the right address in place. Then, when the code is run, it simply jumps to the relevant address. This is a simple task to administer because it lets you to link in only those objects that are actually referred to at some point in the program.
But most shared libraries are dynamically linked. That has several further implications. One is that you can't predict in advance at which address a function will really be when it's called! (There have also been statically linked shared library schemes, such as the one in BSD/OS, but they are beyond the scope of this article.)
The dynamic linker can do a fair amount of work for each function linked, so most linkers are lazy. They only actually finish that work when the function is called. With more than a thousand externally visible symbols in the C library and nearly three thousand more local ones, this idea could save a noticeable amount of time.
The magic trick here that makes it work is a chunk of data called a Procedure Linkage Table (PLT), a table in the program that lists every function that a program calls. When the program is started, the PLT contains code for each function to query the runtime linker for the address at which it has loaded a function. It then fills in that entry in the table and jumps there. As each function is called, its entry in the PLT is simplified into a direct jump to the loaded function.
However, it's important to notice that this still leaves an extra layer of indirection -- each function call is resolved through a jump into a table.
Tutorial Pages:
» Get to know your shared library
» How shared libraries work
» Compatibility's not just for relationships
» To debug, first you must know how to compile
» Modifying the dynamic linker search path
» Linking Mozilla
» Learning more about shared libraries
» Resources
First published by IBM DeveloperWorks
| Related Tutorials: » How to Install PHP 5 on Linux » How to Install Apache 2 on Linux » How to Install MySQL 5.0 on Linux » SMB Caching » Mound --Bind » Tar Wild Card Interpretation |
