I have a reasonable understanding of how to execute buffer overflow attacks and how register allocation works in compilers.
What confuses me is why so many things are on the stack in C programs. Consider this vulnerable program:
#include <stdio.h>
int main() {
int a = 0;
char str[] = "ABC";
gets(str);
printf("int: %d, str: %s\n", a, str);
return a;
}
Let's run it
> gcc run.c
> ./a.out asdfasdf
int: 1717859169, str: asdfasdf
Okay so str is overwritten as is int a
. But why is int a
even on the stack?
Wouldn't it be easiest to just do something like (x86 asm)
.global _main
.text
_main:
// omitting the gets() stuff
movq $0, %rax
retq
Now we have less memory traffic since nothing is on the stack and much less code.
tl;dr why is int a
on the stack at all?
Per the comments on my post. It happens because I am compiling without optimization and when I compile with optimizations
gcc -O3 run.c
I won't see the same behavior.Here's some of the optimized assembly
And the more complicated unoptimized: