Section 5: Procedures & Stacks Stacks in memory and stack operations The stack used to keep track of procedure calls Return addresses and return values Stack-based languages The Linux
Trang 1Section 5: Procedures & Stacks
Stacks in memory and stack operations
The stack used to keep track of procedure calls Return addresses and return values
Stack-based languages
The Linux stack frame
Passing arguments on the stack
Allocating local variables on the stack
Register-saving conventions
Procedures and stacks on x64 architecture
Trang 21 6 6 6¬ da 0i Stack-Based Languages
= Languages that support recursion
= e.g., C, Pascal, Java
=" Code must be re-entrant
= Multiple simultaneous instantiations of single procedure
= Need some place to store state of each instantiation
= Arguments
= Local variables
= Return pointer
= Stack discipline
= State for a given procedure needed for a limited time
= Starting from when it is called to when it returns
=" Callee always returns before caller does
= Stack allocated in frames
= State for a single procedure instantiation
Trang 3Call Chain Example
Example
{
° who ( ) |
} aml () ; amT ( ) amt amt
amT () ; |
}
Procedure amT i¡s recursive
(calls itself)
Stack-Based Languages
Trang 4
Stack Frames
Previous
= Local variables
=" Function arguments Frame Pointer: sebp —————>
=" Return information Frame
current
proc
Stack Pointer: Šesp ————>
m Management
=" Space allocated when procedure is entered Stack “Top”
» “Set-up” code
= Space deallocated upon return
= “Finish” code
Trang 5Example
yoo
who
IN
amI aml
aml
aml
Stack-Based Languages
Stack
sebp ——>
esp ——
Trang 6Example
who ( )
amT () ; amT () ; }
yoo
who
Stack-Based Languages
sebp ——>
Stack
yoo
%Sesp ——
who
Trang 7
Stack
Example
amT ( ) yoo
= ° who
} %ebp ———>
amt
sesp —
Stack-Based Languages
Trang 8
Stack
Example
amT ( ) yoo
amt
amT
Ssebp ——>
amt
%Sesp ——
Stack-Based Languages
Trang 9
Stack
Example
amT ( ) yoo
= ° who
amT
amT
sebp ——>
amT
%Sesp ——
Stack-Based Languages
Trang 10
Stack
Example
amT ( ) yoo
° "|
ami
sebp ——>
ami
%Sesp ——
Stack-Based Languages
Trang 11
Stack
Example
amT ( ) yoo
° "|
} %ebp ———>
amt
sesp —
Stack-Based Languages
Trang 12Stack
who ( ) yoo
| eee | yoo
who
amT () ;
%Sesp ——
Stack-Based Languages
Trang 13es
Stack
Example
amT ( ) yoo
{
} %ebp ———>
%Sesp ——>
Stack-Based Languages
Trang 14Stack
who ( ) yoo
who
amT () ;
©® ©® ©® sebp —~”
sesp ——
Stack-Based Languages
Trang 15Example
yoo
who
IN
amI aml
aml
aml
Stack-Based Languages
Stack
sebp ——>
esp ——