There is a c runtime library, that according to https://en.wikipedia.org/wiki/Crt0 is in file ctr0.o
called to initialize variables before calling main. I have copied it here :
.text
.globl _start
str : .asciz "abcd\n"
_start:
xor %ebp, %ebp #basePointer == 0
mov (%rsp), %edi #argc from stack
lea 8(%rsp), %rsi #pointer to argv
lea 16(%rsp,%rdi,8), %rdx #pointer to envp
xor %eax, %eax
call main
mov %eax, %edi
xor %eax, %eax
call _exit
main:
lea str(%rip), %rdi
call puts
I have some question regarding the implementation:
What is in stack before called
_start
which should be the only entry for linker? I am asking becuase there are expression such asmov (%rsp), %edi #argc from stack
, where the_start
is getting value from the stack, but_start
should not have anyargc
(onlymain
does) norargv
andenvp
. All these arguments are part ofmain
function, not_start
entry point. So what is in stack before_start
?This should be designed to provide initilization of variables from
.data
or.bss
segments, but I do not see such initialization of them here. It could be related with the stack, but I do not know how. Before the variables are initialized (which should be in thectr0.o
, here), the hold initial value and linker reserve space for them (also from that link). In what section of memory type, does gcc hold space for those not-initialized variables?Finally, how to compile this assembly, without stdlib, but requires some of its function (
puts
,_exit
) in order to work? I have triedcc -nostdlib foo.s
but/usr/bin/ld: /tmp/ccSKxoPY.o: in function `_start': (.text+0x21): undefined reference to `_exit' /usr/bin/ld: /tmp/ccSKxoPY.o: in function `main': (.text+0x2d): undefined reference to `puts' collect2: error: ld returned 1 exit status
(Cannot use stdlib
otherwise, there would be 2 declaration of _start
entrypoint).