assemblyprintingnasm

How to print in NASM assembly


i've made a simple print function in assembly which does not work as intended.

The function should print only the msg variable but instead its printing all the variables declared

this is the code

SECTION .data
msg db "This is our first message!", 0Ah
msg2 db "Test message", 0Ah
msg3 db "idk what to type here", 0Ah

SECTION .text
global _start

_start:
    mov rsi, msg
    call print

    mov rax, 60 ; return 0 and end this operation
    mov rdi, 0
    syscall



print:
    ; the only argument will be the buffer.
    ; rsi is the buffer in the sys call
    push rax
    push rdi
    push rsi ; makes sure all the registry we use will be saved and restored once finished.
    mov rax, 1
    mov rdi, 1 

    push rdx
    mov rdx, rsi
    call str_len

    syscall
    pop rax
    pop rdi
    pop rsi
    pop rdx ; after restoring we return to the main
    ret
    

str_len:
    ; the argument for this will be rdx being the first address
    push rsi
    mov rdx, rsi ; they both need to be the same address so we can calculate the size


can_continue:
    cmp byte[rsi], 0
    jz ended
    add rsi, 1
    jmp can_continue

ended:
    sub rsi, rdx
    mov rdx, rsi
    pop rsi
    ret

output: This is our first message! Test message idk what to type here

im new to assembly and im following this https://asmtutor.com/#lesson1


Solution

  • The newline character is not considered the end of the string. Your current implementation of str_len only stops when it encounters a null character (0), but does not consider the carriage return character (0Ah) to be the end of the string.

    You'll need to change this part:

    msg db “This is our first message!”, 0Ah
    msg2 db “Test message”, 0Ah
    msg3 db “idk what to type here”, 0Ah
    

    By this:

    msg db "This is our first message!", 0Ah, 0
    msg2 db "Test message", 0Ah, 0
    msg3 db "idk what to type here", 0Ah, 0
    

    Ps: It is very important to specify in your header which type of elf version you are using (x64, x32, x86). You can do this with

    BITS
    

    (I used BITS 64)

    And compile your program with:

    $ nasm -f elf64 -o hello.o hello.asm
    $ ld -o hello hello.o 
    $ ./hello
    This is our first message!