Search code examples
cassemblylow-level

Assembly Language to C equivalent


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.


Solution

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