I'm trying to solve a Reverse engineering CTF challenge where I need to input the correct password into a gameboy ROM game to get the flag. I used a Ghidra extension to decompile the code and found an interesting function called multiple times, help me figure out what it does:
Let's analyze the function step-by-step to understand what it does. This is a Game Boy ROM, so the code is likely compiled from C or assembly targeting the Z80-like CPU of the Game Boy.
P1 is a special hardware register on the Game Boy. It is used for reading the joypad input lines or for multiplexing input lines.
DAT_c011 and DAT_c012 are memory locations (likely global variables or hardware registers).
bVar1 and bVar2 are temporary byte variables.
Step 2: What is happening with P1?
The code sets P1 to 0x10 and then reads it multiple times into bVar2.
Then it sets P1 to 0x20 and reads it multiple times into bVar1.
Then it does some bitwise operations on bVar1 and bVar2.
Finally, it sets P1 to 0x30 and updates DAT_c012 and DAT_c011.
Step 3: Why multiple reads of P1?
Reading P1 multiple times is a common technique on the Game Boy to allow the hardware to stabilize or to read the current state of the input lines after setting the multiplex bits.
P1 = 0x10 means the code is selecting one set of input lines (usually the directional buttons).
P1 = 0x20 means the code is selecting another set of input lines (usually the button inputs like A, B, Start, Select).
P1 = 0x30 means both sets are selected or a different state.