P.4 — Reverse engineering puzzles (chapter 13)
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.
After answering, paste your C++ into Compiler Explorer with -O1 and see if you get the same assembly!
Puzzles#
puzzle1(int): lea eax, [rdi+1] retlea is doing simple math here: rdi + 1.
int puzzle1(int x){ return x + 1;}puzzle2(int, int): cmp edi, esi mov eax, esi cmovge eax, edi retcmovge means "move if greater or equal". It picks one of the two arguments.
It returns the bigger of the two numbers:
int puzzle2(int a, int b){ return (a >= b) ? a : b;}puzzle3(int): mov eax, edi and eax, 1 retand 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:
bool puzzle3(int x){ return x & 1; // compilers turn x % 2 != 0 into similar code}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 .L1The 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:
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.
Tip: press ← / → to move between lessons, / to search.