Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/assembly/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Assembly 在x86汇编中创建和调用函数(AT&;T语法)_Assembly_X86_Gnu Assembler_Att - Fatal编程技术网

Assembly 在x86汇编中创建和调用函数(AT&;T语法)

Assembly 在x86汇编中创建和调用函数(AT&;T语法),assembly,x86,gnu-assembler,att,Assembly,X86,Gnu Assembler,Att,请给我一个非常简单的例子,说明如何创建一个函数并用x86汇编(AT&T语法)调用它。实际上,我正在尝试创建一个计算一个数的阶乘的函数。这就是我所做的: #include<syscall.h> #include<asm/unistd.h> # Calculates Factorial, Argument is passed through stack .text .global _start _start: pushl $5 #factorial of

请给我一个非常简单的例子,说明如何创建一个函数并用x86汇编(AT&T语法)调用它。实际上,我正在尝试创建一个计算一个数的
阶乘的函数。这就是我所做的:

#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
#包括
#包括
#计算阶乘,参数通过堆栈传递
.文本
.全球启动
_开始:
pushl$5#将计算该值的阶乘
所谓事实
movl%eax,%ebx#eax包含结果,结果是程序的返回值
movl$1,%eax
整型$0x80
ret
事实:
popl%ebx#返回地址
popl%edx
movl$1,%ecx#将用作计数器
movl$1,%eax#结果(部分和完整)将存储在此处
循环:
mul%ecx
公司%ecx
cmp%ecx,%edx
jle环路
按%ebx#还原返回地址
ret

我一次又一次地遇到分段错误。我正在
Ubuntu
上使用GAS

您的代码不应该崩溃。确保组装和链接为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 $?