简体   繁体   中英

Printing a number in assembly NASM using printf

I've been trying to get this to print 12345 for a while now. Can anyone provide a hint as to what I should do? It will print the three lines of text, then on the fourth line prints "age", which I'm guessing is a remnant in the stack from line 2.

    bits 64
    global main
    extern printf

    section .text
main:
    ; function setup
    push    rbp
    mov     rbp, rsp
    sub     rsp, 32
    ;
    lea     rdi, [rel message]
    mov     al, 0
    call    printf
;above code correctly prints message

;where the issue lies
push rbp
mov rbp, rsp
;sub rsp, 32

mov rax, 12345
;push rax   
mov al,0
call printf


    ; function return
    mov     eax, 0
    add     rsp, 32
    pop     rbp
    ret

    section .data
message: db      'Lab 3 - Modified Hello program',0x0D,0x0a,'COSC2425 - Pentium assembly language',0x0D,0x0a,'Processed with NASM and GNU gcc',0x0D,0x0a
count   dq  12345

Apparently you don't even know how printf works which makes it hard to invoke it from assembly.

To print a number, printf expects two arguments, a format string and the number to print of course. Example: printf("%d\\n", 12345) .

Now to turn that into assembly, you obviously need to declare that format string, and then pass both arguments using the appropriate convention.

Since you seem to be using sysv abi, this means the first two arguments go into rdi and rsi , respectively. You already seem to know you have to zero al to indicate no SSE registers used. As such, the relevant part could look like:

lea rdi, [rel fmt]
mov rsi, 12345 ; or mov rsi, [count]
mov al, 0
call printf
...
fmt: db "%d", 0x0a, 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM