Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert x86 Assembly Jump Table to C

I have this x86 assembly code and I'm trying to convert it to C:

.GLOBAL calculate
calculate:
    pushl %ebp
    movl %esp,%ebp
    movl 12(%ebp),%eax
    movl 8(%ebp),%ecx
    cmpl $2,%ecx
    ja done
    jmp *operations(,%ecx,4)
operation1:
    imull %eax,%eax
    jmp done
operation2:
    negl %eax
    jmp done
operation3:
    addl $0x80,%eax
done:
    leave
    ret
operations:
    .long operation1, operation2, operation3

My question is about the jmp *operations(,%ecs,4) line. I think this is a switch statement and I know how it works in memory but how does this translate to C? Wouldn't I have to know what's on the stack at those locations in order to write a switch for it?

This is what I have:

int calculate(int a, int b)
{
    if (2 > a)
    {
        return b;
    }
    switch(a) {
        case /* ? */:
            b = (b * b);
            break;
        case /* ? */:
            b = (b * -1);
            break;
        case /* ? */:
            b = (b + 128);
            break;
    }
    return b;
}
like image 417
Benck Avatar asked Nov 21 '22 06:11

Benck


1 Answers

%ecx == 0 -> operations(,%ecx,4) == operations+0 and operation1 is there  
%ecx == 1 -> operations(,%ecx,4) == operations+4 and operation2 is there  
%ecx == 2 -> operations(,%ecx,4) == operations+8 and operation3 is there

As a result, the code should be

int calculate(int a, int b)
{
    if ((unsigned int)a > 2) /* ja is a comparation instruction for unsigned integers */
    {
        return b;
    }
    switch(a) {
        case 0:
            b = (b * b);
            break;
        case 1:
            b = (b * -1);
            break;
        case 2:
            b = (b + 128);
            break;
    }
    return b;
}
like image 171
MikeCAT Avatar answered Dec 08 '22 23:12

MikeCAT