开发者

x86 Assembly: What's the main prologue and epilogue?

I'm following this tutorial on x86 assembly. Every example so far u开发者_如何学Goses what the author calls a "c-driver" program, compiled with the assembly module, for means of some "initialization". Something like:

int main(void) {
  int ret = asm_main();
  return ret;
}

And then the asm_main function is written normally, using a C calling convention. I'm wondering what exactly is the required initialization that's being generated by the C compiler, and if it can be done in a portable manner.

Infos: I'm on Windows XP, 32bit box, using the NASM assembler and mingw32-gcc for linking.


The initialisation isn't generated by the c compiler, it is part of the c library (which makes it easier to tailor for each OS/processor).

The code in question is normally very simple on windows/unixy systems - typically does a bit of library initialisation (opens STDIN, STDOUT, STDERR, sets timezone etc), sets up the environment, processes the command line for passing to main; catches the return from main() and calls exit etc.

The start up code in most c libraries is in a file called crt0.c, crt1.c or something similar (crt = c run time).

On more primitive or bare systems it will also set up the stack and other registers and clear the BSS data area - in this case it would often be in assembler (typically crt0.S).

Here is a link to the BSD c startup code - link text

And the start up code for mingw for windows is in crt1.c here - http://mingw.cvs.sourceforge.net/viewvc/mingw/runtime/


You could write your main in assembly if you want. But a lot of people want to put debugging statements in the main and those are easier in C than in asm.

If you wrote main in asm you might have to deal with main actually being called _main or using an alternate calling convention (especially under Windows) or other strange things like that that the C compiler handles for you automatically when generating code for a function with the name "main". This way makes it so you don't have to do that either.


The stack, registers, and program's file sections (data, rodata, bss, etc) have to be initialized before main() is called. C runtime library (CRT) provides this initialzsation.

CRT also provides prologue and epilogue code that is executed before and after each function is called. The prologue and epilogue code updates the stack and frame pointers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜