I know how to pass parameters to a user-defined function and how to create local variables inside such function. But what I want is to create local variables for the main function.
So the main function is the first thing that executes when the program starts, but what is the initial value of esp when main starts executing? i.e what is on top of the stack when main starts executing, is it the command line arguments?
If I want to create local variables inside main, should I save the value of esp into ebp and then increment esp by how much data I need just like I do inside of a user-defined function?
So the main function is the first thing that executes when the program starts, but what is the initial value of esp when main starts executing? i.e what is on top of the stack when main starts executing, is it the command line arguments?
main
is called as a normal function, so (with cdecl
calling convention), the topmost things are, from the top to the bottom, (optionally) the environment pointer, then the pointer to the argument string pointer array, then argc
, then the return address of main
.
If I want to create local variables inside main, should I save the value of esp into ebp and then increment esp by how much data I need just like I do inside of a user-defined function?
main
is a user function. It is called from crt0.o
(name may differ depending on the operating system) from code roughly like this:
void
_start(void)
{
/* initialisation skipped */
int rv = main(newargc, newargv, environ);
do_global_dtors();
exit(rv);
/* NOTREACHED */
}
So, tl;dr: yes.
(Note that even _start
has a valid stack pointer, but usually no return address, so it must eventually call the exit
syscall.)