Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When a C++ program terminates on Windows what is the last function called by the termination stub?

This question is about reverse engineering and the Microsoft Standard C Library.

When a C program terimates gracefully, i.e. does a return 0; at the end of main(). What all happens (generalize please). Specifically, what is the last function called by the C library?

like image 228
unixman83 Avatar asked Apr 11 '11 09:04

unixman83


2 Answers

You can find the sources of the Microsoft CRT in "%Program Files%\Microsoft Visual Studio x.0\VC\crt\src".

The entrypoint for executables (mainCRTStartup) is in crt0.c, or, in case the runtime DLL is used, in crtexe.c. You can see that after calling main() it calls exit(). The source code of exit() is in crt0dat.c. It calls C and C++ termination handlers (closing stdio handles etc), calls atexit() functions, and finally calls __crtExitProcess() which calls kernel32's ExitProcess().

like image 90
Igor Skochinsky Avatar answered Oct 29 '22 19:10

Igor Skochinsky


If you have strace on your machine, you can use that (invoke it via strace ./program) - on my machine, with the following code, it gives exit_group(0) as the last function:

int main() {
    return 0;
}

As for what happens (warning: sweeping generalisations ahead), the operating system (theoretically) should attempt to start reclaiming memory from your process by deleting all memory you've left new'd.

like image 44
Ben Stott Avatar answered Oct 29 '22 17:10

Ben Stott