4

I am reading some linux assembly manuals and found idea about using printf() function. I need it to output register values for debugging reasons in binary form to terminal, but now I am tried simply to test that function with text.

I am stuck, because of segfault when I am using pushq instead of pushl. How can I change this program to output strings and binary form of registers?

.data
input_prompt:
    .string "Hello, world!"

printf_format:
    .string "%5d "

printf_newline:
    .string "\n"

size:
    .long 0

.text
.globl main
main:
    pushq $input_prompt
    call  printf

    movl  $0, %eax
    ret

It was compiled by GCC as:

gcc tmp.S -o tmp
ISE
  • 436
  • 2
  • 9
  • 21

1 Answers1

10

Linux (and Windows) x86-64 calling convention has the first few arguments not on the stack, but in registers instead

See http://www.x86-64.org/documentation/abi.pdf (page 20)

Specifically:

  1. If the class is MEMORY, pass the argument on the stack.
  2. If the class is INTEGER, the next available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8 and %r9 is used.
  3. If the class is SSE, the next available vector register is used, the registers are taken in the order from %xmm0 to %xmm7.
  4. If the class is SSEUP, the eightbyte is passed in the next available eightbyte chunk of the last used vector register.
  5. If the class is X87, X87UP or COMPLEX_X87, it is passed in memory.

The INTEGER class is anything that will fit in a general purpose register, so that's what you would use for string pointers as well.

Evan Teran
  • 87,561
  • 32
  • 179
  • 238
  • 3
    The [Windows x64 calling convention](http://msdn.microsoft.com/en-us/library/7kcdt6fy) does also pass some arguments in registers, but is not the same as the Linux calling convention (see the ["Parameter Passing"](http://msdn.microsoft.com/en-us/library/zthk2dkh.aspx) section in particular). – Matthew Slattery Jun 02 '12 at 00:34
  • And you must pass `eax = 1` to set the number of varargs, and align the stack: http://stackoverflow.com/questions/10324333/does-printf-require-additional-stack-space-on-the-x86-64 || http://stackoverflow.com/questions/14000351/x86-64-linux-assembly-why-printf-with-float-format-string-work-only-with-rsp – Ciro Santilli OurBigBook.com Jul 08 '15 at 14:26
  • @CiroSantilli六四事件法轮功包卓轩 : _EAX_ would be set to total number of vector registers used. If no vector registers are used (which is probably a more normal case) _EAX_ would be zero. So the value in _EAX_ depends on what you are passing as arguments. – Michael Petch Feb 13 '16 at 22:42