1

请给我一个非常简单的例子来创建一个函数并在 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一次又一次地收到错误。我正在使用GASUbuntu

4

1 回答 1

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 $?
于 2012-09-03T15:25:12.797 回答