'Translating x86 to c. Simple if/else function
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?
Solution 1:[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 >=.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Erik Eidt |
