1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
# Simple example of functions in ASM, following System V ABI
# and C calling convention
# Everything is stored in registers, so, we have nothing in data section
####################
# #
# Function power() #
# #
####################
# Remember the return address (where the program should keep executing after
# function return), is also pushed into the stack by the 'call' command.
# Remember, in x86_64 architecture, the Stack grows 'downwards', so, every time
# we want to look back in the stack, we need to add to the current stack
# pointer, other than subtract.
# Ex:
# 56 <- stack 'bottom'
# 48 pushq
# 40 pushq
# 32 <- %rsp (top of the stack)
.type power, @function
power:
pushq %rbp
movq %rsp, %rbp
movq 16(%rbp), %rcx # Holds the Base number. 16 because:
# Current %rsp (pushq %rbp) plus the
# implicit return address pushed by
# the call command
movq 24(%rbp), %rbx # Holds the power (pushed first before
# function call
movq %rcx, %rax
loop:
cmpq $1, %rbx
je return
imul %rcx, %rax
decq %rbx
jmp loop
return:
movq %rbp, %rsp
popq %rbp
ret
|