How to make it work in x86-64 assembly?

ぃ、小莉子 提交于 2019-12-12 02:06:43

问题


Recently I'm learning assembly and now i have some confusion. I learned it from Professional Assembly language.

My System's arch:

#uname -m
x86_64

This is my code:

.section .data
output:
   .asciz "This is section %d\n"
.section .text
.globl _start
_start:
    pushq $1
    pushq $output
    call printf
    addq $8, %rsp
    call overhere
    pushq $3
    pushq $output
    call printf
    addq $8, %rsp
    pushq $0
    call exit
overhere:
    pushq %rbp
    movq %rsp, %rbp
    pushq $2
    pushq $output
    call printf
    addq $8, %rsp
    movq %rbp, %rsp
    popq %rbp
    ret 

I assemble, link and run it like this, getting the error message shown:

#as -o calltest.o calltest.s
#ld -dynamic-linker /lib64/ld-linux-x86-64.so.2 -lc -o calltest calltest.o
#./calltest 
Segmentation fault

How do I make it work?


回答1:


x86_64 has another kind of passing arguments, see: http://en.wikipedia.org/wiki/X86_calling_conventions#System_V_AMD64_ABI

This is how your example would work:

.section .data
output:
   .asciz "This is section %d\n"
.section .text
.globl _start
_start:
    movq $output, %rdi      # 1st argument
    movq $1, %rsi           # 2nd argument
    xorl %eax, %eax         # no floating point arguments
    call printf
    call overhere
    movq $output, %rdi      # 1st argument
    movq $3, %rsi           # 2nd argument
    xorl %eax, %eax         # no floating point arguments
    call printf
    xor %edi, %edi
    call exit
overhere:
    pushq %rbp
    movq %rsp, %rbp
    movq $output, %rdi      # 1st argument
    movq $2, %rsi           # 2nd argument
    xorl %eax, %eax         # no floating point arguments
    call printf
    movq %rbp, %rsp
    popq %rbp
    ret


来源:https://stackoverflow.com/questions/25401047/how-to-make-it-work-in-x86-64-assembly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!