I am trying to make a simple assembly program that prints "Hey dude!" 3 times to the screen using the C puts() function. My code is as follows:
; ----------------------------------------------------------------------------------------
; This is an macOS console program that writes "Hey dude!" on one line and then exits.
; It uses puts from the C library. To assemble and run:
;
; To compile:
; nasm -fmacho64 Program.asm && gcc Program.o -o Program && ./Program
;
; Line by line:
; nasm -fmacho64 Program.asm # Generate Program.o
; gcc Program.o -o Program # Compile Program.o into an executable
; ./Program # Execute program
;
; ----------------------------------------------------------------------------------------
global _main
extern _puts
section .text
_main:
; Set up stack frame
push rbp
mov rbp, rsp
sub rsp, 24
push rbx ; Call stack must be aligned,
; not doing this leads to segmentation fault
xor rcx, rcx
mov rcx, 3 ; Loop 3 times
While:
cmp rcx, 0
je EndLoop
dec rcx
RCXDEC:
lea rdi, [rel message] ; First argument is address of message
call _puts ; puts(message)
jmp While
EndLoop:
pop rbx ; Fix up stack before returning
xor rax, rax ; Return 0
leave
ret
section .data
message: db "Hey dude!", 0 ; C strings need a zero byte at the end
However, it prints "Hey dude!" infinitely to the screen. Using lldb to debug it, I think I have found the source of the problem. Setting a breakpoint at RCXDEC, I allowed the loop to execute once. Reading the value of rcx, I see it is:
0x0000000000000002
As it should be, since rcx was 3 but was decremented once. The problem appears to occur on the second iteration of the loop. rcx is decremented again, but lldb says its value is now
0x00007fff988c63c7 libsystem_pthread.dylib`_thread + 71
Which would explain my problems. Letting the code run through more times does not change the value of rcx, even though it should be decrementing.
How do I fix this? All I want it to do is print 3 times.
My architecture is x86, and as you can see I am using NASM and GCC to compile.
I'm new to assembly and to stack overflow, so please tell me what I did wrong before down voting. Any and all help will be much appreciated.