Creating a C Library: Difference between revisions

Jump to navigation Jump to search
The wiki doesn't have syntax highlighting for x86 as(1), and add .size for _start
[unchecked revision][unchecked revision]
(Fix the error: crtn.s: Error: .size expression for _init does not evaluate to a constant)
(The wiki doesn't have syntax highlighting for x86 as(1), and add .size for _start)
Line 26:
 
Below is a simple implementation of crt0.s for x86_64. It assumes that the program loader has put *argv and *envp on the stack, and that %rdi contains argc, %rsi contains argv, %rdx contains envc, and %rcx contains envp
<pre>
<source lang="asm">
.section .text
 
Line 57:
movl %eax, %edi
call exit
.size _start, . - _start
</source>
</pre>
 
This implementation is careful to set up the end of the stack frame linked list. If you compile your files without optimization or you use -fno-omit-frame-pointer, then each function adds itself to this linked list. This is very useful if you wish to add calltracing support. In that case, you'll need to know when you have reached the end, which is why we add an explicit zero in the above code..
Line 74 ⟶ 75:
 
Hence an crti.s implementation will simply be (x86_64):
<pre>
<source lang="asm">
.section .init
.global _init
Line 88 ⟶ 89:
movq %rsp, %rbp
/* gcc will nicely put the contents of crtbegin.o's .fini section here. */
</sourcepre>
 
and a simple implementation of crtn.s will be (x86_64):
 
<pre>
<source lang="asm">
.section .init
/* gcc will nicely put the contents of crtend.o's .init section here. */
Line 102 ⟶ 103:
popq %rbp
ret
</sourcepre>
 
Finally, you simply need to assemble your crt0.o, crti.o, and crtn.o files and install them in your system library directory. Your _start function is now able to set up the standard library, call the global constructors, and call exit(main(argc, argv)). Don't forget to call your _fini function in your exit function, or the global destructors won't be run, leading to subtle bugs.
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.

Navigation menu