2013-12-11 71 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: 
    ...