【问题标题】:Creating and calling function in x86 assembly (AT&T syntax)在 x86 程序集中创建和调用函数(AT&T 语法)
【发布时间】:2012-09-03 14:32:45
【问题描述】:

请给我一个创建一个函数并在 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

【问题讨论】:

    标签: assembly x86 gnu-assembler att


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2013-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多