2a - Basics of program execution
2a - Basics of program execution
Ramin Sadre
Memory organization
Code:
0x0l000000 load32 0x02000000,r1
0x01000006 load32 0x02000004,r2
0x0100000C add r1,r2,r1
0x0100000E store32 r1,0x02000000
Start of address space
Memory vs registers
▪ A CPU has several registers = temporary data stores that are used
to perform calculations etc.
▪ For the CPU, variables are just locations in main memory
▪ There is a special register that contains the address of the next
instruction to be executed, called the instruction pointer (IP) or
program counter (PC)
▪ After each instruction, the IP is moved further
IP = 0x0100006
call:
IP = 0x20000000
void f(int a, int b) { 0x20000000 function f
int i, j; ...
... ...
return; 0x20000030 return
}
(higher addresses)
stack frame
SP before of caller g()
calling 𝑓
4 Second parameter value
3 First parameter value
0x3000000e The return address
frame pointer
j Space for local variable j
SP when inside i Space for local variable i
function 𝑓 (unused)
(lower addresses)
Returning from a function
▪ When 𝑓(3,4) returns to 𝑔(), the top stack frame is removed from
the stack and the program execution continues at the instruction
stored at the return address
0x30000000 push 4
(unused) 0x30000004 push 3
0x30000008 call 0x20000000
0x3000000e ...
The frame pointer
SP before
call of 𝑓 4
3
return address
FP when inside
function 𝑓 saved frame pointer
j
SP when inside i
function 𝑓
The frame pointer (2)
4 Address: FP+12
3 Address: FP+8
return address Address: FP+4
FP when inside saved frame pointer Address: FP+0
function 𝑓
j Address: FP-4
SP when inside i Address: FP-8
function 𝑓
Example: Intel x86 32-bit CPU
▪ On Intel CPUs the stack pointer %esp and the framepointer %ebp
(base pointer) are manually managed
▪ Calling the function f(3,4) from g():
pushl 4 ; push 4 onto the stack (4 bytes)
pushl 3 ; push 3 onto the stack (4 bytes)
call 0x20000000 ; put the return address on
; the stack and jump to f()
addl 8,%esp ; remove the parameter values
; from the stack (8 bytes)
Example: Intel x86 32-bit CPU (2)
▪ Function f (starting at address 0x2000000):
pushl %ebp ; save the framepointer on the stack
movl %esp,%ebp ; FP = SP
subl 8,%esp ; make space for the local
; variables i and j (8 bytes)
...
movl %ebp,%esp ; SP = FP. This effectively removes
; the local variables from the stack
popl %ebp ; restores the old value of FP
ret ; jump back to the return address
; and remove it from the stack.