退出程序x86 [英] Exit program x86
问题描述
我正在学习x86汇编.我试图了解退出程序"如何在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
当处理器执行"ret"指令时:
When processor executes instruction "ret" :
EIP将具有从堆栈中弹出的值,即0.
因此,处理器将转到0地址并尝试执行指令...,其中不包含程序代码/可执行代码.
那么,处理器到底在发生什么呢?是否有条件检查,例如if EIP = 0 -> exit program?
Or if ESP out of bounds -> exit program?
`处理器如何理解此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?
推荐答案
main()
.用任何语言(包括asm)编写main
与编写任何其他函数都没有区别.
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.
执行从_start
开始.如果您编写自己的_start
,则没有内容可返回,因此您需要进行_exit(2)
或exit_group(2)
系统调用.
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.
(否则执行时,segfault落在代码末尾,或者如果尝试执行ret
,它将在堆栈中弹出一个值到程序计数器(EIP)中,并可能在从该段中提取代码时出现segfault可能无效的地址.)
(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.)
当您使用C编译器进行+编译+链接时,它会在CRT(C RunTime)启动代码中进行链接,该启动代码提供了_start
,该文件初始化libc,然后调用main
. main
返回后,调用它的CRT代码运行atexit
函数,然后将main的返回值传递给退出系统调用.
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
不是函数,它是进程入口点.例如,在Linux下,进入_start
的ESP指向的是argc
,而不是返回地址. (请参阅i386 System V ABI.)
_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.
这篇关于退出程序x86的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!