Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When a process forks, would the shared library .so still in the address space? And would the constructor be executed again?

When a process forks, would the child process have the customized shared library (.so file) in its address space?

If so, is the address of the shared library be same or different from its parent process (due to ASLR) ?

Would the function running before the main function __attribute__ ((constructor)) constructor be executed again in all the child process? What about thread?

like image 590
WindChaser Avatar asked Apr 19 '15 20:04

WindChaser


1 Answers

Yes, the child will retain the parent's mappings. Ordinarily, Linux's virtual memory system will actually share the page between the two processes, up until either one tries to write new data. At that point, a copy will be made and each process will have its own unique version - at a different physical address but retaining the same virtual address. This is referred to as "copy on write" and is a substantial efficiency and resources advantage over systems which cannot support this, particularly running code which forks frequently.

Address Space Layout Randomization (ASLR) can't apply for libraries or objects which are already allocated virtual addresses, as to do so would break any pointers held anywhere in the code - something that a system running non-managed code can't know enough about to account for.

Since all previously constructed objects already exist in memory, constructors are not called again just because of the fork. Any objects which need to be duplicated because they are being uniquely modified have this done invisibly by the VM system behind the scenes - they don't really know that they are being cloned, and you could very well end up having a pair of objects where part of the implementation continues to share a physical page with identical contents while another part has been invisibly bifurcated into distinct physical pages with differing contents for each process.

You also asked about threads, and that is an area where things get complicated. Normally, only the thread which called fork() will exist in live form in the child (though data belonging to the others will exist in shared mappings, since it can't be known what might be shared with the forked thread). If you need to try to fork a multithreaded program, you will need to see the documentation of your threading implementation. For the common pthreads implementation on Linux, particularly pay attention to pthread_atfork()

like image 86
Chris Stratton Avatar answered Oct 20 '22 01:10

Chris Stratton