Stack - a type of data structure where items are added and then removed in reverse order i.e. the most recently added item is the very first one that is removed.
Stack - heavily used in programming for the storage of information during procedure or function calls.
Push - Adding an item to a stack
Pop - Removing an item from a stack
The stack is implemented in reverse in memory
Stack is implemented growing downward in memory.
The RSP register is used to point to the current top of stack in memory.
The basic stack operations of push and pop adjust the stack pointer register, RSP, during their operation.
For push operation, the RSP register is decreased by 8.
For push operation, the operand is copied to the stack at [RSP].
For a pop operation, the current top of the stack, at [RSP], is copied into the operand.
For a pop operation, the RSP register is increased by 8.
Functions must be written before it can be used (located in the code segment).
A function may be defined only once.
There is no specific order required for how functions are defined.
Functions cannot be nested.
Function calls involve two main actions:
• Linkage
• Argument Transmission
Linkage - the function must be able to return to the correct place in which it was originally called
Argument Transmission - the function must be able to access parameters to operate on or to return results
The linkage is about getting to and returning from a function call correctly.
There are two instructions that handle the linkage:
call
ret
call - transfers control to the named function
ret - returns control back to the calling routine
the call works by saving the address of where to return to when the function completes
call - this is accomplished by placing contents of the RIP register on the stack
the ret instruction pops the current top of the stack (RSP) into the RIP register (thus, the appropriate return address is restored)
Argument Transmission - refers to sending information (variables, etc.) to a function and obtaining a result as appropriate for the specific function
call-by-value - transmitting values to a function
call-by-reference - transmitting addresses to a function is referred
A combination of registers and stack is used to pass parameters to and/or from a function
The first six integer arguments are passed in registers
The seventh and any additional arguments are passed on the stack
Arguments' registers:
rdi
rsi
rdx
rcx
r8
r9
rax - where the return value is stored
Preserved registers
rbx
rbp
r12
r13
r14
r15
Temporary storage
r10
r11
When the function is completed, the calling routine is responsible for clearing the arguments from the stack.
For functions with return value, the result is placed in the A register based on the size of the value being returned.
Call frame - the items on the stack as part of a function call
Call frame - also referred to as an activation record or stack frame