Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

c - How are shared libraries addressed in each processes memory?

From what I understand:

When you compile code into a binary there is no need to translate the addresses in that binary. Since each process has it's own memory space, the addresses used in the binary file can be used at runtime.

However if you have a shared library, how does that get mapped into that processes memory space? If the library code uses virtual memory addresses they'd have to be changed for each process where the library is mapped to a different virtual memory address.

I'm not very experienced in this stuff (as you can probably guess), so sorry if anything is incredibly wrong.

Thanks in advance.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In Linux, references to shared libraries are resolved by default when the library is effectively called in your code. This is called lazy biding. Thus all binaries are not executable by the processor. Most of them are in fact interpreted (see /lib64/ld-linux-*.so).

To perform that, the ELF binary contains two specific tables :

  • the Procedure linkage table (PLT)
  • the Global offset table (GOT)

The code you're executing references the PLT which performs the redirections. On the first call the GOT will contain a callback address which if executed jumps to the loader which will resolve the address to the dynamic library. The library is mapped in the virtual memory of your program, even though it is only present once in your physical memory.

You're using virtual memory so the addresses seen by your processes will be likely different thus the use of one GOT per process. As for the use of two tables : its principally for security reasons so you're never executing instructions from a writable page.

You can disable lazy biding if you wish by setting the LD_BIND_NOW environment variable.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...