Assembly Language to C equivalent

1.4k views Asked by At

I am trying to find the C-equivalent to the following chunk of assembly:

        .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

I get the "begin" section. It seems like a loop that takes on parameter from the function and compares it to whatever is in %ecx. If the jge condition is met, the function returns, if not it adds %edx by 4%ecx, moves it to %eax, increments %ecx, and loops through again.

I really do not understand the "mystery" part. Particularly the xorls and the movl statements. If nothing is in %eax or %ecx to start, what are teh xorl's doing. The movl I'm guessing is taking a parameter from the function and moving it to %edx?

Any insight is helpful and appreciated.

3

There are 3 answers

2
Sergey L. On BEST ANSWER

The function uses cdecl argument passing. The C mane when you compile this will be _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;
}

The function computes the sum over an array of integers.

0
bolov On

xorl %eax, %eax this is a standard way of resetting a register (setting it's value to 0). No matter what value the register has, XOR between the same two values (bit values) is 0.

0
lurker On

This assembly language already looks like a disassembly of a simple C program.

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