Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exit program x86

I am learning x86 assembly. I am trying to understand how "exiting program" works on x86. We have a code :

push ebp
mov ebp,esp
//Some stuff here
mov esp, ebp
pop ebp
ret

When processor executes instruction "ret" :

EIP will have value, which is popped from stack, in other words 0. so processor will go to 0 address and will try to execute instructions ... which doesn't contain program code/executable code. So, what is really going on with processor? Are there condition check, for example, if EIP = 0 -> exit program? Or if ESP out of bounds -> exit program? `How processor understands that this RET instruction is the end of the program?

like image 593
user3719859 Avatar asked Nov 16 '25 05:11

user3719859


1 Answers

main() is called from the normal C runtime initialization functions. Writing main in any language, including asm, is no different from writing any other function.

Execution begins at _start. If you write your own _start, it has nothing to return to, so you need to make an _exit(2) or exit_group(2) system call.

(Or else segfault when execution falls off the end of your code, or if you try to ret it will pop a value off the stack into the program counter (EIP), and probably segfault on code-fetch from that probably-invalid address.)

When you compile + link with a C compiler, it links in CRT (C RunTime) startup code that provides a _start which initializes libc then calls main. After your main returns, the CRT code that called it runs atexit functions and then passes main's return value to an exit system call.

_start isn't a function, it's the process entry point. Under Linux for example, on entry to _start ESP points at argc, not a return address. (See the i386 System V ABI.)


This question comes at the question from a different angle, but my answer to another recent question goes into more detail.

As always, single-stepping with a debugger is a good way to see what's going on and test your understanding.

like image 131
Peter Cordes Avatar answered Nov 18 '25 19:11

Peter Cordes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!