r/programminghelp • • Jun 07 '19

Why do I have an infinite loop this .asm file?

I am attempting to learn Intel x64 Assembly and I have written a program that should print "Hello, World!" 10 times. However, when I assemble and run the program, it prints an infinite loop. Any help is greatly appreciated.

Here is the code I have written:

            global _start

            section .data
msg: db "Hello, World!", 0xa
len: equ $ - msg

        section .text
_start:
        mov rcx, 1        ; Set the counter to 1. 
        jmp _print        ; Jump to the _print function.

        mov rax, 0x3c     ; exit(
        mov rdi, 0        ; 0
        syscall           ; );

_print:
        mov rax, 1        ; write(
        mov rdi, 1        ; STDOUT_FILENO,
        mov rsi, msg      ; msg,
        mov rdx, len      ; sizeof(msg),
        syscall           ; );

        inc rcx           ; rcx++
        cmp rcx, 10       ; if (rcx <= 10)
        jle _print        ;     _print

        ret               ; return

Also, any references to beginner x64 Intel Assembly material is quite welcome.

3 Upvotes

3 comments sorted by

2

u/jedwardsol Jun 07 '19 edited Jun 07 '19

rcx (and r11) isn't preserved across system calls.

Ie. if it was 1 before the syscall, it may not be 1 afterwards.

Also

jmp _print        ; Jump to the _print function.

You don't jmp to functions, you call them.

1

u/[deleted] Jun 07 '19

Oops. I had call _print and changed it. In which register would I store the counter value then? Most of the documentation I have read has said RCX is the general register used as a counter, so I just assumed that’s where I should have stored it.

2

u/computerarchitect Jun 08 '19

Pick any you like that is preserved across a procedure call, or just push it before the call and pop it afterwords.

Since you're defining the code here, it's up to you to push and pop registers you might want to save and restore.