Understanding assembly language _start label in a C program

早过忘川 提交于 2019-12-05 13:02:04

Here is the well commented assembly source of the code you posted.

Summarized, it does the following things:

  1. establish a sentinel stack frame with ebp = 0 so code that walks the stack can find its end easily
  2. Pop the number of command line arguments into esi so we can pass them to __libc_start_main
  3. Align the stack pointer to a multiple of 16 bits in order to comply with the ABI. This is not guaranteed to be the case in some versions of Linux so it has to be done manually just in case.
  4. The addresses of __libc_csu_fini, __libc_csu_init, the argument vector, the number of arguments and the address of main are pushed as arguments to __libc_start_main
  5. __libc_start_main is called. This function (source code here) sets up some glibc-internal variables and eventually calls main. It never returns.
  6. If for any reason __libc_start_main should return, a hlt instruction is placed afterwards. This instruction is not allowed in user code and should cause the program to crash (hopefully).
  7. The final series of nop instructions is padding inserted by the assembler so the next function starts at a multiple of 16 bytes for better performance. It is never reached in normal execution.

for gnu tools the _start label is the entry point of the program. for the C language to work you need to have a stack you need to have some memory/variables zeroed and some set to the values you chose:

int x = 5;
int y;

int fun ( void )
{
   static int z;
}

all three of these variables x,y,z are essentially global, one is a local global. since we wrote it that way we assume that when our program starts x contains the value 5 and it is assumed that y is zero. in order for those things to happen, some bootstrap code is required and that is what happens (and more) between _start and main().

Other toolchains may choose to use a different label to define the entry/start point, but gnu tools use _start. there may be other things your tools require before main() is called C++ for example requires more than C.

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