汇编语言为C等价物

时间:2013-12-11 14:06:21

标签: c assembly low-level

我试图找到与下面的汇编块相当的C语言:

        .section .text
        .globl mystery
        .type mystery, @function
    mystery:
        pushl %ebp
        movl %esp, %ebp
        xorl %eax, %eax
        xorl %exc, %ecx
        movl 8(%ebp), %edx

    begin:
        cmpl 12(%ebp), %ecx
        jge  done
        addl (%edx, %ecx, 4), %eax
        incl %ecx
        jump begin

    done:
        movl %ebp, %esp
        popl %ebp
        ret

我得到了“开始”部分。它似乎是一个循环,从函数中获取参数并将其与%ecx中的任何内容进行比较。如果满足jge条件,则函数返回,否则它将%edx加上4%ecx,将其移至%eax,递增%ecx,然后再循环。

我真的不明白“神秘”部分。特别是xorls和movl语句。如果%eax或%ecx中没有任何内容可以启动,那么xorl正在做什么。我猜测的movl是从函数中取一个参数并将其移动到%edx?

任何见解都是有帮助和赞赏的。

3 个答案:

答案 0 :(得分:6)

该函数使用cdecl参数传递。编译时的C语言为_mystery

int __attribute__((cdecl)) mystery(int * array, int length) {
    // save the rpevious function stack
    // pushl %ebp
    // movl %esp, %ebp

    // xorl %eax, %eax
    int eax = 0;
    // xorl %exc, %ecx
    int ecx = 0;

    // cmpl 12(%ebp), %ecx
    // jge  done
    while (length > ecx) {
        // addl (%edx, %ecx, 4), %eax
        eax += array[ecx];
        // incl %ecx
        ecx++;
        // jump begin
    }

    // restorre previous stack frame
    // movl %ebp, %esp
    // popl %ebp

    // ret
    return eax;
}

该函数计算整数数组的总和。

答案 1 :(得分:2)

这种汇编语言看起来像是一个简单的C程序的反汇编。

mystery:
    % The next two instructions set up the stack frame. %ebp is saved on the 
    % stack to preserve its value. Then %ebp is set to the value in %esp (the 
    % current stack ptr) to establish the stack frame for this function.
    % See http://en.wikibooks.org/wiki/X86_Disassembly/Functions_and_Stack_Frames
    % for details on stack frames.
    pushl %ebp
    movl %esp, %ebp

    % XOR anything with itself zeroes it out since
    % 1 xor 1 is 0, and 0 xor 0 is 0.
    % So the following two instructions clear %eax and %ecx
    xorl %eax, %eax
    xorl %ecx, %ecx     % (note the typo fix :))

    % The following instruction assumes there's a parameter passed from the 
    % caller that's on the stack. It is moving that parameter into %edx
    movl 8(%ebp), %edx
begin:
    ...

答案 2 :(得分:1)

xorl %eax, %eax这是重置寄存器的标准方法(将其值设置为0)。无论寄存器具有什么值,相同的两个值(位值)之间的XOR都为0.

相关问题