0
votes

I'm just starting with assembly, I got some basic stuff down like puts and strlen but some of the concepts don't make sense.

I'm trying to implement a basic loop and print the counter at every iteration. Here is my code so far:

%include 'functions.asm' ;contains print and exit


section .data
    msg db 'loop', 0x0a, 0x00

section .bss

section .text
    global _start

_start:
    mov ecx, 0

repeat:
    cmp ecx, 10
    jz done
    push ecx         ;line 18
    mov ecx, msg     ;line 19
    call print
    pop ecx          ;line 21
    inc ecx
    jmp repeat

done:
    call exit

This works. But the output is 'loop\n' n times. I'm trying to get '0\n1\n2\n3\n....n\n'.

So far this is what I tried: - remove the lines 18, 19 and 21. Segfaults, not sure why. - replace line 19 with add ecx, '0'. Segfault as well.

Also, I'm not sure why cmp works. Should't I compare the value in the register with cmp byte[ecx], 10 instead of the register itself ? Same with inc, it increases the value contained in ecx ? So if I do inc [ecx], 1, it's going to increase the value at the address contained inside ecx ? So xor ecx, ecx, inc [ecx], 1 should increase the value at memory address 0x00000000 by 1 ?

1

1 Answers

1
votes

Apparently you have some custom print function that prints a string pointed to by ecx. You might have print_int or similar function that you can use directly. If not, then you were on the right track by adding '0' however you need to place your string into memory and pass a pointer to it. One possible solution:

%include 'functions.asm' ;contains print and exit

section .data
    msg db '#', 0x0a, 0x00  ; the # is a placeholder for the digit

section .text
    global _start

_start:
    mov ecx, 0

repeat:
    cmp ecx, 10
    je done
    push ecx
    add cl, '0'
    mov [msg], cl
    mov ecx, msg
    call print
    pop ecx          ;line 21
    inc ecx
    jmp repeat

done:
    call exit

Arguably simpler version that uses the text for counting:

%include 'functions.asm' ;contains print and exit

section .data
    msg db '0', 0x0a, 0x00

section .text
    global _start

_start:
    mov ecx, msg
repeat:
    call print
    inc byte [msg]
    cmp byte [msg], '9'
    jbe repeat

done:
    call exit

As for your other question, yes, [] means memory reference so don't use that if you want to operate on the register directly.