2013-12-11 70 views
0

我试图找到C-相当于组装以下块:汇编语言到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?

任何洞察力是有益的和赞赏。

+0

你从哪里找到这段代码? – unwind

+1

@unwind我闻到功课。 – 2013-12-11 14:10:23

+1

XORing本身意味着将其设置为零。 – Michael

回答

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; 
} 

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

+2

或者更现实的说,程序集来自一个C函数,它的主体是:'int i,sum; sum = 0; for(i = 0; i lurker

+3

@mbratch是的,可能,但我想保持与寄存器相同的命名,以显示它们如何互相转换 –

1

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

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: 
    ...