问题
I'm trying to write a printf
replacement in asm and so far have this code:
; string is loaded into r8
print_string:
push rax
push rbx
push rsi
push rdx
; load string pointer into ecx
mov rsi, r8
; loop over every char
print_string_loop0:
cmp sil, 0 ; stop when encounter null character
je print_string_return
mov rax, 1 ; syscall (sys_write)
mov rdi, 1 ; file descriptor for write (stdout = 1)
mov rdx, 1 ; bytes to write (1 character)
syscall
inc rsi
jmp print_string_loop0:
print_string_return:
pop rdx
pop rsi
pop rbx
pop rax
which works, but I always get some sort of garbage after the string that I print.
Heres the code that uses print_string
global _start
section .text
_start:
mov r8, string
call print_string
mov rax, 60 ; syscall (sys_exit)
mov rdi, 0 ; exit code
syscall
.section data
string:
db "Hell! Oh, World.", 10, 0 ; string, newline, null
print_string
is defined in the same file.
So why is garbage being printed after my string? The garbage is the same every time and if I modify the assembly at all, different garbage is output.
回答1:
You've got in R8
and thus in RSI
an address not a character. So change the break condition cmp sil, 0
to cmp byte [rsi], 0
.
来源:https://stackoverflow.com/questions/28668947/garbage-in-string-output-function