views:

66

answers:

2

I've been compiling simple Hello World applications in Visual Studio 2010 with the C++ compiler (Win32 is the target) to see what the product looks like under the microscope when I run it with the Immunity debugger. What I've noticed, however, is that there is some code (quite a bit of code, actually) that gets run before my main function is reached. A lot of this stuff looks security related or maybe prepping the system to manage processes or what not, but there's just a TON of it there. Morever, the EntryPoint part of the PE file header seems to point into the interior of my .text segment, while it appears that my main() function is resting at the very beginning of the .text segment. My question is this: is there some good documentation regarding this prelude that is getting slapped onto the front of my code AND/OR is the main() function typically placed at the very beginning of the .text segment by the VC++ compiler? Thanks for any insight you have!

A: 

Not sure about 2010, but the old VC6 used to come with the source code for its CRT, including the file that contained this initialization code (it was called crtexe.c).

The default entry point in a command line app is called mainCRTStartup.

For statically linked programs, the code is in `crt0.c`. `crtexe.c` for dynamically linked.
Jeff M
Awesome, thanks for your answer!
thegravian
A: 

The compiler places your user code at the beginning of the .text segment because that's where you would expect to find your code. All other non-user code is placed in the end after yours which are necessary to for the programs to work as you expect but you don't need to worry about. When writing a C program, you expect certain things to be available such as the command line arguments in a local array, initializing global variables, making sure standard I/O is available and important other things needed by the C runtime things that need to be initialized.

If you look at the source code for the routines, the comments explain why it is needed.

These routines do the C runtime initialization, call the appropriate user entry function, and handle termination cleanup. For a managed app, they then return the exit code back to the calling routine, which is the managed startup code. For an unmanaged app, they call exit and never return.

Jeff M
Thanks! That definitely cleared things up. It wasn't clear to me what exactly I was looking for, but this is makes it clear. I busted open a few of the vcrt files and they're pretty well documented...makes sense. Thanks again!
thegravian