Source code has if, for, while and switch. A binary has none of them. As the pipeline lesson showed, the compiler turns every one into compares and jumps, and a decompiler has to guess the original shape from where those jumps go. It usually guesses something correct that the author would not recognize.
This lesson takes each construct in turn and puts three things side by side: what the author wrote, what the compiler made of it, and what Ghidra gives back. The goal is that when a decompiled function looks strange, you can tell whether the program is strange or only its rendering.
This lesson's chall takes a number and runs it through five small functions, one for each construct we want to look at:
echo 7 | ./challNumber: rating: failsum: 28halvings: 2digits: 1apply: 4The download holds chall and its source. Import chall into Ghidra as in the last lesson if you want to follow along there. At the end we use what we have learned to find a number that makes it print one more line.
The first function sorts a score into three bands:
1const char *rate(int score)
2{
3 if (score >= 90)
4Here is the machine code for it:
objdump -d -M intel --no-show-raw-insn --disassemble=rate chall0000000000400486 <rate>: 400486: push rbp 400487: mov rbp,rsp 40048a: mov DWORD PTR [rbp-0x4],edi 40048d: cmp DWORD PTR [rbp-0x4],0x59 400491: jle 40049a <rate+0x14> 400493: mov eax,0x401210 400498: jmp 4004ac <rate+0x26> 40049a: cmp DWORD PTR [rbp-0x4],0x31 40049e: jle 4004a7 <rate+0x21> 4004a0: mov eax,0x401216 4004a5: jmp 4004ac <rate+0x26> 4004a7: mov eax,0x40121b 4004ac: pop rbp 4004ad: retEach if became a pair: a cmp that compares two values, and a conditional jump that acts on the result. Look at the first pair. The source asks whether score >= 90. The binary compares against 0x59, which is 89, and uses jle, jump if less or equal. The compiler flipped the question. It asks "is the score 89 or less?" and jumps away to the next test if so. Falling through, without jumping, is the case where the score is at least 90.
This is the normal pattern. A conditional jump skips over code, so the compiler tests for the opposite of what the programmer wrote. Ghidra then has to turn the jumps back into an if, and it does not know which way round the original was:
1char * rate(int param_1)
2{
3 char *pcVar1;
4
5This is the same function, and three things changed on the way:
score >= 90 is now param_1 < 0x5a, with the two branches swapped to match. 0x5a is 90, so Ghidra has at least undone the compiler's switch from 90 to 89.else if chain became nested if statements. The two are the same thing. C has no real else if; it is an if inside an else, and Ghidra shows it that way.return statements became one. The binary has a single exit, the pop rbp and ret at the bottom, and every branch jumps to it. Ghidra invents a variable, pcVar1, to carry the result there.None of this is a mistake. When you read a decompiled condition, do not expect it to match how a person would phrase it. Ask what has to be true to reach the block you care about, and work it out from there. Here, reaching "pass" needs param_1 < 0x5a to be true and param_1 < 0x32 to be false: a score from 50 to 89.
Convert to show it in decimal, or as a character. 0x5a and 0x32 are much easier to reason about as 90 and 50.A loop is a jump that goes backwards. That one fact is how every tool, and every reverse engineer, finds them.
for1int sum_to(int n)
2{
3 int total = 0;
4
5 Ghidra recovers this one almost exactly:
1int sum_to(int param_1)
2{
3 int local_10;
4 int local_c;
5
Only the names are missing. local_10 starts at 1, is compared with the parameter, and goes up by one each time round, so it is the counter. local_c starts at 0 and is added to, so it is the running total. Renaming them i and total, with L as in the last lesson, takes a few seconds and makes the function read like the source.
To see the loop as the binary has it, open Window > Function Graph with the cursor in sum_to:

The Function Graph cuts a function into blocks, runs of instructions with no jumps in or out of the middle, and draws an arrow for every jump. This function has four blocks. From the top: the setup, which zeroes the total and sets the counter to 1; the test, a CMP and a JLE; the body, with two ADD instructions; and the exit. The arrow running from the body back up to the test is the loop. Ghidra labels it for you.
When decompiled code is hard to follow, the graph is the place to look. Arrows that go back up are loops. A block with two arrows leaving it is a decision. The shape is often clear before you have read a single instruction.
while1int halvings(unsigned int n)
2{
3 int steps = 0;
4
51int halvings(uint param_1)
2{
3 uint local_1c;
4 int local_c;
5
The author wrote a while, and Ghidra shows a for. In the binary the two are the same: a test at the top, a body, and a jump back. Ghidra picks for when it can find something that looks like a start value and a step, and it found both here. Whether a loop was written as for or while is not recorded in the binary, so do not read anything into the choice.
Two smaller changes are worth noticing. n > 1 came back as 1 < local_1c, with the sides swapped. And n /= 2 came back as >> 1, a shift right by one bit. For unsigned numbers, shifting right by one is dividing by two, and it is faster, so the compiler made the swap. Compiler Idioms in Assembly 101 covers more substitutions like this.
do-while1int count_digits(unsigned int n)
2{
3 int digits = 0;
4
51int count_digits(uint param_1)
2{
3 uint local_1c;
4 int local_c;
5
This one keeps its shape. A do-while tests at the bottom, so the body always runs at least once, and that difference is real in the binary: there is no jump over the body on the way in.
So the question to ask of a decompiled loop is where the test sits:
| Test is at | The body runs | Ghidra shows it as |
|---|---|---|
| The top | Zero or more times | for or while |
| The bottom | At least once | do { } while |
switch1int apply(int op, int a, int b)
2{
3 switch (opIn our unoptimized chall, the compiler built this as a chain of comparisons, and Ghidra shows exactly that:
1uint apply(int param_1,uint param_2,uint param_3)
2{
3 if (param_1 It is ugly, but the giveaway is easy to spot once you know it: one variable compared against a run of small constants, with each match doing something different. When you see that, read it as a switch on that variable. The default case is whatever is left at the bottom. Note the 0xffffffff there. That is -1, printed as unsigned because Ghidra guessed the return type as uint.
Optimized code handles a switch differently. Build the program with -O2 and look at the top of the same function:
gcc -std=gnu17 -O2 -no-pie -o chall-O2 source.cobjdump -d -M intel --no-show-raw-insn --disassemble=apply chall-O2 | grep -A4 '<apply>:'0000000000400720 <apply>: 400720: cmp edi,0x5 400723: ja 400765 <apply+0x45> 400725: mov edi,edi 400727: jmp QWORD PTR [rdi*8+0x401288]There is one comparison where there was a long chain of them. cmp edi,0x5 and ja send anything above 5 to the default case. Everything else goes through a single jmp that reads its destination out of memory: [rdi*8+0x401288] means "take the entry numbered op from the list of addresses stored at 0x401288". That list is a jump table. It holds one code address per case, and the program jumps straight to the right one without testing the others.
Ghidra knows this pattern. It reads the table and gives the switch back:
1uint apply(undefined4 param_1,uint param_2,uint param_3)
2{
3 switch(param_1) {
4Here the optimized binary decompiles more cleanly than the unoptimized one, which is not what you might expect.
There is a third form. When every case only picks a value and does no other work, an optimizing compiler drops the code entirely and stores the values in an array, which it indexes with the switch variable. GCC names these arrays CSWTCH. If you meet CSWTCH_14[param_1] in a decompilation, a switch used to be there.
Unoptimized code keeps the structure of the source, because the compiler translates one statement at a time. With optimization on, it rearranges freely, and the decompiler shows the rearranged version. Three things in chall-O2 are typical.
Branches get merged. This is rate again:
1char * rate(int param_1)
2{
3 char *pcVar1;
4
5The compiler now assumes an answer first and corrects it afterwards, which saves a jump. Ghidra expresses that with an assignment inside the condition. Read it slowly, left to right: start with "great"; if the score is under 90, change that to "fail"; and if it is also over 49, change it to "pass". The result is the same three bands.
Loops get turned upside down. This is halvings:
1int halvings(uint param_1)
2{
3 int iVar1;
4
5 iVar1 = 0The while loop is now an if followed by a do-while. Compilers prefer the test at the bottom, since that needs one jump per trip instead of two, so they check once up front whether the loop should run at all and then loop with the test at the end. An if guarding a do-while on the same variable is a while loop. This also means the table above is a rule for unoptimized code only.
And goto appears. In chall-O2 the compiler copied sum_to into main, and part of the result looks like this:
1 if ((local_c[0] & 1) != 0) {
2 iVar4 = 2;The author wrote no goto. The compiler rewrote the loop to add two numbers per trip, with a special case for odd counts, and the jumps that result do not fit any combination of if and loops. When Ghidra cannot find a structure that fits, it stops trying and shows the jump as it is. A goto in decompiled code nearly always means this, and the Function Graph is the better view for such a function.
In all three cases the code is correct and the program does what the source says. Only the resemblance to the source is gone.
Run with the right number, chall prints an extra line. This is the end of Ghidra's main for the unoptimized binary, where local_c is the number we typed:
1 iVar1 = halvings(local_c);
2 if ((iVar1 == 5) && (local_c % 7 == Two conditions have to hold. From reading halvings above, it counts how many times a number can be halved before it reaches 1. Five halvings means the number is from 32 to 63. The second condition says it leaves a remainder of 3 when divided by 7. The first number in that range that does is 38:
echo 38 | ./challNumber: rating: failsum: 741halvings: 5digits: 2apply: 114Unlocked.if is a cmp and a conditional jump. Decompilers often invert the condition and swap the branches, so work out what must be true to reach the block you care about.for or while, which are interchangeable. A test at the bottom gives do-while.switch is a chain of compares against small constants, a jump table, or a lookup array, depending on how it was compiled.goto. The logic is unchanged.Next is Data & Types, which deals with the other half of a decompilation: what all those local_ variables hold.