Reputation: 712
In gcc assembly, the main function can either return or exit, where both work. Here I have two programs, where one exits with a syscall int $0x80
, and the other simply calls ret. What is the difference?
.data
hello: .string "Hello, World!"
.globl main
main:
push %rbx
movq $hello, %rdi
call puts
pop %rbx
ret
and
.data
hello: .string "Hello, World!"
.globl main
main:
push %rbx
movq $hello, %rdi
call puts
pop %rbx
movq $1, %rax
movq $0, %rbx
int $0x80
I am aware that ret pops the instruction pointer off the stack, but what does that really do in this case?
Upvotes: 1
Views: 1166
Reputation: 93172
The code that calls main
looks like this:
int status = main(argc, argv, envp);
exit(status);
if main
returns, exit(status)
is executed. exit
is a C library function which flushes all stdio streams, invokes atexit()
handlers and finally calls _exit(status)
, which is the C wrapper for the SYS_exit
system call. If you use the C runtime (e.g. by having your program start at main
or by using any libc functions), I strongly recommend you to never call SYS_exit
directly so the C runtime has a chance to correctly deinitialize the program. The best idea is usually to call exit()
or to return from main
unless you know exactly what you are doing.
Upvotes: 5