P.4 — Reverse engineering puzzles (chapter 13)

📘 Appendix P⏱ about 2 min read✍️ Beginner friendly
Read one box at a time. No rush.

Read the assembly and work out the C++. All of these are real GCC -O1 output for x86-64 Linux, so arguments arrive in edi, esi, edx... and the answer goes back in eax.

Tip

After answering, paste your C++ into Compiler Explorer with -O1 and see if you get the same assembly!

Puzzles#

⭐ Puzzle 1
Assembly (x86-64, GCC -O1)
puzzle1(int):        lea     eax, [rdi+1]        ret

lea is doing simple math here: rdi + 1.

C++
int puzzle1(int x){    return x + 1;}
⭐⭐ Puzzle 2
Assembly (x86-64, GCC -O1)
puzzle2(int, int):        cmp     edi, esi        mov     eax, esi        cmovge  eax, edi        ret

cmovge means "move if greater or equal". It picks one of the two arguments.

It returns the bigger of the two numbers:

C++
int puzzle2(int a, int b){    return (a >= b) ? a : b;}
⭐⭐ Puzzle 3
Assembly (x86-64, GCC -O1)
puzzle3(int):        mov     eax, edi        and     eax, 1        ret

and eax, 1 keeps only the lowest bit of the number. When is the lowest bit 1?

The lowest bit is 1 for odd numbers, so this returns 1 for odd and 0 for even:

C++
bool puzzle3(int x){    return x & 1;   // compilers turn x % 2 != 0 into similar code}
⭐⭐⭐ Puzzle 4
Assembly (x86-64, GCC -O1)
puzzle4(int const*, int):        test    esi, esi        jle     .L4        mov     rax, rdi        movsx   rsi, esi        lea     rcx, [rdi+rsi*4]        mov     edx, 0.L3:        add     edx, DWORD PTR [rax]        add     rax, 4        cmp     rax, rcx        jne     .L3.L1:        mov     eax, edx        ret.L4:        mov     edx, 0        jmp     .L1

The first argument is a pointer to ints, the second is a count. .L3 is a loop (it jumps backwards). Each trip reads [rax] and moves rax forward by 4 bytes — the size of one int.

It adds up count numbers from an array:

C++
int puzzle4(const int* data, int count){    int total = 0;    for (int i = 0; i < count; ++i)        total += data[i];    return total;}

rcx is set to the address just past the end (data + count), and the loop stops when rax reaches it.

Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.