0

I have the following code:

.global _start 
.data 
i : .space 10, 0
format: .asciz "%d \n"
.text
_start:
jmp test1
loop1:
movq $i, %rsi
incq (%rsi)    
movq (%rsi),%rax
pushq %rax
pushq %rcx
movq $format,%rdi
movq %rax,%rsi
xorq %rax,%rax
call printf
popq %rcx
popq %rax
test1:
movq $i, %r8
movq (%r8), %r9
cmp $8, %r9
jl loop1
movq $0, %rdi
movq $60, %rax
syscall

It prints 8 digits starting from 1 to 8 each in a new line, but when I try to print them all in one line by changing the format like this: format: .asciz "%d", it prints nothing. Is there any idea why it happens?

Azer
  • 1
  • 2
    You need to call a flush function or output a linebreak in order to make `printf` flush its buffers. It should also work to call `exit` instead of using a syscall. – ecm Mar 27 '22 at 12:46
  • https://stackoverflow.com/questions/1716296/why-does-printf-not-flush-after-the-call-unless-a-newline-is-in-the-format-strin – ecm Mar 27 '22 at 12:47
  • https://stackoverflow.com/questions/36032305/why-is-this-simple-code-working-with-exit-and-is-not-working-with-exit – ecm Mar 27 '22 at 12:50
  • https://stackoverflow.com/questions/8502945/printf-without-newline-in-assembly – ecm Mar 27 '22 at 12:52
  • 2
    I'm not sure if this code makes sense because it's skipping all the initialization for calling from the C library. It might or might not work depending on how the C library is implemented on your platform. – xiver77 Mar 27 '22 at 12:59
  • 2
    @xiver77: if it was actually skipped, printf would crash. Glibc on Linux uses dynamic linker hooks to get itself initialized before `_start` in a *dynamically* linked executable. Some people consider it bad to rely on this, and say you should only ever use libc functions from main, or after manually calling the init functions in your own _start. I agree as far as it being important to understand why it works, and that `gcc -static -nostartfiles foo.s` would crash while `gcc -nostartfiles -no-pie foo.s` doesn't. (This code uses 32-bit absolute instead of RIP-relative LEA, so can't be PIE) – Peter Cordes Mar 27 '22 at 16:23

0 Answers0