Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
734 views
in Technique[技术] by (71.8m points)

x86 64 - Calling C function from x64 assembly with registers instead of stack

This answer puzzled me.

According to the standard C calling conventions, the standard way to call C functions is to push arguments to the stack and to call the subroutine. That is clearly different from syscalls, where you set different registers with appropriate arguments and then syscall.

However, the answer mentioned above gives this GAS code:

        .global main
        .section .data
hello:  .asciz "Hello
"
        .section .text
main:
        movq $hello, %rdi
        movq $0, %rax
        call printf
        movq $0, %rax
        ret

which works with gcc hello.s -o hello. The part that calls printf is:

        movq $hello, %rdi
        movq $0, %rax
        call printf

It is using the rdi register, not the stack, to pass the argument to printf. Changing the above to

        push $hello
        call printf

causes segmentation fault.

Since printf is a C function, unlike sys_write, I think the arguments should be passed to the stack, not the registers. What am I misunderstanding here? What about other standard C functions, such as malloc?

(Any reference would be truly appreciated.)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Passing arguments to variadic functions is more complicated. See x86-64 ELF ABI, section 3.5.7. Otherwise, x86-64 passes its first 6 arguments using registers: %rdi, %rsi, %rdx, %rcx, %r8, %r9 (excluding float / vector arguments).

From the specification, %rax = 0 means that the variable argument list has no (0) floating-point arguments passed in vector registers. Your approach is wrong, as the first argument (e.g., the nul-terminated string: "Hello ") must be passed in %rdi, and %rax must be zero when the function is called.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...