cassemblyprintfnasm

Using printf from c in Nasm causes the string to add random end line statment


this morning i tried to make a simple output library for my asm projects, i realized using the sys call each time is a waste of time and so i decided to automatize the program using printf function from c, so i tried to make a function with a little help from git hub forums and a bit of ai explaining me how asm works and i came up with this code.

SECTION .data
    endLine db 0Ah, 0
    integer_printf:     db  '%d',   10,0
    float_printf        db  '%f',   10,0
    string_format       db  '%s',   10,0

SECTION .text
    extern printf

printStr:
    ; mov rsi, string please put rsi to have the same value as your string variable (pointer)
    mov rdi,string_format ; mov rdi,printf_format
    call printf
    ret

%include '../script.asm'
%include '../funcio.asm'

extern printf

global main

section .data
    float_point     dq     70.232
    integer_value   dq     33      
    string_value    db     "Hello world!", 0

section .text

main:
    movsd xmm0, [float_point]
    call printFloat
    mov rsi, [integer_value]
    call printInt

    mov rsi, string_value
    call printStr
    call printStr
    call printStr
    call printStr
    call printStr

    mov rdi, 0
    call exit_program

This code is subdivided in two files and for some reason when i print the string hello world it will increase the number of new lines each time a new print function is called. those are the infos: expected output:

33
Hello world!
Hello world!
Hello world!
Hello world!
Hello world!

obtained output:

70.232000
33
Hello world!
Hello world!

Hello world!


Hello world!



Hello world!

thanks for any help in advice!


Solution

  • RSI and RDI are caller-saved in most calling conventions -- which means a function can use them at will without saving them (because the caller already did, if it cared about them). For the same reason you don't have to push them before using them and pop them after, other functions don't either, so you can't rely on those registers to retain their values.

    You'll need to reload them each time.

        ...
        mov rsi, string_value
        call printStr
        mov rsi, string_value
        call printStr
        mov rsi, string_value
        call printStr
        ...