第8部分-Linux x86 64位彙編 AT&T彙編示例三

第8部分-Linux x86 64位彙編 AT&T彙編示例三

示例——求指數

這裏幾個例子還是使用的32位的寄存器,後面會漸漸過渡到64位的寄存器。

在求指數中,我們定義了函數,通過函數來實現指數求解(這裏實現的23+52=33,將參數寫入了代碼中)。

.section .data

.section .text

.code32
.globl _start 
_start:

pushl $3 #壓棧第二個參數
pushl $2 #壓棧第一個參數
call power   #調用函數
addl $8, %esp  #移動棧指針

pushl %eax #保存第一個結果

pushl $2  #壓棧第二參數
pushl $5  ##壓棧第一個參數 
call power #調用函數 
addl $8, %esp #移動棧指針

popl %ebx #第二個值在%eax中,第一個值在棧中

addl %eax, %ebx #將他們相加在%ebx

movl $1, %eax #退出
int $0x80

#INPUT: 第一個參數-基數 %ebx
#	第二個參數-指數 %ecx
#	-4(%ebp) 保存當前結果
#	%eax 用於臨時存儲
#OUTPUT:
#	結果返回

.type power, @function 
power:

pushl %ebp #保存舊的基指針
movl %esp, %ebp #將棧指針移動給基指針
subl $4, %esp #爲本地變量騰出空間

movl 8(%ebp),%ebx #第一個參數放入到%eax
movl 12(%ebp),%ecx #第二個參數放入到%ecx

movl %ebx, -4(%ebp) #存儲當前結果

power_loop_start:

cmpl $1, %ecx #如果結果 是1,則結束
je end_power 
movl -4(%ebp), %eax #移動當前結果到%eax
imull %ebx, %eax #用於基數乘以當前結果
movl %eax, -4(%ebp) #存儲結果

decl %ecx
jmp power_loop_start

end_power:
movl -4(%ebp), %eax 
movl %ebp, %esp 
popl %ebp 
ret

#as -o power.o power.s --32

# ld -o power power.o -melf_i386

#./power

通過echo $?可以得到33.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章