05 Software Security 2
05 Software Security 2
Assembly
cmp eax, 10
jge a1
jmp a2
a1:
mov ebx, 1
a2:
nop
2
3761
Assembly
cmp eax, 10
jge a1
jmp a2
a1:
mov ebx, 1
a2:
nop
Answer B is correct
3
3761
Assembly
mov rcx, 1
shl rcx, 63
test rax, rcx
jz b1
mov rbx, 1
b1:
nop
4
3761
Assembly
mov rcx, 1
shl rcx, 63
test rax, rcx
jz b1
mov rbx, 1
b1:
nop
Answer B is correct 5
3761
Assembly
mov rcx, 1
shl rcx, 63
test rax, rcx
jz b1
mov rbx, 1
b1:
nop
6
3761
Assembly
mov rcx, 1
shl rcx, 63
test rax, rcx
jz b1
mov rbx, 1
b1:
nop
This Lecture
§ Last lectures
- Control flow operations
- (un)conditional jumps
- Loops and similar code constructs
§ This lecture
- Stack and push/pop instructions
- Calling conventions for x64 / x86
8
3761
Stack
10
3761
Stack II
§ push/pop examples
Assembly
SECTION .data
myvar dq 0xcafe;
SECTION .text
lea rax, [myvar] ; rax contains address of myvar
push 0xcabe ; push constant 0x000000000000CABE on stack
push rax ; push value in rax on stack
11
3761
§ One functions calls another and passes arguments to the callee - how is the
communication handled?
Code
int foo (int var1, char *var2) {
…
tmp = bar (23, 42);
…
}
12
3761
Function Calls
13
3761
§ First 6 parameters passed via registers: rdi, rsi, rdx, rcx, r8, r9
§ Additional parameters are passed on the stack
§ Return value in rax
Example
https://godbolt.org/z/9WSBds
15
3761
16
3761
QUIZTIME: Stack
§ Assembly Challenge
- Does push change rsp?
18
3761
QUIZTIME: Stack
§ Assembly Challenge
- Does push change rsp?
Answer B is correct
19
3761
§ Assembly Challenge
- How many parameters can be
passed to a function in x64?
20
3761
§ Assembly Challenge
- How many parameters can be
passed to a function in x64?
Slide 14:
First 6 parameters passed via registers:
rdi, rsi, rdx, rcx, r8, r9
Additional parameters are passed on
the stack
Answer C is correct
21
3761
uint64_t x = a + b + c;
uint64_t y = d + e + f;
uint64_t z = g + h;
uint64_t s = x + y + z;
return s;
}
§ Function prologue
1. Save old rbp: push rbp
2. Establish frame: mov rbp, rsp
3. Reserve stack space for local vars: sub rsp, <size_local_vars>
§ Function epilogue
1. Restore old frame (alternative: leave)
• mov rsp, rbp
• pop rbp
2. Return to caller (ret)
23
3761
C Code
void funA(int a, int b) {
uint64_t vA, vB;
vA = vA + vB;
}
int main(...) {
funB(1, 2);
nM: return 0;
}
24
3761
§ Assembly Challenge
- Suppose fun_A calls fun_B
- How does the stack frame (i.e., the
registers rbp and rsp) of fun_A look like
after fun_B has returned to fun_A?
- Assume x64 calling convention
25
3761
§ Implementation
- Flag –fomit-frame-pointer in gcc (enabled in O1-3) or /Oy in VC does
this
- All stack addresses are relative to rsp
- rbp can be used as a general-purpose register
- Function prologue omits mov rbp, rsp
- Function epilogue omits pop rbp
26
3761
27
3761
§ cdecl example
28
3761
30
3761
32
3761