在x86程序集中创建和调用函数(AT& T语法)

时间:2012-09-03 14:32:46

标签: assembly x86 gas att

请给我一个非常简单的例子创建一个函数并在x86汇编中调用它(AT& T语法)。实际上我试图创建一个计算factorial的函数一个号码。这就是我所做的一切:

#include<syscall.h>
#include<asm/unistd.h>
# Calculates Factorial, Argument is passed through stack
.text
.global _start
_start:
    pushl $5       #factorial of this value will be calculated
    call Fact
    movl %eax, %ebx #eax contains the result, Result is the return val of the program
    movl $1, %eax
    int $0x80
    ret
Fact:
    popl %ebx     #Return address
    popl %edx
    movl $1, %ecx #Will be used as a counter
    movl $1, %eax #Result(Partial & complete) will be stored here
    LOOP:
        mul %ecx
        inc %ecx
        cmp %ecx, %edx
        jle LOOP
    pushl %ebx    #Restore the return address
    ret

我一次又一次地收到 Segmentation Fault 错误。我在Ubuntu上使用 GAS

1 个答案:

答案 0 :(得分:3)

您的代码不应该崩溃。确保组装并链接为32位:

as --32 -o x.o x.s
ld -melf_i386 -o x x.o

但是代码不正确。特别是:

  • 'mul%ecx'改变%edx
  • 'cmp'的参数必须颠倒

以下是更正后的版本:

        .text
        .global _start
_start:
        pushl $5
        call fact
        addl $4, %esp

        movl %eax, %ebx
        movl $1, %eax        # sys_exit
        int $0x80

fact:
        movl 4(%esp), %ecx
        movl $1, %eax
1:
        mul %ecx
        loop 1b
        ret

使用以下命令运行:

./x; echo $?