Some understanding of dynamic library so file under Linux

Source: Internet
Author: User
Tags int size

Transferred from: http://mypyg.iteye.com/blog/845915

Personal creation, welcome to the point of error.
Involved in the ELF format, GCC compilation options to fill, a simple and practical explanation, the Linux under the so file has a practical understanding.
What is a 1.so file?
2. How do I generate and use a so dynamic library file?
3. Address space, and thread safety.
4. Initialization of the library, parsing:
5. Replace the system function with the function in our own library:
//-------------------------------------------------------------------------------
What is a 1.so file?
Also elf format files, shared libraries (dynamic libraries), similar to DLLs. Save resources, speed up, and simplify code upgrades.
It's enough to know so much, pragmatism. And so with the impression to study the principle.
2. How do I generate and use a so dynamic library file?
Write a C file first: S.C

C code
    1. #include <stdio.h>
    2. int count;
    3. void Out_msg (const char *m)
    4. {//2 seconds Output 1 times information, and Count
    5. for (;;)  {printf ("%s%d\n", M, ++count); sleep (2);}
    6. }


Compile: Get output file libs.o
Gcc-fpic-g-C S.c-o LIBS.O

Link: Get output file libs.so
Gcc-g-shared-wl,-soname,libs.so-o libs.so LIBS.O-LC

A header file: s.h

C code
    1. #ifndef _my_so_header_
    2. #define _my_so_header_
    3. void Out_msg (const char *m);
    4. #endif


Another C file to refer to the functions in this library: TS.C

C code
    1. #include  <stdio.h>  
    2.   #include   "s.h" &NBSP;&NBSP;
    3.  int main (int argc, CHAR**&NBSP;ARGV)   
    4.  {  
    5.   printf (
    6.   out_msg (
    7.   sleep (5),   //this sentence can be commented out, in the 4th quarter when you open it.   
    8.   printf (
    9.  }  


Compile link to this file: Get output file ts
Gcc-g ts.c-o ts-l.-ls

Execute./ts, hmm: success ... And almost
Got ts:error while loading shared libraries:libs.so:cannot open Shared object file:no such file or directory
System can not find our own definition of libs.so, then tell him, modify the variable Ld_library_path, for convenience, write a script: E (the file name is E, too lazy to get long)
#!/bin/sh
Export Ld_library_path=${pwd}:${ld_library_path}
./ts
Execute:./E &
On the screen began to have information output, of course, TS quit you can not see, the front is a dead loop, the back will use this sentence
3. Address space, and thread safety:
If so:
./E & After you start the execution, wait a little bit and then./e&
What happens to the screen information at this time? How will the global variable count change?
will be two process cross output information, and the respective count does not interfere with each other, although they refer to the same so file.
This means that only the code is thread safe, and that there is no code that is a process security statement.
4. Initialization of the library, parsing:
Dynamic library loading under Windows, unloading will have initialization functions and unloading functions to complete the initialization of the library and resource recycling, of course, Linux can also be implemented.
The elf file itself executes a _init () function and the _fini () function to do this, and we just have to put our own function to make the system execute at this time.
You can do it.
Modify the S.C file in front of us:

C code
  1. #include <stdio.h>
  2. void My_init (void) __attribute__ ((constructor)); //Tell GCC to throw this function to the init section
  3. void My_fini (void) __attribute__ ((destructor)); //Tell GCC to throw this function into the fini section
  4. void out_msg (const char *m)
  5. {
  6. printf ("ok!\n");
  7. }
  8. int i; //Is still a counter
  9. void My_init (void)
  10. {
  11. printf ("Init ...%d\n", ++i);
  12. }
  13. void My_fini (void)
  14. {
  15. printf ("Fini ...%d\n", ++i);
  16. }


Re-production Libs.so,ts This is not to recompile, code maintenance upgrade a lot easier.
Then execute:./E &
You can see the screen output: (Incomplete information, just the same order)
Init
Main
Ok
Quit
Fini
We can see that our own defined initialization functions, as well as the parsing functions, are executed, both in front and last.
If Sleep (5) in S.C is not commented out, chances are:
./e&
./e& executes two successive times, the initialization function and the parse function are executed two times, although the system only loads once libs.so.
If you kill the background process while sleep, the parse function is not executed.
5. Replace the system function with the function in our own library:
Create a new file B.C: We want to replace the system function malloc and free (you can write a memory leak Detection tool yourself)

C code
    1. #include <stdio.h>
    2. void* malloc (int size)
    3. {
    4. printf ("My malloc\n");
    5. return NULL;
    6. }
    7. void Free (void* AD)
    8. {
    9. printf ("My free\n");
    10. }


The usual, compiled link into an so file: Get libb.so
Gcc-fpic-g-C B.c-o LIBB.O
Gcc-g-shared-wl,-soname,libb.so-o LIBB.SO-LC
Modify S.C: Regenerate libs.so

C code
    1. void Out_msg ()
    2. {
    3. int *p;
    4. p = (int*) malloc (100);
    5. Free (p);
    6. printf ("Stop ok!\n");
    7. }


To modify the script file E:
#!/bin/sh
Export Ld_preload=${pwd}libb.so:${ld_preload}
Export Ld_library_path=${pwd}:${ld_library_path}
./ts
The key is on the ld_preload, and this path specifies that the so will be loaded before all so, and the symbol will overwrite the symbol in the so file that is loaded later. If the permissions of the executable are not appropriate (SID), this variable is ignored.
Execute:./E &
Well, we can see the malloc,free work.
I think so much for the time being.

Some understanding of dynamic library so file under Linux

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.