第17部分-Linux x86 64位彙編 指令行參數
使用指令行參數示例
在堆棧中指令行參數被存儲為字元串值。需要進行轉換工作,轉換為數字。
可以使用C庫函數的:
atoi:把ASCII字元串轉換為短整數值
atol:把ASCII字元串轉換為長整數值
atof:把ASCII字元串轉換為雙精度浮點值
這些函數需要将字元串位置的指針必須放置堆棧中。
atoi函數結果傳回到EAX寄存器中。Atol的結果存放在EDX:EAX寄存器中,需要64位。函數atof結果傳回到fpu的st0寄存器中。
-
-
- 示例
-
讀取指令行參數把它轉換為整數值,然後計算圓面積。
.extern printf ;//調用外部的printf函數
.section .data
output:
.asciz "The area is: %f\n"
.section .bss
.lcomm result, 8
.section .text
.globl _start
_start:
nop
finit;//初始化FPU
mov 16(%rsp),%rdi;//指向第一個參數
call atoi;//調用atoi為短整數
movq %rax, result
fldpi;//加載π到st0
filds result;//加載result到st0,π移動到st1
fmul %st(0), %st(0);//result相等并存放于st0
fmul %st(1), %st(0);//将st0和st1相乘,結果存放于st0
fstpl (%rsp);//将st0存放于堆棧中,覆寫了指向程式名的指針。
movq $output,%rdi;//output2字元串位址
movq (%rsp),%xmm0;//棧指針
call printf;//調用printf函數,列印參數數量
movq $0,%rdi
call exit
as -g -o paramtest.o paramtest3.s
ld -o paramtest paramtest.o -lc -I /lib64/ld-linux-x86-64.so.2
然後執行
./paramtest 20
即可得到輸出:
The area is: 1256.637061
這裡要注意的是,如果不增加一個參數是會報段錯誤的。