Reputation: 4149
I have been tearing my hairs out learning assembly haha. I am trying to get the program to do the following computation: 2^3 + 5^2.
I tried to debug with gdb, but I don't understand much at all and internet searches don't reveal much.
This program is for x86-64. The program compiles fine , but after typing echo $?
, I expected 33
but got 0
instead.
Here is the code:
1 .section .data
2 .section .text
3 .globl _start
4 _start:
5 pushq $3 #push the 2nd arg
6 pushq $2 #push the 1st arg
7
8 call power #call function
9 addq $16, %rsp #move stack back 16 bytes to get rid of first two params
10
11 pushq %rax #save the first answer before
12
13 pushq $2 #push the 2nd arg
14 pushq $5 #push the 1st arg
15
16 call power #call function
17 addq $16, %rsp #move stack back 16 bytes to get rid of first two params
18 popq %rbx #2nd answer already in rax. We saved saved first answer onto stack and now pop it into rbx.
19
20 addq %rax, %rbx #add together
21
22 movq $60, %rax #exit
23 syscall
24
25 .type power, @function
26 power:
27 pushq %rbp #save old base pointer
28 movq %rsp, %rbp #make stack pointer base pointer
29 subq $8, %rsp #get room for local storage
30
31 movq 16(%rbp), %rbx #put 1st arg in rbx
32 movq 24(%rbp), %rcx # put 2nd arg in rbx
33
34 movq %rbx, -8(%rbp) #store current result
35
36 power_loop_start:
37 cmpq $1, %rcx #if power is one, we are done
38 je end_power #jump to end_power
39
40 movq -8(%rbp), %rax #move current result into rax
41 imulq %rbx, %rax #multiply current result by base number
42
43 movq %rax, -8(%rbp) #store the current result
44 decq %rcx #decrease the power
45
46 jmp power_loop_start
47
48 end_power:
49 movq -8(%rbp), %rax #return value back to rax
50 movq %rbp, %rsp #restore stack pointer
51 popq %rbp #restore base pointer
52 retq
Thank you in advance.
Upvotes: 1
Views: 113
Reputation: 2151
since you wish to return the resulted value as exit code, you'd store the result into register rdi
as the argument for system call exit
. In short, please add below line at line#21 :
movq %rbx, %rdi
Upvotes: 1