【问题标题】:Assembly Language to C equivalent汇编语言到 C 等价物
【发布时间】:2013-12-29 13:13:33
【问题描述】:

我正在尝试找到与以下程序集等效的 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?

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

【问题讨论】:

  • 你在哪里找到这个代码?
  • @unwind 我闻到了作业的味道。
  • 单独异或意味着将其设置为零。
  • %exc 是 %ecx,不是吗?

标签: c assembly low-level


【解决方案1】:

该函数使用 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;
}

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

【讨论】:

  • 或者更现实地说,程序集来自一个 C 函数,其主体是:int i, sum; sum = 0; for (i = 0; i < length; i++ ) sum += array[i]; return sum; :)
  • @mbratch 是的,可能,但我想保持与寄存器相同的命名,以显示它们如何相互转换
【解决方案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:
    ...

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多