Virtual address space of program

 image-20240403210900001

Before understanding the stack frame of a function, let's first understand the concept of virtual address space. The operating system allocates a virtual address space to each c program instance, creating the illusion that each program has exclusive memory. The memory addresses are distributed as follows.

Stack area

Stack is a kind of data structure that is first in and then out. In the address space of C program, the% esp register points to the top of the stack, and the% ebp register points to the bottom of the stack. The stack extends from the high address to the low address. When entering the stack, the esp moves to the low address. When exiting the stack, the esp moves to the high address

 image-20240413140207649

Function calls depend on the stack. Call the function, and the stack increases. The function returns, and the stack shrinks.

function call

 one

 image-20240413140907149

The process of calling a function is essentially to modify the value of PC (program counter), The PC points to the address of the next execution instruction

Before calling the function

  1. The parameters are stacked from right to left,
  2. The call instruction puts the return address on the stack, which indicates the next execution statement when the function returns

Parameter transfer

In 32-bit systems, parameters are passed on the stack.

In the X86-64 architecture, the function parameters are stored in registers, respectively in di, Si, dx, cx, r8, r9 registers. If the parameter of the function is greater than 6, the excess part needs to be passed using the stack

 image-20240403211624970

local variable

 one
two
three
four
five
six
seven
eight
 long  caller () 
{
long argl = five hundred and thirty-four ;
long arg2 = one thousand and fifty-seven ;
long sum= swap_add(&argl, &arg2);
long diff = argl -arg2;
return sum* diff;
}

Corresponding assembly code

 one
two
 subq $16, %rsp
movq $534, (%rsp)

Create local variables