📗 -> 11/4: Function Call Visualization and Matrix Addition in C


Slides
Recording

🎤 Vocab

❗ Unit and Larger Context

Small summary

✒️ -> Scratch Notes

Leal

Provides an address, does not dereference memory. Copies the address.
Leal d(o,i,s), register
LEA = Load Effective Address

Function Calling

The caller will push args to the stack in reverse order (so the first arg is on top, f(a,b,c) => push c, b, a)

  • It also pushes a return label/address to continue execution from

The callee then deals with the EBP, ESP, and maintaining registers

Prologue

Establish the stack frame for the current function
EBP holds the pointer to the start of the stack frame
Stack frame is everything between EBP and ESP
The stack frame gives you a fixed location for accessing locals and arguments
ESP keeps changing throughout the runtime of your function so it makes really hard to keep accessing locals and args through it because it keeps changing

push %ebp
movl %esp, %ebp
subl $num_locals * ws, %esp
Push those registers

EBP Offsets for args:

Positive offsets are function arguments
Negative offsets are local variables

After the prologue of fun1(a,b,c)

Can move up to a future by following the ebp pointers of call stack

movl %ebp, %eax // ebp into eax
movl (%eax), %eax // following the ebp pointer (fun3->fun2)
movl (%eax), %eax // following the ebp pointer (fun2->fun1)
movl 2*ws(%eax), %eax // accessing the 1st fun1 arg, a

Epilogue

Undoes the prologue

Restore saved registers
Remove the locals
Restore the old stack frame

Pop the saved registers off the stack or move them off the stack
movl %ebp, %esp
pop %ebp
After the epilogue of fun3(f,g)

Calling Malloc

A function, like any other. Feed it args through stack

  • Can multiply by 4 (ws) fast with shll $2, %eax (shift left 2 bits)
push %eax
call malloc        # return value is in eax
movl %eax, C(%ebp) # moving it to our local C variable
addl $1*ws, %esp   # remove our arg from the stack 

Resources

  • Put useful links here

Connections

  • Link all related words