Relationship between startup code, atexit() and global ctors/dtors

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hi,

I am having some problems understanding clearly the relationship between startup code, atexit() and global ctors/dtors in GCC. I would appreciate it very much if somebody would validate this and point out what i may be doing wrong.

I am building GCC for --target=i386-elf and using a 3rd party standard c/c++ libraries.

1. When i build GCC for --target=i386-elf i get only crtbegin.o and crtend.o files. For global ctors/dtors support you also need crti.o and crtn.o(to start and end _init() and _fini() in the .init and .fini sections) so why are they not created? 

2. In a final executable, .ctors section has an array of function pointers __CTOR_LIST__ and .dtors section has an array of function pointers __DTOR_LIST__(the lists start in crtbegin.o and end in crtend.o). For every object file(for every global object) GCC adds in a pointer to the global ctor function in its .ctors section and a pointer to the global dtor function in its .dtors section. ld concatenates all the .ctors and .dtors from all the object files to produce the final list. To run the function we need to walk the lists before and after calling main(). This can be done by calling __do_global_ctors_aux()(defined in crtend.o) and __do_global_dtors_aux()(defined in crtbegin.o)

3. I have written my crt0.o where in "_start()" i do,

atexit(&_fini)	<=== my 3rd party library's
_init()
//...call user main()
RunAtexitFuncs()

I have defined _init() and _fini() as follows( and have placed them in the .init and .fini sections respectively)

void _init(void)
{
	extern void __do_global_ctors_aux(void);    <=== made global in crtstuff.c
	__do_global_ctors_aux();
}

void _fini(void)
{
	extern void __do_global_dtors_aux(void);    <=== made global in crtstuff.c
	__do_global_dtors_aux();
}

I have also commented out the calls to the __do_global_ctors_aux()/__do_global_dtors_aux() functions which are injected into the .init and .fini sections in crtstuff.c.

4. After return from "main()", i walk through the atexit() functions array invoking each function. My ctors run fine but i get a seg fault in the dtors. 
My questions is;
 - What is wrong with my startup code?
 - Since ALL the dtors will be run as a result of one function in the atexit array how are normal function calls to atexit() and global dtors interleaved? 

Thanks
Ram

Ramanathan Ramadass
Sr. Software Engineer,
Performance Analysis - Broadband,
Spirent Communications, 
Voice: 408-752-7310
Fax: 408-752-7186
mailto:ramanathan.ramadass@xxxxxxxxxxxxxx
http://www.spirentcom.com







[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux