2015-12-15 159 views
2

我正在編寫打印出程序的第二個參數的代碼。據瞭解,ebp+8保存了參數編號,ebp+12包含了程序名稱地址等。到目前爲止,我有:打印第二個命令行參數

%include "asm_io.inc" 

SECTION .data 
err1: db "Incorrect number of command line arguments",10,0 

SECTION .text 
    global asm_main 

asm_main: 
    enter 0,0 
    pusha 

    mov eax, dword [ebp+8] 
    cmp eax, dword 2 
    jne ERR1 

    mov eax, dword [ebp+16] ; prints 1st letter of 2nd argument 
    mov al, byte[eax] 
    call print_string 
    jmp asm_main_end 


ERR1: 
    mov eax, err1 
    call print_string 
    jmp asm_main_end 

asm_main_end: 
    call print_nl 
    popa     ; restore all registers 
    leave      
    ret 

可執行文件叫lynarr。當我執行lynarr abcd時,我可以打印程序名稱(即lynarr),但我不知道如何打印第二個參數。我正在使用redhat-linux和nasm 2.10.07。有任何想法嗎?

回答

4

dword [ebp+12]是指向字符串指針數組的指針。該數組的第一個元素是指向第一個字符串的指針,第二個元素是指向第二個字符串的指針等。每個指針都是32位(4字節)寬。

要獲得指向第二個字符串的指針,需要獲取指針dword [ebp+12] + 4。您無法直接在x86地址中執行此操作。你可以通過將dword [ebp+12]移動到像EAX這樣的寄存器中,向其中添加4(因爲指針是4個字節寬),然後取消引用以獲得第二個字符串的指針。

替換:

mov eax, dword [ebp+16] ; prints 1st letter of 2nd argument 
mov al, byte[eax] 
call print_string 

有了:

mov eax, dword [ebp+12] 
mov eax, [eax+4]   ; EAX = pointer to 2nd argument 
call print_string 

這將打印出的第二個參數。

mov eax, dword [ebp+12] 
mov eax, [eax]   ; EAX = pointer to 1st argument 
call print_string 

當然mov eax, [eax+8]會得到第三個參數等等:第一個參數可以被打印出來。

您不能使用print_string在寄存器中打印單個字符(如AL)。 EAX必須是指向NUL(\ 0)終止字符串的指針。


別的東西,你可以做的是使用scaled index addressing步驟通過一個數組(如你的論點):

mov ebx, dword [ebp+12] 
xor esi, esi   ; Index of first argument (index=0) 
mov eax, [ebx+esi*4] ; EAX = pointer to 1st argument 
call print_string 
inc esi     ; Next argument (index=1) 
mov eax, [ebx+esi*4] ; EAX = pointer to 2nd argument 
call print_string 
inc esi     ; Next argument (index=2) 
mov eax, [ebx+esi*4] ; EAX = pointer to 3rd argument 
call print_string 

有了這樣的想法,你可能可以看到如何創建一個循環,通過雲參數。我把它作爲讀者的練習。這是尋址模式的另一個方便的quick reference

+1

謝謝!我正試圖直接跳到'ebp + 16',現在我可以看到它是錯誤的。另外,我並不知道'print_string'不能用於打印AL。非常感謝! – Sally

+0

是的,我看到了。你只需先取消引用[ebp + 12],然後再添加4.你知道必須添加4才能進入下一個元素。你只需要有正確的指針開始。 –

+1

@Sally我已經添加了一段關於使用縮放索引尋址的內容,您稍後可能會發現它很有用。 –