0

I'm doing the challenges here.

I'm at the exercise called Mini #2: junior decompiler. Here, I have to look at some assembly, and then translate it to a c function. The assembly looks like this:

Assembly (x86-64)
0x00:  push   rbp
0x01:  mov    rbp,rsp
0x04:  mov    DWORD PTR [rbp-0x4],edi
0x07:  mov    DWORD PTR [rbp-0x8],esi
0x0a:  mov    eax,DWORD PTR [rbp-0x4]
0x0d:  cmp    eax,DWORD PTR [rbp-0x8]
0x10:  jl     17 <foo+0x17>
0x12:  mov    eax,DWORD PTR [rbp-0x4]
0x15:  jmp    1a <foo+0x1a>
0x17:  mov    eax,DWORD PTR [rbp-0x8]
0x1a:  pop    rbp
0x1b:  ret

So the lines: 0x04: mov DWORD PTR [rbp-0x4],edi 0x07: mov DWORD PTR [rbp-0x8],esi I'm pretty confident correspond to two arguments. then comes and if statement with il, which decides how the function ends. My own translation is something like this:

int foo(int a, int b) {
int c = a;
if (c > a){
    c = a;
} else {
    c = b;
}
return c;
}

Because it looks to me like all the function is doing is, comparing two inputs, and returning the larger one, storing the larger one in eax.

The online code checker tells me I am wrong though. Where am I probably going wrong?

Grazosi
  • 603
  • 1
  • 10
  • 3
    After `int c = a;` you do `if (c > a)` which compares `a` against itself. But that's not what the assembly does. – Raymond Chen Feb 25 '22 at 22:07
  • You invented another variable `int c = a;` for one arg but not the other. If you actually wrote `int c = a;` and compiled a debug build like this is doing, the compile would spill the register args to stack space like it's already doing, and then reload and store one of them to a 3rd dword. [Why does clang produce inefficient asm with -O0 (for this simple floating point sum)?](https://stackoverflow.com/q/53366394). Also try it yourself: https://godbolt.org/z/vnj6T6Tqa / [How to remove "noise" from GCC/clang assembly output?](https://stackoverflow.com/q/38552116) – Peter Cordes Feb 26 '22 at 00:24

1 Answers1

1

I don't know how picky your checker is, but storage below rbp is for local variables, so it is copying the formal parameters into local variable memory.

Also, you're comparing the first parameter value with itself, so doing a > a.

Further, you are right that the relation should be negated for bringing that to C but the opposite of < is >=.

Erik Eidt
  • 23,049
  • 2
  • 29
  • 53