where goes the ret instruction of the main

人盡茶涼 提交于 2020-12-05 11:55:48

问题


I learned how assembly (x86) globally works in the book : "Programming from ground up". In this book, every program ends with an interruption call to exit.

However, in C compiled programs, I found out that programs end with a ret. This supposes that there is an address to be popped and that would lead to the end of the program.

So my question is : What is this address? (And what is the code there?)


回答1:


You start your program by asking the OS to pass control to the start or _start function of your program by jumping to that label in your code. In a C program the start function comes from the C library and (as others already said before) does some platform specific environment initialization. Then the start function calls your main and the control is yours. After you return from the main, it passes control back to the C library that terminates the program properly and does the platform specific system call to return control back to the OS.

So the address main pops is a label coming from the C library. If you want to check it, it should be in stdlib.h (cstdlib) and you will see it calling exit that does the cleanup.

Its function is to destroy the static objects (C++ of course) at program termination or thread termination (C++11). In the C case it just closes the streams, flushes their buffers, calls atexit functions and does the system call.

I hope this is the answer you seek.




回答2:


It is implementation specific.

On Linux, main is called by crt0, and the _start entry point there is analyzing the initial call stack set up by the kernel interpreting the execve(2) system call of your executable program. On return from main the epilogue part of crt0 is dealing with atexit(3) registered functions and flushing stdio.

FWIW, crt0 is provided by your GCC compiler, and perhaps your C standard library. All this (with the Linux kernel) is free software on Linux distribution.

every program ends with an interruption call to exit.

Not really. It is a system call (see syscalls(2) for their list), not an interrupt. See also this.



来源:https://stackoverflow.com/questions/47336142/where-goes-the-ret-instruction-of-the-main

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!