Author Topic: how to printf from xmm0  (Read 10329 times)

Offline markallyn

  • Jr. Member
  • *
  • Posts: 10
how to printf from xmm0
« on: March 06, 2017, 05:37:37 PM »
Hello everyone,

As a newcomer to 64-bit linux (ubuntu) I'm having a problem trying to print a double using printf.  In this little program I first call the c math library log function and then try to print the results with printf.  As follows:

Quote
extern   printf
extern   log
extern   exit

section .data
;align   16
   s db "%.4Lf",13,10,0
   x dq 45.3
section   .bss
   result  resq   1

section .text
_start:
   sub   rsp, 8
   movq   xmm0,

   call   log
   movsd   [rsi], xmm0
   mov    rdi, s
   mov   rax, 0
   call    printf
   add   rsp, 8
   mov   rdi, 0
   call    exit

If, as in the above, I try to print from the contents of rsi  I get a seg fault.  If I change rst to rsp and print from the contents of rsp I get zeroes.  I've also tried to print directly from the call assuming that xmm0 now contains the results of the log calculation, setting rax to 1 instead of zero.  That doesn't work either.

For some reason, the quoted material is split after the movq instruction so that the operands are incomplete.  Can't figure out why.  Anyway, the correct line should be
     
       movq  xmm0,


No doubt someone can explain how to fix what must surely be a simple bug. 

Thanks,
Mark Allyn

Offline markallyn

  • Jr. Member
  • *
  • Posts: 10
Re: how to printf from xmm0
« Reply #1 on: March 06, 2017, 06:58:49 PM »
Hello everyone,

Well, I "fixed" the problem by removing the sub/add rsp,8 instruction.  Then, if I simply use xmm0 directly into the printf call and also loading the format (s) into rdi, the program runs as expected.  The new code is as follows:

Code: [Select]
global _start
extern printf
extern log
extern exit

section .data
;align 16
s db "%f",13,10,0
x dq 45.3
section .bss
result  resq 1

section .text
_start:
movq xmm0, [x]
call log
mov rdi, s
mov rax, 1
call printf
mov rdi, 0
call exit

So, what I don't understand AT ALL is what purpose the sub/ rsp pair serves.  Could someone kindly explain when the stack has to be aligned before a function call, and by how many bytes?

Thanks much.

Mark Allyn