Quaxton Hale
Quaxton Hale

Reputation: 2540

For loop in x86 assembly

I don't understand why I can use the ebx register and not the ecx register for this for loop.

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

I think call _printf is messing the ecx register and therefore causing the loop to go on indefinitely?

How would I preserve the ecx register so that it doesn't get affected by call _printf?

Upvotes: 0

Views: 1505

Answers (1)

Brendan
Brendan

Reputation: 37252

For 32-bit C calling conventions on 80x86; registers EAX, ECX and EDX are "caller saved". What this means is that any C function can trash those registers.

The remaining registers (EBX, ESI, EDI and EBP) are "callee saved" and can't be trashed by a C function.

If you want to use ECX instead of EBX; then you'd have to do something like this:

.next:
    push ecx         ;Save ECX

    push msg
    call _printf
    add esp,4       

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

Of course this is just makes the code less efficient.

Upvotes: 1

Related Questions