Calling printf in x86_64 using GNU assembler

后端 未结 2 2201
攒了一身酷
攒了一身酷 2020-11-27 06:29

I\'ve written a program using AT&T syntax for use with GNU assembler:

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

            .text
            .glob         


        
2条回答
  •  鱼传尺愫
    2020-11-27 06:55

    You can look at assembly code generated from an equivalent c file.
    Running gcc -o - -S -fno-asynchronous-unwind-tables test.c with test.c

    #include 
    int main() {
       return printf("%d\n", 1);
    }
    

    This output the assembly code:

            .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
    

    This give you a sample of an assembly code calling printf that you can then modify.


    Comparing with your code, you should modify 2 things:

    • %rdi should point to the format, you should not unreferenced %rbx, this could be done with mov $format, %rdi
    • printf has a variable number of arguments, then you should add mov $0, %eax

    Applying these modifications will give something like :

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

    And then running it print :

    1

提交回复
热议问题