Search code examples
cassemblyattx86

Given Assembly, translate to C


I am originally given the function prototype:

void decode1(int *xp, int *yp, int *zp)

now i am told to convert the following assembly into C code:

movl 8(%ebp), %edi //line 1 ;; gets xp
movl 12(%ebp), %edx //line 2 ;; gets yp
movl 16(%ebp),%ecx //line 3 ;; gets zp
movl (%edx), %ebx //line 4 ;; gets y
movl (%ecx), %esi //line 5 ;; gets z
movl (%edi), %eax //line 6 ;; gets x
movl %eax, (%edx) //line 7 ;; stores x into yp
movl %ebx, (%ecx) //line 8 ;; stores y into zp
movl %esi, (%edi) //line 9 ;; stores z into xp

These comments were not given to me in the problem this is what I believe they are doing but am not 100% sure.

My question is, for lines 4-6, am I able to assume that the command

movl (%edx), %ebx 
movl (%ecx), %esi
movl (%edi), %eax

just creates a local variables to y,z,x?

also, do the registers that each variable get stored in i.e (edi,edx,ecx) matter or can I use any register in any order to take the pointers off of the stack?

C code:

int tx = *xp;
int ty = *yp;
int tz = *zp;
*yp = tx;
*zp = ty;
*xp = tz;

If I wasn't given the function prototype how would I tell what type of return type is used?


Solution

  • Let's focus on a simpler set of instructions.

    First:

    movl 8(%ebp), %edi
    

    will load into the EDI register the content of the 4 bytes that are situated on memory at 8 eight bytes beyond the address set in the EBP register. This special EBP usage is a convention followed by the compiler code generator, that per each function, saves the stack pointer ESP into the EBP registers, and then creates a stack frame for the function local variables.

    Now, in the EDI register, we have the first parameter passed to the function, that is a pointer to an integer, so EDI contains now the address of that integer, but not the integer itself.

    movl (%edi), %eax
    

    will get the 4 bytes pointed by the EDI register and load them into the EAX register.

    Now in EAX we have the value of the integer pointed by the xp in the first parameter.

    And then:

    movl %eax, (%edx)
    

    will save this integer value into the memory pointed by the content of the EDX register which was in turn loaded from EBP+12 which is the second parameter passed to the function.

    So, your first question, is this assembly code equivalent to this?

    int tx = *xp;
    int ty = *yp;
    int tz = *zp;
    *yp = tx;
    *zp = ty;
    *xp = tz;
    

    is, yes, but note that there are no tx,ty,tz local variables created, but just processor registers.

    And your second question, is no, you can't tell the type of return, it is, again, a convention on the register usage that you can't infer just by looking at the generated assembly code.