简体   繁体   中英

Reverse engineering C codes with GCC -march=i686

Here're my C codes:

int test(int x, int y){
    int val=4*x;
    if (y>0){
        if (x<y) val=x-y;
        else val=x^y;
    }
    else if (y<-2) val=x+y;
    return val;
}

And here're what I entered in the GCC command line:

gcc -O1 -S -march=i686 test.c

And here is the S file I got (only the calculation part):

pushl   %ebx
movl    8(%esp), %ecx
movl    12(%esp), %edx
testl   %edx, %edx
jle     L2
movl    %ecx, %eax
subl    %edx, %eax
movl    %edx, %ebx
xorl    %ecx, %ebx
cmpl    %edx, %ecx
cmovge  %ebx, %eax
jmp     L4

L2:
leal    0(,%ecx,4), %eax
addl    %edx, %ecx
cmpl    $-2, %edx
cmovl   %ecx, %eax

L4:
popl    %ebx
ret

My question is: can I get back exactly the same C codes using the S file above? I mean EXACTLY the same. For example can I determine the default value of val is 4*x (line #2 of C codes)? Can I determine the test-expression of each if statement?

I really need your help. Thank you!!!

In this case, you can find out that the each registers corresponding to a variable:

  • %eax - var
  • %ebx - a contextual temporary variable
  • %ecx - x
  • %edx - y

If you mean 'exactly' for the identifiers, it is only possible when a special structure named 'symbol table'. (compiled with -g flag in GCC)

Anyway, you should know a code can be always optimized by the compiler. It means, in this case, your code is changed to another having same mathematical meaning. If your code is backward-translated, it should be like this.

int test(int x, int y) {
    int val;
    if (y > 0) {
        if (x < y)
            val = x - y;
        else
            val = x ^ y;
    } else {
        if (y < -2)
            val = x + y;
        else
            val = 4 * x;
    }
    return val;
}

If you want no optimization, use flag -O0 instead of -O1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM