2013-12-11 3 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 

본인은 "시작"GET 절을 참조하십시오. 그것은 함수에서 매개 변수를 취하는 루프처럼 보이고 % ecx에있는 것과 비교합니다. jge 조건이 충족되면 함수가 반환되고, 그렇지 않으면 % edx를 4 % ecx만큼 추가하고, % eax로 이동하고, % ecx를 증가시키고, 다시 반복합니다.

나는 "신비"부분을 정말로 이해하지 못합니다. 특히 xorls 및 movl 문 % eax 나 % ecx에 아무것도 나타나지 않으면, xorl이하는 일은 무엇입니까? 내가 추측하고있는 movl은 함수에서 매개 변수를 가져 와서 % edx로 옮기는 것입니다.

모든 통찰력이 도움이되고 감사합니다.

+0

이 코드를 어디에서 찾을 수 있습니까? – unwind

+1

@unwind 나는 숙제를 냄새 맡는다. –

+1

무언가를 배타적으로 의미하는 것은 0으로 설정한다는 의미입니다. – 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; 합계 = 0; for (i = 0; i <길이; i ++) sum + = array [i]; return sum;':) – 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: 
    ...