2014-02-16 45 views
0

我不明白爲什麼我可以使用ebx寄存器而不是ecx寄存器for this for循環。在x86彙編中的循環

section .data 
msg: db "Hello World",10,0 
section .text 
    global _main 
    extern _printf 


_main: 

    mov ebx, 5 
    push ebx 

.next: 
    ;push dword msg 

    push msg 
    call _printf 
     add esp,4  
    sub ebx, 1 

    jne .next   



    add esp,4   
    mov eax,0   


    ret 

我覺得call _printf是搞亂ECX寄存器,因此導致循環無限期地進行下去?

我將如何保留ecx寄存器,使其不受call _printf的影響?

回答

1

對於80x86上的32位C調用約定;寄存器EAX,ECX和EDX是「呼叫者保存」的。這意味着任何C函數都可能會破壞這些寄存器。

其餘寄存器(EBX,ESI,EDI和EBP)是「被保存的」,不能被C函數刪除。

如果您想使用ECX而不是EBX;那麼你必須這樣做:

.next: 
    push ecx   ;Save ECX 

    push msg 
    call _printf 
    add esp,4  

    pop ecx   ;Restore ECX 
    sub ecx, 1 
    jne .next 

當然,這只是使代碼效率降低。