1

I was analyzing C++ constructor/destructor calling code, what I came to know is before main() begins, libc (or glibc) code calls constructors and registers destructors, I see the following stack trace

A::A() at clA.cc:3 0x5555555549a6   
__static_initialization_and_destruction_0() at main.cc:4 0x55555555493b 
_GLOBAL__sub_I_a() at main.cc:10 0x555555554997 
__libc_csu_init() at 0x555555554c1d 
__libc_start_main() at libc-start.c:266 0x7ffff7464b28  
_start() at 0x5555555547ba  

Now I understand that __libc_start_main comes from libc, which calls the statically linked __libc_csu_init (reason I don't see it's source) but I found it in glibc/glibc-2.27/csu/elf-init.c but I am unable to find the source of _GLOBAL__sub_I_a() and __static_initialization_and_destruction_O() from which library these functions come and get statically linked with our executable, I know these are statically linked but want to see the source to understand them, on what goes behind the scene.

Thanks, Fahad

273K
  • 29,503
  • 10
  • 41
  • 64
Fahad Mubeen
  • 91
  • 1
  • 8
  • Have you considered the possibility that the compiler could generate them? Note that your stack trace shows them coming from 'main.cc'. – Marshall Clow May 06 '20 at 02:58
  • Yes, stack trace shows coming from main.cc, seems like the compiler embedded those assembly function in main.cc file. – Fahad Mubeen May 07 '20 at 15:30

1 Answers1

2

The clang docs have a section on Constructing and destroying global objects that you might find interesting.

And you should definitely read What does '_GLOBAL__sub_I_' mean in nm output?

Marshall Clow
  • 15,972
  • 2
  • 29
  • 45
  • Thanks @Marshall Clow for the link :) , the article was helpful, it looks like these functions are getting generated by some gcc script, and there isn't any coded version in .c files of gcc. So only way to look at their code is I guess by assembly. – Fahad Mubeen May 07 '20 at 15:29