从汇编中调用main

时间:2011-12-10 14:20:06

标签: c linux assembly x86-64

我正在编写一个小型库,用于在小型应用程序中代替libc。我已经阅读了主要libc替代方案的来源,但我无法让参数传递给Linux上的 x86_64 架构。

该库不需要_startmain之间的任何初始化步骤。由于libc及其替代方案确实使用了初始化步骤,并且我的汇编知识有限,我怀疑参数重新排序会给我带来麻烦。

这就是我所拥有的,其中包含受各种实现启发的程序集:

.text
.global _start

_start:
    /* Mark the outmost frame by clearing the frame pointer. */
    xorl %ebp, %ebp

    /* Pop the argument count of the stack and place it
     * in the first parameter-passing register. */
    popq %rdi

    /* Place the argument array in the second parameter-passing register. */
    movq %rsi, %rsp

    /* Align the stack at a 16-byte boundary. */
    andq $~15, %rsp

    /* Invoke main (defined by the host program). */
    call main

    /* Request process termination by the kernel. This
     * is x86 assembly but it works for now. */
    mov  %ebx, %eax
    mov  %eax, 1
    int  $80

入口点是普通的主要签名:int main(int argc, char* argv[])。此特定项目不需要环境变量等。

AMD64 ABI说rdi应该用作第一个参数,rsi用于第二个参数。

如何在Linux x86_64上正确设置堆栈并将参数传递给main?谢谢!

参考文献:
http://www.eglibc.org/cgi-bin/viewvc.cgi/trunk/libc/sysdeps/x86_64/elf/start.S?view=markup
http://git.uclibc.org/uClibc/tree/libc/sysdeps/linux/x86_64/crt1.S

2 个答案:

答案 0 :(得分:1)

我认为你有

 /* Place the argument array in the second parameter-passing register. */
    movq %rsi, %rsp

错误。它应该是

movq %rsp, %rsi      # move argv to rsi, the second parameter in x86_64 abi

答案 1 :(得分:0)

crt0.o调用

main;另见this question

内核正在execve文档中指定的ABI之后设置初始堆栈和进程环境(特定于体系结构); crt0(及相关)代码负责调用main