In the program below, I am trying to print out even numbers from 2 to n, with n passed in as an argument for function void even(int n). I have a different main.c file to call this function.
.extern printf
.section .data
format:
.asciz "%d\n"
.section .text
.global even
even:
cmpl $2, %edi #compare n to 2
jl less_than_two #if n < 2 then jump to less_than_two
#if not, start from 2
movl $2, %ebx # start from 2
loop:
# print the number
movl $format, %esi # the string format of printf is in esi
movl %ebx, %edi # the first argument of printf is in edi
subq $8, %rsp # make room on the stack for the argument
movl %edi, (%rsp) # push the argument onto the stack
call printf
addq $8, %rsp # clean up the stack
addl $2, %ebx #add 2 to ebx
cmpl %ebx, %edi # compare n with ebx
jl end # if n < ebx then jump to end
jmp loop #else continue to print
less_than_two:
movl $format, %esi
xorl %edi, %edi
subq $8, %rsp # make room on the stack for the argument
movl %edi, (%rsp) # push the argument onto the stack
call printf
addq $8, %rsp # clean up the stack
ret
end:
ret
When I try to compile and run it on Linux terminal, I get the result as: Segmentation fault (Core dumped).
In x86_64 Linux, arguments are passed in registers, not on the stack, so your printing code should be more like
See the ABI spec for all the gory details