2012-04-04 48 views
1

這個(Linux,AT & T,Intel)x86程序旨在讀取三個參數,並將%ebx中最大的值存儲爲存在狀態。當我將參數彈入寄存器時,結果值似乎是字節。我如何獲得int值?將命令行參數視爲x86中的整數AT&T彙編程序

[編輯 - 感謝哈羅德的評論下面,我認爲這個問題是我如何使用atoi得到args來int值]

.section .text 

.globl _start   

_start: 
popl %edi  # Get the number of arguments 
popl %eax  # Get the program name 
popl %ebx  # Get the first actual argument 
movl (%ebx), %ebx # get the actual value into the register (?) 
popl %ecx  # ; 
movl (%ecx), %ecx 
popl %edx  # 
movl (%edx), %edx 

bxcx: 
cmpl %ebx,%ecx 
jle  bxdx 
movl %ecx,%ebx 
bxdx: 
cmpl %ebx,%edx 
jle end 
movl %edx,%ebx 

end: 
movl $1,%eax   
int $0x80   
+0

什麼int值?你在尋找相當於'atoi'嗎? – harold 2012-04-04 14:09:00

+0

程序運行後,命令行參數的int值類似於'./a.out 5 6 7' - 在這種情況下,退出狀態應該是7.所以如果我需要'atoi'之類的東西,這意味着值5,6等被讀入字符串? – jaybee 2012-04-04 14:30:50

回答

3

爲了能夠調用atoi,你會需要鏈接到libc。例如: -

ld -lc foo.o 

要實際撥打電話,你需要按照cdecl調用約定:

  1. 函數的參數是在棧上傳遞的最左邊的參數進行最後推。
  2. 函數的返回值將被放入累加器(在這種情況下爲%eax)。
  3. 寄存器跨越通話保留%ebp,%esi,%edi和%ebx,因此您可以將它們用於臨時存儲。
  4. 任何其他需要的寄存器都必須由調用代碼保存(在上面的被調用方保存的寄存器中,在參數前面的堆棧或存儲器中的其他地方)。

atoi簽名是

int atoi(const char *nptr); 

所以要得到第一個命令行參數的整數值,我們可以做

.section .text 

.globl _start   

_start: 
popl %edi  # Get the number of arguments 
popl %eax  # Get the program name 
call atoi  # Try to read the first argument as an integer and clobber %eax with the value 
+0

謝謝,最有幫助。 – jaybee 2012-04-08 16:23:20

+0

爲了得到這個工作,我需要動態鏈接它:'ld -dynamic-linker /lib/ld-linux.so.2 -o test -lc test.o' – jaybee 2012-04-08 21:30:00