问题
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
回答1:
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
来源:https://stackoverflow.com/questions/31143237/printing-a-number-in-assembly-nasm-using-printf