Call printf on x86_64 using GNU assembler

I wrote a program using AT & T syntax for use with the GNU assembler:

            .data
format:   .ascii "%d\n"  

            .text
            .global main  
main:
            mov    $format, %rbx
            mov    (%rbx), %rdi
            mov    $1, %rsi
            call     printf
            ret

I use GCC to build and communicate with:

gcc -o main main.s

I run it with this command:

./home

When I run the program, I get a seg error. Using gdb, he says he was printfnot found. I tried ".extern printf" which does not work. Someone suggested I keep the stack pointer before the call printfand restore to RET, how can I do this?

+4
source share
2 answers

. 64- Linux System V ABI . , CALL 16 ( 32 ):

16 (32, __m256 ).

, C runtime main, 8, CALL. 16- , PUSH , POP - .

, RAX , :

% rax , ,

printf - , RAX. , RAX 0.

$format, . :

mov  $format, %rbx
mov  (%rbx), %rdi 

RBX. 8 RBX RDI. RDI , . :

lea  format(%rip), %rdi

RIP, :

mov $format, %rdi

NUL . .ascii .asciz x86.

:

# global data  #
    .data
format: .asciz "%d\n"
.text
    .global main
main:
  push %rbx
  lea  format(%rip), %rdi
  mov  $1, %esi           # Writing to ESI zero extends to RSI.
  xor %eax, %eax          # Writing to EAX zero extends to RAX.
  call printf
  pop %rbx
  ret

/

64- Linux ABI, , , . :

enter image description here

, Yes - , , . main C.


/, , , , .rodata .section .rodata, .data


64- : -, 32- , 64- . .

+16

, c.
gcc -o - -S -fno-asynchronous-unwind-tables test.c test.c

#include <stdio.h>
int main() {
   return printf("%d\n", 1);
}

:

        .file   "test.c"
        .section        .rodata
.LC0:
        .string "%d\n"
        .text
        .globl  main
        .type   main, @function
main:
        pushq   %rbp
        movq    %rsp, %rbp
        movl    $1, %esi
        movl    $.LC0, %edi
        movl    $0, %eax
        call    printf
        popq    %rbp
        ret
        .size   main, .-main
        .ident  "GCC: (GNU) 6.1.1 20160602"
        .section        .note.GNU-stack,"",@progbits

, printf, .


, 2 :

  • % rdi , % rbx, mov $format, %rdi
  • printf , mov $0, %eax

- :

    .data
format: .ascii "%d\n"  
.text
    .global main  
main:
  mov  $format, %rdi
  mov  $1, %rsi
  mov  $0, %eax
  call printf
  ret

:

1

+3

All Articles