diff --git a/README.md b/README.md index 750e74b..9fd5985 100644 --- a/README.md +++ b/README.md @@ -309,6 +309,8 @@ Variables in Embedded Systems: Debugging and Hacking Variables w/ GPIO Output Ba ### Week 4-BN Notebook [HERE](https://github.com/mytechnotalent/Embedded-Hacking/blob/main/WEEK04/WEEK04-BN.md) +### Week 4-IDA Notebook [HERE](https://github.com/mytechnotalent/Embedded-Hacking/blob/main/WEEK04/WEEK04-IDA.md) + ### RP2350 SVD [HERE](https://github.com/mytechnotalent/Embedded-Hacking/blob/main/WEEK04/rp2350.svd) ### Chapter 5: Intro To Variables @@ -352,6 +354,8 @@ Integers and Floats in Embedded Systems: Debugging and Hacking Integers and Floa ### Week 5-BN Notebook [HERE](https://github.com/mytechnotalent/Embedded-Hacking/blob/main/WEEK05/WEEK05-BN.md) +### Week 5-IDA Notebook [HERE](https://github.com/mytechnotalent/Embedded-Hacking/blob/main/WEEK05/WEEK05-IDA.md) + ### Float/Hex Converter Tool [HERE](https://github.com/mytechnotalent/Embedded-Hacking/blob/main/WEEK05/float_hex_converter.py) ### Chapter 11: Integer Data Type @@ -414,6 +418,8 @@ Static Variables in Embedded Systems: Debugging and Hacking Static Variables w/ ### Week 6-BN Notebook [HERE](https://github.com/mytechnotalent/Embedded-Hacking/blob/main/WEEK06/WEEK06-BN.md) +### Week 6-IDA Notebook [HERE](https://github.com/mytechnotalent/Embedded-Hacking/blob/main/WEEK06/WEEK06-IDA.md) + ### Chapter 20: Static Variables This chapter covers static variables as well as an intro to GPIO inputs as we work with push buttons as it relates to embedded development on the Pico 2. @@ -444,6 +450,8 @@ Constants in Embedded Systems: Debugging and Hacking Constants w/ 1602 LCD I2C B ### Week 7-BN Notebook [HERE](https://github.com/mytechnotalent/Embedded-Hacking/blob/main/WEEK07/WEEK07-BN.md) +### Week 7-IDA Notebook [HERE](https://github.com/mytechnotalent/Embedded-Hacking/blob/main/WEEK07/WEEK07-IDA.md) + ### Chapter 23: Constants This chapter covers constants as well as an intro to I2C as we work a 1602 LCD as it relates to embedded development on the Pico 2. @@ -488,6 +496,8 @@ Operators in Embedded Systems: Debugging and Hacking Operators w/ DHT11 Temperat ### Week 9-BN Notebook [HERE](https://github.com/mytechnotalent/Embedded-Hacking/blob/main/WEEK09/WEEK09-BN.md) +### Week 9-IDA Notebook [HERE](https://github.com/mytechnotalent/Embedded-Hacking/blob/main/WEEK09/WEEK09-IDA.md) + ### Chapter 26: Operators This chapter covers operators as well as an intro to single-wire protocol as we work a DHT11 temperature and humidity sensor as it relates to embedded development on the Pico 2. @@ -519,6 +529,8 @@ Conditionals in Embedded Systems: Debugging and Hacking Static & Dynamic Conditi ## Week 10-BN Notebook [HERE](https://github.com/mytechnotalent/Embedded-Hacking/blob/main/WEEK10/WEEK10-BN.md) +## Week 10-IDA Notebook [HERE](https://github.com/mytechnotalent/Embedded-Hacking/blob/main/WEEK10/WEEK10-IDA.md) + ### Chapter 29: Static Conditionals This chapter covers static conditionals as well as an intro to PWM as we work a SG90 servo motor as it relates to embedded development on the Pico 2. @@ -565,6 +577,8 @@ Structures and Functions in Embedded Systems: Debugging and Hacking w/ IR Remote ## Week 11-BN Notebook [HERE](https://github.com/mytechnotalent/Embedded-Hacking/blob/main/WEEK11/WEEK11-BN.md) +## Week 11-IDA Notebook [HERE](https://github.com/mytechnotalent/Embedded-Hacking/blob/main/WEEK11/WEEK11-IDA.md) + ### Chapter 35: Structures This chapter covers structures as well as an intro to infrared basics as we work a infrared receiver and infrared remote controller as it relates to embedded development on the Pico 2. diff --git a/WEEK04/WEEK04-IDA.md b/WEEK04/WEEK04-IDA.md new file mode 100644 index 0000000..eb67652 --- /dev/null +++ b/WEEK04/WEEK04-IDA.md @@ -0,0 +1,1840 @@ +# Week 4-IDA: IDA Pro — Resolve, Hack, and Patch the RP2350 (Raw `.bin`) + +*** + +**LEGAL DISCLAIMER:** +The information, tools, and code provided in this repository and course are strictly for educational, research, and defensive purposes only. + +You are explicitly prohibited from using any materials contained herein to access, test, modify, or exploit any device, network, or system that you do not own 100% or for which you do not have explicit, documented, and legally binding authorization to interact with. + +By using this repository and course, you acknowledge and agree that: + +1. Any illegal, unauthorized, or malicious use of this information is solely your responsibility. +2. The author(s) and contributor(s) of this repository and course shall not be held liable for any damages, legal repercussions, criminal charges, or unauthorized actions resulting from the use, misuse, or abuse of the contents herein. +3. You will comply with all applicable local, state, national, and international laws regarding cybersecurity and computer fraud. + +**IF YOU DO NOT AGREE WITH THESE TERMS, DO NOT USE THIS REPOSITORY AND COURSE.** + +*** + +## What You'll Learn This Week + +- Build the two lesson projects with `Release` and get both an `.elf` and a raw `.bin` +- Dump the **ELF symbol map** with `arm-none-eabi-nm` and use it as ground truth +- Load the raw `.bin` into IDA at `0x10000000` +- **Break at `main`** on live silicon, even though `main` can move between programs +- **Hack a running target live** by editing a register in IDA's Registers widget +- **Resolve the functions in the IDA GUI** using the ELF symbol map +- **Patch** the bytes that control the behavior, export the image, and flash it + +--- + +## How This Guide Works + +The build produces two files for each project: + +| File | What it is | How we use it | +| ---- | ---------- | ------------- | +| `.elf` | The linked image with a full symbol table | Ground truth for every function address and name | +| `.bin` | The raw flash image, no headers, no symbols | The image we load into IDA and reverse | + +The `.bin` is built **from** the `.elf`, so the ELF tells you exactly what is at every address. We use the ELF symbol map to resolve functions in IDA, and we reverse-engineer the raw `.bin` the way a real extracted firmware image is reversed. + +> **Build `Release`, not `Debug`.** Every address in this guide matches the Week 4 lesson, and the Week 4 lesson is a `Release` build. `Release` optimizes the code the same way the original lesson was built: it folds `age = 42` away in Project 1 and inlines `blink_and_print` into `main` in Project 2. If you build `Debug`, the SDK function addresses move and Project 2 keeps a separate `blink_and_print`, so nothing lines up. Always build `Release` for this lesson. + +The order is **dynamic first, static second**, twice — once per project: + +1. Break on the live target and prove what the code does. +2. Hack it live in the debugger and watch the behavior change. +3. Resolve the functions in IDA using the ELF symbol map. +4. Patch the bytes, export, convert, and flash. + +| Project | Prints | Also does | The hack | +| ------- | ------ | --------- | -------- | +| `0x0005_intro-to-variables` | `age: 43` | loops on `printf` | change `43` to `70` | +| `0x0008_uninitialized-variables` | `age: 0` | blinks the red LED on GPIO 16 | change `0` to `66`, move the LED to GPIO 17 | + +> **Addresses come from your build.** Every address here is from the `Release` build produced in Step 3. Confirm against your own `.elf` with the command in Step 4. + +--- + +## Part 1: Build, Flash, and Get the Symbol Map + +### Step 1: Install the toolchain + +**Windows x64** + +- Install the **Raspberry Pi Pico** extension in VS Code. It installs the ARM GNU toolchain, CMake, Ninja, and the Pico SDK. +- Install **IDA Pro** and complete its license activation. +- Install **PuTTY** for the serial monitor. + +**macOS Apple Silicon** + +```bash +brew install cmake ninja +``` + +- Install **IDA Pro** and complete its license activation. +- Install the **Arm GNU Toolchain**, or let the VS Code Pico extension manage it. + +**Linux x64** + +```bash +sudo apt install cmake ninja-build gcc-arm-none-eabi libnewlib-arm-none-eabi git python3 openocd minicom +``` + +- Install **IDA Pro** and complete its license activation. + +### Step 2: Verify your tools are the right architecture (do not skip this) + +On **macOS Apple Silicon**, the most common failure is an Intel `x86_64` tool on your `PATH`: + +``` +zsh: bad CPU type in executable: cmake +``` + +You may have **two Homebrews**: the arm64 one at `/opt/homebrew` and the Intel one at `/usr/local`. If `/usr/local/bin` wins, every `brew` tool is x86_64. Check: + +```bash +file "$(which cmake)" +file "$(which ninja)" +file "$(which arm-none-eabi-gdb)" +file "$(which arm-none-eabi-nm)" +file "$(which openocd)" +file "$(which telnet)" +``` + +All must report `arm64`. If any is `x86_64`, put the Apple Silicon prefix first for the session and check again: + +```bash +export PATH="/opt/homebrew/bin:$PATH" +hash -r +file "$(which cmake)" +``` + +To make it permanent, add that `export` to `~/.zshrc`. Do not use Rosetta as a fix; OpenOCD and GDB are exactly the kind of programs where a translation layer produces failures that look like debugger bugs. + +**`telnet` is special — and optional.** The GDB MI workflow does not need it; it is only used by the command-port fallback. macOS no longer ships `telnet`, and the Homebrew build is often the Intel one, so `telnet 127.0.0.1 4444` fails with `bad CPU type in executable`. Your `brew` command itself may also be the Intel one: if `brew install telnet` fails with `.../portable-ruby/.../ruby: Bad CPU type in executable`, you are running the Intel Homebrew. Call the Apple Silicon Homebrew explicitly: + +```bash +/opt/homebrew/bin/brew install telnet +``` + +If you would rather not install anything, macOS ships an arm64 `nc`, which can connect to the same OpenOCD port: + +```bash +nc 127.0.0.1 4444 +``` + +**Windows x64** and **Linux x64** do not have this problem. Skip to Step 3. + +### Step 3: Build the two projects with `Release` + +Run this once inside `0x0005_intro-to-variables/` and once inside `0x0008_uninitialized-variables/`: + +```bash +cmake -B build -G Ninja -DPICO_BOARD=pico2 -DPICO_PLATFORM=rp2350 -DCMAKE_BUILD_TYPE=Release +cmake --build build +``` + +**Point IDA at this repository (once).** Every console snippet below reads the repo root from `~/.embedded-hacking-repo`, so IDA never needs a database open and nothing is hardcoded. From the repo root, run once: + +**macOS / Linux:** + +```bash +pwd > ~/.embedded-hacking-repo +``` + +**Windows (PowerShell):** + +```powershell +(Get-Location).Path | Set-Content "$env:USERPROFILE\.embedded-hacking-repo" +``` + +**Then build from the IDA console**, so the whole build -> patch -> flash loop stays inside IDA. The console inherits a minimal `PATH` — on macOS just `/usr/bin:/bin:/usr/sbin:/sbin` — so it does not see Homebrew; add your package manager's `bin` first, then run plain `cmake`. + +**macOS Apple Silicon:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() +os.environ["PATH"] = "/opt/homebrew/bin:" + os.environ["PATH"] # the console's PATH omits Homebrew +for name in ("0x0005_intro-to-variables", "0x0008_uninitialized-variables"): + proj = os.path.join(root, name) + subprocess.run(["cmake", "-B", "build", "-G", "Ninja", "-DPICO_BOARD=pico2", + "-DPICO_PLATFORM=rp2350", "-DCMAKE_BUILD_TYPE=Release"], cwd=proj) + subprocess.run(["cmake", "--build", "build"], cwd=proj) +``` + +**Linux x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() +for name in ("0x0005_intro-to-variables", "0x0008_uninitialized-variables"): + proj = os.path.join(root, name) + subprocess.run(["cmake", "-B", "build", "-G", "Ninja", "-DPICO_BOARD=pico2", + "-DPICO_PLATFORM=rp2350", "-DCMAKE_BUILD_TYPE=Release"], cwd=proj) + subprocess.run(["cmake", "--build", "build"], cwd=proj) +``` + +**Windows x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() +for name in ("0x0005_intro-to-variables", "0x0008_uninitialized-variables"): + proj = os.path.join(root, name) + subprocess.run(["cmake", "-B", "build", "-G", "Ninja", "-DPICO_BOARD=pico2", + "-DPICO_PLATFORM=rp2350", "-DCMAKE_BUILD_TYPE=Release"], cwd=proj) + subprocess.run(["cmake", "--build", "build"], cwd=proj) +``` + +Each build directory now contains the pair we need: + +- `0x0005_intro-to-variables/build/0x0005_intro-to-variables.elf` and `.bin` — `.bin` is **15292** bytes +- `0x0008_uninitialized-variables/build/0x0008_uninitialized-variables.elf` and `.bin` — `.bin` is **15668** bytes + +If the ARM toolchain is not on your `PATH`, add `-DPICO_TOOLCHAIN_PATH=...`: + +| OS | Typical toolchain path | +| -- | ---------------------- | +| Windows x64 | `C:/Program Files/Arm GNU Toolchain arm-none-eabi/14.2 rel1/bin` | +| macOS Apple Silicon | `/Applications/ArmGNUToolchain/14.2.rel1/arm-none-eabi/bin` | +| Linux x64 | `/usr` | + +### Step 4: Dump the ELF symbol map + +This is the ground truth for the whole lesson. Run `arm-none-eabi-nm` on each ELF and keep the output in a terminal or a text file: + +**macOS Apple Silicon / Linux x64:** + +```bash +arm-none-eabi-nm -n --defined-only build/0x0005_intro-to-variables.elf | grep -E ' [Tt] ' +arm-none-eabi-nm -n --defined-only build/0x0008_uninitialized-variables.elf | grep -E ' [Tt] ' +``` + +**Windows x64:** + +```powershell +arm-none-eabi-nm -n --defined-only build\0x0005_intro-to-variables.elf | Select-String ' [Tt] ' +``` + +Each line is `address type name`. The `T`/`t` type is a function. Here are the functions this lesson uses. + +**Project 1 — `0x0005_intro-to-variables`:** + +| Address | ELF symbol | Signature | Role | +| ------- | ---------- | --------- | ---- | +| `0x1000015c` | `_reset_handler` | `void _reset_handler(void)` | reset entry | +| `0x10000186` | `platform_entry` | `void platform_entry(void)` | calls `runtime_init`, `main`, `exit` | +| `0x1000019a` | `data_cpy` | `void data_cpy(void*, void*, void*)` | copies `.data` from flash to SRAM | +| `0x100001e4` | `_init` | `void _init(void)` | runs `.init_array` | +| `0x10000210` | `frame_dummy` | `void frame_dummy(void)` | C runtime boilerplate | +| `0x10000234` | `main` | `int main(void)` | the lesson function | +| `0x10000248` | `gpio_set_function` | `void gpio_set_function(uint, gpio_function_t)` | SDK GPIO helper | +| `0x10002cfc` | `exit` | `void exit(int)` | C runtime exit | +| `0x10002d04` | `runtime_init` | `void runtime_init(void)` | SDK runtime init | +| `0x10002f54` | `stdio_init_all` | `bool stdio_init_all(void)` | SDK serial init | +| `0x100030e4` | `__wrap_printf` | `int __wrap_printf(const char*, ...)` | the `printf` wrapper | + +These signatures come from the ELF's DWARF debug info, so they are exact. You apply them in IDA in Step 16 (`G` -> address, then `Y` -> Change Type). + +**Project 2 — `0x0008_uninitialized-variables`:** + +| Address | ELF symbol | Signature | Role | +| ------- | ---------- | --------- | ---- | +| `0x1000015c` | `_reset_handler` | `void _reset_handler(void)` | reset entry | +| `0x10000186` | `platform_entry` | `void platform_entry(void)` | calls `runtime_init`, `main`, `exit` | +| `0x1000019a` | `data_cpy` | `void data_cpy(void*, void*, void*)` | copies `.data` from flash to SRAM | +| `0x100001e4` | `_init` | `void _init(void)` | runs `.init_array` | +| `0x10000210` | `frame_dummy` | `void frame_dummy(void)` | C runtime boilerplate | +| `0x10000234` | `main` | `int main(void)` | the lesson function (`blink_and_print` inlined) | +| `0x10000278` | `gpio_set_function` | `void gpio_set_function(uint, gpio_function_t)` | SDK GPIO helper | +| `0x100002b4` | `gpio_init` | `void gpio_init(uint)` | SDK GPIO init | +| `0x10000d10` | `sleep_ms` | `void sleep_ms(uint32_t)` | SDK delay | +| `0x10002e74` | `exit` | `void exit(int)` | C runtime exit | +| `0x10002e7c` | `runtime_init` | `void runtime_init(void)` | SDK runtime init | +| `0x100030cc` | `stdio_init_all` | `bool stdio_init_all(void)` | SDK serial init | +| `0x1000325c` | `__wrap_printf` | `int __wrap_printf(const char*, ...)` | the `printf` wrapper | + +> **`main` is `0x10000234` in both projects.** In Project 2 the `static void blink_and_print` helper is inlined into `main` by the `Release` optimizer, so it does not appear as a separate symbol. That is why both projects put `main` at the same address. In a `Debug` build it stays separate and `main` moves — another reason to build `Release`. + +### Step 5: Flash Project 1 and confirm `age: 43` + +A `.bin` has no headers, so OpenOCD must be told the base address `0x10000000`. From the repository root: + +**macOS Apple Silicon / Linux x64:** + +```bash +./flash.sh 0x0005_intro-to-variables/build/0x0005_intro-to-variables.bin +``` + +**Windows x64 (PowerShell):** + +```powershell +.\flash.ps1 -Bin 0x0005_intro-to-variables\build\0x0005_intro-to-variables.bin +``` + +**Or flash from the IDA console** (with a database open, so the repo root is taken from it — otherwise use the terminal form above): + +**macOS Apple Silicon / Linux x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) +bin_path = os.path.join(root, "0x0005_intro-to-variables", "build", "0x0005_intro-to-variables.bin") +log = os.path.join(os.path.dirname(bin_path), "flash.log") +subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # free the probe first +subprocess.Popen([os.path.join(root, "flash.sh"), bin_path], + stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) +print("flashing in the background; log:", log) +``` + +**Windows x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) +bin_path = os.path.join(root, "0x0005_intro-to-variables", "build", "0x0005_intro-to-variables.bin") +log = os.path.join(os.path.dirname(bin_path), "flash.log") +subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"]) # free the probe first +subprocess.Popen(["powershell", "-ExecutionPolicy", "Bypass", "-File", + os.path.join(root, "flash.ps1"), "-Bin", bin_path], + stdout=open(log, "w"), stderr=subprocess.STDOUT) +print("flashing in the background; log:", log) +``` + +Wait for `wrote 15292 bytes ...` and `** Verified OK **`. Open a serial monitor at **115200** baud: + +- **Windows x64:** PuTTY -> Connection type **Serial**, the Pico's COM port, speed `115200`. +- **macOS Apple Silicon:** `screen /dev/tty.usbmodem* 115200` (quit with `Ctrl-A` then `K`). +- **Linux x64:** `minicom -D /dev/ttyACM0 -b 115200`. + +``` +age: 43 +age: 43 +age: 43 +... +``` + +### Step 6: Flash Project 2 and confirm `age: 0` + red LED + +```bash +# macOS / Linux +./flash.sh 0x0008_uninitialized-variables/build/0x0008_uninitialized-variables.bin +``` +```powershell +# Windows +.\flash.ps1 -Bin 0x0008_uninitialized-variables\build\0x0008_uninitialized-variables.bin +``` + +**Or flash from the IDA console** (same form as Step 5, pointing at the Project 2 `.bin`): + +**macOS / Linux:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) +bin_path = os.path.join(root, "0x0008_uninitialized-variables", "build", "0x0008_uninitialized-variables.bin") +log = os.path.join(os.path.dirname(bin_path), "flash.log") +subprocess.run(["pkill", "-TERM", "-f", "openocd"]) +subprocess.Popen([os.path.join(root, "flash.sh"), bin_path], + stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) +print("flashing in the background; log:", log) +``` + +**Windows:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) +bin_path = os.path.join(root, "0x0008_uninitialized-variables", "build", "0x0008_uninitialized-variables.bin") +log = os.path.join(os.path.dirname(bin_path), "flash.log") +subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"]) +subprocess.Popen(["powershell", "-ExecutionPolicy", "Bypass", "-File", + os.path.join(root, "flash.ps1"), "-Bin", bin_path], + stdout=open(log, "w"), stderr=subprocess.STDOUT) +print("flashing in the background; log:", log) +``` + +Wait for `wrote 15668 bytes ...`. The serial monitor shows: + +``` +age: 0 +age: 0 +age: 0 +... +``` + +and the **red LED on GPIO 16** blinks once per second. + +--- + +## Part 2: Load the Raw `.bin` into IDA + +Start from a fresh IDA state. If you already have a database for this lesson, **close it and start over**; a stale database keeps old names and patches. + +### Step 7: Bring the raw `.bin` into IDA + +A raw `.bin` has no headers, so IDA cannot know where it belongs or what architecture it is. You must supply both. If you just double-click the `.bin`, IDA may load it with a guessed architecture, and every address in this lesson will be wrong. + +#### 1.1 Open the file +1. **File ▸ Open…** (Ctrl/Cmd+O). +2. Select the `.bin` file and click **Open**. + +IDA opens the **"Load a new file"** dialog because a raw `.bin` has no header. + +#### 1.2 Set the format and processor +In the *Load a new file* dialog: +1. **Format**: leave it as **Binary file** (IDA auto-detects a headerless image). +2. **Processor type**: click the **…** button next to the processor field. In the *Processor type* dialog: + - Family: **ARM** + - Type: **ARM Little-endian** (the 32-bit ARM module). + - Click **OK**. + +> If IDA asks **"Do you want to disassemble it as 64-bit code?"** — click **No**. +> The RP2350 is 32-bit; answering *Yes* loads AArch64 and you get `X` registers / data. (This is the single most common cause of the `DCB` wall.) + +#### 1.3 Configure the ARM architecture and Thumb mode +Still in the *Load a new file* dialog, open the processor options (the **Processor options** / **Set…** button, which opens the dialog titled **ARM architecture options**): +- **ARM architecture**: choose **ARMv8-M** (this is the Cortex-M33 / RP2350 core). +- **Thumb instructions**: select **Thumb-2** (ARMv8-M is Thumb-only, so this is the correct mode). +- Leave **automatic ARM-THUMB switch** off; we want Thumb throughout. + +#### 1.4 Set the loading address +- **Loading address**: enter **`10000000`** (hex; the RP2350 XIP flash base). + IDA rejects addresses that don't look like ROM/RAM with *"The loading address should belong to RAM or ROM"* — `0x10000000` is the correct flash window. + +Leave **Manual load** and **Create segments** at their defaults. Click **OK**. + +#### 1.5 Force Thumb, then seed the code from the vector table +A raw `.bin` has no header, so IDA's loader has **no entry point** and defaults the segment to **ARM mode** (which cannot decode Thumb). Two required steps — in this order: + +**A. Set the segment to Thumb (do this first).** +- **Edit ▸ Segments ▸ Set default segment register value…** → register **`T`** = **`1`** (or press **`Alt+G`**). IDA reanalyzes the segment as Thumb automatically. + +**B. Seed the code from the vector table.** +1. **G** → `10000000`. The first two words are the initial stack pointer and the **reset vector**. +2. **Read the 4-byte word at `0x10000004`** (do **not** assume its value — it differs per build). +3. **Clear bit 0** (the ARM **Thumb** flag) → the reset handler address. +4. **G** to that address → press **C** (**MakeCode**). IDA disassembles the reset handler and follows its `bl`s into `main`. + +Once `main` shows code, the import is correct. + +**Why IDA needs this and others don't:** IDA's generic raw-binary ARM loader treats the image as flat data and waits for you to set Thumb and mark the entry point. It's an IDA quirk, not a mistake on your part. + +### Step 8: Save it as a IDA database (`.i64`) + +IDA never writes back into the `.bin`. Your names, comments, types, and patches live in a separate **`.i64`** database. Save one now, before you make any changes: + +1. Choose `File -> Save As...`. +2. Save it next to the image as `0x0005_intro-to-variables.i64`. +3. From now on, save with `File -> Save` (`Cmd+S` on macOS, `Ctrl+S` on Windows/Linux) whenever you rename or patch. + +The two files have different roles: + +| File | Role | +| ---- | ---- | +| `0x0005_intro-to-variables.bin` | the raw firmware image; IDA never modifies it | +| `0x0005_intro-to-variables.i64` | your analysis database: names, types, comments, and patches | + +When you come back later, **open the `.i64`**, not the `.bin`; that restores all your work. If a database gets messy, delete the `.i64` and re-import the `.bin` from Step 7 — the firmware is never at risk. You export the patched image out of this view later, in Step 19. + +### Step 9: The views you will use + +- **Linear view:** the disassembly listing. You navigate, read, and patch here. +- **Graph view:** the control-flow graph of the current function. +- **Decompiler (HLIL):** the pseudo-C decompilation. +- **Hex view:** raw bytes, used for patching. +- **Function list:** the sidebar list of every detected function. + +Navigation: `G` go to address, `N` rename, `Y` set type or signature, `;` add a comment. Breakpoints are set from the OpenOCD command port, not from the GUI — see Step 13. + +> **macOS function keys:** the top-row `F` keys are usually mapped to system functions. Every step here uses menu paths that work without them. + +--- + +## Part 3: Dynamic — Break at `main` and Hack Live (Project 1) + +### Step 10: Start OpenOCD as a live debug server + +Make sure no other OpenOCD is running; a forgotten server holds port `3333`. + +**macOS / Linux:** + +```bash +ps aux | grep -i openocd +``` + +**Windows (PowerShell):** + +```powershell +Get-Process | Where-Object { $_.ProcessName -like '*openocd*' } +``` + +Stop any leftover server gracefully: + +**macOS / Linux:** + +```bash +pkill -TERM -f openocd +``` + +**Windows (PowerShell):** + +```powershell +Get-Process openocd -ErrorAction SilentlyContinue | Stop-Process +``` + +Start the server **parked at `main`**: + +**macOS Apple Silicon / Linux x64:** + +```bash +BP_ADDR=0x10000234 ./debug-server.sh +``` + +**Windows x64 (PowerShell):** + +```powershell +$env:BP_ADDR="0x10000234"; .\debug-server.ps1 +``` + +**Or start it from the IDA console**, freeing the probe first and launching the server in the background so the console returns immediately: + +**macOS Apple Silicon / Linux x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) +subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # stop any running server first +log = os.path.join(root, "openocd.log") +p = subprocess.Popen([os.path.join(root, "debug-server.sh")], cwd=root, + env=dict(os.environ, BP_ADDR="0x10000234"), + stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) +print("OpenOCD started (pid", p.pid, "); log:", log) +``` + +**Windows x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) +subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"]) # stop any running server first +log = os.path.join(root, "openocd.log") +p = subprocess.Popen(["powershell", "-ExecutionPolicy", "Bypass", "-File", + os.path.join(root, "debug-server.ps1")], cwd=root, + env=dict(os.environ, BP_ADDR="0x10000234"), + stdout=open(log, "w"), stderr=subprocess.STDOUT) +print("OpenOCD started (pid", p.pid, "); log:", log) +``` + +`Popen` returns in a few milliseconds; the server keeps running in the background. Check `openocd.log` for `Listening on port 3333`, then connect in Step 11. + +Wait for: + +``` +Info : [rp2350.dap.core0] Examination succeed +Startup breakpoint at 0x10000234 (2-byte hardware execute, one-shot). +Info : starting gdb server for rp2350.dap.core0 on 3333 +Info : Listening on port 3333 for gdb connections +``` + +> **`BP_ADDR` parks the core at `main` before any client connects.** The script arms a 2-byte hardware breakpoint and then does the startup `reset run`, so the core runs from the vector table and stops at your address with no debugger attached yet. When IDA connects a moment later, the first thing it reads is already the truth: `Stopped at 0x10000234`. This is the whole reason the lab works cleanly — you never have to drive a reset from outside the GUI. +> +> Use the address you actually want to stop at: +> +> | What you want to stop at | Project 1 `0x0005` | Project 2 `0x0008` | Command | +> | --- | --- | --- | --- | +> | `main` (once per reset) | `0x10000234` | `0x10000234` | `BP_ADDR=0x10000234 ./debug-server.sh` | +> | The **loop** — the `printf` call, hit every iteration | `0x1000023e` | `0x1000024e` | `BP_ADDR=0x1000023e ./debug-server.sh` | +> +> ```bash +> BP_ADDR=0x10000234 ./debug-server.sh # park at main +> BP_ADDR=0x1000023e ./debug-server.sh # park in the loop instead +> ``` +> +> ```powershell +> $env:BP_ADDR="0x10000234"; .\debug-server.ps1 # park at main +> $env:BP_ADDR="0x1000023e"; .\debug-server.ps1 # park in the loop +> ``` +> +> **Note the loop address is not the same in both projects.** Project 2 does more setup before the loop, so its `bl __wrap_printf` sits at `0x1000024e`, not `0x1000023e`. Both were verified against the Release `.elf` with `arm-none-eabi-objdump` and confirmed live on hardware. +> +> **This startup stop is single-use.** OpenOCD flushes breakpoints when a client connects, so this one is gone once IDA attaches — fine for `main`, which only runs once per reset. Every breakpoint after that is set from the IDA GUI (Step 13) and is repeatable. To stop at `main` again, restart the server with `BP_ADDR` and reconnect. + +> **Exactly one core.** The line must say `core0` and must **not** mention `core1`. Core1 is never started by this firmware; exposing it makes IDA read core1's reset-state registers, which are not real addresses, and OpenOCD floods the log with `Failed to read memory at 0xf0000000`. The scripts already use `USE_CORE=0`; do not change it. + +> **Windows driver note:** the Debug Probe must use the **WinUSB** driver. If OpenOCD reports `unable to open CMSIS-DAP device`, install it with [Zadig](https://zadig.akeo.ie/) (select `Debug Probe (CMSIS-DAP)` -> WinUSB). + +### Step 11: Connect IDA to the GDB server + +1. Make sure the image is open and analyzed (Part 2) and the server from Step 10 is running (parked at `main`). +2. Choose `Debugger -> Connect to Remote Process`. +3. In the **adapter** dropdown, select **GDB MI**. +4. In the **connect** settings group, set **IP Address** to `127.0.0.1` and **Port** to `3333`. +5. Set **Full GDB Executable Path** to the `arm-none-eabi-gdb` from the **Arm GNU Toolchain 14.2.rel1**. It ships for all three hosts, and the Raspberry Pi Pico VS Code extension installs that same 14.2.rel1 toolchain (including `arm-none-eabi-gdb`) on all of them: + + | OS | `arm-none-eabi-gdb` path | + | -- | ------------------------ | + | macOS Apple Silicon | `/Applications/ArmGNUToolchain/14.2.rel1/arm-none-eabi/bin/arm-none-eabi-gdb` (or the Pico extension's `~/.pico-sdk/toolchain/14_2_Rel1/bin/arm-none-eabi-gdb`) | + | Windows x64 | `%USERPROFILE%\.pico-sdk\toolchain\14_2_Rel1\bin\arm-none-eabi-gdb.exe` (Pico extension), or `C:\Program Files (x86)\Arm GNU Toolchain arm-none-eabi\14.2 rel1\bin\arm-none-eabi-gdb.exe` | + | Linux x64 | `~/.pico-sdk/toolchain/14_2_Rel1/bin/arm-none-eabi-gdb` (Pico extension), or the `bin/` directory of the extracted `arm-gnu-toolchain-14.2.rel1-x86_64-arm-none-eabi` tarball | +6. Click **Accept**. + +> **Use the GDB MI adapter.** It launches a real `arm-none-eabi-gdb --interpreter=mi2` and lets IDA drive it, so breakpoints and stepping go through real GDB — which sends the correct 2-byte breakpoint length and handles step-over itself. Verified working end to end: connect, GUI breakpoints (**Add Hardware Breakpoint...**, hardware execute), **Step Into** / **Step Over**, and register edits. Stops are reported as `Breakpoint` (not `SingleStep`). +> +> **Do NOT have any breakpoints set in IDA before you connect.** With the GDB MI adapter, attaching while IDA already has a breakpoint **hangs the session**. Start the server parked with `BP_ADDR` (Step 10), connect, and only add hardware breakpoints *after* the connection is up. This is a IDA bug; it is the single most common GDB MI failure. +> +> **The GDB executable path matters.** Use the **14.2.rel1** build on every OS (Windows, macOS, Linux). The 13.3.rel1 build — which is what `/opt/homebrew/bin/arm-none-eabi-gdb` symlinks to — did **not** connect in testing. +> +> **This step is temporary.** Vector35 plans to ship a GDB binary with the GDB MI adapter ([Vector35/debugger#929](https://github.com/Vector35/debugger/issues/929), milestone *Langara*). Once that lands, IDA provides GDB itself and you will not need to set **Full GDB Executable Path** at all. +> +> **Do not pick Corellium.** IDA's adapter dropdown also lists **Corellium**, which is for Corellium's virtual devices and expects an API token, not a local OpenOCD server. It is not the adapter for this lab. The dropdown is a combo box, so an accidental arrow-key press can land on it — always read the label back and confirm it says **GDB MI** before clicking **Accept**. + +> **The adapter and port are not saved in the `.i64`.** Every time you relaunch IDA you must re-select **GDB MI**, re-enter port `3333`, and re-set the GDB path. + +> **Watch for an off-screen error dialog.** When a connection fails, IDA pops a `IDA critical alert` window that can be positioned mostly outside the main window (seen at `2430,331` with the main window at `2560,30`), which makes it look like nothing happened. If the connect seems to do nothing, check your other display. + +The target keeps running. Open the **Registers** tab (bug icon) and confirm you see live values. `pc` inside `0x10003xxx` and `sp` just below `0x20082000` are healthy. + +> **If `pc` is `0x00000088`, `0x000000ec`, or `sp` is `0xf0000000`, the session is bad.** Restart the server, then restart IDA (a server restart while attached leaves IDA in a stale session), and connect again. + +### Step 12: Find `main` without relying on its address + +`main` can move between programs, so we do not guess it. We follow the one fixed path to it. Press `G` and go to `0x10000000`: + +``` +0x10000000 0x20082000 initial stack pointer (top of SRAM) +0x10000004 0x1000015d reset vector +``` + +Bit 0 of a vector is the Thumb bit, so `0x1000015d` means "start at `0x1000015c`". That is `_reset_handler`. Follow the reset path to `0x10000186`, `platform_entry`: + +```asm +10000186 : +10000186: 4914 ldr r1, [pc, #80] ; @ 0x100001d8 +10000188: 4788 blx r1 ; runtime_init +1000018a: 4914 ldr r1, [pc, #80] ; @ 0x100001dc +1000018c: 4788 blx r1 ; main <-- the fixed anchor +1000018e: 4914 ldr r1, [pc, #80] ; @ 0x100001e0 +10000190: 4788 blx r1 ; exit +10000192: be00 bkpt 0x0000 +``` + +**The middle `blx` at `0x1000018c` is the call to `main`.** `platform_entry` is byte-identical in both projects, so `0x1000018c` catches `main` no matter where the linker placed it. The literal pool at `0x100001dc` holds `main | 1`, and clearing bit 0 gives `0x10000234`. + +### Step 13: Set a hardware breakpoint in the GUI + +With the **GDB MI** adapter, IDA sets breakpoints through real GDB, which sends the correct 2-byte length, so you set them **in the UI**. There is no command port here. + +> **Why older drafts used the command port.** IDA's **GDB RSP** adapter is its own minimal RSP client and sends a **1-byte** breakpoint (`Z0,,1`); the Cortex-M33 FPB comparators need 2 bytes, so OpenOCD rejected it with `only breakpoints of two bytes length supported`. The old workaround was to arm breakpoints by hand over telnet. **The GDB MI adapter does not have this problem** — it drives real `arm-none-eabi-gdb`, which sends the right length. So everything below is done in the GUI. The command port still exists as a fallback (see the end of this step), but you do not need it. + +#### Where you can stop + +| You want to stop at | Address | How | Repeatable? | +| --- | --- | --- | --- | +| **`main`** | `0x10000234` | The server starts parked there with `BP_ADDR=0x10000234` (Step 10), so IDA is already stopped at `main` when it connects. | No — `main` runs once per reset. | +| **The loop** (`printf` call) | Project 1 `0x1000023e`, Project 2 `0x1000024e` | Set a hardware breakpoint in the GUI, then click **Resume**. | Yes — fires on every iteration. | + +#### Set the loop breakpoint in the GUI + +1. Press `G`, type the loop address (`0x1000023e` for Project 1, `0x1000024e` for Project 2), and press Enter. +2. Set a **hardware execution** breakpoint at that address, either way: + - `Debugger -> Add Hardware Breakpoint...` — a **hardware execute** (`HE`) breakpoint. **Use this one.** + - click the line and press `F2` (`Debugger -> Toggle Breakpoint`) — a **software** breakpoint. It will **not** work here: the code is in read-only flash, so GDB cannot install it and the core just keeps running. +3. Click **Resume**. The core is already running the loop, so the breakpoint fires on the next iteration. IDA stops with the PC at the loop address and reports it as a **Breakpoint** — verified: `Stopped (Breakpoint) at 0x1000023e`. + +> **No breakpoints before you connect.** With GDB MI, a breakpoint set before the connection hangs the session (Step 11). Start parked with `BP_ADDR`, connect, *then* add breakpoints. + +#### Stepping + +With the target halted at the breakpoint, **Step Into** (`F7`) and **Step Over** (`F8`) run through real GDB and move the PC. Verified: `0x1000023e -> 0x100030e4 -> 0x100030e6 -> ...`. + +> **Step Over on the raw `.bin` steps *into* calls.** The raw image has no symbol for `__wrap_printf`, so **Step Over** at the `printf` call behaves like **Step Into**. When the lab needs to execute the call and then stop, it moves the breakpoint to the return site and clicks **Resume** instead (Step 14 shows this). + +> **Never use IDA's Restart button.** On RP2350 it resets and halts inside the boot ROM (`pc=0x88`, `sp=0xf0000000`). To reset cleanly, restart the server with `BP_ADDR` and reconnect. + +> **If you ever need the command port.** It is still there — `nc 127.0.0.1 4444`, and `bp 2 hw` still arms a breakpoint, `rbp ` / `rbp all` still remove them. It is the fallback if you switch back to the **GDB RSP** adapter, whose 1-byte breakpoints the GUI cannot set. With GDB MI you do not need it for this lab. + +### Step 14: HACK IT LIVE — change the printed value + +`main` loads the constant `0x2b` (43) into `r1` and calls `printf` on every iteration. We break on that call in the GUI and change it live. + +1. Press `G`, go to `0x1000023e` (the `bl __wrap_printf`). +2. Set a **hardware execute** breakpoint there: `Debugger -> Add Hardware Breakpoint...`. (Do not use `F2` — that is a software breakpoint and will not work on read-only flash.) +3. Click **Resume** in IDA. The target is already running the loop, so the breakpoint fires on the next iteration. IDA stops with the program counter at `0x1000023e` and `r1 = 0x2b`. +4. Open the **Registers** widget (bug icon -> **Registers**). +5. Find `r1`. Its value is `0x2b`. +6. **Set `r1` to `0x46`.** From IDA's Python console (`Plugins -> Python Console`): + ```python + dbg.set_reg_value("r1", 0x46) + ``` + `dbg.set_reg_value(name, value)` writes one register (returns `True` on success). You can also right-click `r1` in the **Registers** widget, press `E` (edit), type `46`, and press Enter. The widget may not repaint the value, but the write reaches the target — you confirm it by the printed output in the next steps. +7. **Move the breakpoint past the call.** You want `printf` to run once and then stop, so move the breakpoint from `0x1000023e` to the instruction *after* the call, `0x10000242` (the `b.n` that closes the loop): remove the breakpoint at `0x1000023e` and set a hardware breakpoint at `0x10000242`. Two reasons not to just click **Step Over** here: a breakpoint left on the current PC re-traps the step, and IDA's **Step Over** steps *into* `__wrap_printf` on this raw `.bin` because the image carries no symbol for the call. Moving the breakpoint to the return site is deterministic. +8. Click **Resume** in IDA. The core executes `bl __wrap_printf` with `r1 = 0x46`, so this iteration prints `age: 70`, then stops at `0x10000242`. +9. Look at your serial monitor — the `screen` session on the Pico's USB serial port — and at the **Target** tab in IDA: + + ``` + age: 70 + ``` + +You changed a running program's output without touching the binary. + +### Step 14b: HACK THE STRING LIVE — change `age:` to `foo:` + +The text `"age: %d\r\n"` lives in flash (`.rodata`) at `0x100034a0`, and flash is **read-only at runtime** — a debugger write there does not stick (verified: writing `0x66` to `0x100034a0` read back unchanged). So you cannot overwrite the text in place. Instead you redirect the pointer: at the `printf` call, `r0` holds the string address, so you point `r0` at a replacement string you place in RAM. + +1. Arm the breakpoint at the `printf` call and hit it, exactly as in Step 14 steps 1-3. At the stop, `r0 = 0x100034a0` and `r1 = 0x2b`. +2. Put the replacement string into free RAM at `0x20080000` from IDA's **Python console** (`Plugins -> Python Console`) — no command port needed: + ```python + dbg.write_memory(0x20080000, b"foo: %d\r\n\x00") + ``` + `dbg.write_memory(address, bytes)` is IDA's debugger memory-write API; it returns `True` on success. That writes the bytes `66 6f 6f 3a 20 25 64 0d 0a 00` = `"foo: %d\r\n\0"`. +3. Point `r0` at that string: + ```python + dbg.set_reg_value("r0", 0x20080000) + ``` + (Or right-click `r0` in the **Registers** widget, press `E`, type `0x20080000`, and press Enter.) +4. Move the breakpoint past the call in the GUI (remove it at `0x1000023e`, set one at `0x10000242`) and click **Resume**. The core runs `printf` with `r0` pointing at your RAM string and `r1 = 0x2b`, so this iteration prints: + ``` + foo: 43 + ``` + then stops at `0x10000242`. + +Like the value hack, this is **one iteration only**: the loop reloads `r0` (and `r1`) from flash on every pass, so the next line is `age: 43` again. The permanent version is the static patch in Step 19b. + +### Step 15: Why the hack reverts (and why we patch next) + +Press **Resume**. The loop branches back to `0x1000023a`, which reloads `movs r1, #43`, so the next line is `age: 43`. The live edit changed one iteration only. There is no variable in memory to change; the value is baked into the instruction. To make `age: 70` permanent we must patch the instruction. That is the static pass. + +Press **Pause** to stop the output flood. + +### Step 15b: Kill the debugger and OpenOCD + +The live hack is done. Do this **before** the static pass. + +1. In the **Debugger** sidebar, click the **X** (**Kill**) (or **`Debugger -> Kill`**) to disconnect IDA. +2. **Kill does not stop the OpenOCD process** — `debug-server.sh` started it separately, and it keeps running and holding the probe. Stop it from the IDA console: + + **macOS / Linux:** + + ```python + import subprocess + subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # stop the debug server, free the probe + ``` + + **Windows:** + + ```python + import subprocess + subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"]) # stop the debug server, free the probe + ``` + +3. Confirm nothing is left: `pgrep -fl openocd` (macOS/Linux) prints nothing. + +From a terminal it is the same: `pkill -TERM -f openocd`, or `Get-Process openocd | Stop-Process` on Windows. + +--- + +## Part 4: Static — Resolve the Functions in IDA and Patch (Project 1) + +### Step 16: Resolve the functions in the IDA GUI + +We now name the functions in IDA using the ELF symbol map from Step 4. IDA loaded the raw `.bin` with **no symbols**, so every function shows as `sub_` — resolving means giving each one its real name and signature. + +Three keys do all the work: + +| Key | IDA action | Use it for | +| --- | --- | --- | +| `G` | Go to address | Jump to a function's address | +| `Y` | **Change Type** | Set the function's signature. The dialog shows the full prototype, so this sets the name *and* the type in one step. | +| `N` | Rename | Rename only, when you just want the name and not the type | + +For each function below: `G` to its address, then **`Y` (Change Type)** and type the prototype from the table. + +#### How to resolve a function in IDA (`Y`) + +`Y` is the **Change Type** key, and it is what actually resolves the function — it turns `void sub_10002f54()` into `bool stdio_init_all(void)`. The Change Type dialog shows the full declaration (name and type), so typing the prototype sets both: + +1. `G` to the function's address. The cursor lands on the function. +2. Press **`Y`**. In the Change Type dialog, type the prototype from the table exactly — for example `bool stdio_init_all(void)` — and press Enter. + +The decompiler header then shows the real prototype, and calls to the function read cleanly instead of `sub_()`. `N` is only for renaming without touching the type; `Y` alone sets both the name and the type. + +If `Y` seems to do nothing, confirm the cursor is on the function, or right-click it and pick **Change Type...**. IDA parses what you type and silently keeps the old type if it does not parse, so glance at the header after each `Y`. + +#### Worked example: `main` + +1. Press `G`, type `0x10000234`, press Enter. The view jumps there; the cursor lands on `sub_10000234`. +2. Press **`Y`** (Change Type), type `int main(void)`, press Enter. That sets the name to `main` and the type to `int(void)`. + +> **IDA shows `int32_t` where Ghidra shows `int`.** After you set `int main(void)`, the decompiler header may read `int32_t main(void)`. That is the same type — on this platform `int` is 32 bits and IDA's parser normalises it to `int32_t`. Do not fight it; it is not an error. + +#### Worked example: `stdio_init_all` + +1. `G` -> `0x10002f54`. +2. `Y` -> `bool stdio_init_all(void)`. + +It returns **`bool`**, not `void` — the ELF says `_Bool stdio_init_all(void)`. Our `main` ignores the return value, so the decompiler still reads cleanly. + +#### Worked example: `uart_init` + +1. `G` -> `0x10000e10`. +2. `Y` -> `uint uart_init(uart_inst_t *uart, uint baudrate)`. + +#### Worked example: `__wrap_printf` + +1. `G` -> `0x100030e4`. +2. `Y` -> `int __wrap_printf(const char *fmt, ...)`. Keep the `...` — `printf` is variadic. + +> **`printf` in our source is `__wrap_printf` in the binary.** The SDK links our `printf` calls to its `__wrap_printf` wrapper. + +The rest of the chain is the same two keystrokes per function (`G`, then `Y`). This is **our code plus the library functions it actually calls** — not the whole SDK. `main` only calls `stdio_init_all` and `printf`, so we follow that chain down: `stdio_init_all` pulls in the stdio/UART setup, and `printf` lands in the SDK's `__wrap_printf`. + +The call chain for this project: + +``` +main +├── stdio_init_all +│ ├── stdio_uart_init ── gpio_set_function, uart_init +│ ├── stdio_set_driver_enabled +│ ├── stdio_out_chars_crlf +│ ├── stdio_put_string ── strlen +│ └── time_us_64 +└── __wrap_printf ── __wrap_vprintf +``` + +**Project 1 — resolve every function in that chain:** + +| Address | Rename to (`N`) | Signature (`Y`) | +| ------- | --------------- | --------------- | +| `0x1000015c` | `_reset_handler` | `void _reset_handler(void)` | +| `0x10000186` | `platform_entry` | `void platform_entry(void)` | +| `0x1000019a` | `data_cpy` | `void data_cpy(void*, void*, void*)` | +| `0x100001e4` | `_init` | `void _init(void)` | +| `0x10000210` | `frame_dummy` | `void frame_dummy(void)` | +| **`0x10000234`** | **`main`** | **`int main(void)`** | +| `0x10002cfc` | `exit` | `void exit(int)` | +| `0x10002d04` | `runtime_init` | `void runtime_init(void)` | +| `0x10002f54` | `stdio_init_all` | `bool stdio_init_all(void)` | +| `0x100032a0` | `stdio_uart_init` | `void stdio_uart_init(void)` | +| `0x10002f2c` | `stdio_set_driver_enabled` | `void stdio_set_driver_enabled(stdio_driver_t*, bool)` | +| `0x10002d30` | `stdio_out_chars_crlf` | `void stdio_out_chars_crlf(stdio_driver_t*, const char*, int)` | +| `0x10002e40` | `stdio_put_string` | `int stdio_put_string(const char*, int, bool, bool)` | +| `0x100030e4` | `__wrap_printf` | `int __wrap_printf(const char*, ...)` | +| `0x10003020` | `__wrap_vprintf` | `int __wrap_vprintf(const char*, va_list)` | +| `0x10000248` | `gpio_set_function` | `void gpio_set_function(uint, gpio_function_t)` | +| `0x10000e10` | `uart_init` | `uint uart_init(uart_inst_t*, uint)` | +| `0x10000da0` | `time_us_64` | `uint64_t time_us_64(void)` | +| `0x100033e0` | `strlen` | `size_t strlen(const char*)` | + +> **A `void` return type may not stick — here is the fix.** IDA treats `void` as low-confidence, and its analysis can override it with an inferred type — most often `int32_t` on this 32-bit target. It is most visible on `_reset_handler` (a hand-written assembly entry that never returns normally), but it can happen to **any** function whose return type IDA thinks it can infer. +> +> Setting the full signature with `Y` reproduces the unwanted `int32_t`, and `fn.return_type = ...` fails too. What works is the **return-value** setter: +> +> ```python +> from binaryninja import ReturnValue, Type +> fn = bv.get_function_at(0x1000015c) +> if fn is not None: +> fn.return_value = ReturnValue(Type.void()) +> ``` +> +> That holds `_reset_handler` at `void` even after reanalysis (verified live). Setting the signature and the return type both failing while `return_value` succeeds looks like a bug or inconsistency in this build (BN 6.0.10601). If it still will not stick, leave it — it does not affect the rest of the lesson. + +> **`__wrap_printf` is the real symbol.** `printf` in our source compiles to the SDK's `__wrap_printf` (which forwards to `__wrap_vprintf`). Rename it `printf` if you prefer the lesson's shorthand, but `__wrap_printf` is what the ELF says. +> +> **`stdio_init_all` returns `bool`, not `void`** — `_Bool stdio_init_all(void)` in the ELF. The `main` source ignores the return value, so the decompiler still reads fine. + +> **Shortcut — resolves name *and* type for every function.** Instead of doing `N` + `Y` by hand, paste this into IDA's Python console (`Plugins -> Python Console`). It sets each function's name and signature programmatically: +> +> ```python +> from binaryninja import Symbol, SymbolType +> # The raw .bin has no headers, so these SDK types don't exist. set_user_type() +> # re-parses each signature as C, so an undefined name raises +> # "SyntaxError: unknown type name '...'". Define them first. +> sdk = bv.parse_types_from_string(""" +> typedef unsigned int uint; +> typedef char* va_list; +> struct stdio_driver; +> typedef struct stdio_driver stdio_driver_t; +> struct uart_inst; +> typedef struct uart_inst uart_inst_t; +> enum gpio_function { +> GPIO_FUNC_XIP = 0, GPIO_FUNC_SPI = 1, GPIO_FUNC_UART = 2, GPIO_FUNC_I2C = 3, +> GPIO_FUNC_PWM = 4, GPIO_FUNC_SIO = 5, GPIO_FUNC_PIO0 = 6, GPIO_FUNC_PIO1 = 7, +> GPIO_FUNC_GPCK = 8, GPIO_FUNC_USB = 9, GPIO_FUNC_NULL = 0x1f, +> }; +> typedef enum gpio_function gpio_function_t; +> """) +> for name, ty in sdk.types.items(): +> bv.define_user_type(name, ty) +> +> # address: (name, signature); None means "leave the type alone" +> funcs = { +> 0x1000015c: ("_reset_handler", "void _reset_handler(void)"), +> 0x10000186: ("platform_entry", "void platform_entry(void)"), +> 0x1000019a: ("data_cpy", "void data_cpy(void*, void*, void*)"), +> 0x100001e4: ("_init", "void _init(void)"), +> 0x10000210: ("frame_dummy", "void frame_dummy(void)"), +> 0x10000234: ("main", "int main(void)"), +> 0x10002cfc: ("exit", "void exit(int)"), +> 0x10002d04: ("runtime_init", "void runtime_init(void)"), +> 0x10002f54: ("stdio_init_all", "bool stdio_init_all(void)"), +> 0x100032a0: ("stdio_uart_init", "void stdio_uart_init(void)"), +> 0x10002f2c: ("stdio_set_driver_enabled", "void stdio_set_driver_enabled(stdio_driver_t*, bool)"), +> 0x10002d30: ("stdio_out_chars_crlf", "void stdio_out_chars_crlf(stdio_driver_t*, const char*, int)"), +> 0x10002e40: ("stdio_put_string", "int stdio_put_string(const char*, int, bool, bool)"), +> 0x100030e4: ("__wrap_printf", "int __wrap_printf(const char*, ...)"), +> 0x10003020: ("__wrap_vprintf", "int __wrap_vprintf(const char*, va_list)"), +> 0x10000248: ("gpio_set_function", "void gpio_set_function(uint, gpio_function_t)"), +> 0x10000e10: ("uart_init", "uint uart_init(uart_inst_t*, uint)"), +> 0x10000da0: ("time_us_64", "uint64_t time_us_64(void)"), +> 0x100033e0: ("strlen", "size_t strlen(const char*)"), +> } +> for addr, (name, sig) in funcs.items(): +> bv.define_user_symbol(Symbol(SymbolType.FunctionSymbol, addr, name)) +> if sig: +> f = bv.get_function_at(addr) +> if f is not None: +> f.set_user_type(sig) +> ``` +> +> SDK type names (`stdio_driver_t`, `gpio_function_t`, `uart_inst_t`, plus `uint` and `va_list`) are **not** in the raw `.bin`. `set_user_type` re-parses each signature as C, so an undefined name raises `SyntaxError: unknown type name '...'` and stops the loop — it is not harmless. The `sdk` block above defines them first (an opaque `struct`/`enum`/`typedef` is enough to parse). If you add a function that uses another SDK type, add a definition for it to that block too. + +### Step 17: Read `main` in the decompiler + +Open the **Decompiler** view on `main`. It reads: + +```c +int32_t main(void) +{ + stdio_init_all(); + do + { + printf("age: %d\r\n", 0x2b); + } while (true); +} +``` + +The `0x2b` is the value we edited live. Now make it permanent. + +### Step 18: Patch `0x2b` to `0x46` in the GUI + +Go to `0x1000023a`: + +```asm +1000023a: 212b movs r1, #43 ; 0x2b +``` + +The halfword is `0x212b`, stored little-endian as `2b 21`. The immediate is the low byte, so the byte at the instruction's own address is `0x2b`. Change it to `0x46` (70). + +**Option A — Hex view:** + +1. Switch to the **Hex** view (`View -> Hex`). +2. Toggle the lock off so editing is enabled. +3. Go to `0x1000023a` and change the byte `2B` to `46`. +4. Return to the linear view, right-click the function -> `Reanalyze`. + +**Option B — Python console:** + +```python +bv.write(0x1000023a, b"\x46") +print(hex(bv.read(0x1000023a, 1)[0])) # -> 0x46 +``` + +After reanalysis the instruction reads `movs r1, #70`. + +### Step 18b: Patch the string `age:` to `foo:` in the GUI + +The format string `"age: %d\r\n"` starts at `0x100034a0`. Its first three bytes are `61 67 65` (`age`). Change them to `66 6f 6f` (`foo`), leaving the `: %d\r\n` tail untouched, so the line prints `foo: 70`. + +**Option A — Hex view:** + +1. Switch to the **Hex** view (`View -> Hex`). +2. Go to `0x100034a0` and change the three bytes `61 67 65` to `66 6f 6f`. +3. Return to the linear view and reanalyze. + +**Option B — Python console:** + +```python +bv.write(0x100034a0, b"foo") +print(bv.read(0x100034a0, 10)) # -> b'foo: %d\r\n\x00' +``` + +Keep the replacement exactly three bytes. If you use a shorter string you must pad it, or `%d` shifts and `printf` reads the wrong argument. A longer string would overwrite the `: %d` tail. + +### Step 19: Export the patched `.bin` + +```python +import os +seg = next(s for s in bv.segments if s.data_length) # the loadable image segment +data = bv.read(seg.start, seg.data_length) # base + size come from the view itself +out = os.path.join(os.path.join(root, "0x0005_intro-to-variables", "build"), "0x0005_intro-to-variables-h.bin") +open(out, "wb").write(data) +print(len(data), out) # -> 15292 /.../build/0x0005_intro-to-variables-h.bin +``` + +Where the two numbers come from — nothing is hardcoded: + +- **`seg.start`** is the image base IDA loaded the `.bin` at (`0x10000000`), the same value you pass to `uf2conv --base`. +- **`seg.data_length`** is the segment's size in the file (`0x3bbc` = 15292). Exactly one segment carries data (the image); every peripheral and synthetic segment has `data_length == 0`, so `next(...)` picks the image. +- Reading `seg.start` for `seg.data_length` bytes therefore grabs exactly the image. + +Two gotchas this avoids: + +- **No relative path.** IDA's Python console runs with a read-only working directory (inside the app bundle), so `open("0x0005_intro-to-variables-h.bin", "wb")` fails with `OSError: [Errno 30] Read-only file system`. `root` (from `~/.embedded-hacking-repo`, Step 3) is the repo, so the file is written into the project's `build/` — no machine-specific path and no database needed. +- **Read the image, not the whole view.** `bv.read(bv.start, bv.length)` spans the entire mapped range (`0x10000000`..`0xe008000c`), which is not the image. The segment's `data_length` is the image size. + +A different size means you exported a partial view. + +### Step 20: Convert to UF2 + +Run from the project directory: + +**macOS Apple Silicon / Linux x64:** + +```bash +python3 ../uf2conv.py 0x0005_intro-to-variables-h.bin \ + --base 0x10000000 --family 0xe48bff59 --output hacked.uf2 +``` + +**Windows x64:** + +```cmd +python ..\uf2conv.py 0x0005_intro-to-variables-h.bin ^ + --base 0x10000000 --family 0xe48bff59 --output hacked.uf2 +``` + +> **Or convert from the IDA console** — it is a normal Python interpreter, so you never have to leave the app. `chdir` to a writable directory first (the default one is read-only), then run the script: +> +> ```python +> import os, sys, runpy +> os.chdir(os.path.join(root, "0x0005_intro-to-variables", "build")) # the project build dir (writable) +> sys.argv = ["uf2conv.py", "0x0005_intro-to-variables-h.bin", +> "--base", "0x10000000", "--family", "0xe48bff59", "--output", "hacked.uf2"] +> runpy.run_path("../../uf2conv.py", run_name="__main__") # path to your uf2conv.py +> ``` +> +> This writes `hacked.uf2` next to the `.bin`, ready to drag onto the Pico. + +### Step 21: Flash and verify `age: 70` + +Hold **BOOTSEL**, plug in the Pico 2, and drag `hacked.uf2` onto the **`RP2350`** drive. Open the serial monitor: + +``` +age: 70 +age: 70 +age: 70 +... +``` + +**43 became 70, permanently, with one byte changed and no source code.** + +> **Faster: flash over the Debug Probe (no BOOTSEL).** The repo's `flash.sh` writes the raw `.bin` straight into XIP flash over SWD (`program 0x10000000 verify reset exit`), so you never touch BOOTSEL or a UF2. Run it from a terminal (`./flash.sh `), or from the IDA console **without freezing it** — use `subprocess.Popen`, which returns immediately, and send OpenOCD's output to a log file. (`subprocess.run` blocks the console until the flash finishes; do not use it here.) +> +> ```python +> import os, subprocess +> root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() +> bin_path = os.path.join(os.path.join(root, "0x0005_intro-to-variables", "build"), "0x0005_intro-to-variables-h.bin") +> log = os.path.join(os.path.join(root, "0x0005_intro-to-variables", "build"), "flash.log") +> subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # free the probe first +> p = subprocess.Popen([os.path.join(root, "flash.sh"), bin_path], +> stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) +> print("flashing in the background; log:", log) +> ``` +> +> The `pkill` frees the probe first; on Windows use `subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"])`. +> +> The console is free the moment this returns. Check it with `print(p.poll())` (`None` = still running, `0` = done) or read `flash.log` — success ends with `** Verified OK **`. (Verified: `Popen` returns in ~1 ms; the flash itself takes ~2 s.) +> +> The same non-blocking form without the script: +> +> ```python +> import os, subprocess +> ocd = os.path.expanduser("~/.pico-sdk/openocd/0.12.0+dev") +> bin_path = os.path.join(os.path.join(root, "0x0005_intro-to-variables", "build"), "0x0005_intro-to-variables-h.bin") +> log = os.path.join(os.path.join(root, "0x0005_intro-to-variables", "build"), "flash.log") +> subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # free the probe first +> p = subprocess.Popen([f"{ocd}/openocd", "-s", f"{ocd}/scripts", +> "-f", "interface/cmsis-dap.cfg", "-f", "target/rp2350.cfg", +> "-c", "adapter speed 5000", +> "-c", f"program {bin_path} 0x10000000 verify reset exit"], +> stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) +> print("flashing in the background; log:", log) +> ``` +> +> **The Debug Probe is single-owner.** If IDA is still attached (the `debug-server.sh` OpenOCD is running), the flash cannot grab the probe. Detach in IDA and stop that OpenOCD first: +> +> ```bash +> # macOS / Linux +> pkill -TERM -f openocd +> ``` +> ```powershell +> # Windows +> Get-Process openocd -ErrorAction SilentlyContinue | Stop-Process +> ``` +> +> Success looks like `Programming Finished` -> `Verified OK` -> `Resetting Target`. On Windows use `flash.ps1` (`.\flash.ps1 -Bin `) the same way. + +--- + +## Part 5: Dynamic — Break at `main` and Hack Live (Project 2) + +### Step 22: Reflash Project 2 and reload IDA + +Part 4 left the Pico running the patched Project 1 image. Put the original Project 2 back and start a fresh session. + +1. Stop any running debug server so the flash script can use the probe: + + ```bash + # macOS / Linux + pkill -TERM -f openocd + ``` + ```powershell + # Windows + Get-Process openocd -ErrorAction SilentlyContinue | Stop-Process + ``` + +2. Flash the original Project 2 image: + + ```bash + # macOS / Linux + ./flash.sh 0x0008_uninitialized-variables/build/0x0008_uninitialized-variables.bin + ``` + ```powershell + # Windows + .\flash.ps1 -Bin 0x0008_uninitialized-variables\build\0x0008_uninitialized-variables.bin + ``` + + **Or do steps 1–2 from the IDA console** (the active view is still Project 1, so take the repo root from it and point at the Project 2 `.bin`): + + **macOS / Linux:** + + ```python + import os, subprocess + root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) + bin_path = os.path.join(root, "0x0008_uninitialized-variables", "build", "0x0008_uninitialized-variables.bin") + log = os.path.join(os.path.dirname(bin_path), "flash.log") + subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # free the probe first + subprocess.Popen([os.path.join(root, "flash.sh"), bin_path], + stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) + print("flashing Project 2 in the background; log:", log) + ``` + + **Windows:** + + ```python + import os, subprocess + root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) + bin_path = os.path.join(root, "0x0008_uninitialized-variables", "build", "0x0008_uninitialized-variables.bin") + log = os.path.join(os.path.dirname(bin_path), "flash.log") + subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"]) # free the probe first + subprocess.Popen(["powershell", "-ExecutionPolicy", "Bypass", "-File", + os.path.join(root, "flash.ps1"), "-Bin", bin_path], + stdout=open(log, "w"), stderr=subprocess.STDOUT) + print("flashing Project 2 in the background; log:", log) + ``` + +3. Start the debug server again (Step 10) and wait for `Listening on port 3333`. +4. Load Project 2 and save its database — see Step 22b. +5. Connect IDA again (Step 11): adapter **GDB MI**, IP `127.0.0.1`, port `3333`. + +Confirm the Pico prints `age: 0` and blinks the red LED. + +### Step 22b: Load Project 2 into IDA and save the database + +Exactly like Steps 7–8, but for Project 2. **Use `File -> Open with Options...`** (not plain `File -> Open`), select `0x0008_uninitialized-variables/build/0x0008_uninitialized-variables.bin`, and set: + +- **Architecture:** `thumb2` +- **Platform:** `thumb2` +- **Base Address:** `0x10000000` + +Click **Open**. Then press `G`, type `0x10000000`, and confirm the first two words: + +``` +0x10000000 0x20082000 initial stack pointer +0x10000004 0x1000015d reset vector (bit 0 = Thumb) +``` + +If you see data at `0x00000000`, close the tab and redo it with `Open with Options`. + +Save it with `File -> Save As...` as `0x0008_uninitialized-variables.i64` (next to the `.bin`). From now on open the `.i64`, not the `.bin`; save with `Cmd+S` / `Ctrl+S` after every rename or patch. + +> **Console equivalent:** +> ```python +> load("0x0008_uninitialized-variables/build/0x0008_uninitialized-variables.bin", +> options={"loader.imageBase": 0x10000000, "loader.platform": "thumb2"}) +> ``` + +Then resolve the functions for Project 2 the same way as Project 1 — Step 26. + +### Step 23: Break at `main` + +`main` is at `0x10000234` in this project too. The GUI sets breakpoints fine (Step 13); the only caution is not to drive `reset run` from the port while IDA is attached (it desyncs IDA's view). Use `BP_ADDR`, which arms `main` before IDA connects: + +1. Stop the server (Ctrl-C), then start it parked at `main`: + ```bash + # macOS / Linux + BP_ADDR=0x10000234 ./debug-server.sh + ``` + ```powershell + # Windows + $env:BP_ADDR="0x10000234"; .\debug-server.ps1 + ``` + + **Or restart it from the IDA console** — kill any running server, then start it parked at `main`: + + **macOS / Linux:** + + ```python + import os, subprocess + root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() + log = os.path.join(root, "openocd.log") + subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # kill any running server first + subprocess.Popen([os.path.join(root, "debug-server.sh")], cwd=root, + env=dict(os.environ, BP_ADDR="0x10000234"), + stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) + print("OpenOCD restarted parked at main; log:", log) + ``` + + **Windows:** + + ```python + import os, subprocess + root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() + log = os.path.join(root, "openocd.log") + subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"]) # kill any running server first + subprocess.Popen(["powershell", "-ExecutionPolicy", "Bypass", "-File", + os.path.join(root, "debug-server.ps1")], cwd=root, + env=dict(os.environ, BP_ADDR="0x10000234"), + stdout=open(log, "w"), stderr=subprocess.STDOUT) + print("OpenOCD restarted parked at main; log:", log) + ``` +2. Connect IDA (Step 11): adapter **GDB MI**, IP `127.0.0.1`, port `3333`. + +The target is already halted at `main` when IDA connects, and the sidebar reads `Stopped at 0x10000234`. + +> If you instead want to reach `main` on an already-connected session, you must Detach, send `reset run` from the port, then reconnect. Arming `main` and resetting while attached leaves the sidebar showing a stale address. + +`main` sets up GPIO 16 and then loops: print `age`, turn the LED on, sleep, turn it off, sleep. The whole loop is one function because `blink_and_print` was inlined: + +```asm +10000234
: +10000234: b538 push {r3, r4, r5, lr} +10000236: f002 ff49 bl 0x100030cc ; stdio_init_all +1000023a: 2010 movs r0, #16 ; LED_PIN +1000023c: f000 f83a bl 0x100002b4 ; gpio_init +10000240: f04f 0501 mov.w r5, #1 +10000244: 2310 movs r3, #16 ; LED_PIN +10000246: ec45 3044 mcrr 0, 4, r3, r5, cr4 ; gpio_set_dir(16, OUT) +1000024a: 2100 movs r1, #0 ; age +1000024c: 4809 ldr r0, [pc, #36] ; @ 0x10000274 -> "age: %d\r\n" +1000024e: f003 f805 bl 0x1000325c ; __wrap_printf +10000252: 2410 movs r4, #16 ; LED_PIN +10000254: ec45 4040 mcrr 0, 4, r4, r5, cr0 ; gpio_put(16, 1) +10000258: f44f 70fa mov.w r0, #500 +1000025c: f000 fd58 bl 0x10000d10 ; sleep_ms +10000260: f04f 0300 mov.w r3, #0 +10000264: ec43 4040 mcrr 0, 4, r4, r3, cr0 ; gpio_put(16, 0) +10000268: f44f 70fa mov.w r0, #500 +1000026c: f000 fd50 bl 0x10000d10 ; sleep_ms +10000270: e7eb b.n 0x1000024a +10000272: bf00 nop +10000274: 10003618 .word 0x10003618 +``` + +Look at the **Registers** widget at `0x1000024e`: `r1` is `0`, which is why the Pico prints `age: 0`. + +### Step 24: Inspect the GPIO registers live + +The GPIO hardware is memory-mapped. Go to each address and watch it change as you step: + +| Address | Block | Role | +| ------- | ----- | ---- | +| `0x40028000` | `IO_BANK0` | pin function select and status | +| `0x40038000` | `PADS_BANK0` | pad configuration | +| `0xd0000000` | `SIO` | single-cycle GPIO block driven by `mcrr` | + +Step Over through `0x10000254` (`mcrr 0, 4, r4, r5, cr0`) and watch the SIO output register change: this is `gpio_put(16, 1)` turning the red LED on at the hardware level. + +### Step 25: HACK IT LIVE — change the printed value + +1. Press `G`, go to `0x1000024e` (the `bl __wrap_printf`). +2. Set a **hardware execute** breakpoint at `0x1000024e` in the GUI (`Debugger -> Add Hardware Breakpoint...`; not `F2`). Note `0x1000024e` — Project 2's loop sits at a different address than Project 1's. +3. Click **Resume** in IDA. The target is already looping, so the breakpoint fires on the next pass. IDA stops with `r1 = 0`. +4. Set `r1` to `0x42` (66): + ```python + dbg.set_reg_value("r1", 0x42) + ``` + (Or right-click `r1` in the **Registers** widget, press `E`, type `42`, and press Enter.) +5. **Move the breakpoint past the call.** `0x10000252` is the instruction right after the `bl __wrap_printf`. Remove the breakpoint at `0x1000024e` and set a hardware breakpoint at `0x10000252`, then click **Resume**. The core runs `printf` with `r1 = 0x42` and stops at `0x10000252`. (Not **Step Over** — it steps into the call on this symbol-less `.bin`, and a breakpoint left on the current PC re-traps the step; Step 13 explains both.) +6. Look at your serial monitor and the **Target** tab: + + ``` + age: 66 + ``` + +Press **Resume** and the next iteration prints `age: 0` again, because the loop reloads `movs r1, #0` each pass. The live hack is temporary; the static patch makes it permanent. + +### Step 25b: HACK THE STRING LIVE — change `age:` to `foo:` + +Same idea as Project 1, different addresses. Here the format string is at `0x10003618` and the `printf` call is at `0x1000024e`. + +1. Hit the breakpoint at `0x1000024e` as in Step 25. At the stop, `r0 = 0x10003618` and `r1 = 0`. +2. Write the replacement string to free RAM at `0x20080000` from the **Python console** (`dbg.write_memory` — no command port needed): + ```python + dbg.write_memory(0x20080000, b"foo: %d\r\n\x00") + ``` + Bytes `66 6f 6f 3a 20 25 64 0d 0a 00` = `"foo: %d\r\n\0"`. +3. Point `r0` at that string: + ```python + dbg.set_reg_value("r0", 0x20080000) + ``` + (Or right-click `r0` in the **Registers** widget, press `E`, type `0x20080000`, and press Enter.) +4. Move the breakpoint past the call in the GUI (remove it at `0x1000024e`, set one at `0x10000252`) and click **Resume**. This iteration prints: + ``` + foo: 0 + ``` + then stops at `0x10000252`. One iteration only — the loop reloads `r0` each pass. The permanent version is the static patch in Step 28b. + +### Step 25c: Kill the debugger and OpenOCD + +Same as Step 15b: click the **X** (**Kill**) in the **Debugger** sidebar (or **`Debugger -> Kill`**), then stop OpenOCD from the IDA console: + +**macOS / Linux:** + +```python +import subprocess +subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # stop the debug server, free the probe +``` + +**Windows:** + +```python +import subprocess +subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"]) # stop the debug server, free the probe +``` + +--- + +## Part 6: Static — Resolve the Functions and Patch (Project 2) + +### Step 26: Resolve the functions in the IDA GUI + +Same two keys as Step 16 — `G` to the address, then `Y` (Change Type) to set the prototype — using the Project 2 ELF symbol map from Step 4. + +The mechanics are identical to Step 16, so here are the worked examples for the functions that are specific to this project. + +#### `main` + +1. `G` -> `0x10000234`. +2. `Y` -> `int main(void)` (IDA shows `int32_t main(void)` — the same 32-bit `int`). + +#### `gpio_init` + +1. `G` -> `0x100002b4`. +2. `Y` -> `void gpio_init(uint gpio)`. + +#### `sleep_ms` + +1. `G` -> `0x10000d10`. +2. `Y` -> `void sleep_ms(uint32_t ms)`. + +#### `stdio_init_all` and `__wrap_printf` + +Same as Project 1, different addresses: `stdio_init_all` at `0x100030cc` (`bool stdio_init_all(void)`), and `__wrap_printf` at `0x1000325c` (`int __wrap_printf(const char *fmt, ...)`). + +Then work down the table the same way. + +Same idea as Project 1: **our code plus what it calls**, not the whole SDK. The call chain here is one function longer because `main` also drives the GPIO and sleeps: + +``` +main +├── stdio_init_all +│ ├── stdio_uart_init ── gpio_set_function, uart_init +│ ├── stdio_set_driver_enabled +│ ├── stdio_out_chars_crlf +│ ├── stdio_put_string ── strlen +│ └── time_us_64 +├── gpio_init +├── __wrap_printf ── __wrap_vprintf +└── sleep_ms +``` + +Two things in this project have **no symbol of their own**, because the compiler inlined them into `main`: + +- `blink_and_print` — the `static` helper in our own source is inlined, so there is no `blink_and_print` address to rename. You see its body directly inside `main`. +- `gpio_set_dir` and `gpio_put` — these are `static inline` in the SDK headers, so they compile to the `mcrr`/SIO writes you see in `main` rather than to calls. + +**Project 2 — resolve every function in that chain:** + +| Address | Rename to (`N`) | Signature (`Y`) | +| ------- | --------------- | --------------- | +| `0x1000015c` | `_reset_handler` | `void _reset_handler(void)` | +| `0x10000186` | `platform_entry` | `void platform_entry(void)` | +| `0x1000019a` | `data_cpy` | `void data_cpy(void*, void*, void*)` | +| `0x100001e4` | `_init` | `void _init(void)` | +| `0x10000210` | `frame_dummy` | `void frame_dummy(void)` | +| **`0x10000234`** | **`main`** | **`int main(void)`** | +| `0x100002b4` | `gpio_init` | `void gpio_init(uint)` | +| `0x10000278` | `gpio_set_function` | `void gpio_set_function(uint, gpio_function_t)` | +| `0x10000d10` | `sleep_ms` | `void sleep_ms(uint32_t)` | +| `0x10002e74` | `exit` | `void exit(int)` | +| `0x10002e7c` | `runtime_init` | `void runtime_init(void)` | +| `0x100030cc` | `stdio_init_all` | `bool stdio_init_all(void)` | +| `0x10003418` | `stdio_uart_init` | `void stdio_uart_init(void)` | +| `0x100030a4` | `stdio_set_driver_enabled` | `void stdio_set_driver_enabled(stdio_driver_t*, bool)` | +| `0x10002ea8` | `stdio_out_chars_crlf` | `void stdio_out_chars_crlf(stdio_driver_t*, const char*, int)` | +| `0x10002fb8` | `stdio_put_string` | `int stdio_put_string(const char*, int, bool, bool)` | +| `0x1000325c` | `__wrap_printf` | `int __wrap_printf(const char*, ...)` | +| `0x10003198` | `__wrap_vprintf` | `int __wrap_vprintf(const char*, va_list)` | +| `0x10000f88` | `uart_init` | `uint uart_init(uart_inst_t*, uint)` | +| `0x10000ef4` | `time_us_64` | `uint64_t time_us_64(void)` | +| `0x10003558` | `strlen` | `size_t strlen(const char*)` | + +Python console shortcut (resolves name **and** type): + +```python +from binaryninja import Symbol, SymbolType +# The raw .bin has no headers, so these SDK types don't exist. set_user_type() +# re-parses each signature as C, so an undefined name raises +# "SyntaxError: unknown type name '...'". Define them first. +sdk = bv.parse_types_from_string(""" +typedef unsigned int uint; +typedef char* va_list; +struct stdio_driver; +typedef struct stdio_driver stdio_driver_t; +struct uart_inst; +typedef struct uart_inst uart_inst_t; +enum gpio_function { + GPIO_FUNC_XIP = 0, GPIO_FUNC_SPI = 1, GPIO_FUNC_UART = 2, GPIO_FUNC_I2C = 3, + GPIO_FUNC_PWM = 4, GPIO_FUNC_SIO = 5, GPIO_FUNC_PIO0 = 6, GPIO_FUNC_PIO1 = 7, + GPIO_FUNC_GPCK = 8, GPIO_FUNC_USB = 9, GPIO_FUNC_NULL = 0x1f, +}; +typedef enum gpio_function gpio_function_t; +""") +for name, ty in sdk.types.items(): + bv.define_user_type(name, ty) + +# address: (name, signature); None means "leave the type alone" +funcs = { + 0x1000015c: ("_reset_handler", "void _reset_handler(void)"), + 0x10000186: ("platform_entry", "void platform_entry(void)"), + 0x1000019a: ("data_cpy", "void data_cpy(void*, void*, void*)"), + 0x100001e4: ("_init", "void _init(void)"), + 0x10000210: ("frame_dummy", "void frame_dummy(void)"), + 0x10000234: ("main", "int main(void)"), + 0x100002b4: ("gpio_init", "void gpio_init(uint)"), + 0x10000278: ("gpio_set_function", "void gpio_set_function(uint, gpio_function_t)"), + 0x10000d10: ("sleep_ms", "void sleep_ms(uint32_t)"), + 0x10002e74: ("exit", "void exit(int)"), + 0x10002e7c: ("runtime_init", "void runtime_init(void)"), + 0x100030cc: ("stdio_init_all", "bool stdio_init_all(void)"), + 0x10003418: ("stdio_uart_init", "void stdio_uart_init(void)"), + 0x100030a4: ("stdio_set_driver_enabled", "void stdio_set_driver_enabled(stdio_driver_t*, bool)"), + 0x10002ea8: ("stdio_out_chars_crlf", "void stdio_out_chars_crlf(stdio_driver_t*, const char*, int)"), + 0x10002fb8: ("stdio_put_string", "int stdio_put_string(const char*, int, bool, bool)"), + 0x1000325c: ("__wrap_printf", "int __wrap_printf(const char*, ...)"), + 0x10003198: ("__wrap_vprintf", "int __wrap_vprintf(const char*, va_list)"), + 0x10000f88: ("uart_init", "uint uart_init(uart_inst_t*, uint)"), + 0x10000ef4: ("time_us_64", "uint64_t time_us_64(void)"), + 0x10003558: ("strlen", "size_t strlen(const char*)"), +} +for addr, (name, sig) in funcs.items(): + bv.define_user_symbol(Symbol(SymbolType.FunctionSymbol, addr, name)) + if sig: + f = bv.get_function_at(addr) + if f is not None: + f.set_user_type(sig) +``` + +The decompiler now shows `main` initializing GPIO 16 and looping. We make two changes: + +- **Move the LED from GPIO 16 to GPIO 17** by patching three `0x10` immediates. +- **Change the printed value from 0 to 66** by patching one `0x00` immediate. + +### Step 27: Patch 1 — move the LED from GPIO 16 to GPIO 17 + +GPIO 16 is the red LED; GPIO 17 is the green LED. The pin number appears in three instructions. Change the low byte of each from `10` to `11`: + +| Address | Instruction | Bytes before | Bytes after | Role | +| ------- | ----------- | ------------ | ----------- | ---- | +| `0x1000023a` | `movs r0, #16` | `10 20` | `11 20` | pin passed to `gpio_init` | +| `0x10000244` | `movs r3, #16` | `10 23` | `11 23` | pin used by `gpio_set_dir` | +| `0x10000252` | `movs r4, #16` | `10 24` | `11 24` | pin used by `gpio_put` in the blink loop | + +In the **Hex** view (lock off), change each byte and reanalyze. Or in the Python console: + +```python +for addr in (0x1000023a, 0x10000244, 0x10000252): + bv.write(addr, b"\x11") +``` + +> **All three are required.** If you patch only the `gpio_set_dir` site, pin 17's output driver is enabled but `gpio_put` still drives pin 16, whose driver was never enabled. Nothing lights up. This is the most common mistake in this lesson. + +### Step 28: Patch 2 — change the printed value from 0 to 66 + +`main` loads `age = 0` with `movs r1, #0` at `0x1000024a`. Change the immediate byte from `00` to `42` (`0x42` = 66): + +```python +bv.write(0x1000024a, b"\x42") +``` + +Verify all four patches: + +```python +for addr in (0x1000023a, 0x10000244, 0x10000252, 0x1000024a): + print(hex(addr), hex(bv.read(addr, 1)[0])) +# -> 0x1000023a 0x11 +# -> 0x10000244 0x11 +# -> 0x10000252 0x11 +# -> 0x1000024a 0x42 +``` + +### Step 28b: Patch the string `age:` to `foo:` + +The format string starts at `0x10003618`; change its first three bytes `61 67 65` (`age`) to `66 6f 6f` (`foo`): + +```python +bv.write(0x10003618, b"foo") +print(bv.read(0x10003618, 10)) # -> b'foo: %d\r\n\x00' +``` + +Exactly three bytes, same rule as Project 1: a shorter string must be padded, a longer one overwrites the `: %d` tail. + +### Step 29: Export, convert, and flash + +```python +import os +seg = next(s for s in bv.segments if s.data_length) # the loadable image segment +data = bv.read(seg.start, seg.data_length) # base + size from the view itself +out = os.path.join(os.path.join(root, "0x0008_uninitialized-variables", "build"), "0x0008_uninitialized-variables-h.bin") +open(out, "wb").write(data) +print(len(data), out) # -> 15668 /.../build/0x0008_uninitialized-variables-h.bin +``` + +Same as Project 1: `seg.start` is the load base and `seg.data_length` is the image size (here `0x3d34` = 15668) — both read from the view, and no relative path (the console's CWD is read-only). + +**macOS Apple Silicon / Linux x64:** + +```bash +python3 ../uf2conv.py 0x0008_uninitialized-variables-h.bin \ + --base 0x10000000 --family 0xe48bff59 --output hacked.uf2 +``` + +**Windows x64:** + +```cmd +python ..\uf2conv.py 0x0008_uninitialized-variables-h.bin ^ + --base 0x10000000 --family 0xe48bff59 --output hacked.uf2 +``` + +Or run the conversion from the IDA console, exactly as in Step 20 (`os.chdir` to the build dir, then `runpy.run_path("../../uf2conv.py", run_name="__main__")` with `sys.argv` set to the arguments above). + +Hold **BOOTSEL**, plug in the Pico 2, drag `hacked.uf2` onto the **`RP2350`** drive. Or flash the `.bin` over the Debug Probe with SWD — no BOOTSEL — from the console, exactly as in Step 21 (stop any running OpenOCD first, and use `Popen`, not `run`, so the console is not blocked): + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() +bin_path = os.path.join(os.path.join(root, "0x0008_uninitialized-variables", "build"), "0x0008_uninitialized-variables-h.bin") +log = os.path.join(os.path.join(root, "0x0008_uninitialized-variables", "build"), "flash.log") +subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # free the probe first +p = subprocess.Popen([os.path.join(root, "flash.sh"), bin_path], + stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) +print("flashing in the background; log:", log) +``` + +### Step 30: Verify + +Open the serial monitor: + +``` +age: 66 +age: 66 +age: 66 +... +``` + +The **green LED on GPIO 17** now blinks instead of the red one. + +**We changed the printed value and moved the LED, with four bytes and no source code.** + +--- + +## Cheatsheet + +### IDA GUI actions + +| Action | How | +| ------ | --- | +| Go to address | `G` | +| Rename function/symbol | `N` | +| Set type or signature | `Y` | +| Add comment | `;` | +| Open Hex view | `View -> Hex` | +| Enable hex editing | Toggle the lock in the status bar | +| Reanalyze after a patch | Right-click function -> `Reanalyze` | +| Edit a register live | `dbg.set_reg_value("r1", 0x46)` in the Python console (or right-click the register, press `E`, type hex, Enter) | +| Set a breakpoint | `Debugger -> Add Hardware Breakpoint...` (hardware execute). Do **not** use `F2` — software breakpoints cannot be written to read-only flash. | +| Move a breakpoint | Remove it and set it at the new address in the GUI (command-port fallback: `rbp ` then `bp 2 hw`) | +| Confirm what is armed | The **Breakpoints** widget lists it (command-port fallback: `mdw 0xE0002000 8`, each armed breakpoint shows as ``) | +| Apply the ELF symbol map | Paste the Python snippet from Step 16 / 26 into the Python Console | + +### OpenOCD server and reset + +The server runs with `gdb_breakpoint_override hard` so that flash-writes are never attempted. Breakpoints in this lab are set in the IDA GUI through the **GDB MI** adapter (Step 13). The command-port rows below are the fallback if you use the **GDB RSP** adapter instead. + +| Action | Command | +| ------ | ------- | +| Connect to the OpenOCD prompt (fallback) | `nc 127.0.0.1 4444` (or `telnet 127.0.0.1 4444`) | +| Reset and run (command port) | `reset run` | +| Check core state (command port) | `targets` | +| Set a breakpoint in the GUI | `Debugger -> Add Hardware Breakpoint...` (hardware execute; `F2` software breakpoints do not work on flash) | +| (fallback) Add a breakpoint without the GUI | `bp 2 hw` | +| Remove one breakpoint | `rbp ` — **address only, no length, no `hw`** | +| Remove every breakpoint | `rbp all` | +| Start the server parked at `main` | macOS/Linux: `BP_ADDR=0x10000234 ./debug-server.sh` — Windows: `$env:BP_ADDR="0x10000234"; .\debug-server.ps1` (one-shot) | +| Start the server parked in the loop | macOS/Linux: `BP_ADDR=0x1000023e ./debug-server.sh` — Windows: `$env:BP_ADDR="0x1000023e"; .\debug-server.ps1` (`0x1000024e` for Project 2) | +| Break on the loop in a running target | set a hardware breakpoint in the GUI at the loop address, then **Resume** — repeatable | +| Make IDA stepping work | `rp2350.dap.core0 configure -rtos none` (already in the scripts) | +| Step without re-trapping | move the breakpoint off the current PC first, then **Step Into**/**Step Over** | +| Reset without desyncing IDA | **Detach**, `reset run` on the port, reconnect — never `reset run` while attached | + +### Every address and byte we changed + +| Project | Address | Before | After | Effect | +| ------- | ------- | ------ | ----- | ------ | +| `0x0005` | `0x1000023a` | `2b` | `46` | prints `age: 70` | +| `0x0008` | `0x1000023a` | `10` | `11` | `gpio_init` configures GPIO 17 | +| `0x0008` | `0x10000244` | `10` | `11` | `gpio_set_dir` enables GPIO 17 | +| `0x0008` | `0x10000252` | `10` | `11` | `gpio_put` drives GPIO 17 | +| `0x0008` | `0x1000024a` | `00` | `42` | prints `age: 66` | +| `0x0005` | `0x100034a0` | `61 67 65` | `66 6f 6f` | string prints `foo:` instead of `age:` | +| `0x0008` | `0x10003618` | `61 67 65` | `66 6f 6f` | string prints `foo:` instead of `age:` | + +### Raw image facts + +| Item | Value | +| ---- | ----- | +| Build type | `Release` | +| Load base address | `0x10000000` | +| Project 1 size | `15292` bytes | +| Project 2 size | `15668` bytes | +| Fixed `main` anchor (both projects) | `0x1000018c` (reset handler middle `blx`) | +| `main` (both projects) | `0x10000234` | +| `printf` call, Project 1 | `0x1000023e` | +| `printf` call, Project 2 | `0x1000024e` | +| RP2350 UF2 family ID | `0xe48bff59` | + +--- + +## Troubleshooting + +### IDA hangs or crashes when you connect (macOS 27) + +Three different causes have been seen on this setup; check them in this order. + +- **A breakpoint set before connecting.** With the **GDB MI** adapter, if the binary view already has a breakpoint, the session hangs. Start parked with `BP_ADDR`, connect, then add breakpoints (see the next entry). +- **The wrong GDB executable.** Point **Full GDB Executable Path** at the **14.2.rel1** toolchain (Step 11). The 13.3.rel1 build (what `/opt/homebrew/bin/arm-none-eabi-gdb` symlinks to) did not connect in testing. +- **The LLDB adapter.** A crash report with `libdebuggercore.dylib -> std::terminate() -> abort()` and `liblldb` in the stack is the **LLDB** adapter, not GDB MI. Avoid LLDB on this setup. + +**Use GDB MI**, with the 14.2.rel1 path above. If it still fails, fall back to plain `arm-none-eabi-gdb` against the same server — the addresses and register values are identical to the GUI steps. + +If IDA hangs, force-quit it; the connect dialog has no working Cancel. The static steps (resolve, patch, export, flash) never touch the debugger and always work. + +### The GUI refuses to set a breakpoint (GDB RSP adapter only) + +If you are on the **GDB RSP** adapter, the GUI cannot set breakpoints on this target. That adapter is IDA's own minimal RSP client and sends a **1-byte** breakpoint (`Z0,,1`); the Cortex-M33 comparators need 2 bytes, so OpenOCD answers `only breakpoints of two bytes length supported`. It affects every address, both `Toggle Breakpoint` and `Add Hardware Breakpoint`, and the dialog's **Size** field is disabled. `gdb_breakpoint_override` makes no difference. + +**Fix: use the GDB MI adapter** (Step 11). It drives real GDB, which sends the correct length, so GUI breakpoints just work. If you must stay on GDB RSP, arm breakpoints from the command port after connecting (`bp 2 hw`) — but the lab uses GDB MI and does not need that. + +### GDB MI hangs when you connect (a breakpoint already existed) + +With the **GDB MI** adapter, if IDA already has a breakpoint set when you connect, the session **hangs**. This is a IDA bug. The working order is: + +1. Start the server parked, e.g. `BP_ADDR=0x10000234 ./debug-server.sh` (Windows: `$env:BP_ADDR="0x10000234"; .\debug-server.ps1`). +2. Connect with the **GDB MI** adapter. +3. Only *then* set hardware breakpoints in the UI. + +Never have a breakpoint in the binary view before the GDB MI connection. If it hangs, quit IDA, restart the server with `BP_ADDR`, and connect again before adding any breakpoints. + +### Step Into / Step Over does nothing (PC never moves) + +Two causes have been seen on this target. + +1. **A breakpoint on the current PC re-traps the step.** OpenOCD's step-over-breakpoint logic fails with `Duplicate Breakpoint address` and the PC stays put. Fix: move the breakpoint off the current PC (in the GUI), then step. +2. **The `hwthread` RTOS (GDB RSP adapter only).** With the **GDB RSP** adapter, OpenOCD can log `fake step thread 0` and reply without stepping, because the RP2350 config's `-rtos hwthread` makes the current thread id 1 while IDA sends thread id 0. Fix: `rp2350.dap.core0 configure -rtos none` (the launcher scripts already pass this). **GDB MI does not hit this.** + +To tell them apart, turn on OpenOCD logging (`log_output /tmp/ocd.log`, then `debug_level 3` on the command port) and look for `fake step` versus `Duplicate Breakpoint`. + +### `zsh: bad CPU type in executable: cmake` + +An Intel `x86_64` tool is on your `PATH` on Apple Silicon. Run Step 2: `export PATH="/opt/homebrew/bin:$PATH"`, then `hash -r`. Add it to `~/.zshrc` to make it permanent. + +### My addresses do not match this guide + +You probably built `Debug`. This lesson is a `Release` build. Re-run Step 3 with `-DCMAKE_BUILD_TYPE=Release`. A `Debug` build moves the SDK functions and keeps `blink_and_print` separate, so Project 2's `main` is not at `0x10000234`. + +### A breakpoint never fires + +First, confirm you actually set one, and that it is a **hardware** breakpoint. With the **GDB MI** adapter, `Debugger -> Add Hardware Breakpoint...` (hardware execute) should land in the **Breakpoints** widget. If nothing lands, or the core keeps running, you probably used `F2` (`Toggle Breakpoint`) — that is a software breakpoint and cannot be written to read-only flash, so it never installs. Also check you are on **GDB MI**, not **GDB RSP** (the GDB RSP adapter cannot set breakpoints on this target at all). + +Then check the order and the state: + +- **Arm it only after IDA is connected.** OpenOCD flushes every breakpoint when a client attaches (`breakpoint_remove_all_internal` -> `Delete all breakpoints`), so anything armed earlier is gone. This also applies to `BP_ADDR` on the startup command line, and to `hbreak` followed by `detach` in GDB. +- **Verify it is armed:** `mdw 0xE0002000 8`. You should see your address with the low bit set (`0x10000234` -> `0x10000235`). All zeros means nothing is armed — re-read this first, because it distinguishes "not armed" from "armed but never reached". +- **Is the core running?** `poll` on the command port should not report a halt. If it is stopped, click **Resume**. +- **Does the address get reached again?** `main` runs once per reset, so use `BP_ADDR` at startup (Step 10) rather than `reset run` while attached. Loop addresses such as `0x1000023e` fire on the next pass with no reset — arm them and click **Resume** in IDA. +- **With GDB MI the stop is reported as `Breakpoint`** and appears in the **Breakpoints** widget, because GDB really did set it. (On the old **GDB RSP** workaround the stop showed as `SingleStep` with an empty widget, because the breakpoint was armed behind IDA's back.) + +### I edit `r1` (or another register) and it reverts + +`main` reloads the value at the top of every loop iteration — `movs r1, #43` at `0x1000023a` runs right before the `printf` at `0x1000023e`. So `r1` is only `0x46` for the instant between your edit and the next pass; then it is `0x2b` again. The edit sticks only if the core is **genuinely stopped** at the breakpoint and stays stopped. + +If it keeps reverting, the core is running, which almost always means the breakpoint is not installed — usually because it is a **software** breakpoint (`F2`) that cannot be written to read-only flash. Use `Debugger -> Add Hardware Breakpoint...` (hardware execute). Confirm with `mdw 0xE0002000 4` on the command port: a hardware breakpoint shows as `0x1000023f`; all zeros means nothing is armed. + +> **The Registers widget is a snapshot, not a live view.** IDA reads the registers at each stop and shows that snapshot; it does not poll the target, and there is no "refresh registers" command (only "Force Update Memory Cache", which is for memory). So a value changed outside IDA will not appear until the next stop. + +### The serial capture is garbage on macOS + +Reading `/dev/cu.usbmodem*` with a bare `read()` returns garbage. Set **raw termios at 115200** first: clear canonical/echo flags, set `CLOCAL|CREAD`, and `B115200` on input and output. `screen /dev/cu.usbmodem* 115200` does all of this for you; a script must call `tcsetattr` itself. Once set, the capture reads clean `age: 43` lines. + +### It worked for a second, then stopped (IDA's view desyncs) + +This is the most common failure, and it has one main cause: **driving the core from the OpenOCD command port while IDA is connected.** + +- If you send `reset run` from the port while attached, the core resets, runs, and halts at your breakpoint — but IDA never receives the stop event. Its sidebar keeps showing the *previous* location, so **Step** and **Resume** act on a stale PC and appear to do nothing. Verified: target at `0x1000023e` while the sidebar still read `Stopped at 0x10003020`. +- If the OpenOCD process dies (or you restart it) while attached, IDA keeps believing it is connected: the sidebar stays, but the menu shows **Pause** enabled and **Resume**/**Step** disabled because IDA last saw the target *running*. + +Recovery: **Detach, then reconnect.** If Detach does nothing (the connection is already dead), restart IDA — its menu still shows a session that no longer exists. + +Prevention: +- Stop at `main` with `BP_ADDR` on a fresh server start, not with `reset run` while attached. +- For loop addresses, set the breakpoint in the GUI and click **Resume**. Let IDA be the thing that starts the core. +- If you must reset, **Detach first**, `reset run`, then reconnect. +- Never leave a breakpoint on the PC you are about to step or resume from (see the stepping section above). + +> **If the stop is at `0x1000320c` rather than your breakpoint,** you stopped inside `stdio_uart_out_flush`, not at `main`. See the next section. + +### The target "blows past" `main` and stops at `0x1000320c` instead + +`0x1000320c` is inside `stdio_uart_out_flush`: + +```asm +1000320c: 6993 ldr r3, [r2, #24] +1000320e: 071b lsls r3, r3, #28 +10003210: d4fc bmi.n 0x1000320c +``` + +That is the UART transmit-FIFO drain loop inside `printf`, so the core is running `main`'s loop and simply spends nearly all its time there. The breakpoint at `main` did not fire because `main`'s entry (`0x10000234`) runs exactly **once per reset**. If you arm the breakpoint after the reset, or set it while the target is already running and just resume, the core is already past `0x10000234` and will never re-execute it. Either arm the breakpoint **before** resetting, or break inside the loop at `0x1000023e`, which fires every iteration. + +**`0x1000320c` is not a function.** It is one instruction inside `stdio_uart_out_flush`, which starts at `0x10003208`: + +```asm +10003208 : +10003208: 4b02 ldr r3, [pc, #8] ; @ 0x10003214 +1000320a: 681a ldr r2, [r3] +1000320c: 6993 ldr r3, [r2, #24] ; the core sits here while the UART drains +1000320e: 071b lsls r3, r3, #28 +10003210: d4fc bmi.n 0x1000320c +10003212: 4770 bx lr +10003214: 20000850 .word 0x20000850 +``` + +If IDA has created a function at `0x1000320c` (for example because the debugger stopped at that PC), the decompiler shows garbage: registers named `entry_r4`/`entry_r5`, and stores to invented constants like `0x3a` and `0xfffffff6`. Delete that bogus function (right-click it -> `Delete Function`, or put the cursor on it and press `U` to undefine) and reanalyze. The real function is `stdio_uart_out_flush` at `0x10003208`. + +### The console floods with `Failed to read memory at 0xf0000000` + +Core1 is exposed. The scripts must run with `USE_CORE=0`. Stop the server, confirm only `core0` is reported, restart, then restart IDA. + +### `Connect to Remote Process` is greyed out and Pause does nothing + +IDA is in a stale session, usually because the debug server restarted while attached. Quit and reopen IDA (or the `.i64`) and connect again. + +### The decompiler still shows the old value after patching + +Right-click the function and choose `Reanalyze`. + +### Project 2's LED does not light at all after patching + +You patched only some of the three GPIO 16 sites. All three of `0x1000023a`, `0x10000244`, and `0x10000252` must change. + +--- + +## Fallback: do the dynamic steps with GDB (macOS 27) + +If IDA's debugger crashes on attach on macOS 27 (see Troubleshooting), you can still do the live hack with the ARM GDB from the toolchain, against the same OpenOCD server. The addresses and register values are identical to the GUI steps. + +Start the debug server (Step 10), then in a new terminal: + +``` +arm-none-eabi-gdb +``` + +At the `(gdb)` prompt: + +``` +set architecture armv8-m.main +target extended-remote :3333 +hbreak *0x1000023e +continue +``` + +Do **not** run `monitor reset run` before `hbreak`. `0x1000023e` is inside `main`'s loop, so the breakpoint fires on the next iteration with no reset. If you reset first, the core runs `main` and you will not catch it. + +GDB stops at the `printf` call. Confirm the value, change it, and let it run: + +``` +info registers pc r1 # pc = 0x1000023e, r1 = 0x2b +set $r1 = 0x46 +stepi +continue +``` + +The serial monitor prints `age: 70` for the iteration you changed — the same temporary live hack as editing `r1` in the IDA Registers widget. When you are done, press `Ctrl-C`, then `detach` and `quit`. + +**If you specifically want to stop at `main` (`0x10000234`),** remember its entry runs only once per reset, so the breakpoint must be armed *before* the reset: + +``` +monitor reset halt +hbreak *0x10000234 +continue +``` + +If you instead set it while the target is running and just `continue`, you will "blow past" `main` and catch the core inside `printf` — in this build at `0x1000320c`, the `stdio_uart_out_flush` UART-drain loop. + +Project 2 is the same with the other call site and value: + +``` +hbreak *0x1000024e +continue +info registers pc r1 # pc = 0x1000024e, r1 = 0 +set $r1 = 0x42 +stepi +``` + +`hbreak` sets a hardware breakpoint, which is required for read-only flash. It works from plain GDB because GDB sends the 2-byte length the Cortex-M33 comparators need. IDA's **GDB MI** adapter goes through the same GDB, so its GUI breakpoints work too; the old **GDB RSP** adapter was the one that sent a 1-byte length and could not set breakpoints here. + +## Glossary + +| Term | Definition | +| ---- | ---------- | +| **`.bss`** | Section for uninitialized global variables; zeroed by startup code | +| **`.data`** | Section for initialized global variables; copied from flash to SRAM at boot | +| **`.elf`** | Linked image with the symbol table; the ground truth for addresses and names | +| **`.rodata`** | Read-only section for constants and string literals; stays in flash | +| **GPIO** | General Purpose Input/Output — controllable pins on the microcontroller | +| **Hardware breakpoint** | A breakpoint serviced by the CPU comparators, required for read-only flash | +| **Inlining** | The optimizer replacing a function call with the function body; why `blink_and_print` disappears in `Release` | +| **Literal pool** | A block of 32-bit constants that Thumb-2 code reaches with PC-relative `ldr` | +| **MMIO** | Memory-mapped I/O — hardware registers accessed as memory addresses | +| **SIO** | Single-cycle I/O — the fast GPIO block in the RP2350, at `0xd0000000` | +| **Thumb bit** | Bit 0 of a Cortex-M function pointer; selects Thumb instruction mode | +| **UF2** | USB Flashing Format — the file format the Pico 2 bootloader accepts | +| **Vector table** | The first words of flash: initial stack pointer and exception vectors | + +--- + +**Remember:** the ELF tells you what every address is, and the `.bin` is what you actually patch. Prove the behavior dynamically, resolve the names from the ELF, then patch the bytes and flash. diff --git a/WEEK04/WEEK04-IDA.pdf b/WEEK04/WEEK04-IDA.pdf new file mode 100644 index 0000000..ad54289 Binary files /dev/null and b/WEEK04/WEEK04-IDA.pdf differ diff --git a/WEEK05/WEEK05-IDA.md b/WEEK05/WEEK05-IDA.md new file mode 100644 index 0000000..3c1e925 --- /dev/null +++ b/WEEK05/WEEK05-IDA.md @@ -0,0 +1,2023 @@ +# Week 5-IDA: IDA Pro — Decode, Hack, and Patch IEEE 754 Floats and Doubles (Raw `.bin`) + +*** + +**LEGAL DISCLAIMER:** +The information, tools, and code provided in this repository and course are strictly for educational, research, and defensive purposes only. + +You are explicitly prohibited from using any materials contained herein to access, test, modify, or exploit any device, network, or system that you do not own 100% or for which you do not have explicit, documented, and legally binding authorization to interact with. + +By using this repository and course, you acknowledge and agree that: + +1. Any illegal, unauthorized, or malicious use of this information is solely your responsibility. +2. The author(s) and contributor(s) of this repository and course shall not be held liable for any damages, legal repercussions, criminal charges, or unauthorized actions resulting from the use, misuse, or abuse of the contents herein. +3. You will comply with all applicable local, state, national, and international laws regarding cybersecurity and computer fraud. + +**IF YOU DO NOT AGREE WITH THESE TERMS, DO NOT USE THIS REPOSITORY AND COURSE.** + +*** + +## What You'll Learn This Week + +- Build the two lesson projects with `Release` and get both an `.elf` and a raw `.bin` +- Dump the **ELF symbol map** with `arm-none-eabi-nm` and use it as ground truth +- Load the raw `.bin` into IDA at `0x10000000` +- Read how a `float`/`double` constant is materialized from the compiler's literal pool +- **Break at `main`** on live silicon, even though `main` moves between these two programs +- Reconstruct a 64-bit `double` from the ABI register pair `r2:r3` and hack it live +- **Resolve the functions in the IDA GUI** using the ELF symbol map, including the `pico_double` formatting helpers `printf` pulls in +- **Patch** the constant bytes, export the image, convert to UF2, and flash it +- Prove why `42.5 -> 99.0` is a one-word patch but `42.52525 -> 99.99` needs two + +--- + +## How This Guide Works + +The build produces two files for each project: + +| File | What it is | How we use it | +| ---- | ---------- | ------------- | +| `.elf` | The linked image with a full symbol table | Ground truth for every function address and name | +| `.bin` | The raw flash image, no headers, no symbols | The image we load into IDA and reverse | + +The `.bin` is built **from** the `.elf`, so the ELF tells you exactly what is at every address. We use the ELF symbol map to resolve functions in IDA, and we reverse-engineer the raw `.bin` the way a real extracted firmware image is reversed. + +> **Build `Release`, not `Debug`.** Every address in this guide matches the Week 5 lesson, and the Week 5 lesson is a `Release` build. `Release` optimizes the code the same way the original lesson was built: it folds the `float`/`double` initializer into the literal pool and links the `pico_double` formatting helpers straight into the `printf` path. If you build `Debug`, the SDK function addresses move and the float/double helpers are laid out differently, so nothing lines up. Always build `Release` for this lesson. + +The order is **dynamic first, static second**, twice — once per project: + +1. Break on the live target and prove what the code does. +2. Hack it live in the debugger and watch the output change. +3. Resolve the functions in IDA using the ELF symbol map. +4. Patch the bytes, export, convert, and flash. + +| Project | Prints | The hack | +| ------- | ------ | -------- | +| `0x000e_floating-point-data-type` | `fav_num: 42.500000` | change the printed double `42.5` to `99.0` (one word) | +| `0x0011_double-floating-point-data-type` | `fav_num: 42.525250` | change the printed double `42.52525` to `99.99` (two words) | + +> **Addresses come from your build.** Every address here is from the `Release` build produced in Step 3. Confirm against your own `.elf` with the command in Step 4. + +> **`main` is not at the same address in both projects this week.** It is `0x10000234` in Project 1 and `0x10000238` in Project 2, because each program materializes its constant slightly differently. We still anchor to `main` through the one byte-identical place that always names it: the middle `blx` in `platform_entry` (Step 12). + +--- + +## Part 1: Build, Flash, and Get the Symbol Map + +### Step 1: Install the toolchain + +**Windows x64** + +- Install the **Raspberry Pi Pico** extension in VS Code. It installs the ARM GNU toolchain, CMake, Ninja, and the Pico SDK. +- Install **IDA Pro** and complete its license activation. +- Install **PuTTY** for the serial monitor. + +**macOS Apple Silicon** + +```bash +brew install cmake ninja +``` + +- Install **IDA Pro** and complete its license activation. +- Install the **Arm GNU Toolchain**, or let the VS Code Pico extension manage it. + +**Linux x64** + +```bash +sudo apt install cmake ninja-build gcc-arm-none-eabi libnewlib-arm-none-eabi git python3 openocd minicom +``` + +- Install **IDA Pro** and complete its license activation. + +### Step 2: Verify your tools are the right architecture (do not skip this) + +On **macOS Apple Silicon**, the most common failure is an Intel `x86_64` tool on your `PATH`: + +``` +zsh: bad CPU type in executable: cmake +``` + +You may have **two Homebrews**: the arm64 one at `/opt/homebrew` and the Intel one at `/usr/local`. If `/usr/local/bin` wins, every `brew` tool is x86_64. Check: + +```bash +file "$(which cmake)" +file "$(which ninja)" +file "$(which arm-none-eabi-gdb)" +file "$(which arm-none-eabi-nm)" +file "$(which openocd)" +file "$(which telnet)" +``` + +All must report `arm64`. If any is `x86_64`, put the Apple Silicon prefix first for the session and check again: + +```bash +export PATH="/opt/homebrew/bin:$PATH" +hash -r +file "$(which cmake)" +``` + +To make it permanent, add that `export` to `~/.zshrc`. Do not use Rosetta as a fix; OpenOCD and GDB are exactly the kind of programs where a translation layer produces failures that look like debugger bugs. + +**`telnet` is special — and optional.** The GDB MI workflow does not need it; it is only used by the command-port fallback. macOS no longer ships `telnet`, and the Homebrew build is often the Intel one, so `telnet 127.0.0.1 4444` fails with `bad CPU type in executable`. Your `brew` command itself may also be the Intel one: if `brew install telnet` fails with `.../portable-ruby/.../ruby: Bad CPU type in executable`, you are running the Intel Homebrew. Call the Apple Silicon Homebrew explicitly: + +```bash +/opt/homebrew/bin/brew install telnet +``` + +If you would rather not install anything, macOS ships an arm64 `nc`, which can connect to the same OpenOCD port: + +```bash +nc 127.0.0.1 4444 +``` + +**Windows x64** and **Linux x64** do not have this problem. Skip to Step 3. + +### Step 3: Build the two projects with `Release` + +Run this once inside `0x000e_floating-point-data-type/` and once inside `0x0011_double-floating-point-data-type/`: + +```bash +cmake -B build -G Ninja -DPICO_BOARD=pico2 -DPICO_PLATFORM=rp2350 -DCMAKE_BUILD_TYPE=Release +cmake --build build +``` + +**Point IDA at this repository (once).** Every console snippet below reads the repo root from `~/.embedded-hacking-repo`, so IDA never needs a database open and nothing is hardcoded. From the repo root, run once: + +**macOS / Linux:** + +```bash +pwd > ~/.embedded-hacking-repo +``` + +**Windows (PowerShell):** + +```powershell +(Get-Location).Path | Set-Content "$env:USERPROFILE\.embedded-hacking-repo" +``` + +**Then build from the IDA console**, so the whole build -> patch -> flash loop stays inside IDA. The console inherits a minimal `PATH` — on macOS just `/usr/bin:/bin:/usr/sbin:/sbin` — so it does not see Homebrew; add your package manager's `bin` first, then run plain `cmake`. + +**macOS Apple Silicon:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() +os.environ["PATH"] = "/opt/homebrew/bin:" + os.environ["PATH"] # the console's PATH omits Homebrew +for name in ("0x000e_floating-point-data-type", "0x0011_double-floating-point-data-type"): + proj = os.path.join(root, name) + subprocess.run(["cmake", "-B", "build", "-G", "Ninja", "-DPICO_BOARD=pico2", + "-DPICO_PLATFORM=rp2350", "-DCMAKE_BUILD_TYPE=Release"], cwd=proj) + subprocess.run(["cmake", "--build", "build"], cwd=proj) +``` + +**Linux x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() +for name in ("0x000e_floating-point-data-type", "0x0011_double-floating-point-data-type"): + proj = os.path.join(root, name) + subprocess.run(["cmake", "-B", "build", "-G", "Ninja", "-DPICO_BOARD=pico2", + "-DPICO_PLATFORM=rp2350", "-DCMAKE_BUILD_TYPE=Release"], cwd=proj) + subprocess.run(["cmake", "--build", "build"], cwd=proj) +``` + +**Windows x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() +for name in ("0x000e_floating-point-data-type", "0x0011_double-floating-point-data-type"): + proj = os.path.join(root, name) + subprocess.run(["cmake", "-B", "build", "-G", "Ninja", "-DPICO_BOARD=pico2", + "-DPICO_PLATFORM=rp2350", "-DCMAKE_BUILD_TYPE=Release"], cwd=proj) + subprocess.run(["cmake", "--build", "build"], cwd=proj) +``` + +Each build directory now contains the pair we need: + +- `0x000e_floating-point-data-type/build/0x000e_floating-point-data-type.elf` and `.bin` — `.bin` is **15308** bytes (`0x3bcc`) +- `0x0011_double-floating-point-data-type/build/0x0011_double-floating-point-data-type.elf` and `.bin` — `.bin` is **15324** bytes (`0x3bdc`) + +If the ARM toolchain is not on your `PATH`, add `-DPICO_TOOLCHAIN_PATH=...`: + +| OS | Typical toolchain path | +| -- | ---------------------- | +| Windows x64 | `C:/Program Files/Arm GNU Toolchain arm-none-eabi/14.2 rel1/bin` | +| macOS Apple Silicon | `~/.pico-sdk/toolchain/14_2_Rel1/bin` | +| Linux x64 | `/usr` | + +> **This guide's toolchain lives at `~/.pico-sdk/toolchain/14_2_Rel1/bin`.** All of `arm-none-eabi-nm`, `arm-none-eabi-objdump`, and `arm-none-eabi-gdb` resolved in this document come from there. If your install is elsewhere, `which arm-none-eabi-nm` tells you where to point. + +### Step 4: Dump the ELF symbol map + +This is the ground truth for the whole lesson. Run `arm-none-eabi-nm` on each ELF and keep the output in a terminal or a text file: + +**macOS Apple Silicon / Linux x64:** + +```bash +arm-none-eabi-nm -n --defined-only build/0x000e_floating-point-data-type.elf | grep -E ' [Tt] ' +arm-none-eabi-nm -n --defined-only build/0x0011_double-floating-point-data-type.elf | grep -E ' [Tt] ' +``` + +**Windows x64:** + +```powershell +arm-none-eabi-nm -n --defined-only build\0x000e_floating-point-data-type.elf | Select-String ' [Tt] ' +arm-none-eabi-nm -n --defined-only build\0x0011_double-floating-point-data-type.elf | Select-String ' [Tt] ' +``` + +Each line is `address type name`. The `T`/`t` type is a function. Here are the functions this lesson uses. The signatures come from the ELF's DWARF debug info queried with `arm-none-eabi-gdb -batch -ex "ptype "`, so they are exact. + +**Project 1 — `0x000e_floating-point-data-type`:** + +| Address | ELF symbol | Signature | Role | +| ------- | ---------- | --------- | ---- | +| `0x1000015c` | `_reset_handler` | `void _reset_handler(void)` | reset entry | +| `0x10000186` | `platform_entry` | `void platform_entry(void)` | calls `runtime_init`, `main`, `exit` | +| `0x1000019a` | `data_cpy` | `void data_cpy(void*, void*, void*)` | copies `.data` from flash to SRAM | +| `0x100001e4` | `_init` | `void _init(void)` | runs `.init_array` | +| `0x10000210` | `frame_dummy` | `void frame_dummy(void)` | C runtime boilerplate | +| `0x10000234` | `main` | `int main(void)` | the lesson function | +| `0x10000254` | `gpio_set_function` | `void gpio_set_function(uint, gpio_function_t)` | SDK GPIO helper | +| `0x10000da8` | `time_us_64` | `uint64_t time_us_64(void)` | SDK microsecond clock | +| `0x10000e18` | `uart_init` | `uint uart_init(uart_inst_t*, uint)` | SDK UART init | +| `0x10002ca8` | `vfctprintf` | `int vfctprintf(void (*)(char, void*), void*, const char*, va_list)` | printf format engine | +| `0x10002d04` | `exit` | `void exit(int)` | C runtime exit | +| `0x10002d0c` | `runtime_init` | `void runtime_init(void)` | SDK runtime init | +| `0x10002d38` | `stdio_out_chars_crlf` | `void stdio_out_chars_crlf(stdio_driver_t*, const char*, int)` | CRLF output driver | +| `0x10002e48` | `stdio_put_string` | `int stdio_put_string(const char*, int, bool, bool)` | buffered string output | +| `0x10002f34` | `stdio_set_driver_enabled` | `void stdio_set_driver_enabled(stdio_driver_t*, bool)` | enable the UART driver | +| `0x10002f5c` | `stdio_init_all` | `bool stdio_init_all(void)` | SDK serial init | +| `0x10003028` | `__wrap_vprintf` | `int __wrap_vprintf(const char*, va_list)` | printf core | +| `0x100030ec` | `__wrap_printf` | `int __wrap_printf(const char*, ...)` | the `printf` wrapper | +| `0x100032a8` | `stdio_uart_init` | `void stdio_uart_init(void)` | SDK UART stdio init | +| `0x100033e8` | `strlen` | `size_t strlen(const char*)` | C runtime string length | + +Project 1 also links in the `pico_double` formatting helpers that `printf`'s `%f` path calls. These are reachable from `main` through `__wrap_printf`: + +| Address | ELF symbol | Signature | Role | +| ------- | ---------- | --------- | ---- | +| `0x10001384` | `__wrap___aeabi_dadd` | `double __wrap___aeabi_dadd(double, double)` | double add | +| `0x100013ac` | `__wrap___aeabi_dsub` | `double __wrap___aeabi_dsub(double, double)` | double subtract | +| `0x100013d4` | `__wrap___aeabi_dmul` | `double __wrap___aeabi_dmul(double, double)` | double multiply | +| `0x10001420` | `__wrap___aeabi_ddiv` | `double __wrap___aeabi_ddiv(double, double)` | double divide | +| `0x100014bc` | `__wrap___aeabi_i2d` | `double __wrap___aeabi_i2d(int)` | int -> double | +| `0x100014e0` | `__wrap___aeabi_ui2d` | `double __wrap___aeabi_ui2d(unsigned)` | unsigned -> double | +| `0x10001504` | `__wrap___aeabi_d2iz` | `int __wrap___aeabi_d2iz(double)` | double -> int | +| `0x10001528` | `__wrap___aeabi_d2uiz` | `unsigned __wrap___aeabi_d2uiz(double)` | double -> unsigned | +| `0x1000154c` | `__wrap___aeabi_dcmpun` | `int __wrap___aeabi_dcmpun(double, double)` | unordered compare | +| `0x10001570` | `__wrap___aeabi_dcmplt` | `int __wrap___aeabi_dcmplt(double, double)` | less-than compare | +| `0x10001598` | `__wrap___aeabi_dcmple` | `int __wrap___aeabi_dcmple(double, double)` | less-or-equal compare | +| `0x100015c0` | `__wrap___aeabi_dcmpge` | `int __wrap___aeabi_dcmpge(double, double)` | greater-or-equal compare | +| `0x100015e8` | `__wrap___aeabi_dcmpgt` | `int __wrap___aeabi_dcmpgt(double, double)` | greater-than compare | +| `0x1000160c` | `_out_rev` | `unsigned _out_rev(out_fct_type, char*, size_t, size_t, const char*, size_t, unsigned, unsigned)` | reversed-digit output | +| `0x100016a8` | `_ntoa_format` | `unsigned _ntoa_format(out_fct_type, char*, size_t, size_t, char*, size_t, bool, unsigned, unsigned, unsigned, unsigned)` | number formatter | +| `0x1000187c` | `_out_char` | `void _out_char(char, void*, size_t, size_t)` | single-char sink | +| `0x10001890` | `_ftoa` | `unsigned int _ftoa(out_fct_type, char*, size_t, size_t, double, unsigned int, unsigned int, unsigned int)` | fixed-point float formatter | +| `0x10001d50` | `_etoa` | `unsigned int _etoa(out_fct_type, char*, size_t, size_t, double, unsigned int, unsigned int, unsigned int)` | exponential float formatter | +| `0x100022c4` | `_vsnprintf` | `int _vsnprintf(out_fct_type, char*, size_t, const char*, va_list)` | the format dispatcher | +| `0x10000dbc` | `busy_wait_us` | `void busy_wait_us(uint64_t)` | UART timing loop | +| `0x10000fec` | `clock_get_hz` | `unsigned long clock_get_hz(clock_handle_t)` | UART clock lookup | + +**Project 2 — `0x0011_double-floating-point-data-type`:** + +| Address | ELF symbol | Signature | Role | +| ------- | ---------- | --------- | ---- | +| `0x1000015c` | `_reset_handler` | `void _reset_handler(void)` | reset entry | +| `0x10000186` | `platform_entry` | `void platform_entry(void)` | calls `runtime_init`, `main`, `exit` | +| `0x1000019a` | `data_cpy` | `void data_cpy(void*, void*, void*)` | copies `.data` from flash to SRAM | +| `0x100001e4` | `_init` | `void _init(void)` | runs `.init_array` | +| `0x10000210` | `frame_dummy` | `void frame_dummy(void)` | C runtime boilerplate | +| `0x10000238` | `main` | `int main(void)` | the lesson function | +| `0x1000025c` | `gpio_set_function` | `void gpio_set_function(uint, gpio_function_t)` | SDK GPIO helper | +| `0x10000db0` | `time_us_64` | `uint64_t time_us_64(void)` | SDK microsecond clock | +| `0x10000e20` | `uart_init` | `uint uart_init(uart_inst_t*, uint)` | SDK UART init | +| `0x10002cb0` | `vfctprintf` | `int vfctprintf(void (*)(char, void*), void*, const char*, va_list)` | printf format engine | +| `0x10002d0c` | `exit` | `void exit(int)` | C runtime exit | +| `0x10002d14` | `runtime_init` | `void runtime_init(void)` | SDK runtime init | +| `0x10002d40` | `stdio_out_chars_crlf` | `void stdio_out_chars_crlf(stdio_driver_t*, const char*, int)` | CRLF output driver | +| `0x10002e50` | `stdio_put_string` | `int stdio_put_string(const char*, int, bool, bool)` | buffered string output | +| `0x10002f3c` | `stdio_set_driver_enabled` | `void stdio_set_driver_enabled(stdio_driver_t*, bool)` | enable the UART driver | +| `0x10002f64` | `stdio_init_all` | `bool stdio_init_all(void)` | SDK serial init | +| `0x10003030` | `__wrap_vprintf` | `int __wrap_vprintf(const char*, va_list)` | printf core | +| `0x100030f4` | `__wrap_printf` | `int __wrap_printf(const char*, ...)` | the `printf` wrapper | +| `0x100032b0` | `stdio_uart_init` | `void stdio_uart_init(void)` | SDK UART stdio init | +| `0x100033f0` | `strlen` | `size_t strlen(const char*)` | C runtime string length | + +Project 2 uses the same `pico_double` formatting helpers as Project 1, shifted by eight bytes because `main` moved: + +| Address | ELF symbol | Signature | Role | +| ------- | ---------- | --------- | ---- | +| `0x1000138c` | `__wrap___aeabi_dadd` | `double __wrap___aeabi_dadd(double, double)` | double add | +| `0x100013b4` | `__wrap___aeabi_dsub` | `double __wrap___aeabi_dsub(double, double)` | double subtract | +| `0x100013dc` | `__wrap___aeabi_dmul` | `double __wrap___aeabi_dmul(double, double)` | double multiply | +| `0x10001428` | `__wrap___aeabi_ddiv` | `double __wrap___aeabi_ddiv(double, double)` | double divide | +| `0x100014c4` | `__wrap___aeabi_i2d` | `double __wrap___aeabi_i2d(int)` | int -> double | +| `0x100014e8` | `__wrap___aeabi_ui2d` | `double __wrap___aeabi_ui2d(unsigned)` | unsigned -> double | +| `0x1000150c` | `__wrap___aeabi_d2iz` | `int __wrap___aeabi_d2iz(double)` | double -> int | +| `0x10001530` | `__wrap___aeabi_d2uiz` | `unsigned __wrap___aeabi_d2uiz(double)` | double -> unsigned | +| `0x10001554` | `__wrap___aeabi_dcmpun` | `int __wrap___aeabi_dcmpun(double, double)` | unordered compare | +| `0x10001578` | `__wrap___aeabi_dcmplt` | `int __wrap___aeabi_dcmplt(double, double)` | less-than compare | +| `0x100015a0` | `__wrap___aeabi_dcmple` | `int __wrap___aeabi_dcmple(double, double)` | less-or-equal compare | +| `0x100015c8` | `__wrap___aeabi_dcmpge` | `int __wrap___aeabi_dcmpge(double, double)` | greater-or-equal compare | +| `0x100015f0` | `__wrap___aeabi_dcmpgt` | `int __wrap___aeabi_dcmpgt(double, double)` | greater-than compare | +| `0x10001614` | `_out_rev` | `unsigned _out_rev(out_fct_type, char*, size_t, size_t, const char*, size_t, unsigned, unsigned)` | reversed-digit output | +| `0x100016b0` | `_ntoa_format` | `unsigned _ntoa_format(out_fct_type, char*, size_t, size_t, char*, size_t, bool, unsigned, unsigned, unsigned, unsigned)` | number formatter | +| `0x10001884` | `_out_char` | `void _out_char(char, void*, size_t, size_t)` | single-char sink | +| `0x10001898` | `_ftoa` | `unsigned int _ftoa(out_fct_type, char*, size_t, size_t, double, unsigned int, unsigned int, unsigned int)` | fixed-point float formatter | +| `0x10001d58` | `_etoa` | `unsigned int _etoa(out_fct_type, char*, size_t, size_t, double, unsigned int, unsigned int, unsigned int)` | exponential float formatter | +| `0x100022cc` | `_vsnprintf` | `int _vsnprintf(out_fct_type, char*, size_t, const char*, va_list)` | the format dispatcher | +| `0x10000dc4` | `busy_wait_us` | `void busy_wait_us(uint64_t)` | UART timing loop | +| `0x10000ff4` | `clock_get_hz` | `unsigned long clock_get_hz(clock_handle_t)` | UART clock lookup | + +> **A literal pool is still a pool.** The `float`/`double` initializer does not survive as a C variable, but the compiler still has to place the IEEE-754 bit pattern somewhere. It parks the 32-bit word (or word pair) right after `main`'s code and reaches it with a PC-relative `ldr`/`ldrd`. That is why the value you patch is a `.word` in the image, not a stack store. + +### Step 5: Flash Project 1 and confirm `fav_num: 42.500000` + +A `.bin` has no headers, so OpenOCD must be told the base address `0x10000000`. From the repository root: + +**macOS Apple Silicon / Linux x64:** + +```bash +./flash.sh 0x000e_floating-point-data-type/build/0x000e_floating-point-data-type.bin +``` + +**Windows x64 (PowerShell):** + +```powershell +.\flash.ps1 -Bin 0x000e_floating-point-data-type\build\0x000e_floating-point-data-type.bin +``` + +**Or flash from the IDA console** (the console reads the repo root from the marker file, so it works with no database open): + +**macOS Apple Silicon / Linux x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) +bin_path = os.path.join(root, "0x000e_floating-point-data-type", "build", "0x000e_floating-point-data-type.bin") +log = os.path.join(os.path.dirname(bin_path), "flash.log") +subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # free the probe first +subprocess.Popen([os.path.join(root, "flash.sh"), bin_path], + stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) +print("flashing in the background; log:", log) +``` + +**Windows x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) +bin_path = os.path.join(root, "0x000e_floating-point-data-type", "build", "0x000e_floating-point-data-type.bin") +log = os.path.join(os.path.dirname(bin_path), "flash.log") +subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"]) # free the probe first +subprocess.Popen(["powershell", "-ExecutionPolicy", "Bypass", "-File", + os.path.join(root, "flash.ps1"), "-Bin", bin_path], + stdout=open(log, "w"), stderr=subprocess.STDOUT) +print("flashing in the background; log:", log) +``` + +Wait for `wrote 15308 bytes ...` and `** Verified OK **`. Open a serial monitor at **115200** baud: + +- **Windows x64:** PuTTY -> Connection type **Serial**, the Pico's COM port, speed `115200`. +- **macOS Apple Silicon:** `screen /dev/tty.usbmodem* 115200` (quit with `Ctrl-A` then `K`). +- **Linux x64:** `minicom -D /dev/ttyACM0 -b 115200`. + +``` +fav_num: 42.500000 +fav_num: 42.500000 +fav_num: 42.500000 +... +``` + +The program prints `42.500000` because `printf` with `%f` defaults to six decimal places. + +### Step 6: Flash Project 2 and confirm `fav_num: 42.525250` + +```bash +# macOS / Linux +./flash.sh 0x0011_double-floating-point-data-type/build/0x0011_double-floating-point-data-type.bin +``` +```powershell +# Windows +.\flash.ps1 -Bin 0x0011_double-floating-point-data-type\build\0x0011_double-floating-point-data-type.bin +``` + +**Or flash from the IDA console** (same form as Step 5, pointing at the Project 2 `.bin`): + +**macOS / Linux:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) +bin_path = os.path.join(root, "0x0011_double-floating-point-data-type", "build", "0x0011_double-floating-point-data-type.bin") +log = os.path.join(os.path.dirname(bin_path), "flash.log") +subprocess.run(["pkill", "-TERM", "-f", "openocd"]) +subprocess.Popen([os.path.join(root, "flash.sh"), bin_path], + stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) +print("flashing in the background; log:", log) +``` + +**Windows:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) +bin_path = os.path.join(root, "0x0011_double-floating-point-data-type", "build", "0x0011_double-floating-point-data-type.bin") +log = os.path.join(os.path.dirname(bin_path), "flash.log") +subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"]) +subprocess.Popen(["powershell", "-ExecutionPolicy", "Bypass", "-File", + os.path.join(root, "flash.ps1"), "-Bin", bin_path], + stdout=open(log, "w"), stderr=subprocess.STDOUT) +print("flashing in the background; log:", log) +``` + +Wait for `wrote 15324 bytes ...`. The serial monitor shows: + +``` +fav_num: 42.525250 +fav_num: 42.525250 +fav_num: 42.525250 +... +``` + +`42.52525` has a repeating binary fraction, so its 52 mantissa bits are not all zero. Remember that: it is why this value needs two words patched, and `42.5` needs only one. +--- + +## Part 2: Load the Raw `.bin` into IDA + +Start from a fresh IDA state. If you already have a database for this lesson, **close it and start over**; a stale database keeps old names and patches. + +### Step 7: Bring the raw `.bin` into IDA + +A raw `.bin` has no headers, so IDA cannot know where it belongs or what architecture it is. You must supply both. If you just double-click the `.bin`, IDA may load it with a guessed architecture, and every address in this lesson will be wrong. + +#### 1.1 Open the file +1. **File ▸ Open…** (Ctrl/Cmd+O). +2. Select the `.bin` file and click **Open**. + +IDA opens the **"Load a new file"** dialog because a raw `.bin` has no header. + +#### 1.2 Set the format and processor +In the *Load a new file* dialog: +1. **Format**: leave it as **Binary file** (IDA auto-detects a headerless image). +2. **Processor type**: click the **…** button next to the processor field. In the *Processor type* dialog: + - Family: **ARM** + - Type: **ARM Little-endian** (the 32-bit ARM module). + - Click **OK**. + +> If IDA asks **"Do you want to disassemble it as 64-bit code?"** — click **No**. +> The RP2350 is 32-bit; answering *Yes* loads AArch64 and you get `X` registers / data. (This is the single most common cause of the `DCB` wall.) + +#### 1.3 Configure the ARM architecture and Thumb mode +Still in the *Load a new file* dialog, open the processor options (the **Processor options** / **Set…** button, which opens the dialog titled **ARM architecture options**): +- **ARM architecture**: choose **ARMv8-M** (this is the Cortex-M33 / RP2350 core). +- **Thumb instructions**: select **Thumb-2** (ARMv8-M is Thumb-only, so this is the correct mode). +- Leave **automatic ARM-THUMB switch** off; we want Thumb throughout. + +#### 1.4 Set the loading address +- **Loading address**: enter **`10000000`** (hex; the RP2350 XIP flash base). + IDA rejects addresses that don't look like ROM/RAM with *"The loading address should belong to RAM or ROM"* — `0x10000000` is the correct flash window. + +Leave **Manual load** and **Create segments** at their defaults. Click **OK**. + +#### 1.5 Force Thumb, then seed the code from the vector table +A raw `.bin` has no header, so IDA's loader has **no entry point** and defaults the segment to **ARM mode** (which cannot decode Thumb). Two required steps — in this order: + +**A. Set the segment to Thumb (do this first).** +- **Edit ▸ Segments ▸ Set default segment register value…** → register **`T`** = **`1`** (or press **`Alt+G`**). IDA reanalyzes the segment as Thumb automatically. + +**B. Seed the code from the vector table.** +1. **G** → `10000000`. The first two words are the initial stack pointer and the **reset vector**. +2. **Read the 4-byte word at `0x10000004`** (do **not** assume its value — it differs per build). +3. **Clear bit 0** (the ARM **Thumb** flag) → the reset handler address. +4. **G** to that address → press **C** (**MakeCode**). IDA disassembles the reset handler and follows its `bl`s into `main`. + +Once `main` shows code, the import is correct. + +**Why IDA needs this and others don't:** IDA's generic raw-binary ARM loader treats the image as flat data and waits for you to set Thumb and mark the entry point. It's an IDA quirk, not a mistake on your part. + +### Step 8: Save it as a IDA database (`.i64`) + +IDA never writes back into the `.bin`. Your names, comments, types, and patches live in a separate **`.i64`** database. Save one now, before you make any changes: + +1. Choose `File -> Save As...`. +2. Save it next to the image as `0x000e_floating-point-data-type.i64`. +3. From now on, save with `File -> Save` (`Cmd+S` on macOS, `Ctrl+S` on Windows/Linux) whenever you rename or patch. + +The two files have different roles: + +| File | Role | +| ---- | ---- | +| `0x000e_floating-point-data-type.bin` | the raw firmware image; IDA never modifies it | +| `0x000e_floating-point-data-type.i64` | your analysis database: names, types, comments, and patches | + +When you come back later, **open the `.i64`**, not the `.bin`; that restores all your work. If a database gets messy, delete the `.i64` and re-import the `.bin` from Step 7 — the firmware is never at risk. You export the patched image out of this view later, in Step 19. + +### Step 9: The views you will use + +- **Linear view:** the disassembly listing. You navigate, read, and patch here. +- **Graph view:** the control-flow graph of the current function. +- **Decompiler (HLIL):** the pseudo-C decompilation. +- **Hex view:** raw bytes, used for patching. +- **Function list:** the sidebar list of every detected function. + +Navigation: `G` go to address, `N` rename, `Y` set type or signature, `;` add a comment. Breakpoints are set from the GUI through the GDB MI adapter — see Step 13. + +> **macOS function keys:** the top-row `F` keys are usually mapped to system functions. Every step here uses menu paths that work without them. + +--- + +## Part 3: Dynamic — Break at `main` and Hack Live (Project 1) + +### Step 10: Start OpenOCD as a live debug server + +Make sure no other OpenOCD is running; a forgotten server holds port `3333`. + +**macOS / Linux:** + +```bash +ps aux | grep -i openocd +``` + +**Windows (PowerShell):** + +```powershell +Get-Process | Where-Object { $_.ProcessName -like '*openocd*' } +``` + +Stop any leftover server gracefully: + +**macOS / Linux:** + +```bash +pkill -TERM -f openocd +``` + +**Windows (PowerShell):** + +```powershell +Get-Process openocd -ErrorAction SilentlyContinue | Stop-Process +``` + +Start the server **parked at `main`**: + +**macOS Apple Silicon / Linux x64:** + +```bash +BP_ADDR=0x10000234 ./debug-server.sh +``` + +**Windows x64 (PowerShell):** + +```powershell +$env:BP_ADDR="0x10000234"; .\debug-server.ps1 +``` + +**Or start it from the IDA console**, freeing the probe first and launching the server in the background so the console returns immediately: + +**macOS Apple Silicon / Linux x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) +subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # stop any running server first +log = os.path.join(root, "openocd.log") +p = subprocess.Popen([os.path.join(root, "debug-server.sh")], cwd=root, + env=dict(os.environ, BP_ADDR="0x10000234"), + stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) +print("OpenOCD started (pid", p.pid, "); log:", log) +``` + +**Windows x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) +subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"]) # stop any running server first +log = os.path.join(root, "openocd.log") +p = subprocess.Popen(["powershell", "-ExecutionPolicy", "Bypass", "-File", + os.path.join(root, "debug-server.ps1")], cwd=root, + env=dict(os.environ, BP_ADDR="0x10000234"), + stdout=open(log, "w"), stderr=subprocess.STDOUT) +print("OpenOCD started (pid", p.pid, "); log:", log) +``` + +`Popen` returns in a few milliseconds; the server keeps running in the background. Check `openocd.log` for `Listening on port 3333`, then connect in Step 11. + +Wait for: + +``` +Info : [rp2350.dap.core0] Examination succeed +Startup breakpoint at 0x10000234 (2-byte hardware execute, one-shot). +Info : starting gdb server for rp2350.dap.core0 on 3333 +Info : Listening on port 3333 for gdb connections +``` + +> **`BP_ADDR` parks the core at `main` before any client connects.** The script arms a 2-byte hardware breakpoint and then does the startup `reset run`, so the core runs from the vector table and stops at your address with no debugger attached yet. When IDA connects a moment later, the first thing it reads is already the truth: `Stopped at 0x10000234`. This is the whole reason the lab works cleanly — you never have to drive a reset from outside the GUI. +> +> Use the address you actually want to stop at: +> +> | What you want to stop at | Project 1 `0x000e` | Project 2 `0x0011` | Command | +> | --- | --- | --- | --- | +> | `main` (once per reset) | `0x10000234` | `0x10000238` | `BP_ADDR=0x10000234 ./debug-server.sh` | +> | The **loop** — the `printf` call, hit every iteration | `0x10000244` | `0x1000024a` | `BP_ADDR=0x10000244 ./debug-server.sh` | +> +> ```bash +> BP_ADDR=0x10000234 ./debug-server.sh # park at main +> BP_ADDR=0x10000244 ./debug-server.sh # park in the loop instead +> ``` +> +> ```powershell +> $env:BP_ADDR="0x10000234"; .\debug-server.ps1 # park at main +> $env:BP_ADDR="0x10000244"; .\debug-server.ps1 # park in the loop +> ``` +> +> **Note the loop address differs from Week 4 and between the two projects.** In Project 1 the `bl __wrap_printf` sits at `0x10000244`; in Project 2 it sits at `0x1000024a`, because Project 2 loads the pair with `ldrd` first. Both were verified against the Release `.elf` with `arm-none-eabi-objdump` and confirmed live on hardware. +> +> **This startup stop is single-use.** OpenOCD flushes breakpoints when a client connects, so this one is gone once IDA attaches — fine for `main`, which only runs once per reset. Every breakpoint after that is set from the IDA GUI (Step 13) and is repeatable. To stop at `main` again, restart the server with `BP_ADDR` and reconnect. + +> **Exactly one core.** The line must say `core0` and must **not** mention `core1`. Core1 is never started by this firmware; exposing it makes IDA read core1's reset-state registers, which are not real addresses, and OpenOCD floods the log with `Failed to read memory at 0xf0000000`. The scripts already use `USE_CORE=0`; do not change it. + +> **Windows driver note:** the Debug Probe must use the **WinUSB** driver. If OpenOCD reports `unable to open CMSIS-DAP device`, install it with [Zadig](https://zadig.akeo.ie/) (select `Debug Probe (CMSIS-DAP)` -> WinUSB). + +### Step 11: Connect IDA to the GDB server + +1. Make sure the image is open and analyzed (Part 2) and the server from Step 10 is running (parked at `main`). +2. Choose `Debugger -> Connect to Remote Process`. +3. In the **adapter** dropdown, select **GDB MI**. +4. In the **connect** settings group, set **IP Address** to `127.0.0.1` and **Port** to `3333`. +5. Set **Full GDB Executable Path** to the `arm-none-eabi-gdb` from the **Arm GNU Toolchain 14.2.rel1**. It ships for all three hosts, and the Raspberry Pi Pico VS Code extension installs that same 14.2.rel1 toolchain (including `arm-none-eabi-gdb`) on all of them: + + | OS | `arm-none-eabi-gdb` path | + | -- | ------------------------ | + | macOS Apple Silicon | `/Applications/ArmGNUToolchain/14.2.rel1/arm-none-eabi/bin/arm-none-eabi-gdb` (or the Pico extension's `~/.pico-sdk/toolchain/14_2_Rel1/bin/arm-none-eabi-gdb`) | + | Windows x64 | `%USERPROFILE%\.pico-sdk\toolchain\14_2_Rel1\bin\arm-none-eabi-gdb.exe` (Pico extension), or `C:\Program Files (x86)\Arm GNU Toolchain arm-none-eabi\14.2 rel1\bin\arm-none-eabi-gdb.exe` | + | Linux x64 | `~/.pico-sdk/toolchain/14_2_Rel1/bin/arm-none-eabi-gdb` (Pico extension), or the `bin/` directory of the extracted `arm-gnu-toolchain-14.2.rel1-x86_64-arm-none-eabi` tarball | +6. Click **Accept**. + +> **Use the GDB MI adapter.** It launches a real `arm-none-eabi-gdb --interpreter=mi2` and lets IDA drive it, so breakpoints and stepping go through real GDB — which sends the correct 2-byte breakpoint length and handles step-over itself. Verified working end to end: connect, GUI breakpoints (**Add Hardware Breakpoint...**, hardware execute), **Step Into** / **Step Over**, and register edits. Stops are reported as `Breakpoint` (not `SingleStep`). +> +> **Do NOT have any breakpoints set in IDA before you connect.** With the GDB MI adapter, attaching while IDA already has a breakpoint **hangs the session**. Start the server parked with `BP_ADDR` (Step 10), connect, and only add hardware breakpoints *after* the connection is up. This is a IDA bug; it is the single most common GDB MI failure. +> +> **The GDB executable path matters.** Use the **14.2.rel1** build on every OS (Windows, macOS, Linux). The 13.3.rel1 build did **not** connect in testing. +> +> **This step is temporary.** Vector35 plans to ship a GDB binary with the GDB MI adapter ([Vector35/debugger#929](https://github.com/Vector35/debugger/issues/929), milestone *Langara*). Once that lands, IDA provides GDB itself and you will not need to set **Full GDB Executable Path** at all. +> +> **Do not pick Corellium.** IDA's adapter dropdown also lists **Corellium**, which is for Corellium's virtual devices and expects an API token, not a local OpenOCD server. It is not the adapter for this lab. The dropdown is a combo box, so an accidental arrow-key press can land on it — always read the label back and confirm it says **GDB MI** before clicking **Accept**. + +> **The adapter and port are not saved in the `.i64`.** Every time you relaunch IDA you must re-select **GDB MI**, re-enter port `3333`, and re-set the GDB path. + +> **Watch for an off-screen error dialog.** When a connection fails, IDA pops a `IDA critical alert` window that can be positioned mostly outside the main window, which makes it look like nothing happened. If the connect seems to do nothing, check your other display. + +The target keeps running. Open the **Registers** tab (bug icon) and confirm you see live values. `pc` inside `0x10003xxx` and `sp` just below `0x20082000` are healthy. + +> **If `pc` is `0x00000088`, `0x000000ec`, or `sp` is `0xf0000000`, the session is bad.** Restart the server, then restart IDA (a server restart while attached leaves IDA in a stale session), and connect again. + +### Step 12: Find `main` without relying on its address + +`main` moves between these programs (`0x10000234` vs `0x10000238`), so we do not guess it. We follow the one fixed path to it. Press `G` and go to `0x10000000`: + +``` +0x10000000 0x20082000 initial stack pointer (top of SRAM) +0x10000004 0x1000015d reset vector +``` + +Bit 0 of a vector is the Thumb bit, so `0x1000015d` means "start at `0x1000015c`". That is `_reset_handler`. Follow the reset path to `0x10000186`, `platform_entry`: + +```asm +10000186: 4914 ldr r1, [pc, #80] ; @ 0x100001d8 +10000188: 4788 blx r1 ; runtime_init +1000018a: 4914 ldr r1, [pc, #80] ; @ 0x100001dc +1000018c: 4788 blx r1 ; main <-- the fixed anchor +1000018e: 4914 ldr r1, [pc, #80] ; @ 0x100001e0 +10000190: 4788 blx r1 ; exit +10000192: be00 bkpt 0x0000 +``` + +**The middle `blx` at `0x1000018c` is the call to `main`.** `platform_entry` is byte-identical in both projects, so `0x1000018c` catches `main` no matter where the linker placed it. The literal pool at `0x100001dc` holds `main | 1`; clearing bit 0 gives `0x10000234` for Project 1 and `0x10000238` for Project 2. + +### Step 13: Set a hardware breakpoint in the GUI + +With the **GDB MI** adapter, IDA sets breakpoints through real GDB, which sends the correct 2-byte length, so you set them **in the UI**. There is no command port here. + +> **Why older drafts used the command port.** IDA's **GDB RSP** adapter is its own minimal RSP client and sends a **1-byte** breakpoint (`Z0,,1`); the Cortex-M33 FPB comparators need 2 bytes, so OpenOCD rejected it with `only breakpoints of two bytes length supported`. The old workaround was to arm breakpoints by hand over telnet. **The GDB MI adapter does not have this problem** — it drives real `arm-none-eabi-gdb`, which sends the right length. So everything below is done in the GUI. The command port still exists as a fallback (see the end of this step), but you do not need it. + +#### Where you can stop + +| You want to stop at | Address | How | Repeatable? | +| --- | --- | --- | --- | +| **`main`** | Project 1 `0x10000234`, Project 2 `0x10000238` | The server starts parked there with `BP_ADDR` (Step 10), so IDA is already stopped at `main` when it connects. | No — `main` runs once per reset. | +| **The loop** (`printf` call) | Project 1 `0x10000244`, Project 2 `0x1000024a` | Set a hardware breakpoint in the GUI, then click **Resume**. | Yes — fires on every iteration. | + +#### Set the loop breakpoint in the GUI + +1. Press `G`, type the loop address (`0x10000244` for Project 1, `0x1000024a` for Project 2), and press Enter. +2. Set a **hardware execution** breakpoint at that address, either way: + - `Debugger -> Add Hardware Breakpoint...` — a **hardware execute** (`HE`) breakpoint. **Use this one.** + - click the line and press `F2` (`Debugger -> Toggle Breakpoint`) — a **software** breakpoint. It will **not** work here: the code is in read-only flash, so GDB cannot install it and the core just keeps running. +3. Click **Resume**. The core is already running the loop, so the breakpoint fires on the next iteration. IDA stops with the PC at the loop address and reports it as a **Breakpoint** — verified: `Stopped (Breakpoint) at 0x10000244`. + +> **No breakpoints before you connect.** With GDB MI, a breakpoint set before the connection hangs the session (Step 11). Start parked with `BP_ADDR`, connect, *then* add breakpoints. + +#### Stepping + +With the target halted at the breakpoint, **Step Into** (`F7`) and **Step Over** (`F8`) run through real GDB and move the PC. Verified: `0x10000244 -> 0x100030ec -> 0x100030ee -> ...`. + +> **Step Over on the raw `.bin` steps *into* calls.** The raw image has no symbol for `__wrap_printf`, so **Step Over** at the `printf` call behaves like **Step Into**. When the lab needs to execute the call and then stop, it moves the breakpoint to the return site and clicks **Resume** instead (Step 14 shows this). + +> **Never use IDA's Restart button.** On RP2350 it resets and halts inside the boot ROM (`pc=0x88`, `sp=0xf0000000`). To reset cleanly, restart the server with `BP_ADDR` and reconnect. + +> **If you ever need the command port.** It is still there — `nc 127.0.0.1 4444`, and `bp 2 hw` still arms a breakpoint, `rbp ` / `rbp all` still remove them. It is the fallback if you switch back to the **GDB RSP** adapter, whose 1-byte breakpoints the GUI cannot set. With GDB MI you do not need it for this lab. + +### Step 14: HACK IT LIVE — change the printed double + +Project 1's `main` sets `r4 = 0`, loads the high word of the double into `r5`, and on every iteration copies them into the `r2:r3` argument pair before calling `printf`. We break on that call and change the value live: + +1. Press `G`, go to `0x10000244` (the `bl __wrap_printf`). +2. Set a **hardware execute** breakpoint there: `Debugger -> Add Hardware Breakpoint...`. (Do not use `F2` — that is a software breakpoint and will not work on read-only flash.) +3. Click **Resume** in IDA. The target is already running the loop, so the breakpoint fires on the next iteration. IDA stops with the program counter at `0x10000244`, `r2 = 0x00000000`, and `r3 = 0x40454000`. +4. Open the **Registers** widget (bug icon -> **Registers**). +5. The ABI passes the promoted `double` in `r2:r3` — `r2` is the low 32 bits, `r3` the high 32 bits. Together they are `0x40454000_00000000`, the IEEE-754 encoding of `42.5`. +6. **Set `r3` to `0x4058C000`** — the high word of `99.0` — from IDA's Python console (`Plugins -> Python Console`): + ```python + dbg.set_reg_value("r2", 0x00000000) # low word of the 99.0 double (unchanged) + dbg.set_reg_value("r3", 0x4058C000) # high word of the 99.0 double + ``` + `dbg.set_reg_value(name, value)` writes one register (returns `True` on success). You can also right-click a register in the **Registers** widget, press `E` (edit), type the hex value, and press Enter. The widget may not repaint, but the write reaches the target — you confirm it by the printed output in the next steps. +7. **Move the breakpoint past the call.** You want `printf` to run once and then stop, so move the breakpoint from `0x10000244` to the instruction *after* the call, `0x10000248` (the `b.n` that closes the loop): remove the breakpoint at `0x10000244` and set a hardware breakpoint at `0x10000248`. Two reasons not to just click **Step Over** here: a breakpoint left on the current PC re-traps the step, and IDA's **Step Over** steps *into* `__wrap_printf` on this raw `.bin` because the image carries no symbol for the call. Moving the breakpoint to the return site is deterministic. +8. Click **Resume** in IDA. The core executes `bl __wrap_printf` with `r2:r3 = 0x4058C000_00000000`, so this iteration prints `fav_num: 99.000000`, then stops at `0x10000248`. +9. Look at your serial monitor — the `screen` session on the Pico's USB serial port — and at the **Target** tab in IDA: + + ``` + fav_num: 99.000000 + ``` + +You changed a running program's output without touching the binary. + +### Step 14b: HACK THE STRING LIVE — change `fav_num:` to `myvalue:` + +The text `"fav_num: %f\r\n"` lives in flash (`.rodata`) at `0x100034a8`, and flash is **read-only at runtime** — a debugger write there does not stick. So instead of overwriting the text in place, redirect the pointer: at the `printf` call, `r0` holds the string address, so point `r0` at a replacement string you place in RAM. + +1. Arm the breakpoint at the `printf` call and hit it, exactly as in Step 14 steps 1-3. At the stop, `r0 = 0x100034a8`, `r2 = 0x00000000`, and `r3 = 0x40454000`. +2. Put the replacement string into free RAM at `0x20080000` from IDA's **Python console** (`Plugins -> Python Console`) — no command port needed: + ```python + dbg.write_memory(0x20080000, b"myvalue: %f\r\n\x00") + ``` + `dbg.write_memory(address, bytes)` is IDA's debugger memory-write API; it returns `True` on success. That writes the bytes `6d 79 76 61 6c 75 65 3a 20 25 66 0d 0a 00` = `"myvalue: %f\r\n\0"`. +3. Point `r0` at that string: + ```python + dbg.set_reg_value("r0", 0x20080000) + ``` + (Or right-click `r0` in the **Registers** widget, press `E`, type `0x20080000`, and press Enter.) +4. If you want the value hack too, set `r3` to `0x4058C000` as in Step 14. Then move the breakpoint past the call in the GUI (remove it at `0x10000244`, set one at `0x10000248`) and click **Resume**. The core runs `printf` with `r0` pointing at your RAM string and `r2:r3` holding `99.0`, so this iteration prints: + ``` + myvalue: 99.000000 + ``` + then stops at `0x10000248`. + +Like the value hack, this is **one iteration only**: the loop reloads `r0` (and `r2`/`r3`) from flash/literals on every pass, so the next line is `fav_num: 42.500000` again. The permanent version is the static patch in Step 18b. + +### Step 15: Why the hack reverts (and why we patch next) + +Press **Resume**. The loop branches back to `0x1000023e`, which copies `r4` and `r5` into `r2` and `r3` again. `r4` and `r5` were set once before the loop (`movs r4, #0`, `ldr r5, [pc, #12]`), so your `r3` edit is overwritten and the next line is `fav_num: 42.500000`. The live edit changed one iteration only. There is no variable in memory to change; the value is baked into the instruction/literal pool. To make `99.0` permanent we must patch the constant. That is the static pass. + +Press **Pause** to stop the output flood. + +### Step 15b: Kill the debugger and OpenOCD + +The live hack is done. Do this **before** the static pass. + +1. In the **Debugger** sidebar, click the **X** (**Kill**) (or **`Debugger -> Kill`**) to disconnect IDA. +2. **Kill does not stop the OpenOCD process** — `debug-server.sh` started it separately, and it keeps running and holding the probe. Stop it from the IDA console: + + **macOS / Linux:** + + ```python + import subprocess + subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # stop the debug server, free the probe + ``` + + **Windows:** + + ```python + import subprocess + subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"]) # stop the debug server, free the probe + ``` + +3. Confirm nothing is left: `pgrep -fl openocd` (macOS/Linux) prints nothing. + +From a terminal it is the same: `pkill -TERM -f openocd`, or `Get-Process openocd | Stop-Process` on Windows. +--- + +## Part 4: Static — Resolve the Functions in IDA and Patch (Project 1) + +### Step 16: Resolve the functions in the IDA GUI + +We now name the functions in IDA using the ELF symbol map from Step 4. IDA loaded the raw `.bin` with **no symbols**, so every function shows as `sub_` — resolving means giving each one its real name and signature. + +Three keys do all the work: + +| Key | IDA action | Use it for | +| --- | --- | --- | +| `G` | Go to address | Jump to a function's address | +| `Y` | **Change Type** | Set the function's signature. The dialog shows the full prototype, so this sets the name *and* the type in one step. | +| `N` | Rename | Rename only, when you just want the name and not the type | + +For each function below: `G` to its address, then **`Y` (Change Type)** and type the prototype from the table. + +#### How to resolve a function in IDA (`Y`) + +`Y` is the **Change Type** key, and it is what actually resolves the function — it turns `void sub_10002f5c()` into `bool stdio_init_all(void)`. The Change Type dialog shows the full declaration (name and type), so typing the prototype sets both: + +1. `G` to the function's address. The cursor lands on the function. +2. Press **`Y`**. In the Change Type dialog, type the prototype from the table exactly — for example `bool stdio_init_all(void)` — and press Enter. + +The decompiler header then shows the real prototype, and calls to the function read cleanly instead of `sub_()`. `N` is only for renaming without touching the type; `Y` alone sets both the name and the type. + +If `Y` seems to do nothing, confirm the cursor is on the function, or right-click it and pick **Change Type...**. IDA parses what you type and silently keeps the old type if it does not parse, so glance at the header after each `Y`. + +#### Worked example: `main` + +1. Press `G`, type `0x10000234`, press Enter. The view jumps there; the cursor lands on `sub_10000234`. +2. Press **`Y`** (Change Type), type `int main(void)`, press Enter. That sets the name to `main` and the type to `int(void)`. + +> **IDA shows `int32_t` where Ghidra shows `int`.** After you set `int main(void)`, the decompiler header may read `int32_t main(void)`. That is the same type — on this platform `int` is 32 bits and IDA's parser normalises it to `int32_t`. Do not fight it; it is not an error. + +#### Worked example: `stdio_init_all` + +1. `G` -> `0x10002f5c`. +2. `Y` -> `bool stdio_init_all(void)`. + +It returns **`bool`**, not `void` — the ELF says `_Bool stdio_init_all(void)`. Our `main` ignores the return value, so the decompiler still reads cleanly. + +#### Worked example: `uart_init` + +1. `G` -> `0x10000e18`. +2. `Y` -> `uint uart_init(uart_inst_t *uart, uint baudrate)`. + +#### Worked example: `__wrap_printf` + +1. `G` -> `0x100030ec`. +2. `Y` -> `int __wrap_printf(const char *fmt, ...)`. Keep the `...` — `printf` is variadic. + +> **`printf` in our source is `__wrap_printf` in the binary.** The SDK links our `printf` calls to its `__wrap_printf` wrapper. + +#### Worked example: `_ftoa` (the double formatter) + +1. `G` -> `0x10001890`. +2. `Y` -> `unsigned int _ftoa(out_fct_type, char*, size_t, size_t, double, unsigned int, unsigned int, unsigned int)`. + +This is the function that actually turns the double into the `42.500000` text. It is why the `pico_double` `__aeabi_*` helpers are in the image at all. + +The rest of the chain is the same two keystrokes per function (`G`, then `Y`). This is **our code plus the library functions it actually calls** — not the whole SDK. `main` only calls `stdio_init_all` and `printf`, so we follow that chain down: `stdio_init_all` pulls in the stdio/UART setup, and `printf` lands in the SDK's `__wrap_printf`, which reaches the `pico_double` formatter. + +The call chain for this project: + +``` +main +├── stdio_init_all +│ └── stdio_uart_init ── gpio_set_function, uart_init, stdio_set_driver_enabled +│ └── uart_init ── clock_get_hz, busy_wait_us +└── __wrap_printf ── __wrap_vprintf + ├── vfctprintf ── _vsnprintf + │ ├── _ftoa / _etoa ── __wrap___aeabi_* (the pico_double helpers) + │ └── _ntoa_format / _out_rev + ├── stdio_out_chars_crlf + └── time_us_64 +``` + +**Project 1 — resolve every function in that chain:** + +| Address | Rename to (`N`) | Signature (`Y`) | +| ------- | --------------- | --------------- | +| `0x1000015c` | `_reset_handler` | `void _reset_handler(void)` | +| `0x10000186` | `platform_entry` | `void platform_entry(void)` | +| `0x1000019a` | `data_cpy` | `void data_cpy(void*, void*, void*)` | +| `0x100001e4` | `_init` | `void _init(void)` | +| `0x10000210` | `frame_dummy` | `void frame_dummy(void)` | +| **`0x10000234`** | **`main`** | **`int main(void)`** | +| `0x10002ca8` | `vfctprintf` | `int vfctprintf(void (*)(char, void*), void*, const char*, va_list)` | +| `0x10002d04` | `exit` | `void exit(int)` | +| `0x10002d0c` | `runtime_init` | `void runtime_init(void)` | +| `0x10002d38` | `stdio_out_chars_crlf` | `void stdio_out_chars_crlf(stdio_driver_t*, const char*, int)` | +| `0x10002e48` | `stdio_put_string` | `int stdio_put_string(const char*, int, bool, bool)` | +| `0x10002f34` | `stdio_set_driver_enabled` | `void stdio_set_driver_enabled(stdio_driver_t*, bool)` | +| `0x10002f5c` | `stdio_init_all` | `bool stdio_init_all(void)` | +| `0x10003028` | `__wrap_vprintf` | `int __wrap_vprintf(const char*, va_list)` | +| `0x100030ec` | `__wrap_printf` | `int __wrap_printf(const char*, ...)` | +| `0x100032a8` | `stdio_uart_init` | `void stdio_uart_init(void)` | +| `0x100033e8` | `strlen` | `size_t strlen(const char*)` | +| `0x10000254` | `gpio_set_function` | `void gpio_set_function(uint, gpio_function_t)` | +| `0x10000e18` | `uart_init` | `uint uart_init(uart_inst_t*, uint)` | +| `0x10000da8` | `time_us_64` | `uint64_t time_us_64(void)` | + +**Project 1 — resolve the `pico_double` formatting helpers `printf` reaches:** + +| Address | Rename to (`N`) | Signature (`Y`) | +| ------- | --------------- | --------------- | +| `0x10001384` | `__wrap___aeabi_dadd` | `double __wrap___aeabi_dadd(double, double)` | +| `0x100013ac` | `__wrap___aeabi_dsub` | `double __wrap___aeabi_dsub(double, double)` | +| `0x100013d4` | `__wrap___aeabi_dmul` | `double __wrap___aeabi_dmul(double, double)` | +| `0x10001420` | `__wrap___aeabi_ddiv` | `double __wrap___aeabi_ddiv(double, double)` | +| `0x100014bc` | `__wrap___aeabi_i2d` | `double __wrap___aeabi_i2d(int)` | +| `0x100014e0` | `__wrap___aeabi_ui2d` | `double __wrap___aeabi_ui2d(unsigned)` | +| `0x10001504` | `__wrap___aeabi_d2iz` | `int __wrap___aeabi_d2iz(double)` | +| `0x10001528` | `__wrap___aeabi_d2uiz` | `unsigned __wrap___aeabi_d2uiz(double)` | +| `0x1000154c` | `__wrap___aeabi_dcmpun` | `int __wrap___aeabi_dcmpun(double, double)` | +| `0x10001570` | `__wrap___aeabi_dcmplt` | `int __wrap___aeabi_dcmplt(double, double)` | +| `0x10001598` | `__wrap___aeabi_dcmple` | `int __wrap___aeabi_dcmple(double, double)` | +| `0x100015c0` | `__wrap___aeabi_dcmpge` | `int __wrap___aeabi_dcmpge(double, double)` | +| `0x100015e8` | `__wrap___aeabi_dcmpgt` | `int __wrap___aeabi_dcmpgt(double, double)` | +| `0x1000160c` | `_out_rev` | `unsigned _out_rev(out_fct_type, char*, size_t, size_t, const char*, size_t, unsigned, unsigned)` | +| `0x100016a8` | `_ntoa_format` | `unsigned _ntoa_format(out_fct_type, char*, size_t, size_t, char*, size_t, bool, unsigned, unsigned, unsigned, unsigned)` | +| `0x1000187c` | `_out_char` | `void _out_char(char, void*, size_t, size_t)` | +| `0x10001890` | `_ftoa` | `unsigned int _ftoa(out_fct_type, char*, size_t, size_t, double, unsigned int, unsigned int, unsigned int)` | +| `0x10001d50` | `_etoa` | `unsigned int _etoa(out_fct_type, char*, size_t, size_t, double, unsigned int, unsigned int, unsigned int)` | +| `0x100022c4` | `_vsnprintf` | `int _vsnprintf(out_fct_type, char*, size_t, const char*, va_list)` | +| `0x10000dbc` | `busy_wait_us` | `void busy_wait_us(uint64_t)` | +| `0x10000fec` | `clock_get_hz` | `unsigned long clock_get_hz(clock_handle_t)` | + +> **A `void` return type may not stick — here is the fix.** IDA treats `void` as low-confidence, and its analysis can override it with an inferred type — most often `int32_t` on this 32-bit target. It is most visible on `_reset_handler` (a hand-written assembly entry that never returns normally), but it can happen to **any** function whose return type IDA thinks it can infer. +> +> Setting the full signature with `Y` reproduces the unwanted `int32_t`, and `fn.return_type = ...` fails too. What works is the **return-value** setter: +> +> ```python +> from binaryninja import ReturnValue, Type +> fn = bv.get_function_at(0x1000015c) +> if fn is not None: +> fn.return_value = ReturnValue(Type.void()) +> ``` +> +> That holds `_reset_handler` at `void` even after reanalysis. If it still will not stick, leave it — it does not affect the rest of the lesson. + +> **`__wrap_printf` is the real symbol.** `printf` in our source compiles to the SDK's `__wrap_printf` (which forwards to `__wrap_vprintf`). Rename it `printf` if you prefer the lesson's shorthand, but `__wrap_printf` is what the ELF says. +> +> **`stdio_init_all` returns `bool`, not `void`** — `_Bool stdio_init_all(void)` in the ELF. + +> **Shortcut — resolves name *and* type for every function.** Instead of doing `N` + `Y` by hand, paste this into IDA's Python console (`Plugins -> Python Console`). It sets each function's name and signature programmatically: +> +> ```python +> from binaryninja import Symbol, SymbolType +> # The raw .bin has no headers, so these SDK types don't exist. set_user_type() +> # re-parses each signature as C, so an undefined name raises +> # "SyntaxError: unknown type name '...'". Define them first. +> sdk = bv.parse_types_from_string(""" +> typedef unsigned int uint; +> typedef char* va_list; +> typedef unsigned long clock_handle_t; +> typedef void (*out_fct_type)(char, void*, size_t, size_t); +> struct stdio_driver; +> typedef struct stdio_driver stdio_driver_t; +> struct uart_inst; +> typedef struct uart_inst uart_inst_t; +> enum gpio_function { +> GPIO_FUNC_XIP = 0, GPIO_FUNC_SPI = 1, GPIO_FUNC_UART = 2, GPIO_FUNC_I2C = 3, +> GPIO_FUNC_PWM = 4, GPIO_FUNC_SIO = 5, GPIO_FUNC_PIO0 = 6, GPIO_FUNC_PIO1 = 7, +> GPIO_FUNC_GPCK = 8, GPIO_FUNC_USB = 9, GPIO_FUNC_NULL = 0x1f, +> }; +> typedef enum gpio_function gpio_function_t; +> """) +> for name, ty in sdk.types.items(): +> bv.define_user_type(name, ty) +> +> # address: (name, signature) +> funcs = { +> 0x1000015c: ("_reset_handler", "void _reset_handler(void)"), +> 0x10000186: ("platform_entry", "void platform_entry(void)"), +> 0x1000019a: ("data_cpy", "void data_cpy(void*, void*, void*)"), +> 0x100001e4: ("_init", "void _init(void)"), +> 0x10000210: ("frame_dummy", "void frame_dummy(void)"), +> 0x10000234: ("main", "int main(void)"), +> 0x10002ca8: ("vfctprintf", "int vfctprintf(void (*)(char, void*), void*, const char*, va_list)"), +> 0x10002d04: ("exit", "void exit(int)"), +> 0x10002d0c: ("runtime_init", "void runtime_init(void)"), +> 0x10002d38: ("stdio_out_chars_crlf", "void stdio_out_chars_crlf(stdio_driver_t*, const char*, int)"), +> 0x10002e48: ("stdio_put_string", "int stdio_put_string(const char*, int, bool, bool)"), +> 0x10002f34: ("stdio_set_driver_enabled", "void stdio_set_driver_enabled(stdio_driver_t*, bool)"), +> 0x10002f5c: ("stdio_init_all", "bool stdio_init_all(void)"), +> 0x10003028: ("__wrap_vprintf", "int __wrap_vprintf(const char*, va_list)"), +> 0x100030ec: ("__wrap_printf", "int __wrap_printf(const char*, ...)"), +> 0x100032a8: ("stdio_uart_init", "void stdio_uart_init(void)"), +> 0x100033e8: ("strlen", "size_t strlen(const char*)"), +> 0x10000254: ("gpio_set_function", "void gpio_set_function(uint, gpio_function_t)"), +> 0x10000e18: ("uart_init", "uint uart_init(uart_inst_t*, uint)"), +> 0x10000da8: ("time_us_64", "uint64_t time_us_64(void)"), +> 0x10001384: ("__wrap___aeabi_dadd", "double __wrap___aeabi_dadd(double, double)"), +> 0x100013ac: ("__wrap___aeabi_dsub", "double __wrap___aeabi_dsub(double, double)"), +> 0x100013d4: ("__wrap___aeabi_dmul", "double __wrap___aeabi_dmul(double, double)"), +> 0x10001420: ("__wrap___aeabi_ddiv", "double __wrap___aeabi_ddiv(double, double)"), +> 0x100014bc: ("__wrap___aeabi_i2d", "double __wrap___aeabi_i2d(int)"), +> 0x100014e0: ("__wrap___aeabi_ui2d", "double __wrap___aeabi_ui2d(unsigned)"), +> 0x10001504: ("__wrap___aeabi_d2iz", "int __wrap___aeabi_d2iz(double)"), +> 0x10001528: ("__wrap___aeabi_d2uiz", "unsigned __wrap___aeabi_d2uiz(double)"), +> 0x1000154c: ("__wrap___aeabi_dcmpun", "int __wrap___aeabi_dcmpun(double, double)"), +> 0x10001570: ("__wrap___aeabi_dcmplt", "int __wrap___aeabi_dcmplt(double, double)"), +> 0x10001598: ("__wrap___aeabi_dcmple", "int __wrap___aeabi_dcmple(double, double)"), +> 0x100015c0: ("__wrap___aeabi_dcmpge", "int __wrap___aeabi_dcmpge(double, double)"), +> 0x100015e8: ("__wrap___aeabi_dcmpgt", "int __wrap___aeabi_dcmpgt(double, double)"), +> 0x1000160c: ("_out_rev", "unsigned _out_rev(out_fct_type, char*, size_t, size_t, const char*, size_t, unsigned, unsigned)"), +> 0x100016a8: ("_ntoa_format", "unsigned _ntoa_format(out_fct_type, char*, size_t, size_t, char*, size_t, bool, unsigned, unsigned, unsigned, unsigned)"), +> 0x1000187c: ("_out_char", "void _out_char(char, void*, size_t, size_t)"), +> 0x10001890: ("_ftoa", "unsigned int _ftoa(out_fct_type, char*, size_t, size_t, double, unsigned int, unsigned int, unsigned int)"), +> 0x10001d50: ("_etoa", "unsigned int _etoa(out_fct_type, char*, size_t, size_t, double, unsigned int, unsigned int, unsigned int)"), +> 0x100022c4: ("_vsnprintf", "int _vsnprintf(out_fct_type, char*, size_t, const char*, va_list)"), +> 0x10000dbc: ("busy_wait_us", "void busy_wait_us(uint64_t)"), +> 0x10000fec: ("clock_get_hz", "unsigned long clock_get_hz(clock_handle_t)"), +> } +> for addr, (name, sig) in funcs.items(): +> bv.define_user_symbol(Symbol(SymbolType.FunctionSymbol, addr, name)) +> f = bv.get_function_at(addr) +> if f is not None: +> f.set_user_type(sig) +> ``` +> +> SDK type names (`stdio_driver_t`, `gpio_function_t`, `uart_inst_t`, plus `uint`, `va_list`, `out_fct_type`, and `clock_handle_t`) are **not** in the raw `.bin`. `set_user_type` re-parses each signature as C, so an undefined name raises `SyntaxError: unknown type name '...'` and stops the loop — it is not harmless. The `sdk` block above defines them first (an opaque `struct`/`enum`/`typedef` is enough to parse). If you add a function that uses another SDK type, add a definition for it to that block too. + +### Step 17: Read `main` in the decompiler + +Open the **Decompiler** view on `main`. It reads: + +```c +int32_t main(void) +{ + stdio_init_all(); + do + { + __wrap_printf("fav_num: %f\r\n", 0, 0x40454000); + } while (true); +} +``` + +The trailing pair is the promoted `double`: `r2 = 0`, `r3 = 0x40454000`. IDA already knows the calling convention, so once `__wrap_printf` is typed `int __wrap_printf(const char*, ...)`, the pair is shown as data. Now make the hack permanent. + +### Step 18: Patch `0x40454000` to `0x4058C000` in the GUI + +Go to `0x1000024c`: + +```asm +1000024c: 40454000 .word 0x40454000 +``` + +That word is the high half of the `double` `42.5`. Its bytes, little-endian, are `00 40 45 40`. Change them to `00 c0 58 40`, the high half of `99.0`: + +| Project | Address | Before | After | Effect | +| ------- | ------- | ------ | ----- | ------ | +| `0x000e` | `0x1000024c` | `00 40 45 40` | `00 c0 58 40` | high word of `42.5` -> `99.0` | + +**Option A — Hex view:** + +1. Switch to the **Hex** view (`View -> Hex`). +2. Toggle the lock off so editing is enabled. +3. Go to `0x1000024c` and change `00 40 45 40` to `00 c0 58 40`. +4. Return to the linear view, right-click the function -> `Reanalyze`. + +**Option B — Python console:** + +```python +bv.write(0x1000024c, bytes.fromhex("00c05840")) +print(bv.read(0x1000024c, 4)) # -> b'\x00\xc0X@' +``` + +After reanalysis the literal reads `0x4058C000`, and the decompiler shows `__wrap_printf("fav_num: %f\r\n", 0, 0x4058c000)`. + +### Step 18b: Patch the string `fav_num:` to `myvalue:` in the GUI + +The format string `"fav_num: %f\r\n"` starts at `0x100034a8`. Its first eight bytes are `66 61 76 5f 6e 75 6d 3a` (`fav_num:`). Change them to `6d 79 76 61 6c 75 65 3a` (`myvalue:`), leaving the ` %f\r\n` tail untouched, so the line prints `myvalue: 99.000000`. + +| Project | Address | Before | After | Effect | +| ------- | ------- | ------ | ----- | ------ | +| `0x000e` | `0x100034a8` | `66 61 76 5f 6e 75 6d 3a` | `6d 79 76 61 6c 75 65 3a` | `fav_num:` -> `myvalue:` | + +**Option A — Hex view:** + +1. Switch to the **Hex** view (`View -> Hex`). +2. Go to `0x100034a8` and change the eight bytes `66 61 76 5f 6e 75 6d 3a` to `6d 79 76 61 6c 75 65 3a`. +3. Return to the linear view and reanalyze. + +**Option B — Python console:** + +```python +bv.write(0x100034a8, b"myvalue:") +print(bv.read(0x100034a8, 15)) # -> b'myvalue: %f\r\n\x00' +``` + +Keep the replacement exactly eight bytes. If you use a shorter string you must pad it, or `%f` shifts and `printf` reads the wrong argument. A longer string would overwrite the ` %f` tail. + +### Step 19: Export the patched `.bin` + +```python +import os +seg = next(s for s in bv.segments if s.data_length) # the loadable image segment +data = bv.read(seg.start, seg.data_length) # base + size come from the view itself +out = os.path.join(os.path.join(root, "0x000e_floating-point-data-type", "build"), "0x000e_floating-point-data-type-h.bin") +open(out, "wb").write(data) +print(len(data), out) # -> 15308 /.../build/0x000e_floating-point-data-type-h.bin +``` + +Where the two numbers come from — nothing is hardcoded: + +- **`seg.start`** is the image base IDA loaded the `.bin` at (`0x10000000`), the same value you pass to `uf2conv --base`. +- **`seg.data_length`** is the segment's size in the file (`0x3bcc` = 15308). Exactly one segment carries data (the image); every peripheral and synthetic segment has `data_length == 0`, so `next(...)` picks the image. +- Reading `seg.start` for `seg.data_length` bytes therefore grabs exactly the image. + +Two gotchas this avoids: + +- **No relative path.** IDA's Python console runs with a read-only working directory (inside the app bundle), so `open("0x000e_floating-point-data-type-h.bin", "wb")` fails with `OSError: [Errno 30] Read-only file system`. `root` (from `~/.embedded-hacking-repo`, Step 3) is the repo, so the file is written into the project's `build/` — no machine-specific path and no database needed. +- **Read the image, not the whole view.** `bv.read(bv.start, bv.length)` spans the entire mapped range, which is not the image. The segment's `data_length` is the image size. + +A different size means you exported a partial view. + +### Step 20: Convert to UF2 + +Run from the project directory: + +**macOS Apple Silicon / Linux x64:** + +```bash +python3 ../uf2conv.py 0x000e_floating-point-data-type-h.bin \ + --base 0x10000000 --family 0xe48bff59 --output hacked.uf2 +``` + +**Windows x64:** + +```cmd +python ..\uf2conv.py 0x000e_floating-point-data-type-h.bin ^ + --base 0x10000000 --family 0xe48bff59 --output hacked.uf2 +``` + +> **Or convert from the IDA console** — it is a normal Python interpreter, so you never have to leave the app. `chdir` to a writable directory first (the default one is read-only), then run the script: +> +> ```python +> import os, sys, runpy +> os.chdir(os.path.join(root, "0x000e_floating-point-data-type", "build")) # the project build dir (writable) +> sys.argv = ["uf2conv.py", "0x000e_floating-point-data-type-h.bin", +> "--base", "0x10000000", "--family", "0xe48bff59", "--output", "hacked.uf2"] +> runpy.run_path("../../uf2conv.py", run_name="__main__") # path to your uf2conv.py +> ``` +> +> This writes `hacked.uf2` next to the `.bin`, ready to drag onto the Pico. + +### Step 21: Flash and verify `fav_num: 99.000000` + +Hold **BOOTSEL**, plug in the Pico 2, and drag `hacked.uf2` onto the **`RP2350`** drive. Open the serial monitor: + +``` +myvalue: 99.000000 +myvalue: 99.000000 +myvalue: 99.000000 +... +``` + +**42.5 became 99.0, permanently, with one 32-bit word changed and no source code.** + +> **Faster: flash over the Debug Probe (no BOOTSEL).** The repo's `flash.sh` writes the raw `.bin` straight into XIP flash over SWD (`program 0x10000000 verify reset exit`), so you never touch BOOTSEL or a UF2. Run it from a terminal (`./flash.sh `), or from the IDA console **without freezing it** — use `subprocess.Popen`, which returns immediately, and send OpenOCD's output to a log file. (`subprocess.run` blocks the console until the flash finishes; do not use it here.) +> +> ```python +> import os, subprocess +> root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() +> bin_path = os.path.join(os.path.join(root, "0x000e_floating-point-data-type", "build"), "0x000e_floating-point-data-type-h.bin") +> log = os.path.join(os.path.join(root, "0x000e_floating-point-data-type", "build"), "flash.log") +> subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # free the probe first +> p = subprocess.Popen([os.path.join(root, "flash.sh"), bin_path], +> stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) +> print("flashing in the background; log:", log) +> ``` +> +> The `pkill` frees the probe first; on Windows use `subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"])`. +> +> The console is free the moment this returns. Check it with `print(p.poll())` (`None` = still running, `0` = done) or read `flash.log` — success ends with `** Verified OK **`. +> +> The same non-blocking form without the script: +> +> ```python +> import os, subprocess +> ocd = os.path.expanduser("~/.pico-sdk/openocd/0.12.0+dev") +> bin_path = os.path.join(os.path.join(root, "0x000e_floating-point-data-type", "build"), "0x000e_floating-point-data-type-h.bin") +> log = os.path.join(os.path.join(root, "0x000e_floating-point-data-type", "build"), "flash.log") +> subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # free the probe first +> p = subprocess.Popen([f"{ocd}/openocd", "-s", f"{ocd}/scripts", +> "-f", "interface/cmsis-dap.cfg", "-f", "target/rp2350.cfg", +> "-c", "adapter speed 5000", +> "-c", f"program {bin_path} 0x10000000 verify reset exit"], +> stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) +> print("flashing in the background; log:", log) +> ``` +> +> **The Debug Probe is single-owner.** If IDA is still attached (the `debug-server.sh` OpenOCD is running), the flash cannot grab the probe. Detach in IDA and stop that OpenOCD first: +> +> ```bash +> # macOS / Linux +> pkill -TERM -f openocd +> ``` +> ```powershell +> # Windows +> Get-Process openocd -ErrorAction SilentlyContinue | Stop-Process +> ``` +> +> Success looks like `Programming Finished` -> `Verified OK` -> `Resetting Target`. On Windows use `flash.ps1` (`.\flash.ps1 -Bin `) the same way. +--- + +## Part 5: Dynamic — Break at `main` and Hack Live (Project 2) + +### Step 22: Reflash Project 2 and reload IDA + +Part 4 left the Pico running the patched Project 1 image. Put the original Project 2 back and start a fresh session. + +1. Stop any running debug server so the flash script can use the probe: + + ```bash + # macOS / Linux + pkill -TERM -f openocd + ``` + ```powershell + # Windows + Get-Process openocd -ErrorAction SilentlyContinue | Stop-Process + ``` + +2. Flash the original Project 2 image: + + ```bash + # macOS / Linux + ./flash.sh 0x0011_double-floating-point-data-type/build/0x0011_double-floating-point-data-type.bin + ``` + ```powershell + # Windows + .\flash.ps1 -Bin 0x0011_double-floating-point-data-type\build\0x0011_double-floating-point-data-type.bin + ``` + + **Or do steps 1-2 from the IDA console** (the active view is still Project 1, so take the repo root from the marker file and point at the Project 2 `.bin`): + + **macOS / Linux:** + + ```python + import os, subprocess + root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) + bin_path = os.path.join(root, "0x0011_double-floating-point-data-type", "build", "0x0011_double-floating-point-data-type.bin") + log = os.path.join(os.path.dirname(bin_path), "flash.log") + subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # free the probe first + subprocess.Popen([os.path.join(root, "flash.sh"), bin_path], + stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) + print("flashing Project 2 in the background; log:", log) + ``` + + **Windows:** + + ```python + import os, subprocess + root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) + bin_path = os.path.join(root, "0x0011_double-floating-point-data-type", "build", "0x0011_double-floating-point-data-type.bin") + log = os.path.join(os.path.dirname(bin_path), "flash.log") + subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"]) # free the probe first + subprocess.Popen(["powershell", "-ExecutionPolicy", "Bypass", "-File", + os.path.join(root, "flash.ps1"), "-Bin", bin_path], + stdout=open(log, "w"), stderr=subprocess.STDOUT) + print("flashing Project 2 in the background; log:", log) + ``` + +3. Start the debug server again (Step 10) and wait for `Listening on port 3333`. +4. Load Project 2 and save its database — see Step 22b. +5. Connect IDA again (Step 11): adapter **GDB MI**, IP `127.0.0.1`, port `3333`. + +Confirm the Pico prints `fav_num: 42.525250`. + +### Step 22b: Load Project 2 into IDA and save the database + +Exactly like Steps 7-8, but for Project 2. **Use `File -> Open with Options...`** (not plain `File -> Open`), select `0x0011_double-floating-point-data-type/build/0x0011_double-floating-point-data-type.bin`, and set: + +- **Architecture:** `thumb2` +- **Platform:** `thumb2` +- **Base Address:** `0x10000000` + +Click **Open**. Then press `G`, type `0x10000000`, and confirm the first two words: + +``` +0x10000000 0x20082000 initial stack pointer +0x10000004 0x1000015d reset vector (bit 0 = Thumb) +``` + +If you see data at `0x00000000`, close the tab and redo it with `Open with Options`. + +Save it with `File -> Save As...` as `0x0011_double-floating-point-data-type.i64` (next to the `.bin`). From now on open the `.i64`, not the `.bin`; save with `Cmd+S` / `Ctrl+S` after every rename or patch. + +> **Console equivalent:** +> ```python +> load("0x0011_double-floating-point-data-type/build/0x0011_double-floating-point-data-type.bin", +> options={"loader.imageBase": 0x10000000, "loader.platform": "thumb2"}) +> ``` + +Then resolve the functions for Project 2 the same way as Project 1 — Step 26. + +### Step 23: Break at `main` + +`main` is at `0x10000238` in this project. The GUI sets breakpoints fine (Step 13); the only caution is not to drive `reset run` from the port while IDA is attached (it desyncs IDA's view). Use `BP_ADDR`, which arms `main` before IDA connects: + +1. Stop the server (Ctrl-C), then start it parked at `main`: + ```bash + # macOS / Linux + BP_ADDR=0x10000238 ./debug-server.sh + ``` + ```powershell + # Windows + $env:BP_ADDR="0x10000238"; .\debug-server.ps1 + ``` + + **Or restart it from the IDA console** — kill any running server, then start it parked at `main`: + + **macOS / Linux:** + + ```python + import os, subprocess + root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() + log = os.path.join(root, "openocd.log") + subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # kill any running server first + subprocess.Popen([os.path.join(root, "debug-server.sh")], cwd=root, + env=dict(os.environ, BP_ADDR="0x10000238"), + stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) + print("OpenOCD restarted parked at main; log:", log) + ``` + + **Windows:** + + ```python + import os, subprocess + root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() + log = os.path.join(root, "openocd.log") + subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"]) # kill any running server first + subprocess.Popen(["powershell", "-ExecutionPolicy", "Bypass", "-File", + os.path.join(root, "debug-server.ps1")], cwd=root, + env=dict(os.environ, BP_ADDR="0x10000238"), + stdout=open(log, "w"), stderr=subprocess.STDOUT) + print("OpenOCD restarted parked at main; log:", log) + ``` +2. Connect IDA (Step 11): adapter **GDB MI**, IP `127.0.0.1`, port `3333`. + +The target is already halted at `main` when IDA connects, and the sidebar reads `Stopped at 0x10000238`. + +> If you instead want to reach `main` on an already-connected session, you must Detach, send `reset run` from the port, then reconnect. Arming `main` and resetting while attached leaves the sidebar showing a stale address. + +`main` loads the whole 64-bit `double` from a single literal-pool address, then loops: copy the pair into `r2:r3` and call `printf`. The whole thing is one function: + +```asm +10000238: b538 push {r3, r4, r5, lr} +1000023a: a506 add r5, pc, #24 ; adr r5, 0x10000254 +1000023c: e9d5 4500 ldrd r4, r5, [r5] ; r4 = low word, r5 = high word +10000240: f002 fe90 bl 0x10002f64 ; stdio_init_all +10000244: 4622 mov r2, r4 +10000246: 462b mov r3, r5 +10000248: 4801 ldr r0, [pc, #4] ; -> 0x10000250 = 0x100034b0 (format string) +1000024a: f002 ff53 bl 0x100030f4 ; __wrap_printf +1000024e: e7f9 b.n 0x10000244 +10000250: 100034b0 .word 0x100034b0 +10000254: 645a1cac .word 0x645a1cac +10000258: 4045433b .word 0x4045433b +``` + +Notice the `ldrd r4, r5, [r5]` — a single 64-bit load from the literal pool at `0x10000254`, which fills **both** halves of the double at once. That is the structural difference from Project 1, where the low half was a register zero (`movs r4, #0`) and only the high half lived in the pool. + +Look at the **Registers** widget at `0x1000024a`: `r2 = 0x645A1CAC` (low) and `r3 = 0x4045433B` (high). Together that is `0x4045433B_645A1CAC`, the IEEE-754 encoding of `42.52525`. + +### Step 24: Inspect the double argument live + +The `double` crosses the ABI in two registers. At the `printf` call the pair is exactly the literal-pool word pair: + +| Register | Value | Role | +| -------- | ----- | ---- | +| `r2` | `0x645A1CAC` | low 32 bits of `42.52525` | +| `r3` | `0x4045433B` | high 32 bits of `42.52525` | + +Step Over through `0x10000244` (`mov r2, r4`) and `0x10000246` (`mov r3, r5`) and watch `r2`/`r3` populate from `r4`/`r5`. This is C's variadic rule in action: `printf`'s `%lf` receives a 64-bit `double`, and on this target a `double` argument travels in `r2:r3`. + +> **Why `r2:r3`, not `r0:r1`?** The first variadic argument goes after the named format pointer, so `printf(fmt, value)` puts `fmt` in `r0` and the promoted `double` in `r2:r3`. That leaves `r1` unused here, which is why the format string pointer is `r0` and the number is `r2:r3`. + +### Step 25: HACK IT LIVE — change the printed double + +1. Press `G`, go to `0x1000024a` (the `bl __wrap_printf`). +2. Set a **hardware execute** breakpoint at `0x1000024a` in the GUI (`Debugger -> Add Hardware Breakpoint...`; not `F2`). Note `0x1000024a` — Project 2's loop sits at a different address than Project 1's. +3. Click **Resume** in IDA. The target is already looping, so the breakpoint fires on the next pass. IDA stops with `r2 = 0x645A1CAC`, `r3 = 0x4045433B`. +4. Overwrite both halves with the encoding of `99.99` (`0x4058FF5C_28F5C28F`): + ```python + dbg.set_reg_value("r2", 0x28F5C28F) # low word of the 99.99 double + dbg.set_reg_value("r3", 0x4058FF5C) # high word of the 99.99 double + ``` + (Or right-click each register in the **Registers** widget, press `E`, type the hex value, and press Enter.) +5. **Move the breakpoint past the call.** `0x1000024e` is the instruction right after the `bl __wrap_printf`. Remove the breakpoint at `0x1000024a` and set a hardware breakpoint at `0x1000024e`, then click **Resume**. The core runs `printf` with `r2:r3 = 0x4058FF5C_28F5C28F` and stops at `0x1000024e`. (Not **Step Over** — it steps into the call on this symbol-less `.bin`, and a breakpoint left on the current PC re-traps the step; Step 13 explains both.) +6. Look at your serial monitor and the **Target** tab: + + ``` + fav_num: 99.990000 + ``` + +Press **Resume** and the next iteration prints `fav_num: 42.525250` again, because the loop reloads `r2`/`r3` from `r4`/`r5` each pass. The live hack is temporary; the static patch makes it permanent. + +### Step 25b: HACK THE STRING LIVE — change `fav_num:` to `myvalue:` + +Same idea as Project 1, different addresses. Here the format string is at `0x100034b0` and the `printf` call is at `0x1000024a`. + +1. Hit the breakpoint at `0x1000024a` as in Step 25. At the stop, `r0 = 0x100034b0`, `r2 = 0x645A1CAC`, `r3 = 0x4045433B`. +2. Write the replacement string to free RAM at `0x20080000` from the **Python console** (`dbg.write_memory` — no command port needed): + ```python + dbg.write_memory(0x20080000, b"myvalue: %lf\r\n\x00") + ``` + Bytes `6d 79 76 61 6c 75 65 3a 20 25 6c 66 0d 0a 00` = `"myvalue: %lf\r\n\0"`. +3. Point `r0` at that string: + ```python + dbg.set_reg_value("r0", 0x20080000) + ``` + (Or right-click `r0` in the **Registers** widget, press `E`, type `0x20080000`, and press Enter.) +4. If you want the value hack too, set `r2 = 0x28F5C28F` and `r3 = 0x4058FF5C` as in Step 25. Then move the breakpoint past the call in the GUI (remove it at `0x1000024a`, set one at `0x1000024e`) and click **Resume**. This iteration prints: + ``` + myvalue: 99.990000 + ``` + then stops at `0x1000024e`. One iteration only — the loop reloads `r0` (and `r2`/`r3`) each pass. The permanent version is the static patch in Step 28b. + +### Step 25c: Kill the debugger and OpenOCD + +Same as Step 15b: click the **X** (**Kill**) in the **Debugger** sidebar (or **`Debugger -> Kill`**), then stop OpenOCD from the IDA console: + +**macOS / Linux:** + +```python +import subprocess +subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # stop the debug server, free the probe +``` + +**Windows:** + +```python +import subprocess +subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"]) # stop the debug server, free the probe +``` +--- + +## Part 6: Static — Resolve the Functions and Patch (Project 2) + +### Step 26: Resolve the functions in the IDA GUI + +Same two keys as Step 16 — `G` to the address, then `Y` (Change Type) to set the prototype — using the Project 2 ELF symbol map from Step 4. + +The mechanics are identical to Step 16, so here are the worked examples for the functions that are specific to this project. + +#### `main` + +1. `G` -> `0x10000238`. +2. `Y` -> `int main(void)` (IDA shows `int32_t main(void)` — the same 32-bit `int`). + +#### `stdio_uart_init` + +1. `G` -> `0x100032b0`. +2. `Y` -> `void stdio_uart_init(void)`. + +#### `_ftoa` and `_etoa` + +Same formatters as Project 1, eight bytes higher: `_ftoa` at `0x10001898` (`unsigned int _ftoa(out_fct_type, char*, size_t, size_t, double, unsigned int, unsigned int, unsigned int)`) and `_etoa` at `0x10001d58` (same prototype). + +#### `stdio_init_all` and `__wrap_printf` + +Same as Project 1, different addresses: `stdio_init_all` at `0x10002f64` (`bool stdio_init_all(void)`), and `__wrap_printf` at `0x100030f4` (`int __wrap_printf(const char *fmt, ...)`). + +Then work down the table the same way. + +Same idea as Project 1: **our code plus what it calls**, not the whole SDK. The call chain here is identical to Project 1 — because `%lf` and `%f` both route into the same `pico_double` formatter: + +``` +main +├── stdio_init_all +│ └── stdio_uart_init ── gpio_set_function, uart_init, stdio_set_driver_enabled +│ └── uart_init ── clock_get_hz, busy_wait_us +└── __wrap_printf ── __wrap_vprintf + ├── vfctprintf ── _vsnprintf + │ ├── _ftoa / _etoa ── __wrap___aeabi_* (the pico_double helpers) + │ └── _ntoa_format / _out_rev + ├── stdio_out_chars_crlf + └── time_us_64 +``` + +One thing in this project has **no separate call**, because the compiler emitted it as a single instruction: the 64-bit literal load is the `ldrd r4, r5, [r5]` you see inside `main`. There is no helper function to rename for it — it is two `.word`s in the pool at `0x10000254`. + +**Project 2 — resolve every function in that chain:** + +| Address | Rename to (`N`) | Signature (`Y`) | +| ------- | --------------- | --------------- | +| `0x1000015c` | `_reset_handler` | `void _reset_handler(void)` | +| `0x10000186` | `platform_entry` | `void platform_entry(void)` | +| `0x1000019a` | `data_cpy` | `void data_cpy(void*, void*, void*)` | +| `0x100001e4` | `_init` | `void _init(void)` | +| `0x10000210` | `frame_dummy` | `void frame_dummy(void)` | +| **`0x10000238`** | **`main`** | **`int main(void)`** | +| `0x10002cb0` | `vfctprintf` | `int vfctprintf(void (*)(char, void*), void*, const char*, va_list)` | +| `0x10002d0c` | `exit` | `void exit(int)` | +| `0x10002d14` | `runtime_init` | `void runtime_init(void)` | +| `0x10002d40` | `stdio_out_chars_crlf` | `void stdio_out_chars_crlf(stdio_driver_t*, const char*, int)` | +| `0x10002e50` | `stdio_put_string` | `int stdio_put_string(const char*, int, bool, bool)` | +| `0x10002f3c` | `stdio_set_driver_enabled` | `void stdio_set_driver_enabled(stdio_driver_t*, bool)` | +| `0x10002f64` | `stdio_init_all` | `bool stdio_init_all(void)` | +| `0x10003030` | `__wrap_vprintf` | `int __wrap_vprintf(const char*, va_list)` | +| `0x100030f4` | `__wrap_printf` | `int __wrap_printf(const char*, ...)` | +| `0x100032b0` | `stdio_uart_init` | `void stdio_uart_init(void)` | +| `0x100033f0` | `strlen` | `size_t strlen(const char*)` | +| `0x1000025c` | `gpio_set_function` | `void gpio_set_function(uint, gpio_function_t)` | +| `0x10000e20` | `uart_init` | `uint uart_init(uart_inst_t*, uint)` | +| `0x10000db0` | `time_us_64` | `uint64_t time_us_64(void)` | + +**Project 2 — resolve the `pico_double` formatting helpers `printf` reaches:** + +| Address | Rename to (`N`) | Signature (`Y`) | +| ------- | --------------- | --------------- | +| `0x1000138c` | `__wrap___aeabi_dadd` | `double __wrap___aeabi_dadd(double, double)` | +| `0x100013b4` | `__wrap___aeabi_dsub` | `double __wrap___aeabi_dsub(double, double)` | +| `0x100013dc` | `__wrap___aeabi_dmul` | `double __wrap___aeabi_dmul(double, double)` | +| `0x10001428` | `__wrap___aeabi_ddiv` | `double __wrap___aeabi_ddiv(double, double)` | +| `0x100014c4` | `__wrap___aeabi_i2d` | `double __wrap___aeabi_i2d(int)` | +| `0x100014e8` | `__wrap___aeabi_ui2d` | `double __wrap___aeabi_ui2d(unsigned)` | +| `0x1000150c` | `__wrap___aeabi_d2iz` | `int __wrap___aeabi_d2iz(double)` | +| `0x10001530` | `__wrap___aeabi_d2uiz` | `unsigned __wrap___aeabi_d2uiz(double)` | +| `0x10001554` | `__wrap___aeabi_dcmpun` | `int __wrap___aeabi_dcmpun(double, double)` | +| `0x10001578` | `__wrap___aeabi_dcmplt` | `int __wrap___aeabi_dcmplt(double, double)` | +| `0x100015a0` | `__wrap___aeabi_dcmple` | `int __wrap___aeabi_dcmple(double, double)` | +| `0x100015c8` | `__wrap___aeabi_dcmpge` | `int __wrap___aeabi_dcmpge(double, double)` | +| `0x100015f0` | `__wrap___aeabi_dcmpgt` | `int __wrap___aeabi_dcmpgt(double, double)` | +| `0x10001614` | `_out_rev` | `unsigned _out_rev(out_fct_type, char*, size_t, size_t, const char*, size_t, unsigned, unsigned)` | +| `0x100016b0` | `_ntoa_format` | `unsigned _ntoa_format(out_fct_type, char*, size_t, size_t, char*, size_t, bool, unsigned, unsigned, unsigned, unsigned)` | +| `0x10001884` | `_out_char` | `void _out_char(char, void*, size_t, size_t)` | +| `0x10001898` | `_ftoa` | `unsigned int _ftoa(out_fct_type, char*, size_t, size_t, double, unsigned int, unsigned int, unsigned int)` | +| `0x10001d58` | `_etoa` | `unsigned int _etoa(out_fct_type, char*, size_t, size_t, double, unsigned int, unsigned int, unsigned int)` | +| `0x100022cc` | `_vsnprintf` | `int _vsnprintf(out_fct_type, char*, size_t, const char*, va_list)` | +| `0x10000dc4` | `busy_wait_us` | `void busy_wait_us(uint64_t)` | +| `0x10000ff4` | `clock_get_hz` | `unsigned long clock_get_hz(clock_handle_t)` | + +Python console shortcut (resolves name **and** type): + +```python +from binaryninja import Symbol, SymbolType +# The raw .bin has no headers, so these SDK types don't exist. set_user_type() +# re-parses each signature as C, so an undefined name raises +# "SyntaxError: unknown type name '...'". Define them first. +sdk = bv.parse_types_from_string(""" +typedef unsigned int uint; +typedef char* va_list; +typedef unsigned long clock_handle_t; +typedef void (*out_fct_type)(char, void*, size_t, size_t); +struct stdio_driver; +typedef struct stdio_driver stdio_driver_t; +struct uart_inst; +typedef struct uart_inst uart_inst_t; +enum gpio_function { + GPIO_FUNC_XIP = 0, GPIO_FUNC_SPI = 1, GPIO_FUNC_UART = 2, GPIO_FUNC_I2C = 3, + GPIO_FUNC_PWM = 4, GPIO_FUNC_SIO = 5, GPIO_FUNC_PIO0 = 6, GPIO_FUNC_PIO1 = 7, + GPIO_FUNC_GPCK = 8, GPIO_FUNC_USB = 9, GPIO_FUNC_NULL = 0x1f, +}; +typedef enum gpio_function gpio_function_t; +""") +for name, ty in sdk.types.items(): + bv.define_user_type(name, ty) + +# address: (name, signature) +funcs = { + 0x1000015c: ("_reset_handler", "void _reset_handler(void)"), + 0x10000186: ("platform_entry", "void platform_entry(void)"), + 0x1000019a: ("data_cpy", "void data_cpy(void*, void*, void*)"), + 0x100001e4: ("_init", "void _init(void)"), + 0x10000210: ("frame_dummy", "void frame_dummy(void)"), + 0x10000238: ("main", "int main(void)"), + 0x10002cb0: ("vfctprintf", "int vfctprintf(void (*)(char, void*), void*, const char*, va_list)"), + 0x10002d0c: ("exit", "void exit(int)"), + 0x10002d14: ("runtime_init", "void runtime_init(void)"), + 0x10002d40: ("stdio_out_chars_crlf", "void stdio_out_chars_crlf(stdio_driver_t*, const char*, int)"), + 0x10002e50: ("stdio_put_string", "int stdio_put_string(const char*, int, bool, bool)"), + 0x10002f3c: ("stdio_set_driver_enabled", "void stdio_set_driver_enabled(stdio_driver_t*, bool)"), + 0x10002f64: ("stdio_init_all", "bool stdio_init_all(void)"), + 0x10003030: ("__wrap_vprintf", "int __wrap_vprintf(const char*, va_list)"), + 0x100030f4: ("__wrap_printf", "int __wrap_printf(const char*, ...)"), + 0x100032b0: ("stdio_uart_init", "void stdio_uart_init(void)"), + 0x100033f0: ("strlen", "size_t strlen(const char*)"), + 0x1000025c: ("gpio_set_function", "void gpio_set_function(uint, gpio_function_t)"), + 0x10000e20: ("uart_init", "uint uart_init(uart_inst_t*, uint)"), + 0x10000db0: ("time_us_64", "uint64_t time_us_64(void)"), + 0x1000138c: ("__wrap___aeabi_dadd", "double __wrap___aeabi_dadd(double, double)"), + 0x100013b4: ("__wrap___aeabi_dsub", "double __wrap___aeabi_dsub(double, double)"), + 0x100013dc: ("__wrap___aeabi_dmul", "double __wrap___aeabi_dmul(double, double)"), + 0x10001428: ("__wrap___aeabi_ddiv", "double __wrap___aeabi_ddiv(double, double)"), + 0x100014c4: ("__wrap___aeabi_i2d", "double __wrap___aeabi_i2d(int)"), + 0x100014e8: ("__wrap___aeabi_ui2d", "double __wrap___aeabi_ui2d(unsigned)"), + 0x1000150c: ("__wrap___aeabi_d2iz", "int __wrap___aeabi_d2iz(double)"), + 0x10001530: ("__wrap___aeabi_d2uiz", "unsigned __wrap___aeabi_d2uiz(double)"), + 0x10001554: ("__wrap___aeabi_dcmpun", "int __wrap___aeabi_dcmpun(double, double)"), + 0x10001578: ("__wrap___aeabi_dcmplt", "int __wrap___aeabi_dcmplt(double, double)"), + 0x100015a0: ("__wrap___aeabi_dcmple", "int __wrap___aeabi_dcmple(double, double)"), + 0x100015c8: ("__wrap___aeabi_dcmpge", "int __wrap___aeabi_dcmpge(double, double)"), + 0x100015f0: ("__wrap___aeabi_dcmpgt", "int __wrap___aeabi_dcmpgt(double, double)"), + 0x10001614: ("_out_rev", "unsigned _out_rev(out_fct_type, char*, size_t, size_t, const char*, size_t, unsigned, unsigned)"), + 0x100016b0: ("_ntoa_format", "unsigned _ntoa_format(out_fct_type, char*, size_t, size_t, char*, size_t, bool, unsigned, unsigned, unsigned, unsigned)"), + 0x10001884: ("_out_char", "void _out_char(char, void*, size_t, size_t)"), + 0x10001898: ("_ftoa", "unsigned int _ftoa(out_fct_type, char*, size_t, size_t, double, unsigned int, unsigned int, unsigned int)"), + 0x10001d58: ("_etoa", "unsigned int _etoa(out_fct_type, char*, size_t, size_t, double, unsigned int, unsigned int, unsigned int)"), + 0x100022cc: ("_vsnprintf", "int _vsnprintf(out_fct_type, char*, size_t, const char*, va_list)"), + 0x10000dc4: ("busy_wait_us", "void busy_wait_us(uint64_t)"), + 0x10000ff4: ("clock_get_hz", "unsigned long clock_get_hz(clock_handle_t)"), +} +for addr, (name, sig) in funcs.items(): + bv.define_user_symbol(Symbol(SymbolType.FunctionSymbol, addr, name)) + f = bv.get_function_at(addr) + if f is not None: + f.set_user_type(sig) +``` + +The decompiler now shows `main` loading the `double` pair and looping. We make two changes: + +- **Change the printed value from `42.52525` to `99.99`** by patching **both** literal words. +- **Rename the label** `fav_num:` to `myvalue:` by patching the format string. + +### Step 27: Patch 1 — the low word `0x645A1CAC` to `0x28F5C28F` + +`99.99` is `0x4058FF5C_28F5C28F`, so the low word changes from `0x645A1CAC` to `0x28F5C28F`. At `0x10000254` the stored bytes are `ac 1c 5a 64`; change them to `8f c2 f5 28`: + +| Project | Address | Before | After | Effect | +| ------- | ------- | ------ | ----- | ------ | +| `0x0011` | `0x10000254` | `ac 1c 5a 64` | `8f c2 f5 28` | low word of `42.52525` -> `99.99` | + +**Hex view:** lock off, go to `0x10000254`, change `ac 1c 5a 64` to `8f c2 f5 28`, reanalyze. **Or the Python console:** + +```python +bv.write(0x10000254, bytes.fromhex("8fc2f528")) +print(bv.read(0x10000254, 4)) # -> b'\x8f\xc2\xf5(' +``` + +### Step 28: Patch 2 — the high word `0x4045433B` to `0x4058FF5C` + +At `0x10000258` the stored bytes are `3b 43 45 40`; change them to `5c ff 58 40`: + +| Project | Address | Before | After | Effect | +| ------- | ------- | ------ | ----- | ------ | +| `0x0011` | `0x10000258` | `3b 43 45 40` | `5c ff 58 40` | high word of `42.52525` -> `99.99` | + +**Hex view:** go to `0x10000258`, change `3b 43 45 40` to `5c ff 58 40`, reanalyze. **Or the Python console:** + +```python +bv.write(0x10000258, bytes.fromhex("5cff5840")) +for addr in (0x10000254, 0x10000258): + print(hex(addr), bv.read(addr, 4).hex()) +# -> 0x10000254 8fc2f528 +# -> 0x10000258 5cff5840 +``` + +> **Both words are required.** `42.52525` has a repeating binary fraction, so its low word is non-zero (`0x645A1CAC`). Patching only the high word leaves the low 20 mantissa bits from `0.52525`, and `printf` prints a wrong hybrid. Compare Project 1, where `42.5` is exact and the low word was already `0x00000000`, so one word sufficed. + +### Step 28b: Patch the string `fav_num:` to `myvalue:` + +The format string starts at `0x100034b0`; change its first eight bytes `66 61 76 5f 6e 75 6d 3a` (`fav_num:`) to `6d 79 76 61 6c 75 65 3a` (`myvalue:`): + +| Project | Address | Before | After | Effect | +| ------- | ------- | ------ | ----- | ------ | +| `0x0011` | `0x100034b0` | `66 61 76 5f 6e 75 6d 3a` | `6d 79 76 61 6c 75 65 3a` | `fav_num:` -> `myvalue:` | + +```python +bv.write(0x100034b0, b"myvalue:") +print(bv.read(0x100034b0, 15)) # -> b'myvalue: %lf\r\n\x00' +``` + +Exactly eight bytes, same rule as Project 1: a shorter string must be padded, a longer one overwrites the ` %lf` tail. + +### Step 29: Export, convert, and flash + +```python +import os +seg = next(s for s in bv.segments if s.data_length) # the loadable image segment +data = bv.read(seg.start, seg.data_length) # base + size from the view itself +out = os.path.join(os.path.join(root, "0x0011_double-floating-point-data-type", "build"), "0x0011_double-floating-point-data-type-h.bin") +open(out, "wb").write(data) +print(len(data), out) # -> 15324 /.../build/0x0011_double-floating-point-data-type-h.bin +``` + +Same as Project 1: `seg.start` is the load base and `seg.data_length` is the image size (here `0x3bdc` = 15324) — both read from the view, and no relative path (the console's CWD is read-only). + +**macOS Apple Silicon / Linux x64:** + +```bash +python3 ../uf2conv.py 0x0011_double-floating-point-data-type-h.bin \ + --base 0x10000000 --family 0xe48bff59 --output hacked.uf2 +``` + +**Windows x64:** + +```cmd +python ..\uf2conv.py 0x0011_double-floating-point-data-type-h.bin ^ + --base 0x10000000 --family 0xe48bff59 --output hacked.uf2 +``` + +Or run the conversion from the IDA console, exactly as in Step 20 (`os.chdir` to the build dir, then `runpy.run_path("../../uf2conv.py", run_name="__main__")` with `sys.argv` set to the arguments above). + +Hold **BOOTSEL**, plug in the Pico 2, drag `hacked.uf2` onto the **`RP2350`** drive. Or flash the `.bin` over the Debug Probe with SWD — no BOOTSEL — from the console, exactly as in Step 21 (stop any running OpenOCD first, and use `Popen`, not `run`, so the console is not blocked): + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() +bin_path = os.path.join(os.path.join(root, "0x0011_double-floating-point-data-type", "build"), "0x0011_double-floating-point-data-type-h.bin") +log = os.path.join(os.path.join(root, "0x0011_double-floating-point-data-type", "build"), "flash.log") +subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # free the probe first +p = subprocess.Popen([os.path.join(root, "flash.sh"), bin_path], + stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) +print("flashing in the background; log:", log) +``` + +### Step 30: Verify + +Open the serial monitor: + +``` +myvalue: 99.990000 +myvalue: 99.990000 +myvalue: 99.990000 +... +``` + +**We changed the printed value and relabeled the line, with ten bytes and no source code.** `42.52525` became `99.99` because both halves of the double moved together. +--- + +## Cheatsheet + +### IDA GUI actions + +| Action | How | +| ------ | --- | +| Go to address | `G` | +| Rename function/symbol | `N` | +| Set type or signature | `Y` | +| Add comment | `;` | +| Open Hex view | `View -> Hex` | +| Enable hex editing | Toggle the lock in the status bar | +| Reanalyze after a patch | Right-click function -> `Reanalyze` | +| Edit a register live | `dbg.set_reg_value("r3", 0x4058C000)` in the Python console (or right-click the register, press `E`, type hex, Enter) | +| Write a RAM string live | `dbg.write_memory(0x20080000, b"myvalue: %f\r\n\x00")` | +| Set a breakpoint | `Debugger -> Add Hardware Breakpoint...` (hardware execute). Do **not** use `F2` — software breakpoints cannot be written to read-only flash. | +| Move a breakpoint | Remove it and set it at the new address in the GUI (command-port fallback: `rbp ` then `bp 2 hw`) | +| Confirm what is armed | The **Breakpoints** widget lists it (command-port fallback: `mdw 0xE0002000 8`, each armed breakpoint shows as ``) | +| Apply the ELF symbol map | Paste the Python snippet from Step 16 / 26 into the Python Console | + +### OpenOCD server and reset + +The server runs with `gdb_breakpoint_override hard` so that flash-writes are never attempted. Breakpoints in this lab are set in the IDA GUI through the **GDB MI** adapter (Step 13). The command-port rows below are the fallback if you use the **GDB RSP** adapter instead. + +| Action | Command | +| ------ | ------- | +| Connect to the OpenOCD prompt (fallback) | `nc 127.0.0.1 4444` (or `telnet 127.0.0.1 4444`) | +| Reset and run (command port) | `reset run` | +| Check core state (command port) | `targets` | +| Set a breakpoint in the GUI | `Debugger -> Add Hardware Breakpoint...` (hardware execute; `F2` software breakpoints do not work on flash) | +| (fallback) Add a breakpoint without the GUI | `bp 2 hw` | +| Remove one breakpoint | `rbp ` — **address only, no length, no `hw`** | +| Remove every breakpoint | `rbp all` | +| Start the server parked at `main` | macOS/Linux: `BP_ADDR=0x10000234 ./debug-server.sh` (Project 2: `0x10000238`) — Windows: `$env:BP_ADDR="0x10000234"; .\debug-server.ps1` (one-shot) | +| Start the server parked in the loop | macOS/Linux: `BP_ADDR=0x10000244 ./debug-server.sh` — Windows: `$env:BP_ADDR="0x10000244"; .\debug-server.ps1` (`0x1000024a` for Project 2) | +| Break on the loop in a running target | set a hardware breakpoint in the GUI at the loop address, then **Resume** — repeatable | +| Make IDA stepping work | `rp2350.dap.core0 configure -rtos none` (already in the scripts) | +| Step without re-trapping | move the breakpoint off the current PC first, then **Step Into**/**Step Over** | +| Reset without desyncing IDA | **Detach**, `reset run` on the port, reconnect — never `reset run` while attached | + +### Every address and byte we changed + +| Project | Address | Before | After | Effect | +| ------- | ------- | ------ | ----- | ------ | +| `0x000e` | `0x1000024c` | `00 40 45 40` | `00 c0 58 40` | high word of the double: `42.5` -> `99.0` | +| `0x0011` | `0x10000254` | `ac 1c 5a 64` | `8f c2 f5 28` | low word of the double: `42.52525` -> `99.99` | +| `0x0011` | `0x10000258` | `3b 43 45 40` | `5c ff 58 40` | high word of the double: `42.52525` -> `99.99` | +| `0x000e` | `0x100034a8` | `66 61 76 5f 6e 75 6d 3a` | `6d 79 76 61 6c 75 65 3a` | string prints `myvalue:` instead of `fav_num:` | +| `0x0011` | `0x100034b0` | `66 61 76 5f 6e 75 6d 3a` | `6d 79 76 61 6c 75 65 3a` | string prints `myvalue:` instead of `fav_num:` | + +### IEEE 754 Quick Reference for the Values in This Lesson + +| Value | Double Hex | High Word (`r3`) | Low Word (`r2`) | +| ----- | ---------- | ---------------- | --------------- | +| `42.5` | `0x4045400000000000` | `0x40454000` | `0x00000000` | +| `42.52525` | `0x4045433B645A1CAC` | `0x4045433B` | `0x645A1CAC` | +| `99.0` | `0x4058C00000000000` | `0x4058C000` | `0x00000000` | +| `99.99` | `0x4058FF5C28F5C28F` | `0x4058FF5C` | `0x28F5C28F` | + +### Raw image facts + +| Item | Value | +| ---- | ----- | +| Build type | `Release` | +| Load base address | `0x10000000` | +| Project 1 size | `15308` bytes (`0x3bcc`) | +| Project 2 size | `15324` bytes (`0x3bdc`) | +| Fixed `main` anchor (both projects) | `0x1000018c` (reset handler middle `blx`) | +| `main`, Project 1 | `0x10000234` | +| `main`, Project 2 | `0x10000238` | +| `printf` call / return, Project 1 | `0x10000244` / `0x10000248` | +| `printf` call / return, Project 2 | `0x1000024a` / `0x1000024e` | +| `double` argument registers | `r2` (low) : `r3` (high) | +| RP2350 UF2 family ID | `0xe48bff59` | + +--- + +## Troubleshooting + +### IDA hangs or crashes when you connect (macOS 27) + +Three different causes have been seen on this setup; check them in this order. + +- **A breakpoint set before connecting.** With the **GDB MI** adapter, if the binary view already has a breakpoint, the session hangs. Start parked with `BP_ADDR`, connect, then add breakpoints (see the next entry). +- **The wrong GDB executable.** Point **Full GDB Executable Path** at the **14.2.rel1** toolchain (Step 11). The 13.3.rel1 build did **not** connect in testing. +- **The LLDB adapter.** A crash report with `libdebuggercore.dylib -> std::terminate() -> abort()` and `liblldb` in the stack is the **LLDB** adapter, not GDB MI. Avoid LLDB on this setup. + +**Use GDB MI**, with the 14.2.rel1 path above. If it still fails, fall back to plain `arm-none-eabi-gdb` against the same server — the addresses and register values are identical to the GUI steps. + +If IDA hangs, force-quit it; the connect dialog has no working Cancel. The static steps (resolve, patch, export, flash) never touch the debugger and always work. + +### The GUI refuses to set a breakpoint (GDB RSP adapter only) + +If you are on the **GDB RSP** adapter, the GUI cannot set breakpoints on this target. That adapter is IDA's own minimal RSP client and sends a **1-byte** breakpoint (`Z0,,1`); the Cortex-M33 comparators need 2 bytes, so OpenOCD answers `only breakpoints of two bytes length supported`. It affects every address, both `Toggle Breakpoint` and `Add Hardware Breakpoint`, and the dialog's **Size** field is disabled. `gdb_breakpoint_override` makes no difference. + +**Fix: use the GDB MI adapter** (Step 11). It drives real GDB, which sends the correct length, so GUI breakpoints just work. If you must stay on GDB RSP, arm breakpoints from the command port after connecting (`bp 2 hw`) — but the lab uses GDB MI and does not need that. + +### GDB MI hangs when you connect (a breakpoint already existed) + +With the **GDB MI** adapter, if IDA already has a breakpoint set when you connect, the session **hangs**. This is a IDA bug. The working order is: + +1. Start the server parked, e.g. `BP_ADDR=0x10000234 ./debug-server.sh` (Windows: `$env:BP_ADDR="0x10000234"; .\debug-server.ps1`). +2. Connect with the **GDB MI** adapter. +3. Only *then* set hardware breakpoints in the UI. + +Never have a breakpoint in the binary view before the GDB MI connection. If it hangs, quit IDA, restart the server with `BP_ADDR`, and connect again before adding any breakpoints. + +### Step Into / Step Over does nothing (PC never moves) + +Two causes have been seen on this target. + +1. **A breakpoint on the current PC re-traps the step.** OpenOCD's step-over-breakpoint logic fails with `Duplicate Breakpoint address` and the PC stays put. Fix: move the breakpoint off the current PC (in the GUI), then step. +2. **The `hwthread` RTOS (GDB RSP adapter only).** With the **GDB RSP** adapter, OpenOCD can log `fake step thread 0` and reply without stepping, because the RP2350 config's `-rtos hwthread` makes the current thread id 1 while IDA sends thread id 0. Fix: `rp2350.dap.core0 configure -rtos none` (the launcher scripts already pass this). **GDB MI does not hit this.** + +To tell them apart, turn on OpenOCD logging (`log_output /tmp/ocd.log`, then `debug_level 3` on the command port) and look for `fake step` versus `Duplicate Breakpoint`. + +### `zsh: bad CPU type in executable: cmake` + +An Intel `x86_64` tool is on your `PATH` on Apple Silicon. Run Step 2: `export PATH="/opt/homebrew/bin:$PATH"`, then `hash -r`. Add it to `~/.zshrc` to make it permanent. + +### My addresses do not match this guide + +You probably built `Debug`. This lesson is a `Release` build. Re-run Step 3 with `-DCMAKE_BUILD_TYPE=Release`. A `Debug` build moves the SDK functions and lays the `pico_double` helpers out differently, so Project 2's `main` is not at `0x10000238`. + +### A breakpoint never fires + +First, confirm you actually set one, and that it is a **hardware** breakpoint. With the **GDB MI** adapter, `Debugger -> Add Hardware Breakpoint...` (hardware execute) should land in the **Breakpoints** widget. If nothing lands, or the core keeps running, you probably used `F2` (`Toggle Breakpoint`) — that is a software breakpoint and cannot be written to read-only flash, so it never installs. Also check you are on **GDB MI**, not **GDB RSP** (the GDB RSP adapter cannot set breakpoints on this target at all). + +Then check the order and the state: + +- **Arm it only after IDA is connected.** OpenOCD flushes every breakpoint when a client attaches, so anything armed earlier is gone. This also applies to `BP_ADDR` on the startup command line. +- **Verify it is armed:** `mdw 0xE0002000 8`. You should see your address with the low bit set (`0x10000234` -> `0x10000235`). All zeros means nothing is armed — re-read this first, because it distinguishes "not armed" from "armed but never reached". +- **Is the core running?** `poll` on the command port should not report a halt. If it is stopped, click **Resume**. +- **Does the address get reached again?** `main` runs once per reset, so use `BP_ADDR` at startup (Step 10) rather than `reset run` while attached. Loop addresses such as `0x10000244` fire on the next pass with no reset — arm them and click **Resume** in IDA. +- **With GDB MI the stop is reported as `Breakpoint`** and appears in the **Breakpoints** widget, because GDB really did set it. + +### I edit `r2`/`r3` (or another register) and it reverts + +Both `main`s reload the argument pair at the top of every loop iteration — `mov r2, r4` / `mov r3, r5` run right before the `printf` call. So your edit is only live for the instant between the write and the next pass; then the pair is reloaded from `r4`/`r5` (Project 1) or from the literal pool via `ldrd` (Project 2). The edit sticks only if the core is **genuinely stopped** at the breakpoint and stays stopped. + +If it keeps reverting, the core is running, which almost always means the breakpoint is not installed — usually because it is a **software** breakpoint (`F2`) that cannot be written to read-only flash. Use `Debugger -> Add Hardware Breakpoint...` (hardware execute). + +> **The Registers widget is a snapshot, not a live view.** IDA reads the registers at each stop and shows that snapshot; it does not poll the target, and there is no "refresh registers" command. So a value changed outside IDA will not appear until the next stop. + +### The serial capture is garbage on macOS + +Reading `/dev/cu.usbmodem*` with a bare `read()` returns garbage. Set **raw termios at 115200** first: clear canonical/echo flags, set `CLOCAL|CREAD`, and `B115200` on input and output. `screen /dev/cu.usbmodem* 115200` does all of this for you; a script must call `tcsetattr` itself. Once set, the capture reads clean `fav_num: 42.500000` lines. + +### It worked for a second, then stopped (IDA's view desyncs) + +This is the most common failure, and it has one main cause: **driving the core from the OpenOCD command port while IDA is connected.** + +- If you send `reset run` from the port while attached, the core resets, runs, and halts at your breakpoint — but IDA never receives the stop event. Its sidebar keeps showing the *previous* location, so **Step** and **Resume** act on a stale PC and appear to do nothing. +- If the OpenOCD process dies (or you restart it) while attached, IDA keeps believing it is connected: the sidebar stays, but the menu shows **Pause** enabled and **Resume**/**Step** disabled because IDA last saw the target *running*. + +Recovery: **Detach, then reconnect.** If Detach does nothing (the connection is already dead), restart IDA — its menu still shows a session that no longer exists. + +Prevention: +- Stop at `main` with `BP_ADDR` on a fresh server start, not with `reset run` while attached. +- For loop addresses, set the breakpoint in the GUI and click **Resume**. Let IDA be the thing that starts the core. +- If you must reset, **Detach first**, `reset run`, then reconnect. +- Never leave a breakpoint on the PC you are about to step or resume from. + +### The target "blows past" `main` and stops at `0x10003214` instead + +`0x10003214` is inside `stdio_uart_out_flush`: + +```asm +10003210: 4b02 ldr r3, [pc, #8] ; @ 0x1000321c +10003212: 681a ldr r2, [r3] +10003214: 6993 ldr r3, [r2, #24] ; the core sits here while the UART drains +10003216: 071b lsls r3, r3, #28 +10003218: d4fc bmi.n 0x10003214 +1000321a: 4770 bx lr +1000321c: 20000850 .word 0x20000850 +``` + +That is the UART transmit-FIFO drain loop inside `printf`, so the core is running `main`'s loop and simply spends nearly all its time there. The breakpoint at `main` did not fire because `main`'s entry runs exactly **once per reset**. If you arm the breakpoint after the reset, or set it while the target is already running and just resume, the core is already past `main` and will never re-execute it. Either arm the breakpoint **before** resetting, or break inside the loop at the `printf` call, which fires every iteration. + +**`0x10003214` is not a function.** It is one instruction inside `stdio_uart_out_flush`, which starts at `0x10003210`. If IDA has created a function at `0x10003214` (for example because the debugger stopped at that PC), the decompiler shows garbage. Delete that bogus function (right-click it -> `Delete Function`, or put the cursor on it and press `U` to undefine) and reanalyze. The real function is `stdio_uart_out_flush` at `0x10003210`. (In Project 2 the same drain loop is at `0x1000321c`.) + +### The console floods with `Failed to read memory at 0xf0000000` + +Core1 is exposed. The scripts must run with `USE_CORE=0`. Stop the server, confirm only `core0` is reported, restart, then restart IDA. + +### `Connect to Remote Process` is greyed out and Pause does nothing + +IDA is in a stale session, usually because the debug server restarted while attached. Quit and reopen IDA (or the `.i64`) and connect again. + +### The decompiler still shows the old value after patching + +Right-click the function and choose `Reanalyze`. + +### Project 2 prints a wrong, hybrid number after patching + +You patched only one of the two literal words. `42.52525` has a non-zero low word, so `0x10000254` **and** `0x10000258` must both change. Project 1's `42.5` is the opposite case: its low word is `0x00000000`, so only `0x1000024c` changes. + +### The double does not print as `99.99` after patching + +Confirm you wrote the bytes little-endian. `0x28F5C28F` is stored `8f c2 f5 28`, and `0x4058FF5C` is stored `5c ff 58 40`. If you typed the words in big-endian order the value is nonsense. The Python form `bytes.fromhex("8fc2f528")` is already in file order. + +--- + +## Fallback: do the dynamic steps with GDB (macOS 27) + +If IDA's debugger crashes on attach on macOS 27 (see Troubleshooting), you can still do the live hack with the ARM GDB from the toolchain, against the same OpenOCD server. The addresses and register values are identical to the GUI steps. + +Start the debug server (Step 10), then in a new terminal: + +``` +arm-none-eabi-gdb +``` + +At the `(gdb)` prompt: + +``` +set architecture armv8-m.main +target extended-remote :3333 +hbreak *0x10000244 +continue +``` + +Do **not** run `monitor reset run` before `hbreak`. `0x10000244` is inside `main`'s loop, so the breakpoint fires on the next iteration with no reset. If you reset first, the core runs `main` and you will not catch it. + +GDB stops at the `printf` call. Confirm the pair, change it, and let it run: + +``` +info registers pc r2 r3 # pc = 0x10000244, r2 = 0x00000000, r3 = 0x40454000 +set $r3 = 0x4058C000 +stepi +continue +``` + +The serial monitor prints `fav_num: 99.000000` for the iteration you changed — the same temporary live hack as editing `r3` in the IDA Registers widget. When you are done, press `Ctrl-C`, then `detach` and `quit`. + +**If you specifically want to stop at `main` (`0x10000234`),** remember its entry runs only once per reset, so the breakpoint must be armed *before* the reset: + +``` +monitor reset halt +hbreak *0x10000234 +continue +``` + +If you instead set it while the target is running and just `continue`, you will "blow past" `main` and catch the core inside `printf` — in this build at `0x10003214`, the `stdio_uart_out_flush` UART-drain loop. + +Project 2 is the same with the other call site and pair: + +``` +hbreak *0x1000024a +continue +info registers pc r2 r3 # pc = 0x1000024a, r2 = 0x645A1CAC, r3 = 0x4045433B +set $r2 = 0x28F5C28F +set $r3 = 0x4058FF5C +stepi +``` + +`hbreak` sets a hardware breakpoint, which is required for read-only flash. It works from plain GDB because GDB sends the 2-byte length the Cortex-M33 comparators need. IDA's **GDB MI** adapter goes through the same GDB, so its GUI breakpoints work too; the old **GDB RSP** adapter was the one that sent a 1-byte length and could not set breakpoints here. + +## Glossary + +| Term | Definition | +| ---- | ---------- | +| **`.bss`** | Section for uninitialized global variables; zeroed by startup code | +| **`.data`** | Section for initialized global variables; copied from flash to SRAM at boot | +| **`.elf`** | Linked image with the symbol table; the ground truth for addresses and names | +| **`.rodata`** | Read-only section for constants and string literals; stays in flash | +| **Bias** | Constant added to an IEEE 754 exponent (`127` for float, `1023` for double) | +| **Double** | 64-bit IEEE 754 floating-point type (1 sign, 11 exponent, 52 mantissa) | +| **Float** | 32-bit IEEE 754 floating-point type (1 sign, 8 exponent, 23 mantissa) | +| **GPIO** | General Purpose Input/Output — controllable pins on the microcontroller | +| **Hardware breakpoint** | A breakpoint serviced by the CPU comparators, required for read-only flash | +| **IEEE 754** | The standard that defines binary floating-point encoding | +| **Inlining** | The optimizer replacing a function call with the function body | +| **Literal pool** | A block of 32-bit constants that Thumb-2 code reaches with PC-relative `ldr`/`ldrd` | +| **Mantissa** | The fractional significand bits (23 for float, 52 for double) | +| **MMIO** | Memory-mapped I/O — hardware registers accessed as memory addresses | +| **Promotion** | C's automatic `float` -> `double` conversion for variadic arguments | +| **Register pair** | Two 32-bit registers (`r2:r3`) that together hold a 64-bit value | +| **SIO** | Single-cycle I/O — the fast GPIO block in the RP2350, at `0xd0000000` | +| **Thumb bit** | Bit 0 of a Cortex-M function pointer; selects Thumb instruction mode | +| **UF2** | USB Flashing Format — the file format the Pico 2 bootloader accepts | +| **Vector table** | The first words of flash: initial stack pointer and exception vectors | + +--- + +**Remember:** the ELF tells you what every address is, and the `.bin` is what you actually patch. Prove the behavior dynamically by reading `r2:r3`, resolve the names from the ELF, then patch the constant bytes — one word for a clean fraction like `42.5`, two words for a repeating one like `42.52525` — and flash. diff --git a/WEEK05/WEEK05-IDA.pdf b/WEEK05/WEEK05-IDA.pdf new file mode 100644 index 0000000..3baf0b8 Binary files /dev/null and b/WEEK05/WEEK05-IDA.pdf differ diff --git a/WEEK06/WEEK06-IDA.md b/WEEK06/WEEK06-IDA.md new file mode 100644 index 0000000..b6b207b --- /dev/null +++ b/WEEK06/WEEK06-IDA.md @@ -0,0 +1,1395 @@ +# Week 6-IDA: IDA Pro — Read, Hack, and Patch a Static Variable and a GPIO Input (Raw `.bin`) + +*** + +**LEGAL DISCLAIMER:** +The information, tools, and code provided in this repository and course are strictly for educational, research, and defensive purposes only. + +You are explicitly prohibited from using any materials contained herein to access, test, modify, or exploit any device, network, or system that you do not own 100% or for which you do not have explicit, documented, and legally binding authorization to interact with. + +By using this repository and course, you acknowledge and agree that: + +1. Any illegal, unauthorized, or malicious use of this information is solely your responsibility. +2. The author(s) and contributor(s) of this repository and course shall not be held liable for any damages, legal repercussions, criminal charges, or unauthorized actions resulting from the use, misuse, or abuse of the contents herein. +3. You will comply with all applicable local, state, national, and international laws regarding cybersecurity and computer fraud. + +**IF YOU DO NOT AGREE WITH THESE TERMS, DO NOT USE THIS REPOSITORY AND COURSE.** + +*** + +## What You'll Learn This Week + +- Build the lesson project with `Release` and get both an `.elf` and a raw `.bin` +- Dump the **ELF symbol map** with `arm-none-eabi-nm` and use it as ground truth +- Load the raw `.bin` into IDA at `0x10000000` +- Read how a **static local** keeps a fixed RAM address while a **regular local** is inlined to a constant +- **Break at `main`** on live silicon, even though `main` moves between programs +- **Hack a running target live** by editing a register in IDA's Registers widget +- **Resolve the functions in the IDA GUI** using the ELF symbol map +- **Patch** the value byte, invert the button/LED logic, and (optionally) rename the printed label +- **Export** the patched image, convert it to UF2, and flash it + +--- + +## How This Guide Works + +The build produces two files for the project: + +| File | What it is | How we use it | +| ---- | ---------- | ------------- | +| `.elf` | The linked image with a full symbol table | Ground truth for every function address and name | +| `.bin` | The raw flash image, no headers, no symbols | The image we load into IDA and reverse | + +The `.bin` is built **from** the `.elf`, so the ELF tells you exactly what is at every address. We use the ELF symbol map to resolve functions in IDA, and we reverse-engineer the raw `.bin` the way a real extracted firmware image is reversed. + +> **Build `Release`, not `Debug`.** Every address in this guide matches the Week 6 lesson, and the Week 6 lesson is a `Release` build. `Release` optimizes the code the same way the original lesson was built: it **inlines** the `static` helper `demo_static_variable` (and the SDK's `gpio_set_dir` / `gpio_get` / `gpio_put` / `gpio_pull_up` helpers) into `main`, and it folds the regular local `regular_fav_num` down to a bare `movs r1, #42` constant. If you build `Debug`, the SDK function addresses move and the helper stays a separate call, so nothing lines up. Always build `Release` for this lesson. + +The order is **dynamic first, static second**: + +1. Break on the live target and prove what the code does. +2. Hack it live in the debugger and watch the output change. +3. Resolve the functions in IDA using the ELF symbol map. +4. Patch the bytes, export, convert, and flash. + +| Project | Prints | Also does | The hacks | +| ------- | ------ | --------- | --------- | +| `0x0014_static-variables` | `regular_fav_num: 42`, then `static_fav_num:` incrementing | reads button GPIO 15, drives LED GPIO 16 | change `42` to `43`, invert the button/LED logic, (optional) rename the label | + +> **Addresses come from your build.** Every address here is from the `Release` build produced in Step 3. Confirm against your own `.elf` with the command in Step 4. + +> **`static_fav_num` is the star of this week.** `regular_fav_num` is an automatic (stack) variable that the compiler bakes into a constant; `static_fav_num` is a function-local `static` that the linker parks at a **fixed RAM address** (`0x200005a8`) in `.data`. That fixed address is why it persists across loop iterations, and why you can read and patch it like a global. + +--- + +## Part 1: Build, Flash, and Get the Symbol Map + +### Step 1: Install the toolchain + +**Windows x64** + +- Install the **Raspberry Pi Pico** extension in VS Code. It installs the ARM GNU toolchain, CMake, Ninja, and the Pico SDK. +- Install **IDA Pro** and complete its license activation. +- Install **PuTTY** for the serial monitor. + +**macOS Apple Silicon** + +```bash +brew install cmake ninja +``` + +- Install **IDA Pro** and complete its license activation. +- Install the **Arm GNU Toolchain**, or let the VS Code Pico extension manage it. + +**Linux x64** + +```bash +sudo apt install cmake ninja-build gcc-arm-none-eabi libnewlib-arm-none-eabi git python3 openocd minicom +``` + +- Install **IDA Pro** and complete its license activation. + +### Step 2: Verify your tools are the right architecture (do not skip this) + +On **macOS Apple Silicon**, the most common failure is an Intel `x86_64` tool on your `PATH`: + +``` +zsh: bad CPU type in executable: cmake +``` + +You may have **two Homebrews**: the arm64 one at `/opt/homebrew` and the Intel one at `/usr/local`. If `/usr/local/bin` wins, every `brew` tool is x86_64. Check: + +```bash +file "$(which cmake)" +file "$(which ninja)" +file "$(which arm-none-eabi-gdb)" +file "$(which arm-none-eabi-nm)" +file "$(which openocd)" +file "$(which telnet)" +``` + +All must report `arm64`. If any is `x86_64`, put the Apple Silicon prefix first for the session and check again: + +```bash +export PATH="/opt/homebrew/bin:$PATH" +hash -r +file "$(which cmake)" +``` + +To make it permanent, add that `export` to `~/.zshrc`. Do not use Rosetta as a fix; OpenOCD and GDB are exactly the kind of programs where a translation layer produces failures that look like debugger bugs. + +**`telnet` is special — and optional.** The GDB MI workflow does not need it; it is only used by the command-port fallback. macOS no longer ships `telnet`, and the Homebrew build is often the Intel one, so `telnet 127.0.0.1 4444` fails with `bad CPU type in executable`. Your `brew` command itself may also be the Intel one: if `brew install telnet` fails with `.../portable-ruby/.../ruby: Bad CPU type in executable`, you are running the Intel Homebrew. Call the Apple Silicon Homebrew explicitly: + +```bash +/opt/homebrew/bin/brew install telnet +``` + +If you would rather not install anything, macOS ships an arm64 `nc`, which can connect to the same OpenOCD port: + +```bash +nc 127.0.0.1 4444 +``` + +**Windows x64** and **Linux x64** do not have this problem. Skip to Step 3. + +### Step 3: Build the project with `Release` + +Run this inside `0x0014_static-variables/`: + +```bash +cmake -B build -G Ninja -DPICO_BOARD=pico2 -DPICO_PLATFORM=rp2350 -DCMAKE_BUILD_TYPE=Release +cmake --build build +``` + +**Point IDA at this repository (once).** Every console snippet below reads the repo root from `~/.embedded-hacking-repo`, so IDA never needs a database open and nothing is hardcoded. From the repo root, run once: + +**macOS / Linux:** + +```bash +pwd > ~/.embedded-hacking-repo +``` + +**Windows (PowerShell):** + +```powershell +(Get-Location).Path | Set-Content "$env:USERPROFILE\.embedded-hacking-repo" +``` + +**Then build from the IDA console**, so the whole build -> patch -> flash loop stays inside IDA. The console inherits a minimal `PATH` — on macOS just `/usr/bin:/bin:/usr/sbin:/sbin` — so it does not see Homebrew; add your package manager's `bin` first, then run plain `cmake`. + +**macOS Apple Silicon:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() +os.environ["PATH"] = "/opt/homebrew/bin:" + os.environ["PATH"] # the console's PATH omits Homebrew +proj = os.path.join(root, "0x0014_static-variables") +subprocess.run(["cmake", "-B", "build", "-G", "Ninja", "-DPICO_BOARD=pico2", + "-DPICO_PLATFORM=rp2350", "-DCMAKE_BUILD_TYPE=Release"], cwd=proj) +subprocess.run(["cmake", "--build", "build"], cwd=proj) +``` + +**Linux x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() +proj = os.path.join(root, "0x0014_static-variables") +subprocess.run(["cmake", "-B", "build", "-G", "Ninja", "-DPICO_BOARD=pico2", + "-DPICO_PLATFORM=rp2350", "-DCMAKE_BUILD_TYPE=Release"], cwd=proj) +subprocess.run(["cmake", "--build", "build"], cwd=proj) +``` + +**Windows x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() +proj = os.path.join(root, "0x0014_static-variables") +subprocess.run(["cmake", "-B", "build", "-G", "Ninja", "-DPICO_BOARD=pico2", + "-DPICO_PLATFORM=rp2350", "-DCMAKE_BUILD_TYPE=Release"], cwd=proj) +subprocess.run(["cmake", "--build", "build"], cwd=proj) +``` + +The build directory now contains the pair we need: + +- `0x0014_static-variables/build/0x0014_static-variables.elf` and `.bin` — the `.bin` is **15516** bytes (`0x3c9c`) + +If the ARM toolchain is not on your `PATH`, add `-DPICO_TOOLCHAIN_PATH=...`: + +| OS | Typical toolchain path | +| -- | ---------------------- | +| Windows x64 | `C:/Program Files/Arm GNU Toolchain arm-none-eabi/14.2 rel1/bin` | +| macOS Apple Silicon | `~/.pico-sdk/toolchain/14_2_Rel1/bin` | +| Linux x64 | `/usr` | + +> **This guide's toolchain lives at `~/.pico-sdk/toolchain/14_2_Rel1/bin`.** All of `arm-none-eabi-nm`, `arm-none-eabi-objdump`, and `arm-none-eabi-gdb` resolved in this document come from there. If your install is elsewhere, `which arm-none-eabi-nm` tells you where to point. + +### Step 4: Dump the ELF symbol map + +This is the ground truth for the whole lesson. Run `arm-none-eabi-nm` on the ELF and keep the output in a terminal or a text file: + +**macOS Apple Silicon / Linux x64:** + +```bash +arm-none-eabi-nm -n --defined-only build/0x0014_static-variables.elf | grep -E ' [Tt] ' +``` + +**Windows x64:** + +```powershell +arm-none-eabi-nm -n --defined-only build\0x0014_static-variables.elf | Select-String ' [Tt] ' +``` + +Each line is `address type name`. The `T`/`t` type is a function. Here are the functions this lesson uses. The signatures come from the ELF's DWARF debug info queried with `arm-none-eabi-gdb -batch -ex "ptype "`, so they are exact. + +**Our code and the startup chain:** + +| Address | ELF symbol | Signature | Role | +| ------- | ---------- | --------- | ---- | +| `0x1000015c` | `_reset_handler` | `void _reset_handler(void)` | reset entry | +| `0x10000186` | `platform_entry` | `void platform_entry(void)` | calls `runtime_init`, `main`, `exit` | +| `0x1000019a` | `data_cpy` | `void data_cpy(void*, void*, void*)` | copies `.data` from flash to SRAM | +| `0x100001e4` | `_init` | `void _init(void)` | runs `.init_array` | +| `0x10000210` | `frame_dummy` | `void frame_dummy(void)` | C runtime boilerplate | +| `0x10000234` | `main` | `int main(void)` | the lesson function (`demo_static_variable` inlined) | + +**The GPIO functions `main` calls (or that are inlined into it):** + +| Address | ELF symbol | Signature | Role | +| ------- | ---------- | --------- | ---- | +| `0x1000029c` | `gpio_set_function` | `void gpio_set_function(uint, gpio_function_t)` | SDK GPIO function select (UART pins) | +| `0x100002d8` | `gpio_set_pulls` | `void gpio_set_pulls(uint, bool, bool)` | SDK pull config (`gpio_pull_up` inlined) | +| `0x10000300` | `gpio_init` | `void gpio_init(uint)` | SDK GPIO init | + +**The stdio/UART and printf chain `main` reaches:** + +| Address | ELF symbol | Signature | Role | +| ------- | ---------- | --------- | ---- | +| `0x10000e60` | `time_us_64` | `uint64_t time_us_64(void)` | SDK microsecond clock | +| `0x10000ed0` | `uart_init` | `uint uart_init(uart_inst_t*, uint)` | SDK UART init | +| `0x10002dbc` | `exit` | `void exit(int)` | C runtime exit | +| `0x10002dc4` | `runtime_init` | `void runtime_init(void)` | SDK runtime init | +| `0x10002df0` | `stdio_out_chars_crlf` | `void stdio_out_chars_crlf(stdio_driver_t*, const char*, int)` | CRLF output driver | +| `0x10002f00` | `stdio_put_string` | `int stdio_put_string(const char*, int, bool, bool)` | buffered string output | +| `0x10002fec` | `stdio_set_driver_enabled` | `void stdio_set_driver_enabled(stdio_driver_t*, bool)` | enable the UART driver | +| `0x10003014` | `stdio_init_all` | `bool stdio_init_all(void)` | SDK serial init | +| `0x100030e0` | `__wrap_vprintf` | `int __wrap_vprintf(const char*, va_list)` | printf core | +| `0x100031a4` | `__wrap_printf` | `int __wrap_printf(const char*, ...)` | the `printf` wrapper | +| `0x10003360` | `stdio_uart_init` | `void stdio_uart_init(void)` | SDK UART stdio init | +| `0x100034a0` | `strlen` | `size_t strlen(const char*)` | C runtime string length | + +**SDK helpers the `printf` and `uart_init` paths reach:** + +| Address | ELF symbol | Signature | Role | +| ------- | ---------- | --------- | ---- | +| `0x10002d60` | `vfctprintf` | `int vfctprintf(void (*)(char, void*), void*, const char*, va_list)` | printf format engine | +| `0x1000237c` | `_vsnprintf` | `int _vsnprintf(out_fct_type, char*, size_t, const char*, va_list)` | the format dispatcher | +| `0x10001760` | `_ntoa_format` | `unsigned _ntoa_format(out_fct_type, char*, size_t, size_t, char*, size_t, bool, unsigned, unsigned, unsigned, unsigned)` | number formatter | +| `0x100016c4` | `_out_rev` | `unsigned _out_rev(out_fct_type, char*, size_t, size_t, const char*, size_t, unsigned, unsigned)` | reversed-digit output | +| `0x10001934` | `_out_char` | `void _out_char(char, void*, size_t, size_t)` | single-char sink | +| `0x10000e74` | `busy_wait_us` | `void busy_wait_us(uint64_t)` | UART timing loop | +| `0x100010a4` | `clock_get_hz` | `unsigned long clock_get_hz(clock_handle_t)` | UART clock lookup | + +Two things in this project have **no symbol of their own**, because the compiler inlined them into `main`: + +- `demo_static_variable` — the `static` helper in our own source is inlined, so there is no `demo_static_variable` address to rename. You see its body directly inside `main`. +- `init_gpio`, `gpio_set_dir`, `gpio_get`, `gpio_put`, and `gpio_pull_up` — these are `static inline` in the SDK headers, so they compile to the `mcrr`/SIO writes and the `ldr`/`ubfx` reads you see in `main` rather than to calls. `gpio_pull_up(15)` becomes the direct call to `gpio_set_pulls` at `0x1000024e`. + +> **`static_fav_num` is a `t` symbol, not a function.** `arm-none-eabi-nm -n` lists `200005a8 t static_fav_num.0`. That lowercase `t` is a **local data** symbol: the linker named the function-local static `static_fav_num.0` and parked it at RAM address `0x200005a8`. There is no pool entry for `regular_fav_num` because it is an automatic (stack) variable — and here the compiler never gave it a stack slot at all, folding it into a constant. + +### Step 5: Flash and confirm the output + +A `.bin` has no headers, so OpenOCD must be told the base address `0x10000000`. From the repository root: + +**macOS Apple Silicon / Linux x64:** + +```bash +./flash.sh 0x0014_static-variables/build/0x0014_static-variables.bin +``` + +**Windows x64 (PowerShell):** + +```powershell +.\flash.ps1 -Bin 0x0014_static-variables\build\0x0014_static-variables.bin +``` + +**Or flash from the IDA console** (the console reads the repo root from the marker file, so it works with no database open): + +**macOS Apple Silicon / Linux x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) +bin_path = os.path.join(root, "0x0014_static-variables", "build", "0x0014_static-variables.bin") +log = os.path.join(os.path.dirname(bin_path), "flash.log") +subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # free the probe first +subprocess.Popen([os.path.join(root, "flash.sh"), bin_path], + stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) +print("flashing in the background; log:", log) +``` + +**Windows x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) +bin_path = os.path.join(root, "0x0014_static-variables", "build", "0x0014_static-variables.bin") +log = os.path.join(os.path.dirname(bin_path), "flash.log") +subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"]) # free the probe first +subprocess.Popen(["powershell", "-ExecutionPolicy", "Bypass", "-File", + os.path.join(root, "flash.ps1"), "-Bin", bin_path], + stdout=open(log, "w"), stderr=subprocess.STDOUT) +print("flashing in the background; log:", log) +``` + +Wait for `wrote 15516 bytes ...` and `** Verified OK **`. Open a serial monitor at **115200** baud: + +- **Windows x64:** PuTTY -> Connection type **Serial**, the Pico's COM port, speed `115200`. +- **macOS Apple Silicon:** `screen /dev/tty.usbmodem* 115200` (quit with `Ctrl-A` then `K`). +- **Linux x64:** `minicom -D /dev/ttyACM0 -b 115200`. + +``` +regular_fav_num: 42 +static_fav_num: 42 +regular_fav_num: 42 +static_fav_num: 43 +regular_fav_num: 42 +static_fav_num: 44 +... +``` + +`regular_fav_num` stays at `42` every pass (it is recreated as `42` each loop), while `static_fav_num` keeps climbing (it persists at `0x200005a8`). Wire a push button from GPIO 15 to GND and an LED from GPIO 16 (through a resistor) to GND. With the stock image, the LED is **off** when the button is released and **on** when you press it — the pull-up holds GPIO 15 high when released, and the code inverts that with `eor.w r3, r3, #1`. We will flip that behavior in Step 18b. + +--- + +## Part 2: Load the Raw `.bin` into IDA + +Start from a fresh IDA state. If you already have a database for this lesson, **close it and start over**; a stale database keeps old names and patches. + +### Step 7: Bring the raw `.bin` into IDA + +A raw `.bin` has no headers, so IDA cannot know where it belongs or what architecture it is. You must supply both. If you just double-click the `.bin`, IDA may load it with a guessed architecture, and every address in this lesson will be wrong. + +#### 1.1 Open the file +1. **File ▸ Open…** (Ctrl/Cmd+O). +2. Select the `.bin` file and click **Open**. + +IDA opens the **"Load a new file"** dialog because a raw `.bin` has no header. + +#### 1.2 Set the format and processor +In the *Load a new file* dialog: +1. **Format**: leave it as **Binary file** (IDA auto-detects a headerless image). +2. **Processor type**: click the **…** button next to the processor field. In the *Processor type* dialog: + - Family: **ARM** + - Type: **ARM Little-endian** (the 32-bit ARM module). + - Click **OK**. + +> If IDA asks **"Do you want to disassemble it as 64-bit code?"** — click **No**. +> The RP2350 is 32-bit; answering *Yes* loads AArch64 and you get `X` registers / data. (This is the single most common cause of the `DCB` wall.) + +#### 1.3 Configure the ARM architecture and Thumb mode +Still in the *Load a new file* dialog, open the processor options (the **Processor options** / **Set…** button, which opens the dialog titled **ARM architecture options**): +- **ARM architecture**: choose **ARMv8-M** (this is the Cortex-M33 / RP2350 core). +- **Thumb instructions**: select **Thumb-2** (ARMv8-M is Thumb-only, so this is the correct mode). +- Leave **automatic ARM-THUMB switch** off; we want Thumb throughout. + +#### 1.4 Set the loading address +- **Loading address**: enter **`10000000`** (hex; the RP2350 XIP flash base). + IDA rejects addresses that don't look like ROM/RAM with *"The loading address should belong to RAM or ROM"* — `0x10000000` is the correct flash window. + +Leave **Manual load** and **Create segments** at their defaults. Click **OK**. + +#### 1.5 Force Thumb, then seed the code from the vector table +A raw `.bin` has no header, so IDA's loader has **no entry point** and defaults the segment to **ARM mode** (which cannot decode Thumb). Two required steps — in this order: + +**A. Set the segment to Thumb (do this first).** +- **Edit ▸ Segments ▸ Set default segment register value…** → register **`T`** = **`1`** (or press **`Alt+G`**). IDA reanalyzes the segment as Thumb automatically. + +**B. Seed the code from the vector table.** +1. **G** → `10000000`. The first two words are the initial stack pointer and the **reset vector**. +2. **Read the 4-byte word at `0x10000004`** (do **not** assume its value — it differs per build). +3. **Clear bit 0** (the ARM **Thumb** flag) → the reset handler address. +4. **G** to that address → press **C** (**MakeCode**). IDA disassembles the reset handler and follows its `bl`s into `main`. + +Once `main` shows code, the import is correct. + +**Why IDA needs this and others don't:** IDA's generic raw-binary ARM loader treats the image as flat data and waits for you to set Thumb and mark the entry point. It's an IDA quirk, not a mistake on your part. + +### Step 8: The views you will use + +- **Linear view:** the disassembly listing. You navigate, read, and patch here. +- **Graph view:** the control-flow graph of the current function. +- **Decompiler (HLIL):** the pseudo-C decompilation. +- **Hex view:** raw bytes, used for patching. +- **Function list:** the sidebar list of every detected function. + +Navigation: `G` go to address, `N` rename, `Y` set type or signature, `;` add a comment. Breakpoints are set from the GUI through the GDB MI adapter — see Step 12. + +> **macOS function keys:** the top-row `F` keys are usually mapped to system functions. Every step here uses menu paths that work without them. + +--- + +## Part 3: Dynamic — Break at `main` and Hack Live + +### Step 9: Start OpenOCD as a live debug server + +Make sure no other OpenOCD is running; a forgotten server holds port `3333`. + +**macOS / Linux:** + +```bash +ps aux | grep -i openocd +``` + +**Windows (PowerShell):** + +```powershell +Get-Process | Where-Object { $_.ProcessName -like '*openocd*' } +``` + +Stop any leftover server gracefully: + +**macOS / Linux:** + +```bash +pkill -TERM -f openocd +``` + +**Windows (PowerShell):** + +```powershell +Get-Process openocd -ErrorAction SilentlyContinue | Stop-Process +``` + +Start the server **parked at `main`**: + +**macOS Apple Silicon / Linux x64:** + +```bash +BP_ADDR=0x10000234 ./debug-server.sh +``` + +**Windows x64 (PowerShell):** + +```powershell +$env:BP_ADDR="0x10000234"; .\debug-server.ps1 +``` + +**Or start it from the IDA console**, freeing the probe first and launching the server in the background so the console returns immediately: + +**macOS Apple Silicon / Linux x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) +subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # stop any running server first +log = os.path.join(root, "openocd.log") +p = subprocess.Popen([os.path.join(root, "debug-server.sh")], cwd=root, + env=dict(os.environ, BP_ADDR="0x10000234"), + stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) +print("OpenOCD started (pid", p.pid, "); log:", log) +``` + +**Windows x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) +subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"]) # stop any running server first +log = os.path.join(root, "openocd.log") +p = subprocess.Popen(["powershell", "-ExecutionPolicy", "Bypass", "-File", + os.path.join(root, "debug-server.ps1")], cwd=root, + env=dict(os.environ, BP_ADDR="0x10000234"), + stdout=open(log, "w"), stderr=subprocess.STDOUT) +print("OpenOCD started (pid", p.pid, "); log:", log) +``` + +`Popen` returns in a few milliseconds; the server keeps running in the background. Check `openocd.log` for `Listening on port 3333`, then connect in Step 10. + +Wait for: + +``` +Info : [rp2350.dap.core0] Examination succeed +Startup breakpoint at 0x10000234 (2-byte hardware execute, one-shot). +Info : starting gdb server for rp2350.dap.core0 on 3333 +Info : Listening on port 3333 for gdb connections +``` + +> **`BP_ADDR` parks the core at `main` before any client connects.** The script arms a 2-byte hardware breakpoint and then does the startup `reset run`, so the core runs from the vector table and stops at your address with no debugger attached yet. When IDA connects a moment later, the first thing it reads is already the truth: `Stopped at 0x10000234`. This is the whole reason the lab works cleanly — you never have to drive a reset from outside the GUI. +> +> Use the address you actually want to stop at: +> +> | What you want to stop at | Address | Command | +> | --- | --- | --- | +> | `main` (once per reset) | `0x10000234` | `BP_ADDR=0x10000234 ./debug-server.sh` | +> | The **loop** — the first `printf` call, hit every iteration | `0x10000268` | `BP_ADDR=0x10000268 ./debug-server.sh` | +> +> ```bash +> BP_ADDR=0x10000234 ./debug-server.sh # park at main +> BP_ADDR=0x10000268 ./debug-server.sh # park in the loop instead +> ``` +> +> ```powershell +> $env:BP_ADDR="0x10000234"; .\debug-server.ps1 # park at main +> $env:BP_ADDR="0x10000268"; .\debug-server.ps1 # park in the loop +> ``` +> +> **This startup stop is single-use.** OpenOCD flushes breakpoints when a client connects, so this one is gone once IDA attaches — fine for `main`, which only runs once per reset. Every breakpoint after that is set from the IDA GUI (Step 12) and is repeatable. To stop at `main` again, restart the server with `BP_ADDR` and reconnect. + +> **Exactly one core.** The line must say `core0` and must **not** mention `core1`. Core1 is never started by this firmware; exposing it makes IDA read core1's reset-state registers, which are not real addresses, and OpenOCD floods the log with `Failed to read memory at 0xf0000000`. The scripts already use `USE_CORE=0`; do not change it. + +> **Windows driver note:** the Debug Probe must use the **WinUSB** driver. If OpenOCD reports `unable to open CMSIS-DAP device`, install it with [Zadig](https://zadig.akeo.ie/) (select `Debug Probe (CMSIS-DAP)` -> WinUSB). + +### Step 10: Connect IDA to the GDB server + +1. Make sure the image is open and analyzed (Part 2) and the server from Step 9 is running (parked at `main`). +2. Choose `Debugger -> Connect to Remote Process`. +3. In the **adapter** dropdown, select **GDB MI**. +4. In the **connect** settings group, set **IP Address** to `127.0.0.1` and **Port** to `3333`. +5. Set **Full GDB Executable Path** to the `arm-none-eabi-gdb` from the **Arm GNU Toolchain 14.2.rel1**. It ships for all three hosts, and the Raspberry Pi Pico VS Code extension installs that same 14.2.rel1 toolchain (including `arm-none-eabi-gdb`) on all of them: + + | OS | `arm-none-eabi-gdb` path | + | -- | ------------------------ | + | macOS Apple Silicon | `/Applications/ArmGNUToolchain/14.2.rel1/arm-none-eabi/bin/arm-none-eabi-gdb` (or the Pico extension's `~/.pico-sdk/toolchain/14_2_Rel1/bin/arm-none-eabi-gdb`) | + | Windows x64 | `%USERPROFILE%\.pico-sdk\toolchain\14_2_Rel1\bin\arm-none-eabi-gdb.exe` (Pico extension), or `C:\Program Files (x86)\Arm GNU Toolchain arm-none-eabi\14.2 rel1\bin\arm-none-eabi-gdb.exe` | + | Linux x64 | `~/.pico-sdk/toolchain/14_2_Rel1/bin/arm-none-eabi-gdb` (Pico extension), or the `bin/` directory of the extracted `arm-gnu-toolchain-14.2.rel1-x86_64-arm-none-eabi` tarball | +6. Click **Accept**. + +> **Use the GDB MI adapter.** It launches a real `arm-none-eabi-gdb --interpreter=mi2` and lets IDA drive it, so breakpoints and stepping go through real GDB — which sends the correct 2-byte breakpoint length and handles step-over itself. Verified working end to end: connect, GUI breakpoints (**Add Hardware Breakpoint...**, hardware execute), **Step Into** / **Step Over**, and register edits. Stops are reported as `Breakpoint` (not `SingleStep`). +> +> **Do NOT have any breakpoints set in IDA before you connect.** With the GDB MI adapter, attaching while IDA already has a breakpoint **hangs the session**. Start the server parked with `BP_ADDR` (Step 9), connect, and only add hardware breakpoints *after* the connection is up. This is a IDA bug; it is the single most common GDB MI failure. +> +> **The GDB executable path matters.** Use the **14.2.rel1** build on every OS (Windows, macOS, Linux). The 13.3.rel1 build did **not** connect in testing. +> +> **This step is temporary.** Vector35 plans to ship a GDB binary with the GDB MI adapter ([Vector35/debugger#929](https://github.com/Vector35/debugger/issues/929), milestone *Langara*). Once that lands, IDA provides GDB itself and you will not need to set **Full GDB Executable Path** at all. +> +> **Do not pick Corellium.** IDA's adapter dropdown also lists **Corellium**, which is for Corellium's virtual devices and expects an API token, not a local OpenOCD server. It is not the adapter for this lab. The dropdown is a combo box, so an accidental arrow-key press can land on it — always read the label back and confirm it says **GDB MI** before clicking **Accept**. + +> **The adapter and port are not saved in the `.i64`.** Every time you relaunch IDA you must re-select **GDB MI**, re-enter port `3333`, and re-set the GDB path. + +> **Watch for an off-screen error dialog.** When a connection fails, IDA pops a `IDA critical alert` window that can be positioned mostly outside the main window, which makes it look like nothing happened. If the connect seems to do nothing, check your other display. + +The target keeps running. Open the **Registers** tab (bug icon) and confirm you see live values. `pc` inside `0x10003xxx` and `sp` just below `0x20082000` are healthy. + +> **If `pc` is `0x00000088`, `0x000000ec`, or `sp` is `0xf0000000`, the session is bad.** Restart the server, then restart IDA (a server restart while attached leaves IDA in a stale session), and connect again. + +### Step 11: Find `main` without relying on its address + +`main` can move between programs, so we do not guess it. We follow the one fixed path to it. Press `G` and go to `0x10000000`: + +``` +0x10000000 0x20082000 initial stack pointer (top of SRAM) +0x10000004 0x1000015d reset vector +``` + +Bit 0 of a vector is the Thumb bit, so `0x1000015d` means "start at `0x1000015c`". That is `_reset_handler`. Follow the reset path to `0x10000186`, `platform_entry`: + +```asm +10000186: 4914 ldr r1, [pc, #80] ; @ 0x100001d8 +10000188: 4788 blx r1 ; runtime_init +1000018a: 4914 ldr r1, [pc, #80] ; @ 0x100001dc +1000018c: 4788 blx r1 ; main <-- the fixed anchor +1000018e: 4914 ldr r1, [pc, #80] ; @ 0x100001e0 +10000190: 4788 blx r1 ; exit +10000192: be00 bkpt 0x0000 +10000194: e7fd b.n 0x10000192 +``` + +**The middle `blx` at `0x1000018c` is the call to `main`.** `platform_entry` is byte-identical in every project, so `0x1000018c` catches `main` no matter where the linker placed it. The literal pool at `0x100001dc` holds `main | 1`; clearing bit 0 gives `0x10000234`. + +### Step 12: Set a hardware breakpoint in the GUI + +With the **GDB MI** adapter, IDA sets breakpoints through real GDB, which sends the correct 2-byte length, so you set them **in the UI**. There is no command port here. + +> **Why older drafts used the command port.** IDA's **GDB RSP** adapter is its own minimal RSP client and sends a **1-byte** breakpoint (`Z0,,1`); the Cortex-M33 FPB comparators need 2 bytes, so OpenOCD rejected it with `only breakpoints of two bytes length supported`. The old workaround was to arm breakpoints by hand over telnet. **The GDB MI adapter does not have this problem** — it drives real `arm-none-eabi-gdb`, which sends the right length. So everything below is done in the GUI. The command port still exists as a fallback (see the end of this step), but you do not need it. + +#### Where you can stop + +| You want to stop at | Address | How | Repeatable? | +| --- | --- | --- | --- | +| **`main`** | `0x10000234` | The server starts parked there with `BP_ADDR=0x10000234` (Step 9), so IDA is already stopped at `main` when it connects. | No — `main` runs once per reset. | +| **The regular `printf` call** | `0x10000268` | Set a hardware breakpoint in the GUI, then click **Resume**. | Yes — fires on every iteration. | +| **The static `printf` call** | `0x10000270` | Set a hardware breakpoint in the GUI, then click **Resume**. | Yes — fires on every iteration. | + +#### Set the loop breakpoint in the GUI + +1. Press `G`, type the loop address (`0x10000268`), and press Enter. +2. Set a **hardware execution** breakpoint at that address, either way: + - `Debugger -> Add Hardware Breakpoint...` — a **hardware execute** (`HE`) breakpoint. **Use this one.** + - click the line and press `F2` (`Debugger -> Toggle Breakpoint`) — a **software** breakpoint. It will **not** work here: the code is in read-only flash, so GDB cannot install it and the core just keeps running. +3. Click **Resume**. The core is already running the loop, so the breakpoint fires on the next iteration. IDA stops with the PC at the loop address and reports it as a **Breakpoint** — verified: `Stopped (Breakpoint) at 0x10000268`. + +> **No breakpoints before you connect.** With GDB MI, a breakpoint set before the connection hangs the session (Step 10). Start parked with `BP_ADDR`, connect, *then* add breakpoints. + +#### Stepping + +With the target halted at the breakpoint, **Step Into** (`F7`) and **Step Over** (`F8`) run through real GDB and move the PC. Verified: `0x10000268 -> 0x100031a4 -> 0x100031a6 -> ...`. + +> **Step Over on the raw `.bin` steps *into* calls.** The raw image has no symbol for `__wrap_printf`, so **Step Over** at the `printf` call behaves like **Step Into**. When the lab needs to execute the call and then stop, it moves the breakpoint to the return site and clicks **Resume** instead (Step 13 shows this). + +> **Never use IDA's Restart button.** On RP2350 it resets and halts inside the boot ROM (`pc=0x88`, `sp=0xf0000000`). To reset cleanly, restart the server with `BP_ADDR` and reconnect. + +> **If you ever need the command port.** It is still there — `nc 127.0.0.1 4444`, and `bp 2 hw` still arms a breakpoint, `rbp ` / `rbp all` still remove them. It is the fallback if you switch back to the **GDB RSP** adapter, whose 1-byte breakpoints the GUI cannot set. With GDB MI you do not need it for this lab. + +### Step 13: HACK IT LIVE — change the printed value + +`main` loads the constant `0x2a` (42) into `r1` and calls `printf` for the regular variable on every iteration. We break on that call and change it live: + +1. Press `G`, go to `0x10000268` (the first `bl __wrap_printf`). +2. Set a **hardware execute** breakpoint there: `Debugger -> Add Hardware Breakpoint...`. (Do not use `F2` — that is a software breakpoint and will not work on read-only flash.) +3. Click **Resume** in IDA. The target is already running the loop, so the breakpoint fires on the next iteration. IDA stops with the program counter at `0x10000268` and `r1 = 0x2a`. +4. Open the **Registers** widget (bug icon -> **Registers**). +5. Find `r1`. Its value is `0x2a` (42), loaded by the `movs r1, #42` at `0x10000264`. +6. **Set `r1` to `0x2b` (43).** From IDA's Python console (`Plugins -> Python Console`): + ```python + dbg.set_reg_value("r1", 0x2b) + ``` + `dbg.set_reg_value(name, value)` writes one register (returns `True` on success). You can also right-click `r1` in the **Registers** widget, press `E` (edit), type `2b`, and press Enter. The widget may not repaint the value, but the write reaches the target — you confirm it by the printed output in the next steps. +7. **Move the breakpoint past the call.** You want `printf` to run once and then stop, so move the breakpoint from `0x10000268` to the instruction *after* the call, `0x1000026c` (the `ldrb r1, [r4]` that begins the static-variable half of the loop): remove the breakpoint at `0x10000268` and set a hardware breakpoint at `0x1000026c`. Two reasons not to just click **Step Over** here: a breakpoint left on the current PC re-traps the step, and IDA's **Step Over** steps *into* `__wrap_printf` on this raw `.bin` because the image carries no symbol for the call. Moving the breakpoint to the return site is deterministic. +8. Click **Resume** in IDA. The core executes `bl __wrap_printf` with `r1 = 0x2b`, so this iteration prints `regular_fav_num: 43`, then stops at `0x1000026c`. +9. Look at your serial monitor — the `screen` session on the Pico's USB serial port — and at the **Target** tab in IDA: + + ``` + regular_fav_num: 43 + ``` + +You changed a running program's output without touching the binary. + +### Step 13b: HACK THE STRING LIVE — change `regular_fav_num:` to `patched_fav_num:` (optional) + +The text `"regular_fav_num: %d\r\n"` lives in flash (`.rodata`) at `0x10003560`, and flash is **read-only at runtime** — a debugger write there does not stick. So instead of overwriting the text in place, redirect the pointer: at the `printf` call, `r0` holds the string address, so point `r0` at a replacement string you place in RAM. + +1. Arm the breakpoint at the `printf` call and hit it, exactly as in Step 13 steps 1-3. At the stop, `r0 = 0x10003560` and `r1 = 0x2a`. +2. Put the replacement string into free RAM at `0x20080000` from IDA's **Python console** (`Plugins -> Python Console`) — no command port needed: + ```python + dbg.write_memory(0x20080000, b"patched_fav_num: %d\r\n\x00") + ``` + `dbg.write_memory(address, bytes)` is IDA's debugger memory-write API; it returns `True` on success. That writes `patched_fav_num: %d\r\n\0`. +3. Point `r0` at that string: + ```python + dbg.set_reg_value("r0", 0x20080000) + ``` + (Or right-click `r0` in the **Registers** widget, press `E`, type `0x20080000`, and press Enter.) +4. If you want the value hack too, set `r1` to `0x2b` as in Step 13. Then move the breakpoint past the call in the GUI (remove it at `0x10000268`, set one at `0x1000026c`) and click **Resume**. The core runs `printf` with `r0` pointing at your RAM string and `r1 = 0x2b`, so this iteration prints: + ``` + patched_fav_num: 43 + ``` + then stops at `0x1000026c`. + +Like the value hack, this is **one iteration only**: the loop reloads `r0` (and `r1`) from flash on every pass, so the next line is `regular_fav_num: 42` again. The permanent version is the static patch in Step 18c. + +### Step 14: Why the hack reverts (and why we patch next) + +Press **Resume**. The loop branches back to `0x10000264`, which reloads `movs r1, #42`, so the next line is `regular_fav_num: 42`. The live edit changed one iteration only. There is no stack variable in memory to change; the value is baked into the instruction. To make `regular_fav_num: 43` permanent we must patch the instruction. That is the static pass. + +Press **Pause** to stop the output flood. + +### Step 15: Kill the debugger and OpenOCD + +The live hack is done. Do this **before** the static pass. + +1. In the **Debugger** sidebar, click the **X** (**Kill**) (or **`Debugger -> Kill`**) to disconnect IDA. +2. **Kill does not stop the OpenOCD process** — `debug-server.sh` started it separately, and it keeps running and holding the probe. Stop it from the IDA console: + + **macOS / Linux:** + + ```python + import subprocess + subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # stop the debug server, free the probe + ``` + + **Windows:** + + ```python + import subprocess + subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"]) # stop the debug server, free the probe + ``` + +3. Confirm nothing is left: `pgrep -fl openocd` (macOS/Linux) prints nothing. + +From a terminal it is the same: `pkill -TERM -f openocd`, or `Get-Process openocd | Stop-Process` on Windows. + +--- + +## Part 4: Static — Resolve the Functions in IDA and Patch + +### Step 16: Resolve the functions in the IDA GUI + +We now name the functions in IDA using the ELF symbol map from Step 4. IDA loaded the raw `.bin` with **no symbols**, so every function shows as `sub_` — resolving means giving each one its real name and signature. + +Three keys do all the work: + +| Key | IDA action | Use it for | +| --- | --- | --- | +| `G` | Go to address | Jump to a function's address | +| `Y` | **Change Type** | Set the function's signature. The dialog shows the full prototype, so this sets the name *and* the type in one step. | +| `N` | Rename | Rename only, when you just want the name and not the type | + +For each function below: `G` to its address, then **`Y` (Change Type)** and type the prototype from the table. + +#### How to resolve a function in IDA (`Y`) + +`Y` is the **Change Type** key, and it is what actually resolves the function — it turns `void sub_10003014()` into `bool stdio_init_all(void)`. The Change Type dialog shows the full declaration (name and type), so typing the prototype sets both: + +1. `G` to the function's address. The cursor lands on the function. +2. Press **`Y`**. In the Change Type dialog, type the prototype from the table exactly — for example `bool stdio_init_all(void)` — and press Enter. + +The decompiler header then shows the real prototype, and calls to the function read cleanly instead of `sub_()`. `N` is only for renaming without touching the type; `Y` alone sets both the name and the type. + +If `Y` seems to do nothing, confirm the cursor is on the function, or right-click it and pick **Change Type...**. IDA parses what you type and silently keeps the old type if it does not parse, so glance at the header after each `Y`. + +#### Worked example: `main` + +1. Press `G`, type `0x10000234`, press Enter. The view jumps there; the cursor lands on `sub_10000234`. +2. Press **`Y`** (Change Type), type `int main(void)`, press Enter. That sets the name to `main` and the type to `int(void)`. + +> **IDA shows `int32_t` where Ghidra shows `int`.** After you set `int main(void)`, the decompiler header may read `int32_t main(void)`. That is the same type — on this platform `int` is 32 bits and IDA's parser normalises it to `int32_t`. Do not fight it; it is not an error. + +#### Worked example: `gpio_init` + +1. `G` -> `0x10000300`. +2. `Y` -> `void gpio_init(uint gpio)`. + +#### Worked example: `gpio_set_pulls` + +1. `G` -> `0x100002d8`. +2. `Y` -> `void gpio_set_pulls(uint gpio, bool up, bool down)`. + +This is what `gpio_pull_up(15)` in our source compiles to: the SDK's `static inline` `gpio_pull_up` disappears, and `main` calls `gpio_set_pulls(15, true, false)` directly at `0x1000024e`. + +#### Worked example: `gpio_set_function` + +1. `G` -> `0x1000029c`. +2. `Y` -> `void gpio_set_function(uint gpio, gpio_function_t fn)`. + +#### Worked example: `__wrap_printf` + +1. `G` -> `0x100031a4`. +2. `Y` -> `int __wrap_printf(const char *fmt, ...)`. Keep the `...` — `printf` is variadic. + +> **`printf` in our source is `__wrap_printf` in the binary.** The SDK links our `printf` calls to its `__wrap_printf` wrapper. + +The rest of the chain is the same two keystrokes per function (`G`, then `Y`). This is **our code plus the library functions it actually calls** — not the whole SDK. `main` calls `stdio_init_all`, `gpio_init`, `gpio_set_pulls`, and `printf`, so we follow that chain down: `stdio_init_all` pulls in the stdio/UART setup, `printf` lands in the SDK's `__wrap_printf`, and `uart_init` reaches `clock_get_hz` and `busy_wait_us`. + +The call chain for this project: + +``` +main +├── stdio_init_all +│ └── stdio_uart_init ── gpio_set_function, uart_init, stdio_set_driver_enabled +│ └── uart_init ── clock_get_hz, busy_wait_us +├── gpio_init +├── gpio_set_pulls (gpio_pull_up inlined) +├── __wrap_printf ── __wrap_vprintf +│ ├── vfctprintf ── _vsnprintf +│ │ └── _ntoa_format / _out_rev / _out_char +│ ├── stdio_out_chars_crlf +│ └── time_us_64 +└── gpio_set_dir / gpio_get / gpio_put (inlined; no calls) +``` + +**Resolve every function in that chain:** + +| Address | Rename to (`N`) | Signature (`Y`) | +| ------- | --------------- | --------------- | +| `0x1000015c` | `_reset_handler` | `void _reset_handler(void)` | +| `0x10000186` | `platform_entry` | `void platform_entry(void)` | +| `0x1000019a` | `data_cpy` | `void data_cpy(void*, void*, void*)` | +| `0x100001e4` | `_init` | `void _init(void)` | +| `0x10000210` | `frame_dummy` | `void frame_dummy(void)` | +| **`0x10000234`** | **`main`** | **`int main(void)`** | +| `0x1000029c` | `gpio_set_function` | `void gpio_set_function(uint, gpio_function_t)` | +| `0x100002d8` | `gpio_set_pulls` | `void gpio_set_pulls(uint, bool, bool)` | +| `0x10000300` | `gpio_init` | `void gpio_init(uint)` | +| `0x10000e60` | `time_us_64` | `uint64_t time_us_64(void)` | +| `0x10000ed0` | `uart_init` | `uint uart_init(uart_inst_t*, uint)` | +| `0x10002dbc` | `exit` | `void exit(int)` | +| `0x10002dc4` | `runtime_init` | `void runtime_init(void)` | +| `0x10002df0` | `stdio_out_chars_crlf` | `void stdio_out_chars_crlf(stdio_driver_t*, const char*, int)` | +| `0x10002f00` | `stdio_put_string` | `int stdio_put_string(const char*, int, bool, bool)` | +| `0x10002fec` | `stdio_set_driver_enabled` | `void stdio_set_driver_enabled(stdio_driver_t*, bool)` | +| `0x10003014` | `stdio_init_all` | `bool stdio_init_all(void)` | +| `0x100030e0` | `__wrap_vprintf` | `int __wrap_vprintf(const char*, va_list)` | +| `0x100031a4` | `__wrap_printf` | `int __wrap_printf(const char*, ...)` | +| `0x10003360` | `stdio_uart_init` | `void stdio_uart_init(void)` | +| `0x100034a0` | `strlen` | `size_t strlen(const char*)` | + +**Resolve the SDK helpers the `printf` and `uart_init` paths reach:** + +| Address | Rename to (`N`) | Signature (`Y`) | +| ------- | --------------- | --------------- | +| `0x10002d60` | `vfctprintf` | `int vfctprintf(void (*)(char, void*), void*, const char*, va_list)` | +| `0x1000237c` | `_vsnprintf` | `int _vsnprintf(out_fct_type, char*, size_t, const char*, va_list)` | +| `0x10001760` | `_ntoa_format` | `unsigned _ntoa_format(out_fct_type, char*, size_t, size_t, char*, size_t, bool, unsigned, unsigned, unsigned, unsigned)` | +| `0x100016c4` | `_out_rev` | `unsigned _out_rev(out_fct_type, char*, size_t, size_t, const char*, size_t, unsigned, unsigned)` | +| `0x10001934` | `_out_char` | `void _out_char(char, void*, size_t, size_t)` | +| `0x10000e74` | `busy_wait_us` | `void busy_wait_us(uint64_t)` | +| `0x100010a4` | `clock_get_hz` | `unsigned long clock_get_hz(clock_handle_t)` | + +> **A `void` return type may not stick — here is the fix.** IDA treats `void` as low-confidence, and its analysis can override it with an inferred type — most often `int32_t` on this 32-bit target. It is most visible on `_reset_handler` (a hand-written assembly entry that never returns normally), but it can happen to **any** function whose return type IDA thinks it can infer. +> +> Setting the full signature with `Y` reproduces the unwanted `int32_t`, and `fn.return_type = ...` fails too. What works is the **return-value** setter: +> +> ```python +> from binaryninja import ReturnValue, Type +> fn = bv.get_function_at(0x1000015c) +> if fn is not None: +> fn.return_value = ReturnValue(Type.void()) +> ``` +> +> That holds `_reset_handler` at `void` even after reanalysis. If it still will not stick, leave it — it does not affect the rest of the lesson. + +> **`__wrap_printf` is the real symbol.** `printf` in our source compiles to the SDK's `__wrap_printf` (which forwards to `__wrap_vprintf`). Rename it `printf` if you prefer the lesson's shorthand, but `__wrap_printf` is what the ELF says. +> +> **`stdio_init_all` returns `bool`, not `void`** — `_Bool stdio_init_all(void)` in the ELF. + +> **Shortcut — resolves name *and* type for every function.** Instead of doing `N` + `Y` by hand, paste this into IDA's Python console (`Plugins -> Python Console`). It sets each function's name and signature programmatically: +> +> ```python +> from binaryninja import Symbol, SymbolType +> # The raw .bin has no headers, so these SDK types don't exist. set_user_type() +> # re-parses each signature as C, so an undefined name raises +> # "SyntaxError: unknown type name '...'". Define them first. +> sdk = bv.parse_types_from_string(""" +> typedef unsigned int uint; +> typedef char* va_list; +> typedef unsigned long clock_handle_t; +> typedef void (*out_fct_type)(char, void*, size_t, size_t); +> struct stdio_driver; +> typedef struct stdio_driver stdio_driver_t; +> struct uart_inst; +> typedef struct uart_inst uart_inst_t; +> enum gpio_function { +> GPIO_FUNC_XIP = 0, GPIO_FUNC_SPI = 1, GPIO_FUNC_UART = 2, GPIO_FUNC_I2C = 3, +> GPIO_FUNC_PWM = 4, GPIO_FUNC_SIO = 5, GPIO_FUNC_PIO0 = 6, GPIO_FUNC_PIO1 = 7, +> GPIO_FUNC_GPCK = 8, GPIO_FUNC_USB = 9, GPIO_FUNC_NULL = 0x1f, +> }; +> typedef enum gpio_function gpio_function_t; +> """) +> for name, ty in sdk.types.items(): +> bv.define_user_type(name, ty) +> +> # address: (name, signature) +> funcs = { +> 0x1000015c: ("_reset_handler", "void _reset_handler(void)"), +> 0x10000186: ("platform_entry", "void platform_entry(void)"), +> 0x1000019a: ("data_cpy", "void data_cpy(void*, void*, void*)"), +> 0x100001e4: ("_init", "void _init(void)"), +> 0x10000210: ("frame_dummy", "void frame_dummy(void)"), +> 0x10000234: ("main", "int main(void)"), +> 0x1000029c: ("gpio_set_function", "void gpio_set_function(uint, gpio_function_t)"), +> 0x100002d8: ("gpio_set_pulls", "void gpio_set_pulls(uint, bool, bool)"), +> 0x10000300: ("gpio_init", "void gpio_init(uint)"), +> 0x10000e60: ("time_us_64", "uint64_t time_us_64(void)"), +> 0x10000ed0: ("uart_init", "uint uart_init(uart_inst_t*, uint)"), +> 0x10002dbc: ("exit", "void exit(int)"), +> 0x10002dc4: ("runtime_init", "void runtime_init(void)"), +> 0x10002df0: ("stdio_out_chars_crlf", "void stdio_out_chars_crlf(stdio_driver_t*, const char*, int)"), +> 0x10002f00: ("stdio_put_string", "int stdio_put_string(const char*, int, bool, bool)"), +> 0x10002fec: ("stdio_set_driver_enabled", "void stdio_set_driver_enabled(stdio_driver_t*, bool)"), +> 0x10003014: ("stdio_init_all", "bool stdio_init_all(void)"), +> 0x100030e0: ("__wrap_vprintf", "int __wrap_vprintf(const char*, va_list)"), +> 0x100031a4: ("__wrap_printf", "int __wrap_printf(const char*, ...)"), +> 0x10003360: ("stdio_uart_init", "void stdio_uart_init(void)"), +> 0x100034a0: ("strlen", "size_t strlen(const char*)"), +> 0x10002d60: ("vfctprintf", "int vfctprintf(void (*)(char, void*), void*, const char*, va_list)"), +> 0x1000237c: ("_vsnprintf", "int _vsnprintf(out_fct_type, char*, size_t, const char*, va_list)"), +> 0x10001760: ("_ntoa_format", "unsigned _ntoa_format(out_fct_type, char*, size_t, size_t, char*, size_t, bool, unsigned, unsigned, unsigned, unsigned)"), +> 0x100016c4: ("_out_rev", "unsigned _out_rev(out_fct_type, char*, size_t, size_t, const char*, size_t, unsigned, unsigned)"), +> 0x10001934: ("_out_char", "void _out_char(char, void*, size_t, size_t)"), +> 0x10000e74: ("busy_wait_us", "void busy_wait_us(uint64_t)"), +> 0x100010a4: ("clock_get_hz", "unsigned long clock_get_hz(clock_handle_t)"), +> } +> for addr, (name, sig) in funcs.items(): +> bv.define_user_symbol(Symbol(SymbolType.FunctionSymbol, addr, name)) +> f = bv.get_function_at(addr) +> if f is not None: +> f.set_user_type(sig) +> ``` +> +> SDK type names (`stdio_driver_t`, `gpio_function_t`, `uart_inst_t`, plus `uint`, `va_list`, `out_fct_type`, and `clock_handle_t`) are **not** in the raw `.bin`. `set_user_type` re-parses each signature as C, so an undefined name raises `SyntaxError: unknown type name '...'` and stops the loop — it is not harmless. The `sdk` block above defines them first (an opaque `struct`/`enum`/`typedef` is enough to parse). If you add a function that uses another SDK type, add a definition for it to that block too. + +### Step 17: Read `main` in the decompiler + +Open the **Decompiler** view on `main`. Once the functions above are typed, it reads roughly: + +```c +int32_t main(void) +{ + stdio_init_all(); + gpio_init(0xf); + gpio_set_dir(0xf, GPIO_IN); // inlined: mcrr 0, 4, r0, r3, cr4 + gpio_set_pulls(0xf, true, false); // gpio_pull_up(15) + gpio_init(0x10); + gpio_set_dir(0x10, GPIO_OUT); // inlined + do + { + __wrap_printf("regular_fav_num: %d\r\n", 0x2a); + __wrap_printf("static_fav_num: %d\r\n", *(uint8_t*)0x200005a8); + *(uint8_t*)0x200005a8 = *(uint8_t*)0x200005a8 + 1; // static_fav_num++ + gpio_put(0x10, gpio_get(0xf) ^ 1); // inlined SIO read/write + } while (true); +} +``` + +The `0x2a` is the value we edited live; `0x200005a8` is the fixed RAM address of `static_fav_num`. The `gpio_get(0xf) ^ 1` is the `eor.w r3, r3, #1` we will patch in Step 18b. Now make the hacks permanent. + +### Step 18: Patch 1 — change `regular_fav_num` from 42 to 43 + +Go to `0x10000264`: + +```asm +10000264: 212a movs r1, #42 ; 0x2a +``` + +The halfword is `0x212a`, stored little-endian as `2a 21`. The immediate is the low byte, so the byte at the instruction's own address is `0x2a`. Change it to `0x2b` (43). + +| Project | Address | Before | After | Effect | +| ------- | ------- | ------ | ----- | ------ | +| `0x0014` | `0x10000264` | `2a` | `2b` | `movs r1, #42` -> `#43`, prints `regular_fav_num: 43` | + +**Option A — Hex view:** + +1. Switch to the **Hex** view (`View -> Hex`). +2. Toggle the lock off so editing is enabled. +3. Go to `0x10000264` and change the byte `2A` to `2B`. +4. Return to the linear view, right-click the function -> `Reanalyze`. + +**Option B — Python console:** + +```python +bv.write(0x10000264, b"\x2b") +print(hex(bv.read(0x10000264, 1)[0])) # -> 0x2b +``` + +After reanalysis the instruction reads `movs r1, #43`. + +### Step 18b: Patch 2 — invert the button/LED logic + +The stock code inverts the raw button bit with `eor.w r3, r3, #1` at `0x10000286`. Its four bytes are `83 f0 01 03`; the immediate `#1` is the **third** byte, at `0x10000288`. Change `01` to `00` so the XOR becomes `#0` (a no-op) and the LED follows the raw pin state instead: + +```asm +10000286: f083 0301 eor.w r3, r3, #1 ; immediate byte at 0x10000288 +``` + +| Project | Address | Before | After | Effect | +| ------- | ------- | ------ | ----- | ------ | +| `0x0014` | `0x10000288` | `01` | `00` | `eor.w r3, r3, #1` -> `#0`, inverts the LED behavior | + +**Option A — Hex view:** + +1. Switch to the **Hex** view (`View -> Hex`). +2. Go to `0x10000288` and change the byte `01` to `00`. +3. Return to the linear view and reanalyze. + +**Option B — Python console:** + +```python +bv.write(0x10000288, b"\x00") +print(bv.read(0x10000286, 4).hex()) # -> 83f00003 +``` + +Now the logic is permanently changed: + +- Button released (GPIO 15 reads `1`): `1 XOR 0 = 1` -> LED **ON** +- Button pressed (GPIO 15 reads `0`): `0 XOR 0 = 0` -> LED **OFF** + +This is the **opposite** of the original behavior. The `gpio_get` and `gpio_put` are inlined, so the only byte that controls the inversion is this immediate. + +### Step 18c: Patch 3 — rename the printed label (optional) + +The format string `"regular_fav_num: %d\r\n"` starts at `0x10003560`. Its first 16 bytes are `72 65 67 75 6c 61 72 5f 66 61 76 5f 6e 75 6d 3a` (`regular_fav_num:`). Change them to `70 61 74 63 68 65 64 5f 66 61 76 5f 6e 75 6d 3a` (`patched_fav_num:`), leaving the ` %d\r\n` tail untouched, so the line prints `patched_fav_num: 43`. + +| Project | Address | Before | After | Effect | +| ------- | ------- | ------ | ----- | ------ | +| `0x0014` | `0x10003560` | `72 65 67 75 6c 61 72 5f 66 61 76 5f 6e 75 6d 3a` | `70 61 74 63 68 65 64 5f 66 61 76 5f 6e 75 6d 3a` | `regular_fav_num:` -> `patched_fav_num:` | + +**Option A — Hex view:** + +1. Switch to the **Hex** view (`View -> Hex`). +2. Go to `0x10003560` and change the sixteen bytes `72 65 67 75 6c 61 72 5f 66 61 76 5f 6e 75 6d 3a` to `70 61 74 63 68 65 64 5f 66 61 76 5f 6e 75 6d 3a`. +3. Return to the linear view and reanalyze. + +**Option B — Python console:** + +```python +bv.write(0x10003560, b"patched_fav_num:") +print(bv.read(0x10003560, 22)) # -> b'patched_fav_num: %d\r\n\x00' +``` + +Keep the replacement exactly sixteen bytes — the same length as `regular_fav_num:`. If you use a shorter string you must pad it, or `%d` shifts and `printf` reads the wrong argument. A longer string would overwrite the ` %d` tail. + +### Step 19: Export the patched `.bin` + +```python +import os +seg = next(s for s in bv.segments if s.data_length) # the loadable image segment +data = bv.read(seg.start, seg.data_length) # base + size come from the view itself +out = os.path.join(os.path.join(root, "0x0014_static-variables", "build"), "0x0014_static-variables-h.bin") +open(out, "wb").write(data) +print(len(data), out) # -> 15516 /.../build/0x0014_static-variables-h.bin +``` + +Where the two numbers come from — nothing is hardcoded: + +- **`seg.start`** is the image base IDA loaded the `.bin` at (`0x10000000`), the same value you pass to `uf2conv --base`. +- **`seg.data_length`** is the segment's size in the file (`0x3c9c` = 15516). Exactly one segment carries data (the image); every peripheral and synthetic segment has `data_length == 0`, so `next(...)` picks the image. +- Reading `seg.start` for `seg.data_length` bytes therefore grabs exactly the image. + +Two gotchas this avoids: + +- **No relative path.** IDA's Python console runs with a read-only working directory (inside the app bundle), so `open("0x0014_static-variables-h.bin", "wb")` fails with `OSError: [Errno 30] Read-only file system`. `root` (from `~/.embedded-hacking-repo`, Step 3) is the repo, so the file is written into the project's `build/` — no machine-specific path and no database needed. +- **Read the image, not the whole view.** `bv.read(bv.start, bv.length)` spans the entire mapped range, which is not the image. The segment's `data_length` is the image size. + +A different size means you exported a partial view. + +### Step 20: Convert to UF2 + +Run from the project directory: + +**macOS Apple Silicon / Linux x64:** + +```bash +python3 ../uf2conv.py 0x0014_static-variables-h.bin \ + --base 0x10000000 --family 0xe48bff59 --output hacked.uf2 +``` + +**Windows x64:** + +```cmd +python ..\uf2conv.py 0x0014_static-variables-h.bin ^ + --base 0x10000000 --family 0xe48bff59 --output hacked.uf2 +``` + +> **Or convert from the IDA console** — it is a normal Python interpreter, so you never have to leave the app. `chdir` to a writable directory first (the default one is read-only), then run the script: +> +> ```python +> import os, sys, runpy +> os.chdir(os.path.join(root, "0x0014_static-variables", "build")) # the project build dir (writable) +> sys.argv = ["uf2conv.py", "0x0014_static-variables-h.bin", +> "--base", "0x10000000", "--family", "0xe48bff59", "--output", "hacked.uf2"] +> runpy.run_path("../../uf2conv.py", run_name="__main__") # path to your uf2conv.py +> ``` +> +> This writes `hacked.uf2` next to the `.bin`, ready to drag onto the Pico. + +### Step 21: Flash and verify + +Hold **BOOTSEL**, plug in the Pico 2, and drag `hacked.uf2` onto the **`RP2350`** drive. Open the serial monitor: + +``` +patched_fav_num: 43 +static_fav_num: 42 +patched_fav_num: 43 +static_fav_num: 43 +patched_fav_num: 43 +static_fav_num: 44 +... +``` + +and the **LED is on by default** (button released) and turns **off** when you press the button — the opposite of the stock image. + +**The regular value is now 43, the label reads `patched_fav_num:`, and the button/LED logic is inverted — with eighteen bytes changed and no source code.** (`static_fav_num` keeps incrementing from `42`, unchanged: we left the static variable itself alone so you can watch it persist.) + +> **Faster: flash over the Debug Probe (no BOOTSEL).** The repo's `flash.sh` writes the raw `.bin` straight into XIP flash over SWD (`program 0x10000000 verify reset exit`), so you never touch BOOTSEL or a UF2. Run it from a terminal (`./flash.sh `), or from the IDA console **without freezing it** — use `subprocess.Popen`, which returns immediately, and send OpenOCD's output to a log file. (`subprocess.run` blocks the console until the flash finishes; do not use it here.) +> +> ```python +> import os, subprocess +> root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() +> bin_path = os.path.join(os.path.join(root, "0x0014_static-variables", "build"), "0x0014_static-variables-h.bin") +> log = os.path.join(os.path.join(root, "0x0014_static-variables", "build"), "flash.log") +> subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # free the probe first +> p = subprocess.Popen([os.path.join(root, "flash.sh"), bin_path], +> stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) +> print("flashing in the background; log:", log) +> ``` +> +> The `pkill` frees the probe first; on Windows use `subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"])`. +> +> The console is free the moment this returns. Check it with `print(p.poll())` (`None` = still running, `0` = done) or read `flash.log` — success ends with `** Verified OK **`. +> +> The same non-blocking form without the script: +> +> ```python +> import os, subprocess +> ocd = os.path.expanduser("~/.pico-sdk/openocd/0.12.0+dev") +> bin_path = os.path.join(os.path.join(root, "0x0014_static-variables", "build"), "0x0014_static-variables-h.bin") +> log = os.path.join(os.path.join(root, "0x0014_static-variables", "build"), "flash.log") +> subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # free the probe first +> p = subprocess.Popen([f"{ocd}/openocd", "-s", f"{ocd}/scripts", +> "-f", "interface/cmsis-dap.cfg", "-f", "target/rp2350.cfg", +> "-c", "adapter speed 5000", +> "-c", f"program {bin_path} 0x10000000 verify reset exit"], +> stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) +> print("flashing in the background; log:", log) +> ``` +> +> **The Debug Probe is single-owner.** If IDA is still attached (the `debug-server.sh` OpenOCD is running), the flash cannot grab the probe. Detach in IDA and stop that OpenOCD first: +> +> ```bash +> # macOS / Linux +> pkill -TERM -f openocd +> ``` +> ```powershell +> # Windows +> Get-Process openocd -ErrorAction SilentlyContinue | Stop-Process +> ``` +> +> Success looks like `Programming Finished` -> `Verified OK` -> `Resetting Target`. On Windows use `flash.ps1` (`.\flash.ps1 -Bin `) the same way. + +--- + +## Cheatsheet + +### IDA GUI actions + +| Action | How | +| ------ | --- | +| Go to address | `G` | +| Rename function/symbol | `N` | +| Set type or signature | `Y` | +| Add comment | `;` | +| Open Hex view | `View -> Hex` | +| Enable hex editing | Toggle the lock in the status bar | +| Reanalyze after a patch | Right-click function -> `Reanalyze` | +| Edit a register live | `dbg.set_reg_value("r1", 0x2b)` in the Python console (or right-click the register, press `E`, type hex, Enter) | +| Write a RAM string live | `dbg.write_memory(0x20080000, b"patched_fav_num: %d\r\n\x00")` | +| Set a breakpoint | `Debugger -> Add Hardware Breakpoint...` (hardware execute). Do **not** use `F2` — software breakpoints cannot be written to read-only flash. | +| Move a breakpoint | Remove it and set it at the new address in the GUI (command-port fallback: `rbp ` then `bp 2 hw`) | +| Confirm what is armed | The **Breakpoints** widget lists it (command-port fallback: `mdw 0xE0002000 8`, each armed breakpoint shows as ``) | +| Apply the ELF symbol map | Paste the Python snippet from Step 16 into the Python Console | + +### OpenOCD server and reset + +The server runs with `gdb_breakpoint_override hard` so that flash-writes are never attempted. Breakpoints in this lab are set in the IDA GUI through the **GDB MI** adapter (Step 12). The command-port rows below are the fallback if you use the **GDB RSP** adapter instead. + +| Action | Command | +| ------ | ------- | +| Connect to the OpenOCD prompt (fallback) | `nc 127.0.0.1 4444` (or `telnet 127.0.0.1 4444`) | +| Reset and run (command port) | `reset run` | +| Check core state (command port) | `targets` | +| Set a breakpoint in the GUI | `Debugger -> Add Hardware Breakpoint...` (hardware execute; `F2` software breakpoints do not work on flash) | +| (fallback) Add a breakpoint without the GUI | `bp 2 hw` | +| Remove one breakpoint | `rbp ` — **address only, no length, no `hw`** | +| Remove every breakpoint | `rbp all` | +| Start the server parked at `main` | macOS/Linux: `BP_ADDR=0x10000234 ./debug-server.sh` — Windows: `$env:BP_ADDR="0x10000234"; .\debug-server.ps1` (one-shot) | +| Start the server parked in the loop | macOS/Linux: `BP_ADDR=0x10000268 ./debug-server.sh` — Windows: `$env:BP_ADDR="0x10000268"; .\debug-server.ps1` | +| Break on the loop in a running target | set a hardware breakpoint in the GUI at the loop address, then **Resume** — repeatable | +| Make IDA stepping work | `rp2350.dap.core0 configure -rtos none` (already in the scripts) | +| Step without re-trapping | move the breakpoint off the current PC first, then **Step Into**/**Step Over** | +| Reset without desyncing IDA | **Detach**, `reset run` on the port, reconnect — never `reset run` while attached | + +### Every address and byte we changed + +| Project | Address | Before | After | Effect | +| ------- | ------- | ------ | ----- | ------ | +| `0x0014` | `0x10000264` | `2a` | `2b` | `movs r1, #42` -> `#43`, prints `regular_fav_num: 43` | +| `0x0014` | `0x10000288` | `01` | `00` | `eor.w r3, r3, #1` -> `#0`, inverts the button/LED logic | +| `0x0014` | `0x10003560` | `72 65 67 75 6c 61 72 5f 66 61 76 5f 6e 75 6d 3a` | `70 61 74 63 68 65 64 5f 66 61 76 5f 6e 75 6d 3a` | string prints `patched_fav_num:` instead of `regular_fav_num:` | + +### The static-variable memory map + +| Item | Address | Notes | +| ---- | ------- | ----- | +| `static_fav_num` | `0x200005a8` | RAM `.data`, fixed for the life of the program; initial value `42` copied from flash at boot | +| Literal-pool word 1 | `0x10000290` | `0x200005a8` — the RAM address `r4` holds | +| Literal-pool word 2 | `0x10000294` | `0x10003560` — pointer to `"regular_fav_num: %d\r\n"` | +| Literal-pool word 3 | `0x10000298` | `0x10003578` — pointer to `"static_fav_num: %d\r\n"` | +| `regular_fav_num` | (no address) | inlined to `movs r1, #42`; never given a stack slot | + +### Raw image facts + +| Item | Value | +| ---- | ----- | +| Build type | `Release` | +| Load base address | `0x10000000` | +| Project size | `15516` bytes (`0x3c9c`) | +| Fixed `main` anchor | `0x1000018c` (reset handler middle `blx`) | +| `main` | `0x10000234` | +| `printf` call / return, `regular_fav_num` | `0x10000268` / `0x1000026c` | +| `printf` call, `static_fav_num` | `0x10000270` | +| `static_fav_num` RAM address | `0x200005a8` | +| `regular_fav_num` format string | `0x10003560` | +| `static_fav_num` format string | `0x10003578` | +| RP2350 UF2 family ID | `0xe48bff59` | + +--- + +## Troubleshooting + +### IDA hangs or crashes when you connect (macOS 27) + +Three different causes have been seen on this setup; check them in this order. + +- **A breakpoint set before connecting.** With the **GDB MI** adapter, if the binary view already has a breakpoint, the session hangs. Start parked with `BP_ADDR`, connect, then add breakpoints (see the next entry). +- **The wrong GDB executable.** Point **Full GDB Executable Path** at the **14.2.rel1** toolchain (Step 10). The 13.3.rel1 build did **not** connect in testing. +- **The LLDB adapter.** A crash report with `libdebuggercore.dylib -> std::terminate() -> abort()` and `liblldb` in the stack is the **LLDB** adapter, not GDB MI. Avoid LLDB on this setup. + +**Use GDB MI**, with the 14.2.rel1 path above. If it still fails, fall back to plain `arm-none-eabi-gdb` against the same server — the addresses and register values are identical to the GUI steps. + +If IDA hangs, force-quit it; the connect dialog has no working Cancel. The static steps (resolve, patch, export, flash) never touch the debugger and always work. + +### The GUI refuses to set a breakpoint (GDB RSP adapter only) + +If you are on the **GDB RSP** adapter, the GUI cannot set breakpoints on this target. That adapter is IDA's own minimal RSP client and sends a **1-byte** breakpoint (`Z0,,1`); the Cortex-M33 comparators need 2 bytes, so OpenOCD answers `only breakpoints of two bytes length supported`. It affects every address, both `Toggle Breakpoint` and `Add Hardware Breakpoint`, and the dialog's **Size** field is disabled. `gdb_breakpoint_override` makes no difference. + +**Fix: use the GDB MI adapter** (Step 10). It drives real GDB, which sends the correct length, so GUI breakpoints just work. If you must stay on GDB RSP, arm breakpoints from the command port after connecting (`bp 2 hw`) — but the lab uses GDB MI and does not need that. + +### GDB MI hangs when you connect (a breakpoint already existed) + +With the **GDB MI** adapter, if IDA already has a breakpoint set when you connect, the session **hangs**. This is a IDA bug. The working order is: + +1. Start the server parked, e.g. `BP_ADDR=0x10000234 ./debug-server.sh` (Windows: `$env:BP_ADDR="0x10000234"; .\debug-server.ps1`). +2. Connect with the **GDB MI** adapter. +3. Only *then* set hardware breakpoints in the UI. + +Never have a breakpoint in the binary view before the GDB MI connection. If it hangs, quit IDA, restart the server with `BP_ADDR`, and connect again before adding any breakpoints. + +### Step Into / Step Over does nothing (PC never moves) + +Two causes have been seen on this target. + +1. **A breakpoint on the current PC re-traps the step.** OpenOCD's step-over-breakpoint logic fails with `Duplicate Breakpoint address` and the PC stays put. Fix: move the breakpoint off the current PC (in the GUI), then step. +2. **The `hwthread` RTOS (GDB RSP adapter only).** With the **GDB RSP** adapter, OpenOCD can log `fake step thread 0` and reply without stepping, because the RP2350 config's `-rtos hwthread` makes the current thread id 1 while IDA sends thread id 0. Fix: `rp2350.dap.core0 configure -rtos none` (the launcher scripts already pass this). **GDB MI does not hit this.** + +To tell them apart, turn on OpenOCD logging (`log_output /tmp/ocd.log`, then `debug_level 3` on the command port) and look for `fake step` versus `Duplicate Breakpoint`. + +### `zsh: bad CPU type in executable: cmake` + +An Intel `x86_64` tool is on your `PATH` on Apple Silicon. Run Step 2: `export PATH="/opt/homebrew/bin:$PATH"`, then `hash -r`. Add it to `~/.zshrc` to make it permanent. + +### My addresses do not match this guide + +You probably built `Debug`. This lesson is a `Release` build. Re-run Step 3 with `-DCMAKE_BUILD_TYPE=Release`. A `Debug` build moves the SDK functions and keeps `demo_static_variable` separate, so `main` is not at `0x10000234`. + +### A breakpoint never fires + +First, confirm you actually set one, and that it is a **hardware** breakpoint. With the **GDB MI** adapter, `Debugger -> Add Hardware Breakpoint...` (hardware execute) should land in the **Breakpoints** widget. If nothing lands, or the core keeps running, you probably used `F2` (`Toggle Breakpoint`) — that is a software breakpoint and cannot be written to read-only flash, so it never installs. Also check you are on **GDB MI**, not **GDB RSP** (the GDB RSP adapter cannot set breakpoints on this target at all). + +Then check the order and the state: + +- **Arm it only after IDA is connected.** OpenOCD flushes every breakpoint when a client attaches, so anything armed earlier is gone. This also applies to `BP_ADDR` on the startup command line. +- **Verify it is armed:** `mdw 0xE0002000 8`. You should see your address with the low bit set (`0x10000234` -> `0x10000235`). All zeros means nothing is armed — re-read this first, because it distinguishes "not armed" from "armed but never reached". +- **Is the core running?** `poll` on the command port should not report a halt. If it is stopped, click **Resume**. +- **Does the address get reached again?** `main` runs once per reset, so use `BP_ADDR` at startup (Step 9) rather than `reset run` while attached. Loop addresses such as `0x10000268` fire on the next pass with no reset — arm them and click **Resume** in IDA. +- **With GDB MI the stop is reported as `Breakpoint`** and appears in the **Breakpoints** widget, because GDB really did set it. + +### I edit `r1` (or another register) and it reverts + +`main` reloads the value at the top of every loop iteration — `movs r1, #42` at `0x10000264` runs right before the `printf` at `0x10000268`. So `r1` is only `0x2b` for the instant between your edit and the next pass; then it is `0x2a` again. The edit sticks only if the core is **genuinely stopped** at the breakpoint and stays stopped. + +If it keeps reverting, the core is running, which almost always means the breakpoint is not installed — usually because it is a **software** breakpoint (`F2`) that cannot be written to read-only flash. Use `Debugger -> Add Hardware Breakpoint...` (hardware execute). + +> **The Registers widget is a snapshot, not a live view.** IDA reads the registers at each stop and shows that snapshot; it does not poll the target, and there is no "refresh registers" command. So a value changed outside IDA will not appear until the next stop. + +### The static variable shows a wrong value in GDB / IDA + +`static_fav_num` is a function-local `static`, so it does not appear in the global symbol table as `static_fav_num`; `arm-none-eabi-nm` names it `static_fav_num.0`. A 4-byte read at `0x200005a8` returns `0x0000122a`, whose low byte `0x2a` (42) is the variable — the upper bytes belong to whatever is in adjacent RAM. Read **one byte** (`x/1ub 0x200005a8`) to see `42`, and never add a `*` (that would treat the value as a pointer). In IDA, define a `uint8_t` at `0x200005a8` if you want the decompiler to show the byte cleanly. + +### The serial capture is garbage on macOS + +Reading `/dev/cu.usbmodem*` with a bare `read()` returns garbage. Set **raw termios at 115200** first: clear canonical/echo flags, set `CLOCAL|CREAD`, and `B115200` on input and output. `screen /dev/cu.usbmodem* 115200` does all of this for you; a script must call `tcsetattr` itself. Once set, the capture reads clean `regular_fav_num: 42` lines. + +### It worked for a second, then stopped (IDA's view desyncs) + +This is the most common failure, and it has one main cause: **driving the core from the OpenOCD command port while IDA is connected.** + +- If you send `reset run` from the port while attached, the core resets, runs, and halts at your breakpoint — but IDA never receives the stop event. Its sidebar keeps showing the *previous* location, so **Step** and **Resume** act on a stale PC and appear to do nothing. +- If the OpenOCD process dies (or you restart it) while attached, IDA keeps believing it is connected: the sidebar stays, but the menu shows **Pause** enabled and **Resume**/**Step** disabled because IDA last saw the target *running*. + +Recovery: **Detach, then reconnect.** If Detach does nothing (the connection is already dead), restart IDA — its menu still shows a session that no longer exists. + +Prevention: + +- Stop at `main` with `BP_ADDR` on a fresh server start, not with `reset run` while attached. +- For loop addresses, set the breakpoint in the GUI and click **Resume**. Let IDA be the thing that starts the core. +- If you must reset, **Detach first**, `reset run`, then reconnect. +- Never leave a breakpoint on the PC you are about to step or resume from. + +### The target "blows past" `main` and stops at `0x100032cc` instead + +`0x100032cc` is inside `stdio_uart_out_flush`: + +```asm +100032c8: 4b02 ldr r3, [pc, #8] ; @ 0x100032d4 +100032ca: 681a ldr r2, [r3] +100032cc: 6993 ldr r3, [r2, #24] ; the core sits here while the UART drains +100032ce: 071b lsls r3, r3, #28 +100032d0: d4fc bmi.n 0x100032cc +100032d2: 4770 bx lr +100032d4: 20000850 .word 0x20000850 +``` + +That is the UART transmit-FIFO drain loop inside `printf`, so the core is running `main`'s loop and simply spends nearly all its time there. The breakpoint at `main` did not fire because `main`'s entry runs exactly **once per reset**. If you arm the breakpoint after the reset, or set it while the target is already running and just resume, the core is already past `main` and will never re-execute it. Either arm the breakpoint **before** resetting, or break inside the loop at `0x10000268`, which fires every iteration. + +**`0x100032cc` is not a function.** It is one instruction inside `stdio_uart_out_flush`, which starts at `0x100032c8`. If IDA has created a function at `0x100032cc` (for example because the debugger stopped at that PC), the decompiler shows garbage. Delete that bogus function (right-click it -> `Delete Function`, or put the cursor on it and press `U` to undefine) and reanalyze. The real function is `stdio_uart_out_flush` at `0x100032c8`. + +### The console floods with `Failed to read memory at 0xf0000000` + +Core1 is exposed. The scripts must run with `USE_CORE=0`. Stop the server, confirm only `core0` is reported, restart, then restart IDA. + +### `Connect to Remote Process` is greyed out and Pause does nothing + +IDA is in a stale session, usually because the debug server restarted while attached. Quit and reopen IDA (or the `.i64`) and connect again. + +### The decompiler still shows the old value after patching + +Right-click the function and choose `Reanalyze`. + +### The LED does not change after patching + +You patched the wrong byte. The inversion immediate is the **third** byte of the 4-byte `eor.w` instruction: the instruction is at `0x10000286`, so the byte to change is `0x10000288`. Confirm it now reads `00`, not `01`. + +--- + +## Fallback: do the dynamic steps with GDB (macOS 27) + +If IDA's debugger crashes on attach on macOS 27 (see Troubleshooting), you can still do the live hack with the ARM GDB from the toolchain, against the same OpenOCD server. The addresses and register values are identical to the GUI steps. + +Start the debug server (Step 9), then in a new terminal: + +``` +arm-none-eabi-gdb +``` + +At the `(gdb)` prompt: + +``` +set architecture armv8-m.main +target extended-remote :3333 +hbreak *0x10000268 +continue +``` + +Do **not** run `monitor reset run` before `hbreak`. `0x10000268` is inside `main`'s loop, so the breakpoint fires on the next iteration with no reset. If you reset first, the core runs `main` and you will not catch it. + +GDB stops at the `printf` call. Confirm the value, change it, and let it run: + +``` +info registers pc r1 # pc = 0x10000268, r1 = 0x2a +set $r1 = 0x2b +stepi +continue +``` + +The serial monitor prints `regular_fav_num: 43` for the iteration you changed — the same temporary live hack as editing `r1` in the IDA Registers widget. When you are done, press `Ctrl-C`, then `detach` and `quit`. + +**If you specifically want to stop at `main` (`0x10000234`),** remember its entry runs only once per reset, so the breakpoint must be armed *before* the reset: + +``` +monitor reset halt +hbreak *0x10000234 +continue +``` + +If you instead set it while the target is running and just `continue`, you will "blow past" `main` and catch the core inside `printf` — in this build at `0x100032cc`, the `stdio_uart_out_flush` UART-drain loop. + +`hbreak` sets a hardware breakpoint, which is required for read-only flash. It works from plain GDB because GDB sends the 2-byte length the Cortex-M33 comparators need. IDA's **GDB MI** adapter goes through the same GDB, so its GUI breakpoints work too; the old **GDB RSP** adapter was the one that sent a 1-byte length and could not set breakpoints here. + +## Glossary + +| Term | Definition | +| ---- | ---------- | +| **`.bss`** | Section for uninitialized (or zero-initialized) static/global variables; zeroed by startup code | +| **`.data`** | Section for initialized static/global variables; copied from flash to SRAM at boot | +| **`.elf`** | Linked image with the symbol table; the ground truth for addresses and names | +| **`.rodata`** | Read-only section for constants and string literals; stays in flash | +| **Automatic variable** | A local variable created and destroyed with its block; lives on the stack (or is optimized away) | +| **`eor` / XOR** | Exclusive OR — flips bits where the operands differ | +| **GPIO** | General Purpose Input/Output — controllable pins on the microcontroller | +| **Hardware breakpoint** | A breakpoint serviced by the CPU comparators, required for read-only flash | +| **Inlining** | The optimizer replacing a function call with the function body; why `demo_static_variable` disappears | +| **Literal pool** | A block of 32-bit constants that Thumb-2 code reaches with PC-relative `ldr` | +| **MMIO** | Memory-mapped I/O — hardware registers accessed as memory addresses | +| **Pull-up / pull-down** | A resistor that holds an input pin at a defined level when nothing drives it | +| **SIO** | Single-cycle I/O — the fast GPIO block in the RP2350, at `0xd0000000` | +| **Static variable** | A variable with static storage duration; persists for the whole program and keeps a fixed address | +| **Ternary operator** | `condition ? value_if_true : value_if_false` | +| **Thumb bit** | Bit 0 of a Cortex-M function pointer; selects Thumb instruction mode | +| **`ubfx`** | Unsigned Bit Field Extract — pulls a bit field out of a register | +| **UF2** | USB Flashing Format — the file format the Pico 2 bootloader accepts | +| **Vector table** | The first words of flash: initial stack pointer and exception vectors | + +--- + +**Remember:** the ELF tells you what every address is, and the `.bin` is what you actually patch. Prove the behavior dynamically, read `r1` at the `printf` call, resolve the names from the ELF, then patch the bytes — the constant `42`, the inversion immediate, and (optionally) the label — and flash. diff --git a/WEEK06/WEEK06-IDA.pdf b/WEEK06/WEEK06-IDA.pdf new file mode 100644 index 0000000..64ca2fe Binary files /dev/null and b/WEEK06/WEEK06-IDA.pdf differ diff --git a/WEEK07/WEEK07-IDA.md b/WEEK07/WEEK07-IDA.md new file mode 100644 index 0000000..c55f816 --- /dev/null +++ b/WEEK07/WEEK07-IDA.md @@ -0,0 +1,1499 @@ +# Week 7-IDA: IDA Pro — Read, Hack, and Patch Constants and a 1602 LCD String (Raw `.bin`) + +*** + +**LEGAL DISCLAIMER:** +The information, tools, and code provided in this repository and course are strictly for educational, research, and defensive purposes only. + +You are explicitly prohibited from using any materials contained herein to access, test, modify, or exploit any device, network, or system that you do not own 100% or for which you do not have explicit, documented, and legally binding authorization to interact with. + +By using this repository and course, you acknowledge and agree that: + +1. Any illegal, unauthorized, or malicious use of this information is solely your responsibility. +2. The author(s) and contributor(s) of this repository and course shall not be held liable for any damages, legal repercussions, criminal charges, or unauthorized actions resulting from the use, misuse, or abuse of the contents herein. +3. You will comply with all applicable local, state, national, and international laws regarding cybersecurity and computer fraud. + +**IF YOU DO NOT AGREE WITH THESE TERMS, DO NOT USE THIS REPOSITORY AND COURSE.** + +*** + +## What You'll Learn This Week + +- Build the lesson project with `Release` and get both an `.elf` and a raw `.bin` +- Dump the **ELF symbol map** with `arm-none-eabi-nm` and use it as ground truth +- Load the raw `.bin` into IDA at `0x10000000` +- Read how a `#define` macro **and** a `const` variable both fold to bare instruction immediates +- Tell a 16-bit `movs r1, #42` from a 32-bit `movw r1, #1337` in the disassembly +- Follow the I2C path through the `i2c_inst_t` struct: `I2C_PORT` -> `i2c1` -> `&i2c1_inst` -> `hw` -> `0x40098000` +- **Break at the `printf` call** on live silicon and hack the printed constant live +- Optionally **hack the LCD string live** by pointing `r0` at a RAM replacement +- **Resolve the functions in the IDA GUI** using the ELF symbol map, including the `lcd_1602.c` driver symbols +- **Patch** both constants (`42 -> 43`, `1337 -> 1344`) and the LCD string (`"Reverse" -> "Exploit"`) +- **Export** the patched image, convert it to UF2, and flash it + +--- + +## How This Guide Works + +The build produces two files for the project: + +| File | What it is | How we use it | +| ---- | ---------- | ------------- | +| `.elf` | The linked image with a full symbol table | Ground truth for every function address and name | +| `.bin` | The raw flash image, no headers, no symbols | The image we load into IDA and reverse | + +The `.bin` is built **from** the `.elf`, so the ELF tells you exactly what is at every address. We use the ELF symbol map to resolve functions in IDA, and we reverse-engineer the raw `.bin` the way a real extracted firmware image is reversed. + +> **Build `Release`, not `Debug`.** Every address in this guide matches the Week 7 lesson, and the Week 7 lesson is a `Release` build. `Release` optimizes the code the same way the original lesson was built: it **inlines** the `static` helpers `init_i2c_and_lcd` and `write_lcd_greeting` (and the whole `lcd_1602.c` static helper chain) straight into `main` or into the public `lcd_*` functions, and it folds both `FAV_NUM` and `OTHER_FAV_NUM` down to immediate values. If you build `Debug`, the SDK function addresses move and the helpers stay separate calls, so nothing lines up. Always build `Release` for this lesson. + +The order is **dynamic first, static second**: + +1. Break on the live target and prove what the code does. +2. Hack it live in the debugger and watch the output change. +3. Resolve the functions in IDA using the ELF symbol map. +4. Patch the bytes, export, convert, and flash. + +| Project | Serial output | Also does | The hacks | +| ------- | ------------- | --------- | --------- | +| `0x0017_constants` | `FAV_NUM: 42`, `OTHER_FAV_NUM: 1337` | I2C1 (SDA GP2, SCL GP3) drives a 1602 LCD, writing `Reverse` / `Engineering` | `42 -> 43`, `1337 -> 1344`, and `"Reverse" -> "Exploit"` | + +> **Addresses come from your build.** Every address here is from the `Release` build produced in Step 3. Confirm against your own `.elf` with the command in Step 4. + +> **The surprise of this week is that `const` is not in memory.** `#define FAV_NUM 42` becomes the 16-bit `movs r1, #42`; `const int OTHER_FAV_NUM = 1337` *also* becomes an immediate, the 32-bit `movw r1, #1337`. The compiler only keeps a `const` in `.rodata` if the program **takes its address** (`&OTHER_FAV_NUM`); this program never does, so the `const` is inlined exactly like the macro. You patch an instruction operand, not a data word. + +--- + +## Part 1: Build, Flash, and Get the Symbol Map + +### Step 1: Install the toolchain + +**Windows x64** + +- Install the **Raspberry Pi Pico** extension in VS Code. It installs the ARM GNU toolchain, CMake, Ninja, and the Pico SDK. +- Install **IDA Pro** and complete its license activation. +- Install **PuTTY** for the serial monitor. + +**macOS Apple Silicon** + +```bash +brew install cmake ninja +``` + +- Install **IDA Pro** and complete its license activation. +- Install the **Arm GNU Toolchain**, or let the VS Code Pico extension manage it. + +**Linux x64** + +```bash +sudo apt install cmake ninja-build gcc-arm-none-eabi libnewlib-arm-none-eabi git python3 openocd minicom +``` + +- Install **IDA Pro** and complete its license activation. + +### Step 2: Verify your tools are the right architecture (do not skip this) + +On **macOS Apple Silicon**, the most common failure is an Intel `x86_64` tool on your `PATH`: + +``` +zsh: bad CPU type in executable: cmake +``` + +You may have **two Homebrews**: the arm64 one at `/opt/homebrew` and the Intel one at `/usr/local`. If `/usr/local/bin` wins, every `brew` tool is x86_64. Check: + +```bash +file "$(which cmake)" +file "$(which ninja)" +file "$(which arm-none-eabi-gdb)" +file "$(which arm-none-eabi-nm)" +file "$(which openocd)" +file "$(which telnet)" +``` + +All must report `arm64`. If any is `x86_64`, put the Apple Silicon prefix first for the session and check again: + +```bash +export PATH="/opt/homebrew/bin:$PATH" +hash -r +file "$(which cmake)" +``` + +To make it permanent, add that `export` to `~/.zshrc`. Do not use Rosetta as a fix; OpenOCD and GDB are exactly the kind of programs where a translation layer produces failures that look like debugger bugs. + +**`telnet` is special — and optional.** The GDB MI workflow does not need it; it is only used by the command-port fallback. macOS no longer ships `telnet`, and the Homebrew build is often the Intel one, so `telnet 127.0.0.1 4444` fails with `bad CPU type in executable`. Call the Apple Silicon Homebrew explicitly: + +```bash +/opt/homebrew/bin/brew install telnet +``` + +If you would rather not install anything, macOS ships an arm64 `nc`, which can connect to the same OpenOCD port: + +```bash +nc 127.0.0.1 4444 +``` + +**Windows x64** and **Linux x64** do not have this problem. Skip to Step 3. + +### Step 3: Build the project with `Release` + +Run this inside `0x0017_constants/`: + +```bash +cmake -B build -G Ninja -DPICO_BOARD=pico2 -DPICO_PLATFORM=rp2350 -DCMAKE_BUILD_TYPE=Release +cmake --build build +``` + +**Point IDA at this repository (once).** Every console snippet below reads the repo root from `~/.embedded-hacking-repo`, so IDA never needs a database open and nothing is hardcoded. From the repo root, run once: + +**macOS / Linux:** + +```bash +pwd > ~/.embedded-hacking-repo +``` + +**Windows (PowerShell):** + +```powershell +(Get-Location).Path | Set-Content "$env:USERPROFILE\.embedded-hacking-repo" +``` + +**Then build from the IDA console**, so the whole build -> patch -> flash loop stays inside IDA. The console inherits a minimal `PATH` — on macOS just `/usr/bin:/bin:/usr/sbin:/sbin` — so it does not see Homebrew; add your package manager's `bin` first, then run plain `cmake`. + +**macOS Apple Silicon:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() +os.environ["PATH"] = "/opt/homebrew/bin:" + os.environ["PATH"] # the console's PATH omits Homebrew +proj = os.path.join(root, "0x0017_constants") +subprocess.run(["cmake", "-B", "build", "-G", "Ninja", "-DPICO_BOARD=pico2", + "-DPICO_PLATFORM=rp2350", "-DCMAKE_BUILD_TYPE=Release"], cwd=proj) +subprocess.run(["cmake", "--build", "build"], cwd=proj) +``` + +**Linux x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() +proj = os.path.join(root, "0x0017_constants") +subprocess.run(["cmake", "-B", "build", "-G", "Ninja", "-DPICO_BOARD=pico2", + "-DPICO_PLATFORM=rp2350", "-DCMAKE_BUILD_TYPE=Release"], cwd=proj) +subprocess.run(["cmake", "--build", "build"], cwd=proj) +``` + +**Windows x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() +proj = os.path.join(root, "0x0017_constants") +subprocess.run(["cmake", "-B", "build", "-G", "Ninja", "-DPICO_BOARD=pico2", + "-DPICO_PLATFORM=rp2350", "-DCMAKE_BUILD_TYPE=Release"], cwd=proj) +subprocess.run(["cmake", "--build", "build"], cwd=proj) +``` + +The build directory now contains the pair we need: + +- `0x0017_constants/build/0x0017_constants.elf` and `.bin` — the `.bin` is **17980** bytes (`0x463c`) + +If the ARM toolchain is not on your `PATH`, add `-DPICO_TOOLCHAIN_PATH=...`: + +| OS | Typical toolchain path | +| -- | ---------------------- | +| Windows x64 | `C:/Program Files/Arm GNU Toolchain arm-none-eabi/14.2 rel1/bin` | +| macOS Apple Silicon | `~/.pico-sdk/toolchain/14_2_Rel1/bin` | +| Linux x64 | `/usr` | + +> **This guide's toolchain lives at `~/.pico-sdk/toolchain/14_2_Rel1/bin`.** All of `arm-none-eabi-nm`, `arm-none-eabi-objdump`, and `arm-none-eabi-gdb` resolved in this document come from there. If your install is elsewhere, `which arm-none-eabi-nm` tells you where to point. + +### Step 4: Dump the ELF symbol map + +This is the ground truth for the whole lesson. Run `arm-none-eabi-nm` on the ELF and keep the output in a terminal or a text file: + +**macOS Apple Silicon / Linux x64:** + +```bash +arm-none-eabi-nm -n --defined-only build/0x0017_constants.elf | grep -E ' [Tt] ' +``` + +**Windows x64:** + +```powershell +arm-none-eabi-nm -n --defined-only build\0x0017_constants.elf | Select-String ' [Tt] ' +``` + +Each line is `address type name`. The `T`/`t` type is a function. Here are the functions this lesson uses. The signatures come from the ELF's DWARF debug info queried with `arm-none-eabi-gdb -batch -ex "ptype "`, so they are exact. + +**Our code and the startup chain:** + +| Address | ELF symbol | Signature | Role | +| ------- | ---------- | --------- | ---- | +| `0x1000015c` | `_reset_handler` | `void _reset_handler(void)` | reset entry | +| `0x10000186` | `platform_entry` | `void platform_entry(void)` | calls `runtime_init`, `main`, `exit` | +| `0x1000019a` | `data_cpy` | `void data_cpy(void*, void*, void*)` | copies `.data` from flash to SRAM | +| `0x100001e4` | `_init` | `void _init(void)` | runs `.init_array` | +| `0x10000210` | `frame_dummy` | `void frame_dummy(void)` | C runtime boilerplate | +| `0x10000234` | `main` | `int main(void)` | the lesson function (`init_i2c_and_lcd` and `write_lcd_greeting` inlined) | + +**Our I2C/LCD driver (`lcd_1602.c`) and the SDK I2C functions `main` reaches:** + +| Address | ELF symbol | Signature | Role | +| ------- | ---------- | --------- | ---- | +| `0x100002bc` | `lcd_i2c_init` | `void lcd_i2c_init(i2c_inst_t*, uint8_t, int, uint8_t)` | store config + HD44780 reset/configure | +| `0x100006f4` | `lcd_set_cursor` | `void lcd_set_cursor(int, int)` | move the HD44780 cursor | +| `0x100007f0` | `lcd_puts` | `void lcd_puts(const char*)` | write a string to the LCD | +| `0x10003cdc` | `i2c_init` | `uint i2c_init(i2c_inst_t*, uint)` | SDK I2C init (100 kHz) | +| `0x10003d28` | `i2c_write_blocking` | `int i2c_write_blocking(i2c_inst_t*, uint8_t, const uint8_t*, size_t, bool)` | one blocking I2C transfer | +| `0x100008f0` | `gpio_set_function` | `void gpio_set_function(uint, gpio_function_t)` | SDK GPIO function select (I2C pins) | +| `0x1000092c` | `gpio_set_pulls` | `void gpio_set_pulls(uint, bool, bool)` | SDK pull config (`gpio_pull_up` inlined) | + +> The `lcd_1602.c` static helpers — `pcf_write_byte`, `pcf_pulse_enable`, `lcd_write4`, `lcd_send`, `lcd_store_config`, `lcd_hd44780_reset`, `lcd_hd44780_configure` — have **no symbol of their own** in the `Release` build. They are inlined into `lcd_i2c_init`, `lcd_set_cursor`, and `lcd_puts`, which is why those three functions are large and call `i2c_write_blocking` and the `sleep_*` helpers directly. + +**The stdio/UART and printf chain `main` reaches:** + +| Address | ELF symbol | Signature | Role | +| ------- | ---------- | --------- | ---- | +| `0x10001368` | `sleep_us` | `void sleep_us(uint64_t)` | SDK microsecond delay | +| `0x10001440` | `sleep_ms` | `void sleep_ms(uint32_t)` | SDK millisecond delay | +| `0x10001624` | `time_us_64` | `uint64_t time_us_64(void)` | SDK microsecond clock | +| `0x10001638` | `busy_wait_us` | `void busy_wait_us(uint64_t)` | UART timing loop | +| `0x100016b8` | `uart_init` | `uint uart_init(uart_inst_t*, uint)` | SDK UART init | +| `0x1000188c` | `clock_get_hz` | `unsigned long clock_get_hz(clock_handle_t)` | UART clock lookup | +| `0x100035a4` | `exit` | `void exit(int)` | C runtime exit | +| `0x100035ac` | `runtime_init` | `void runtime_init(void)` | SDK runtime init | +| `0x100035d8` | `stdio_out_chars_crlf` | `void stdio_out_chars_crlf(stdio_driver_t*, const char*, int)` | CRLF output driver | +| `0x100036e8` | `stdio_put_string` | `int stdio_put_string(const char*, int, bool, bool)` | buffered string output | +| `0x100037d4` | `stdio_set_driver_enabled` | `void stdio_set_driver_enabled(stdio_driver_t*, bool)` | enable the UART driver | +| `0x100037fc` | `stdio_init_all` | `bool stdio_init_all(void)` | SDK serial init | +| `0x100038c8` | `__wrap_vprintf` | `int __wrap_vprintf(const char*, va_list)` | printf core | +| `0x1000398c` | `__wrap_printf` | `int __wrap_printf(const char*, ...)` | the `printf` wrapper | +| `0x10003b48` | `stdio_uart_init` | `void stdio_uart_init(void)` | SDK UART stdio init | +| `0x10003e24` | `strlen` | `size_t strlen(const char*)` | C runtime string length | + +**SDK helpers the `printf` path reaches:** + +| Address | ELF symbol | Signature | Role | +| ------- | ---------- | --------- | ---- | +| `0x10003548` | `vfctprintf` | `int vfctprintf(void (*)(char, void*), void*, const char*, va_list)` | printf format engine | +| `0x10002b64` | `_vsnprintf` | `int _vsnprintf(out_fct_type, char*, size_t, const char*, va_list)` | the format dispatcher | +| `0x10001f48` | `_ntoa_format` | `unsigned _ntoa_format(out_fct_type, char*, size_t, size_t, char*, size_t, bool, unsigned, unsigned, unsigned, unsigned)` | number formatter | +| `0x10001eac` | `_out_rev` | `unsigned _out_rev(out_fct_type, char*, size_t, size_t, const char*, size_t, unsigned, unsigned)` | reversed-digit output | +| `0x1000211c` | `_out_char` | `void _out_char(char, void*, size_t, size_t)` | single-char sink | + +Two things in this project have **no symbol of their own**, because the compiler inlined them into `main`: + +- `init_i2c_and_lcd` and `write_lcd_greeting` — the two `static` helpers in our own source are inlined, so there is no address to rename. You see their bodies directly inside `main`. +- `gpio_pull_up` — `static inline` in the SDK, so `gpio_pull_up(2)` and `gpio_pull_up(3)` compile to direct calls to `gpio_set_pulls` at `0x10000258` and `0x10000262`. + +### Step 5: Flash and confirm the output + +A `.bin` has no headers, so OpenOCD must be told the base address `0x10000000`. From the repository root: + +**macOS Apple Silicon / Linux x64:** + +```bash +./flash.sh 0x0017_constants/build/0x0017_constants.bin +``` + +**Windows x64 (PowerShell):** + +```powershell +.\flash.ps1 -Bin 0x0017_constants\build\0x0017_constants.bin +``` + +**Or flash from the IDA console** (the console reads the repo root from the marker file, so it works with no database open): + +**macOS Apple Silicon / Linux x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) +bin_path = os.path.join(root, "0x0017_constants", "build", "0x0017_constants.bin") +log = os.path.join(os.path.dirname(bin_path), "flash.log") +subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # free the probe first +subprocess.Popen([os.path.join(root, "flash.sh"), bin_path], + stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) +print("flashing in the background; log:", log) +``` + +**Windows x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) +bin_path = os.path.join(root, "0x0017_constants", "build", "0x0017_constants.bin") +log = os.path.join(os.path.dirname(bin_path), "flash.log") +subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"]) # free the probe first +subprocess.Popen(["powershell", "-ExecutionPolicy", "Bypass", "-File", + os.path.join(root, "flash.ps1"), "-Bin", bin_path], + stdout=open(log, "w"), stderr=subprocess.STDOUT) +print("flashing in the background; log:", log) +``` + +Wait for `wrote 17980 bytes ...` and `** Verified OK **`. Open a serial monitor at **115200** baud: + +- **Windows x64:** PuTTY -> Connection type **Serial**, the Pico's COM port, speed `115200`. +- **macOS Apple Silicon:** `screen /dev/tty.usbmodem* 115200` (quit with `Ctrl-A` then `K`). +- **Linux x64:** `minicom -D /dev/ttyACM0 -b 115200`. + +``` +FAV_NUM: 42 +OTHER_FAV_NUM: 1337 +FAV_NUM: 42 +OTHER_FAV_NUM: 1337 +... +``` + +The 1602 LCD shows `Reverse` on line 1 and `Engineering` on line 2. Both numbers print forever, because both constants are baked into the loop as immediates. That is the behavior we will change. + +--- + +## Part 2: Load the Raw `.bin` into IDA + +Start from a fresh IDA state. If you already have a database for this lesson, **close it and start over**; a stale database keeps old names and patches. + +### Step 7: Bring the raw `.bin` into IDA + +A raw `.bin` has no headers, so IDA cannot know where it belongs or what architecture it is. You must supply both. If you just double-click the `.bin`, IDA may load it with a guessed architecture, and every address in this lesson will be wrong. + +#### 1.1 Open the file +1. **File ▸ Open…** (Ctrl/Cmd+O). +2. Select the `.bin` file and click **Open**. + +IDA opens the **"Load a new file"** dialog because a raw `.bin` has no header. + +#### 1.2 Set the format and processor +In the *Load a new file* dialog: +1. **Format**: leave it as **Binary file** (IDA auto-detects a headerless image). +2. **Processor type**: click the **…** button next to the processor field. In the *Processor type* dialog: + - Family: **ARM** + - Type: **ARM Little-endian** (the 32-bit ARM module). + - Click **OK**. + +> If IDA asks **"Do you want to disassemble it as 64-bit code?"** — click **No**. +> The RP2350 is 32-bit; answering *Yes* loads AArch64 and you get `X` registers / data. (This is the single most common cause of the `DCB` wall.) + +#### 1.3 Configure the ARM architecture and Thumb mode +Still in the *Load a new file* dialog, open the processor options (the **Processor options** / **Set…** button, which opens the dialog titled **ARM architecture options**): +- **ARM architecture**: choose **ARMv8-M** (this is the Cortex-M33 / RP2350 core). +- **Thumb instructions**: select **Thumb-2** (ARMv8-M is Thumb-only, so this is the correct mode). +- Leave **automatic ARM-THUMB switch** off; we want Thumb throughout. + +#### 1.4 Set the loading address +- **Loading address**: enter **`10000000`** (hex; the RP2350 XIP flash base). + IDA rejects addresses that don't look like ROM/RAM with *"The loading address should belong to RAM or ROM"* — `0x10000000` is the correct flash window. + +Leave **Manual load** and **Create segments** at their defaults. Click **OK**. + +#### 1.5 Force Thumb, then seed the code from the vector table +A raw `.bin` has no header, so IDA's loader has **no entry point** and defaults the segment to **ARM mode** (which cannot decode Thumb). Two required steps — in this order: + +**A. Set the segment to Thumb (do this first).** +- **Edit ▸ Segments ▸ Set default segment register value…** → register **`T`** = **`1`** (or press **`Alt+G`**). IDA reanalyzes the segment as Thumb automatically. + +**B. Seed the code from the vector table.** +1. **G** → `10000000`. The first two words are the initial stack pointer and the **reset vector**. +2. **Read the 4-byte word at `0x10000004`** (do **not** assume its value — it differs per build). +3. **Clear bit 0** (the ARM **Thumb** flag) → the reset handler address. +4. **G** to that address → press **C** (**MakeCode**). IDA disassembles the reset handler and follows its `bl`s into `main`. + +Once `main` shows code, the import is correct. + +**Why IDA needs this and others don't:** IDA's generic raw-binary ARM loader treats the image as flat data and waits for you to set Thumb and mark the entry point. It's an IDA quirk, not a mistake on your part. + +### Step 8: The views you will use + +- **Linear view:** the disassembly listing. You navigate, read, and patch here. +- **Graph view:** the control-flow graph of the current function. +- **Decompiler (HLIL):** the pseudo-C decompilation. +- **Hex view:** raw bytes, used for patching. +- **Function list:** the sidebar list of every detected function. + +Navigation: `G` go to address, `N` rename, `Y` set type or signature, `;` add a comment. Breakpoints are set from the GUI through the GDB MI adapter — see Step 12. + +> **macOS function keys:** the top-row `F` keys are usually mapped to system functions. Every step here uses menu paths that work without them. + +--- + +## Part 3: Dynamic — Break at the `printf` Call and Hack Live + +### Step 9: Start OpenOCD as a live debug server + +Make sure no other OpenOCD is running; a forgotten server holds port `3333`. + +**macOS / Linux:** + +```bash +ps aux | grep -i openocd +``` + +**Windows (PowerShell):** + +```powershell +Get-Process | Where-Object { $_.ProcessName -like '*openocd*' } +``` + +Stop any leftover server gracefully: + +**macOS / Linux:** + +```bash +pkill -TERM -f openocd +``` + +**Windows (PowerShell):** + +```powershell +Get-Process openocd -ErrorAction SilentlyContinue | Stop-Process +``` + +Start the server **parked at `main`**: + +**macOS Apple Silicon / Linux x64:** + +```bash +BP_ADDR=0x10000234 ./debug-server.sh +``` + +**Windows x64 (PowerShell):** + +```powershell +$env:BP_ADDR="0x10000234"; .\debug-server.ps1 +``` + +**Or start it from the IDA console**, freeing the probe first and launching the server in the background so the console returns immediately: + +**macOS Apple Silicon / Linux x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) +subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # stop any running server first +log = os.path.join(root, "openocd.log") +p = subprocess.Popen([os.path.join(root, "debug-server.sh")], cwd=root, + env=dict(os.environ, BP_ADDR="0x10000234"), + stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) +print("OpenOCD started (pid", p.pid, "); log:", log) +``` + +**Windows x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) +subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"]) # stop any running server first +log = os.path.join(root, "openocd.log") +p = subprocess.Popen(["powershell", "-ExecutionPolicy", "Bypass", "-File", + os.path.join(root, "debug-server.ps1")], cwd=root, + env=dict(os.environ, BP_ADDR="0x10000234"), + stdout=open(log, "w"), stderr=subprocess.STDOUT) +print("OpenOCD started (pid", p.pid, "); log:", log) +``` + +`Popen` returns in a few milliseconds; the server keeps running in the background. Check `openocd.log` for `Listening on port 3333`, then connect in Step 10. + +Wait for: + +``` +Info : [rp2350.dap.core0] Examination succeed +Startup breakpoint at 0x10000234 (2-byte hardware execute, one-shot). +Info : starting gdb server for rp2350.dap.core0 on 3333 +Info : Listening on port 3333 for gdb connections +``` + +> **`BP_ADDR` parks the core at `main` before any client connects.** The script arms a 2-byte hardware breakpoint and then does the startup `reset run`, so the core runs from the vector table and stops at your address with no debugger attached yet. When IDA connects a moment later, the first thing it reads is already the truth: `Stopped at 0x10000234`. This is the whole reason the lab works cleanly — you never have to drive a reset from outside the GUI. +> +> Use the address you actually want to stop at: +> +> | What you want to stop at | Address | Command | +> | --- | --- | --- | +> | `main` (once per reset) | `0x10000234` | `BP_ADDR=0x10000234 ./debug-server.sh` | +> | The **loop** — the `FAV_NUM` `printf` call, hit every iteration | `0x10000292` | `BP_ADDR=0x10000292 ./debug-server.sh` | +> +> ```bash +> BP_ADDR=0x10000234 ./debug-server.sh # park at main +> BP_ADDR=0x10000292 ./debug-server.sh # park in the loop instead +> ``` +> +> ```powershell +> $env:BP_ADDR="0x10000234"; .\debug-server.ps1 # park at main +> $env:BP_ADDR="0x10000292"; .\debug-server.ps1 # park in the loop +> ``` +> +> **This startup stop is single-use.** OpenOCD flushes breakpoints when a client connects, so this one is gone once IDA attaches — fine for `main`, which only runs once per reset. Every breakpoint after that is set from the IDA GUI (Step 12) and is repeatable. To stop at `main` again, restart the server with `BP_ADDR` and reconnect. + +> **Exactly one core.** The line must say `core0` and must **not** mention `core1`. Core1 is never started by this firmware; exposing it makes IDA read core1's reset-state registers, which are not real addresses, and OpenOCD floods the log with `Failed to read memory at 0xf0000000`. The scripts already use `USE_CORE=0`; do not change it. + +> **Windows driver note:** the Debug Probe must use the **WinUSB** driver. If OpenOCD reports `unable to open CMSIS-DAP device`, install it with [Zadig](https://zadig.akeo.ie/) (select `Debug Probe (CMSIS-DAP)` -> WinUSB). + +### Step 10: Connect IDA to the GDB server + +1. Make sure the image is open and analyzed (Part 2) and the server from Step 9 is running (parked at `main`). +2. Choose `Debugger -> Connect to Remote Process`. +3. In the **adapter** dropdown, select **GDB MI**. +4. In the **connect** settings group, set **IP Address** to `127.0.0.1` and **Port** to `3333`. +5. Set **Full GDB Executable Path** to the `arm-none-eabi-gdb` from the **Arm GNU Toolchain 14.2.rel1**. It ships for all three hosts, and the Raspberry Pi Pico VS Code extension installs that same 14.2.rel1 toolchain (including `arm-none-eabi-gdb`) on all of them: + + | OS | `arm-none-eabi-gdb` path | + | -- | ------------------------ | + | macOS Apple Silicon | `/Applications/ArmGNUToolchain/14.2.rel1/arm-none-eabi/bin/arm-none-eabi-gdb` (or the Pico extension's `~/.pico-sdk/toolchain/14_2_Rel1/bin/arm-none-eabi-gdb`) | + | Windows x64 | `%USERPROFILE%\.pico-sdk\toolchain\14_2_Rel1\bin\arm-none-eabi-gdb.exe` (Pico extension), or `C:\Program Files (x86)\Arm GNU Toolchain arm-none-eabi\14.2 rel1\bin\arm-none-eabi-gdb.exe` | + | Linux x64 | `~/.pico-sdk/toolchain/14_2_Rel1/bin/arm-none-eabi-gdb` (Pico extension), or the `bin/` directory of the extracted `arm-gnu-toolchain-14.2.rel1-x86_64-arm-none-eabi` tarball | +6. Click **Accept**. + +> **Use the GDB MI adapter.** It launches a real `arm-none-eabi-gdb --interpreter=mi2` and lets IDA drive it, so breakpoints and stepping go through real GDB — which sends the correct 2-byte breakpoint length and handles step-over itself. Verified working end to end: connect, GUI breakpoints (**Add Hardware Breakpoint...**, hardware execute), **Step Into** / **Step Over**, and register edits. Stops are reported as `Breakpoint` (not `SingleStep`). +> +> **Do NOT have any breakpoints set in IDA before you connect.** With the GDB MI adapter, attaching while IDA already has a breakpoint **hangs the session**. Start the server parked with `BP_ADDR` (Step 9), connect, and only add hardware breakpoints *after* the connection is up. This is a IDA bug; it is the single most common GDB MI failure. +> +> **The GDB executable path matters.** Use the **14.2.rel1** build on every OS (Windows, macOS, Linux). The 13.3.rel1 build did **not** connect in testing. +> +> **This step is temporary.** Vector35 plans to ship a GDB binary with the GDB MI adapter ([Vector35/debugger#929](https://github.com/Vector35/debugger/issues/929), milestone *Langara*). Once that lands, IDA provides GDB itself and you will not need to set **Full GDB Executable Path** at all. +> +> **Do not pick Corellium.** IDA's adapter dropdown also lists **Corellium**, which is for Corellium's virtual devices and expects an API token, not a local OpenOCD server. It is not the adapter for this lab. The dropdown is a combo box, so an accidental arrow-key press can land on it — always read the label back and confirm it says **GDB MI** before clicking **Accept**. + +> **The adapter and port are not saved in the `.i64`.** Every time you relaunch IDA you must re-select **GDB MI**, re-enter port `3333`, and re-set the GDB path. + +> **Watch for an off-screen error dialog.** When a connection fails, IDA pops a `IDA critical alert` window that can be positioned mostly outside the main window, which makes it look like nothing happened. If the connect seems to do nothing, check your other display. + +The target keeps running. Open the **Registers** tab (bug icon) and confirm you see live values. `pc` inside `0x10003xxx` and `sp` just below `0x20082000` are healthy. + +> **If `pc` is `0x00000088`, `0x000000ec`, or `sp` is `0xf0000000`, the session is bad.** Restart the server, then restart IDA (a server restart while attached leaves IDA in a stale session), and connect again. + +### Step 11: Find `main` without relying on its address + +`main` can move between programs, so we do not guess it. We follow the one fixed path to it. Press `G` and go to `0x10000000`: + +``` +0x10000000 0x20082000 initial stack pointer (top of SRAM) +0x10000004 0x1000015d reset vector +``` + +Bit 0 of a vector is the Thumb bit, so `0x1000015d` means "start at `0x1000015c`". That is `_reset_handler`. Follow the reset path to `0x10000186`, `platform_entry`: + +```asm +10000186: ldr r1, [pc, #80] @ (100001d8 ) +10000188: blx r1 +1000018a: ldr r1, [pc, #80] @ (100001dc ) +1000018c: blx r1 +1000018e: ldr r1, [pc, #80] @ (100001e0 ) +10000190: blx r1 +10000192: bkpt 0x0000 +10000194: b.n 10000192 @ +``` + +**The middle `blx` at `0x1000018c` is the call to `main`.** `platform_entry` is byte-identical in every project, so `0x1000018c` catches `main` no matter where the linker placed it. The literal pool at `0x100001dc` holds `main | 1`; clearing bit 0 gives `0x10000234`. + +### Step 12: Set a hardware breakpoint in the GUI + +With the **GDB MI** adapter, IDA sets breakpoints through real GDB, which sends the correct 2-byte length, so you set them **in the UI**. There is no command port here. + +> **Why older drafts used the command port.** IDA's **GDB RSP** adapter is its own minimal RSP client and sends a **1-byte** breakpoint (`Z0,,1`); the Cortex-M33 FPB comparators need 2 bytes, so OpenOCD rejected it with `only breakpoints of two bytes length supported`. The old workaround was to arm breakpoints by hand over telnet. **The GDB MI adapter does not have this problem** — it drives real `arm-none-eabi-gdb`, which sends the right length. So everything below is done in the GUI. The command port still exists as a fallback (see the end of this step), but you do not need it. + +#### Where you can stop + +| You want to stop at | Address | How | Repeatable? | +| --- | --- | --- | --- | +| **`main`** | `0x10000234` | The server starts parked there with `BP_ADDR=0x10000234` (Step 9), so IDA is already stopped at `main` when it connects. | No — `main` runs once per reset. | +| **The `FAV_NUM` `printf` call** | `0x10000292` | Set a hardware breakpoint in the GUI, then click **Resume**. | Yes — fires on every iteration. | +| **The `OTHER_FAV_NUM` `printf` call** | `0x1000029c` | Set a hardware breakpoint in the GUI, then click **Resume**. | Yes — fires on every iteration. | +| **The `lcd_puts("Reverse")` call** | `0x1000027c` | Set a hardware breakpoint while stopped at `main`, then click **Resume**. | No — the LCD is written once at init. | + +#### Set the loop breakpoint in the GUI + +1. Press `G`, type the loop address (`0x10000292`), and press Enter. +2. Set a **hardware execution** breakpoint at that address, either way: + - `Debugger -> Add Hardware Breakpoint...` — a **hardware execute** (`HE`) breakpoint. **Use this one.** + - click the line and press `F2` (`Debugger -> Toggle Breakpoint`) — a **software** breakpoint. It will **not** work here: the code is in read-only flash, so GDB cannot install it and the core just keeps running. +3. Click **Resume**. The core is already running the loop, so the breakpoint fires on the next iteration. IDA stops with the PC at the loop address and reports it as a **Breakpoint** — verified: `Stopped (Breakpoint) at 0x10000292`. + +> **No breakpoints before you connect.** With GDB MI, a breakpoint set before the connection hangs the session (Step 10). Start parked with `BP_ADDR`, connect, *then* add breakpoints. + +#### Stepping + +With the target halted at the breakpoint, **Step Into** (`F7`) and **Step Over** (`F8`) run through real GDB and move the PC. Verified: `0x10000292 -> 0x1000398c -> 0x1000398e -> ...`. + +> **Step Over on the raw `.bin` steps *into* calls.** The raw image has no symbol for `__wrap_printf`, so **Step Over** at the `printf` call behaves like **Step Into**. When the lab needs to execute the call and then stop, it moves the breakpoint to the return site and clicks **Resume** instead (Step 13 shows this). + +> **Never use IDA's Restart button.** On RP2350 it resets and halts inside the boot ROM (`pc=0x88`, `sp=0xf0000000`). To reset cleanly, restart the server with `BP_ADDR` and reconnect. + +> **If you ever need the command port.** It is still there — `nc 127.0.0.1 4444`, and `bp 2 hw` still arms a breakpoint, `rbp ` / `rbp all` still remove them. It is the fallback if you switch back to the **GDB RSP** adapter, whose 1-byte breakpoints the GUI cannot set. With GDB MI you do not need it for this lab. + +### Step 13: HACK IT LIVE — change the printed `FAV_NUM` + +`main` loads the `#define` `0x2a` (42) into `r1` and calls `printf` on every iteration. We break on that call and change it live: + +```asm +1000028e: movs r1, #42 @ 0x2a +10000290: ldr r0, [pc, #32] @ (100002b4 ) +10000292: bl 1000398c @ <__wrap_printf> +10000296: movw r1, #1337 @ 0x539 +1000029a: ldr r0, [pc, #28] @ (100002b8 ) +1000029c: bl 1000398c @ <__wrap_printf> +100002a0: b.n 1000028e @ +``` + +1. Press `G`, go to `0x10000292` (the `bl __wrap_printf` for `FAV_NUM`). +2. Set a **hardware execute** breakpoint there: `Debugger -> Add Hardware Breakpoint...`. (Do not use `F2` — that is a software breakpoint and will not work on read-only flash.) +3. Click **Resume** in IDA. The target is already running the loop, so the breakpoint fires on the next iteration. IDA stops with the program counter at `0x10000292` and `r1 = 0x2a`. +4. Open the **Registers** widget (bug icon -> **Registers**). +5. Find `r1`. Its value is `0x2a` (42), loaded by the `movs r1, #42` at `0x1000028e`. +6. **Set `r1` to `0x2b` (43).** From IDA's Python console (`Plugins -> Python Console`): + ```python + dbg.set_reg_value("r1", 0x2b) + ``` + `dbg.set_reg_value(name, value)` writes one register (returns `True` on success). You can also right-click `r1` in the **Registers** widget, press `E` (edit), type `2b`, and press Enter. The widget may not repaint the value, but the write reaches the target — you confirm it by the printed output in the next steps. +7. **Move the breakpoint past the call.** You want `printf` to run once and then stop, so move the breakpoint from `0x10000292` to the instruction *after* the call, `0x10000296` (the `movw r1, #1337` that begins the `OTHER_FAV_NUM` half of the loop): remove the breakpoint at `0x10000292` and set a hardware breakpoint at `0x10000296`. Two reasons not to just click **Step Over** here: a breakpoint left on the current PC re-traps the step, and IDA's **Step Over** steps *into* `__wrap_printf` on this raw `.bin` because the image carries no symbol for the call. Moving the breakpoint to the return site is deterministic. +8. Click **Resume** in IDA. The core executes `bl __wrap_printf` with `r1 = 0x2b`, so this iteration prints `FAV_NUM: 43`, then stops at `0x10000296`. +9. Look at your serial monitor — the `screen` session on the Pico's USB serial port — and at the **Target** tab in IDA: + + ``` + FAV_NUM: 43 + ``` + +You changed a running program's output without touching the binary. + +### Step 13b: HACK THE LCD STRING LIVE — change `"Reverse"` to `"Exploit"` (optional) + +The LCD text `"Reverse"` lives in flash (`.rodata`) at `0x10003ee8`, and flash is **read-only at runtime** — a debugger write there does not stick. So instead of overwriting the text in place, redirect the pointer: at the `lcd_puts` call for `"Reverse"`, `r0` holds the string address, so point `r0` at a replacement string you place in RAM. + +> **Do this one while stopped at `main`, before `Resume`.** The LCD is written once during init, at `0x1000027c`. If you have already resumed into the loop, restart the server parked at `0x10000234` (Step 9) and reconnect, or the breakpoint at `0x1000027c` never fires again. + +1. With IDA stopped at `main` (`0x10000234`), press `G` and go to `0x1000027c` (the `bl lcd_puts` that writes `"Reverse"`, loaded from the literal pool word at `0x100002ac`). +2. Set a **hardware execute** breakpoint at `0x1000027c` and click **Resume**. It fires once, with `r0 = 0x10003ee8`. +3. Put the replacement string into free RAM at `0x20080000` from IDA's **Python console** (`Plugins -> Python Console`) — no command port needed: + ```python + dbg.write_memory(0x20080000, b"Exploit\x00") + ``` + `dbg.write_memory(address, bytes)` is IDA's debugger memory-write API; it returns `True` on success. That writes `Exploit\0`. +4. Point `r0` at that string: + ```python + dbg.set_reg_value("r0", 0x20080000) + ``` + (Or right-click `r0` in the **Registers** widget, press `E`, type `0x20080000`, and press Enter.) +5. Move the breakpoint off the current PC (remove it at `0x1000027c`, set one at `0x10000280`, the `movs r0, #1` after the call) and click **Resume**. `lcd_puts` walks your RAM string and pushes `E x p l o i t` to the PCF8574 over I2C, so line 1 of the LCD now reads: + + ``` + Exploit + ``` + +Like the value hack, this is **one boot only**: the next `lcd_puts` for `"Engineering"` is unaffected, but a reset reloads `r0` from flash. The permanent version is the static patch in Step 18c. + +### Step 14: Why the hack reverts (and why we patch next) + +Press **Resume**. The loop branches back to `0x1000028e`, which reloads `movs r1, #42`, so the next line is `FAV_NUM: 42`. The live edit changed one iteration only. There is no memory variable to change; the value is baked into the instruction. To make `FAV_NUM: 43` permanent we must patch the instruction. That is the static pass. + +Press **Pause** to stop the output flood. + +### Step 15: Kill the debugger and OpenOCD + +The live hack is done. Do this **before** the static pass. + +1. In the **Debugger** sidebar, click the **X** (**Kill**) (or **`Debugger -> Kill`**) to disconnect IDA. +2. **Kill does not stop the OpenOCD process** — `debug-server.sh` started it separately, and it keeps running and holding the probe. Stop it from the IDA console: + + **macOS / Linux:** + + ```python + import subprocess + subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # stop the debug server, free the probe + ``` + + **Windows:** + + ```python + import subprocess + subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"]) # stop the debug server, free the probe + ``` + +3. Confirm nothing is left: `pgrep -fl openocd` (macOS/Linux) prints nothing. + +From a terminal it is the same: `pkill -TERM -f openocd`, or `Get-Process openocd | Stop-Process` on Windows. + +--- + +## Part 4: Static — Resolve the Functions in IDA and Patch + +### Step 16: Resolve the functions in the IDA GUI + +We now name the functions in IDA using the ELF symbol map from Step 4. IDA loaded the raw `.bin` with **no symbols**, so every function shows as `sub_` — resolving means giving each one its real name and signature. + +Three keys do all the work: + +| Key | IDA action | Use it for | +| --- | ------------------- | ---------- | +| `G` | Go to address | Jump to a function's address | +| `Y` | **Change Type** | Set the function's signature. The dialog shows the full prototype, so this sets the name *and* the type in one step. | +| `N` | Rename | Rename only, when you just want the name and not the type | + +For each function below: `G` to its address, then **`Y` (Change Type)** and type the prototype from the table. + +#### How to resolve a function in IDA (`Y`) + +`Y` is the **Change Type** key, and it is what actually resolves the function — it turns `void sub_100037fc()` into `bool stdio_init_all(void)`. The Change Type dialog shows the full declaration (name and type), so typing the prototype sets both: + +1. `G` to the function's address. The cursor lands on the function. +2. Press **`Y`**. In the Change Type dialog, type the prototype from the table exactly — for example `bool stdio_init_all(void)` — and press Enter. + +The decompiler header then shows the real prototype, and calls to the function read cleanly instead of `sub_()`. `N` is only for renaming without touching the type; `Y` alone sets both the name and the type. + +If `Y` seems to do nothing, confirm the cursor is on the function, or right-click it and pick **Change Type...**. IDA parses what you type and silently keeps the old type if it does not parse, so glance at the header after each `Y`. + +#### Worked example: `main` + +1. Press `G`, type `0x10000234`, press Enter. The view jumps there; the cursor lands on `sub_10000234`. +2. Press **`Y`** (Change Type), type `int main(void)`, press Enter. That sets the name to `main` and the type to `int(void)`. + +> **IDA shows `int32_t` where Ghidra shows `int`.** After you set `int main(void)`, the decompiler header may read `int32_t main(void)`. That is the same type — on this platform `int` is 32 bits and IDA's parser normalises it to `int32_t`. Do not fight it; it is not an error. + +#### Worked example: `i2c_init` + +1. `G` -> `0x10003cdc`. +2. `Y` -> `uint i2c_init(i2c_inst_t* i2c, uint baudrate)`. + +> **`i2c_init` returns `uint`, not `void`.** The SDK's `i2c_init` returns the actual configured baud rate; the ELF says `unsigned int (i2c_inst_t *, uint)`. Keep the return type. + +#### Worked example: `lcd_i2c_init` + +1. `G` -> `0x100002bc`. +2. `Y` -> `void lcd_i2c_init(i2c_inst_t* i2c, uint8_t pcf_addr, int nibble_shift, uint8_t backlight_mask)`. + +This is our own `lcd_1602.c` code. In this build it is one big function: the compiler inlined `lcd_store_config`, `lcd_hd44780_reset`, and `lcd_hd44780_configure` into it. + +#### Worked example: `lcd_set_cursor` + +1. `G` -> `0x100006f4`. +2. `Y` -> `void lcd_set_cursor(int line, int position)`. + +#### Worked example: `lcd_puts` + +1. `G` -> `0x100007f0`. +2. `Y` -> `void lcd_puts(const char* s)`. + +#### Worked example: `gpio_set_function` + +1. `G` -> `0x100008f0`. +2. `Y` -> `void gpio_set_function(uint gpio, gpio_function_t fn)`. + +#### Worked example: `gpio_set_pulls` + +1. `G` -> `0x1000092c`. +2. `Y` -> `void gpio_set_pulls(uint gpio, bool up, bool down)`. + +This is what `gpio_pull_up(2)` in our source compiles to: the SDK's `static inline` `gpio_pull_up` disappears, and `main` calls `gpio_set_pulls(2, true, false)` directly at `0x10000258`. + +#### Worked example: `__wrap_printf` + +1. `G` -> `0x1000398c`. +2. `Y` -> `int __wrap_printf(const char *fmt, ...)`. Keep the `...` — `printf` is variadic. + +#### Worked example: `stdio_init_all` + +1. `G` -> `0x100037fc`. +2. `Y` -> `bool stdio_init_all(void)`. + +> **`printf` in our source is `__wrap_printf` in the binary.** The SDK links our `printf` calls to its `__wrap_printf` wrapper, which forwards to `__wrap_vprintf`. Rename it `printf` if you prefer the lesson's shorthand, but `__wrap_printf` is what the ELF says. + +The rest of the chain is the same two keystrokes per function (`G`, then `Y`). This is **our code plus the library functions it actually calls** — not the whole SDK. `main` calls `stdio_init_all`, `i2c_init`, `gpio_set_function`, `gpio_set_pulls`, `lcd_i2c_init`, `lcd_set_cursor`, `lcd_puts`, and `printf`, so we follow that chain down. + +The call chain for this project: + +``` +main +├── stdio_init_all ── stdio_uart_init ── gpio_set_function, uart_init, stdio_set_driver_enabled +│ └── uart_init ── clock_get_hz, busy_wait_us +├── i2c_init +├── gpio_set_function +├── gpio_set_pulls (gpio_pull_up inlined) +├── lcd_i2c_init ── i2c_write_blocking, sleep_us, sleep_ms +│ └── pcf_write_byte / pcf_pulse_enable / lcd_write4 / lcd_send / lcd_store_config / +│ lcd_hd44780_reset / lcd_hd44780_configure (all inlined; no calls) +├── lcd_set_cursor ── i2c_write_blocking, sleep_us +├── lcd_puts ── i2c_write_blocking, sleep_us +└── __wrap_printf ── __wrap_vprintf ── vfctprintf ── _vsnprintf + │ └── _ntoa_format / _out_rev / _out_char + ├── time_us_64 + └── stdio_out_chars_crlf +``` + +**Resolve every function in that chain:** + +| Address | Rename to (`N`) | Signature (`Y`) | +| ------- | --------------- | --------------- | +| `0x1000015c` | `_reset_handler` | `void _reset_handler(void)` | +| `0x10000186` | `platform_entry` | `void platform_entry(void)` | +| `0x1000019a` | `data_cpy` | `void data_cpy(void*, void*, void*)` | +| `0x100001e4` | `_init` | `void _init(void)` | +| `0x10000210` | `frame_dummy` | `void frame_dummy(void)` | +| **`0x10000234`** | **`main`** | **`int main(void)`** | +| `0x100002bc` | `lcd_i2c_init` | `void lcd_i2c_init(i2c_inst_t*, uint8_t, int, uint8_t)` | +| `0x100006f4` | `lcd_set_cursor` | `void lcd_set_cursor(int, int)` | +| `0x100007f0` | `lcd_puts` | `void lcd_puts(const char*)` | +| `0x100008f0` | `gpio_set_function` | `void gpio_set_function(uint, gpio_function_t)` | +| `0x1000092c` | `gpio_set_pulls` | `void gpio_set_pulls(uint, bool, bool)` | +| `0x10001368` | `sleep_us` | `void sleep_us(uint64_t)` | +| `0x10001440` | `sleep_ms` | `void sleep_ms(uint32_t)` | +| `0x10001624` | `time_us_64` | `uint64_t time_us_64(void)` | +| `0x10001638` | `busy_wait_us` | `void busy_wait_us(uint64_t)` | +| `0x100016b8` | `uart_init` | `uint uart_init(uart_inst_t*, uint)` | +| `0x1000188c` | `clock_get_hz` | `unsigned long clock_get_hz(clock_handle_t)` | +| `0x100035a4` | `exit` | `void exit(int)` | +| `0x100035ac` | `runtime_init` | `void runtime_init(void)` | +| `0x100035d8` | `stdio_out_chars_crlf` | `void stdio_out_chars_crlf(stdio_driver_t*, const char*, int)` | +| `0x100036e8` | `stdio_put_string` | `int stdio_put_string(const char*, int, bool, bool)` | +| `0x100037d4` | `stdio_set_driver_enabled` | `void stdio_set_driver_enabled(stdio_driver_t*, bool)` | +| `0x100037fc` | `stdio_init_all` | `bool stdio_init_all(void)` | +| `0x100038c8` | `__wrap_vprintf` | `int __wrap_vprintf(const char*, va_list)` | +| `0x1000398c` | `__wrap_printf` | `int __wrap_printf(const char*, ...)` | +| `0x10003b48` | `stdio_uart_init` | `void stdio_uart_init(void)` | +| `0x10003cdc` | `i2c_init` | `uint i2c_init(i2c_inst_t*, uint)` | +| `0x10003d28` | `i2c_write_blocking` | `int i2c_write_blocking(i2c_inst_t*, uint8_t, const uint8_t*, size_t, bool)` | +| `0x10003e24` | `strlen` | `size_t strlen(const char*)` | + +**Resolve the SDK helpers the `printf` path reaches:** + +| Address | Rename to (`N`) | Signature (`Y`) | +| ------- | --------------- | --------------- | +| `0x10003548` | `vfctprintf` | `int vfctprintf(void (*)(char, void*), void*, const char*, va_list)` | +| `0x10002b64` | `_vsnprintf` | `int _vsnprintf(out_fct_type, char*, size_t, const char*, va_list)` | +| `0x10001f48` | `_ntoa_format` | `unsigned _ntoa_format(out_fct_type, char*, size_t, size_t, char*, size_t, bool, unsigned, unsigned, unsigned, unsigned)` | +| `0x10001eac` | `_out_rev` | `unsigned _out_rev(out_fct_type, char*, size_t, size_t, const char*, size_t, unsigned, unsigned)` | +| `0x1000211c` | `_out_char` | `void _out_char(char, void*, size_t, size_t)` | + +> **A `void` return type may not stick — here is the fix.** IDA treats `void` as low-confidence, and its analysis can override it with an inferred type — most often `int32_t` on this 32-bit target. It is most visible on `_reset_handler` (a hand-written assembly entry that never returns normally), but it can happen to **any** function whose return type IDA thinks it can infer. +> +> Setting the full signature with `Y` reproduces the unwanted `int32_t`, and `fn.return_type = ...` fails too. What works is the **return-value** setter: +> +> ```python +> from binaryninja import ReturnValue, Type +> fn = bv.get_function_at(0x1000015c) +> if fn is not None: +> fn.return_value = ReturnValue(Type.void()) +> ``` +> +> That holds `_reset_handler` at `void` even after reanalysis. If it still will not stick, leave it — it does not affect the rest of the lesson. + +> **`i2c1_inst` is data, not a function.** `arm-none-eabi-nm -n` lists `2000062c T i2c1_inst`. The `T` is a **global data** symbol: the linker parks the `i2c1_inst` struct at RAM address `0x2000062c`. Its first word is the hardware pointer `0x40098000`, the I2C1 register base. There is no function there; do not `Y` it with a prototype. + +> **Shortcut — resolves name *and* type for every function.** Instead of doing `N` + `Y` by hand, paste this into IDA's Python console (`Plugins -> Python Console`). It sets each function's name and signature programmatically: +> +> ```python +> from binaryninja import Symbol, SymbolType +> # The raw .bin has no headers, so these SDK types don't exist. set_user_type() +> # re-parses each signature as C, so an undefined name raises +> # "SyntaxError: unknown type name '...'". Define them first. +> sdk = bv.parse_types_from_string(""" +> typedef unsigned int uint; +> typedef char* va_list; +> typedef unsigned long clock_handle_t; +> typedef void (*out_fct_type)(char, void*, size_t, size_t); +> struct stdio_driver; +> typedef struct stdio_driver stdio_driver_t; +> struct uart_inst; +> typedef struct uart_inst uart_inst_t; +> struct i2c_inst; +> typedef struct i2c_inst i2c_inst_t; +> enum gpio_function { +> GPIO_FUNC_XIP = 0, GPIO_FUNC_SPI = 1, GPIO_FUNC_UART = 2, GPIO_FUNC_I2C = 3, +> GPIO_FUNC_PWM = 4, GPIO_FUNC_SIO = 5, GPIO_FUNC_PIO0 = 6, GPIO_FUNC_PIO1 = 7, +> GPIO_FUNC_GPCK = 8, GPIO_FUNC_USB = 9, GPIO_FUNC_NULL = 0x1f, +> }; +> typedef enum gpio_function gpio_function_t; +> """) +> for name, ty in sdk.types.items(): +> bv.define_user_type(name, ty) +> +> # address: (name, signature) +> funcs = { +> 0x1000015c: ("_reset_handler", "void _reset_handler(void)"), +> 0x10000186: ("platform_entry", "void platform_entry(void)"), +> 0x1000019a: ("data_cpy", "void data_cpy(void*, void*, void*)"), +> 0x100001e4: ("_init", "void _init(void)"), +> 0x10000210: ("frame_dummy", "void frame_dummy(void)"), +> 0x10000234: ("main", "int main(void)"), +> 0x100002bc: ("lcd_i2c_init", "void lcd_i2c_init(i2c_inst_t*, uint8_t, int, uint8_t)"), +> 0x100006f4: ("lcd_set_cursor", "void lcd_set_cursor(int, int)"), +> 0x100007f0: ("lcd_puts", "void lcd_puts(const char*)"), +> 0x100008f0: ("gpio_set_function", "void gpio_set_function(uint, gpio_function_t)"), +> 0x1000092c: ("gpio_set_pulls", "void gpio_set_pulls(uint, bool, bool)"), +> 0x10001368: ("sleep_us", "void sleep_us(uint64_t)"), +> 0x10001440: ("sleep_ms", "void sleep_ms(uint32_t)"), +> 0x10001624: ("time_us_64", "uint64_t time_us_64(void)"), +> 0x10001638: ("busy_wait_us", "void busy_wait_us(uint64_t)"), +> 0x100016b8: ("uart_init", "uint uart_init(uart_inst_t*, uint)"), +> 0x1000188c: ("clock_get_hz", "unsigned long clock_get_hz(clock_handle_t)"), +> 0x100035a4: ("exit", "void exit(int)"), +> 0x100035ac: ("runtime_init", "void runtime_init(void)"), +> 0x100035d8: ("stdio_out_chars_crlf", "void stdio_out_chars_crlf(stdio_driver_t*, const char*, int)"), +> 0x100036e8: ("stdio_put_string", "int stdio_put_string(const char*, int, bool, bool)"), +> 0x100037d4: ("stdio_set_driver_enabled", "void stdio_set_driver_enabled(stdio_driver_t*, bool)"), +> 0x100037fc: ("stdio_init_all", "bool stdio_init_all(void)"), +> 0x100038c8: ("__wrap_vprintf", "int __wrap_vprintf(const char*, va_list)"), +> 0x1000398c: ("__wrap_printf", "int __wrap_printf(const char*, ...)"), +> 0x10003b48: ("stdio_uart_init", "void stdio_uart_init(void)"), +> 0x10003cdc: ("i2c_init", "uint i2c_init(i2c_inst_t*, uint)"), +> 0x10003d28: ("i2c_write_blocking", "int i2c_write_blocking(i2c_inst_t*, uint8_t, const uint8_t*, size_t, bool)"), +> 0x10003e24: ("strlen", "size_t strlen(const char*)"), +> 0x10003548: ("vfctprintf", "int vfctprintf(void (*)(char, void*), void*, const char*, va_list)"), +> 0x10002b64: ("_vsnprintf", "int _vsnprintf(out_fct_type, char*, size_t, const char*, va_list)"), +> 0x10001f48: ("_ntoa_format", "unsigned _ntoa_format(out_fct_type, char*, size_t, size_t, char*, size_t, bool, unsigned, unsigned, unsigned, unsigned)"), +> 0x10001eac: ("_out_rev", "unsigned _out_rev(out_fct_type, char*, size_t, size_t, const char*, size_t, unsigned, unsigned)"), +> 0x1000211c: ("_out_char", "void _out_char(char, void*, size_t, size_t)"), +> } +> for addr, (name, sig) in funcs.items(): +> bv.define_user_symbol(Symbol(SymbolType.FunctionSymbol, addr, name)) +> f = bv.get_function_at(addr) +> if f is not None: +> f.set_user_type(sig) +> ``` +> +> SDK type names (`i2c_inst_t`, `uart_inst_t`, `stdio_driver_t`, `gpio_function_t`, plus `uint`, `va_list`, `clock_handle_t`, and `out_fct_type`) are **not** in the raw `.bin`. `set_user_type` re-parses each signature as C, so an undefined name raises `SyntaxError: unknown type name '...'` and stops the loop — it is not harmless. The `sdk` block above defines them first (an opaque `struct`/`enum`/`typedef` is enough to parse). If you add a function that uses another SDK type, add a definition for it to that block too. + +### Step 17: Read `main` in the decompiler + +Open the **Decompiler** view on `main`. Once the functions above are typed, it reads roughly: + +```c +int32_t main(void) +{ + stdio_init_all(); + i2c_init(&i2c1_inst, 0x186a0); // i2c_init(i2c1, 100000) + gpio_set_function(2, GPIO_FUNC_I2C); + gpio_set_function(3, GPIO_FUNC_I2C); + gpio_set_pulls(2, true, false); // gpio_pull_up(2) + gpio_set_pulls(3, true, false); // gpio_pull_up(3) + lcd_i2c_init(&i2c1_inst, 0x27, 4, 8); // lcd_i2c_init(i2c1, 0x27, 4, 0x08) + lcd_set_cursor(0, 0); + lcd_puts("Reverse"); + lcd_set_cursor(1, 0); + lcd_puts("Engineering"); + while (true) { + __wrap_printf("FAV_NUM: %d\r\n", 0x2a); // FAV_NUM = 42 + __wrap_printf("OTHER_FAV_NUM: %d\r\n", 0x539); // OTHER_FAV_NUM = 1337 + } +} +``` + +The `0x2a` and `0x539` are the constants we will patch. Both are **immediates in the instruction stream** — there is no `.rodata` word to change, which is why the patch edits the instruction operand. Now make the hacks permanent. + +### Step 18: Patch 1 — change `FAV_NUM` from 42 to 43 + +Go to `0x1000028e`: + +```asm +1000028e: 2a 21 movs r1, #42 @ 0x2a +``` + +The halfword is `0x212a`, stored little-endian as `2a 21`. The immediate is the low byte, so the byte at the instruction's own address is `0x2a`. Change it to `0x2b` (43). + +| Project | Address | Before | After | Effect | +| ------- | ------- | ------ | ----- | ------ | +| `0x0017` | `0x1000028e` | `2a` | `2b` | `movs r1, #42` -> `#43`, prints `FAV_NUM: 43` | + +**Option A — Hex view:** + +1. Switch to the **Hex** view (`View -> Hex`). +2. Toggle the lock off so editing is enabled. +3. Go to `0x1000028e` and change the byte `2A` to `2B`. +4. Return to the linear view, right-click the function -> `Reanalyze`. + +**Option B — Python console:** + +```python +bv.write(0x1000028e, b"\x2b") +print(hex(bv.read(0x1000028e, 1)[0])) # -> 0x2b +``` + +After reanalysis the instruction reads `movs r1, #43`. + +### Step 18b: Patch 2 — change `OTHER_FAV_NUM` from 1337 to 1344 + +Go to `0x10000296`: + +```asm +10000296: 40 f2 39 51 movw r1, #1337 @ 0x539 +``` + +This is the 32-bit Thumb-2 encoding of `movw r1, #0x539`. The four bytes and their roles: + +``` ++-----------------------------------------------------------------+ +| movw r1, #0x539 -> bytes: 40 F2 39 51 | +| | +| Byte 0: 0x40 -+ | +| Byte 1: 0xF2 -+ First halfword (opcode + upper imm bits) | +| Byte 2: 0x39 ---- Lower 8 bits of immediate (imm8) <- CHANGE | +| Byte 3: 0x51 ---- Destination register (r1) + upper imm bits | +| | +| imm16 = 0x0539 = 1337 decimal | +| imm8 field = 0x39 (lower 8 bits of the value) | +| | ++-----------------------------------------------------------------+ +``` + +The imm8 byte is the **third** byte of the 4-byte instruction: the instruction starts at `0x10000296`, so the byte to change is `0x10000296 + 2 = 0x10000298`. Change `0x39` to `0x40`, which changes the value from `0x539` (1337) to `0x540` (1344). + +| Project | Address | Before | After | Effect | +| ------- | ------- | ------ | ----- | ------ | +| `0x0017` | `0x10000298` | `39` | `40` | `movw r1, #1337` -> `#1344`, prints `OTHER_FAV_NUM: 1344` | + +**Option A — Hex view:** + +1. Switch to the **Hex** view (`View -> Hex`). +2. Go to `0x10000298` and change the byte `39` to `40`. +3. Return to the linear view and reanalyze. + +**Option B — Python console:** + +```python +bv.write(0x10000298, b"\x40") +print(bv.read(0x10000296, 4).hex()) # -> 40f24051 +``` + +> **Do not patch `0x10000296` itself.** That is the instruction's first byte (the opcode), not the immediate. The immediate's low 8 bits are at `0x10000298`; patching the opcode corrupts the instruction. + +### Step 18c: Patch 3 — change the LCD text from `"Reverse"` to `"Exploit"` + +The string `"Reverse"` starts at `0x10003ee8`. Its eight bytes are `52 65 76 65 72 73 65 00` (`Reverse\0`). Change them to `45 78 70 6c 6f 69 74 00` (`Exploit\0`). **Both strings are exactly seven characters**, so the replacement fits without touching `"Engineering"` at `0x10003ef0`. + +| Project | Address | Before | After | Effect | +| ------- | ------- | ------ | ----- | ------ | +| `0x0017` | `0x10003ee8` | `52 65 76 65 72 73 65 00` | `45 78 70 6c 6f 69 74 00` | LCD line 1 prints `Exploit` instead of `Reverse` | + +**ASCII reference:** + +| Character | Hex | +| --------- | --- | +| E | `0x45` | +| x | `0x78` | +| p | `0x70` | +| l | `0x6c` | +| o | `0x6f` | +| i | `0x69` | +| t | `0x74` | + +**Option A — Hex view:** + +1. Switch to the **Hex** view (`View -> Hex`). +2. Go to `0x10003ee8` and change the eight bytes `52 65 76 65 72 73 65 00` to `45 78 70 6c 6f 69 74 00`. +3. Return to the linear view and reanalyze. + +**Option B — Python console:** + +```python +bv.write(0x10003ee8, b"Exploit\x00") +print(bv.read(0x10003ee8, 8)) # -> b'Exploit\x00' +``` + +Keep the replacement exactly eight bytes. If you use a shorter string you must pad it and keep the terminating `\0`, or `lcd_puts` will run into the `"Engineering"` string that follows at `0x10003ef0`. + +### Step 19: Export the patched `.bin` + +```python +import os +seg = next(s for s in bv.segments if s.data_length) # the loadable image segment +data = bv.read(seg.start, seg.data_length) # base + size come from the view itself +out = os.path.join(os.path.join(root, "0x0017_constants", "build"), "0x0017_constants-h.bin") +open(out, "wb").write(data) +print(len(data), out) # -> 17980 /.../build/0x0017_constants-h.bin +``` + +Where the two numbers come from — nothing is hardcoded: + +- **`seg.start`** is the image base IDA loaded the `.bin` at (`0x10000000`), the same value you pass to `uf2conv --base`. +- **`seg.data_length`** is the segment's size in the file (`0x463c` = 17980). Exactly one segment carries data (the image); every peripheral and synthetic segment has `data_length == 0`, so `next(...)` picks the image. +- Reading `seg.start` for `seg.data_length` bytes therefore grabs exactly the image. + +Two gotchas this avoids: + +- **No relative path.** IDA's Python console runs with a read-only working directory (inside the app bundle), so `open("0x0017_constants-h.bin", "wb")` fails with `OSError: [Errno 30] Read-only file system`. `root` (from `~/.embedded-hacking-repo`, Step 3) is the repo, so the file is written into the project's `build/` — no machine-specific path and no database needed. +- **Read the image, not the whole view.** `bv.read(bv.start, bv.length)` spans the entire mapped range, which is not the image. The segment's `data_length` is the image size. + +A different size means you exported a partial view. + +### Step 20: Convert to UF2 + +Run from the project directory: + +**macOS Apple Silicon / Linux x64:** + +```bash +python3 ../uf2conv.py 0x0017_constants-h.bin \ + --base 0x10000000 --family 0xe48bff59 --output hacked.uf2 +``` + +**Windows x64:** + +```cmd +python ..\uf2conv.py 0x0017_constants-h.bin ^ + --base 0x10000000 --family 0xe48bff59 --output hacked.uf2 +``` + +> **Or convert from the IDA console** — it is a normal Python interpreter, so you never have to leave the app. `chdir` to a writable directory first (the default one is read-only), then run the script: +> +> ```python +> import os, sys, runpy +> os.chdir(os.path.join(root, "0x0017_constants", "build")) # the project build dir (writable) +> sys.argv = ["uf2conv.py", "0x0017_constants-h.bin", +> "--base", "0x10000000", "--family", "0xe48bff59", "--output", "hacked.uf2"] +> runpy.run_path("../../uf2conv.py", run_name="__main__") # path to your uf2conv.py +> ``` +> +> This writes `hacked.uf2` next to the `.bin`, ready to drag onto the Pico. + +### Step 21: Flash and verify + +Hold **BOOTSEL**, plug in the Pico 2, and drag `hacked.uf2` onto the **`RP2350`** drive. Open the serial monitor: + +``` +FAV_NUM: 43 +OTHER_FAV_NUM: 1344 +FAV_NUM: 43 +OTHER_FAV_NUM: 1344 +... +``` + +and the **LCD line 1 reads `Exploit`** while line 2 still reads `Engineering`. + +**Both constants changed and the LCD string changed — with nine operand bytes patched and no source code.** (`0x2a -> 0x2b`, `0x39 -> 0x40`, and the eight-byte string.) + +> **Faster: flash over the Debug Probe (no BOOTSEL).** The repo's `flash.sh` writes the raw `.bin` straight into XIP flash over SWD (`program 0x10000000 verify reset exit`), so you never touch BOOTSEL or a UF2. Run it from a terminal (`./flash.sh `), or from the IDA console **without freezing it** — use `subprocess.Popen`, which returns immediately, and send OpenOCD's output to a log file. (`subprocess.run` blocks the console until the flash finishes; do not use it here.) +> +> ```python +> import os, subprocess +> root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() +> bin_path = os.path.join(os.path.join(root, "0x0017_constants", "build"), "0x0017_constants-h.bin") +> log = os.path.join(os.path.join(root, "0x0017_constants", "build"), "flash.log") +> subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # free the probe first +> p = subprocess.Popen([os.path.join(root, "flash.sh"), bin_path], +> stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) +> print("flashing in the background; log:", log) +> ``` +> +> The `pkill` frees the probe first; on Windows use `subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"])`. +> +> The console is free the moment this returns. Check it with `print(p.poll())` (`None` = still running, `0` = done) or read `flash.log` — success ends with `** Verified OK **`. +> +> The same non-blocking form without the script: +> +> ```python +> import os, subprocess +> ocd = os.path.expanduser("~/.pico-sdk/openocd/0.12.0+dev") +> bin_path = os.path.join(os.path.join(root, "0x0017_constants", "build"), "0x0017_constants-h.bin") +> log = os.path.join(os.path.join(root, "0x0017_constants", "build"), "flash.log") +> subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # free the probe first +> p = subprocess.Popen([f"{ocd}/openocd", "-s", f"{ocd}/scripts", +> "-f", "interface/cmsis-dap.cfg", "-f", "target/rp2350.cfg", +> "-c", "adapter speed 5000", +> "-c", f"program {bin_path} 0x10000000 verify reset exit"], +> stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) +> print("flashing in the background; log:", log) +> ``` +> +> **The Debug Probe is single-owner.** If IDA is still attached (the `debug-server.sh` OpenOCD is running), the flash cannot grab the probe. Detach in IDA and stop that OpenOCD first: +> +> ```bash +> # macOS / Linux +> pkill -TERM -f openocd +> ``` +> ```powershell +> # Windows +> Get-Process openocd -ErrorAction SilentlyContinue | Stop-Process +> ``` +> +> Success looks like `Programming Finished` -> `Verified OK` -> `Resetting Target`. On Windows use `flash.ps1` (`.\flash.ps1 -Bin `) the same way. + +--- + +## Cheatsheet + +### IDA GUI actions + +| Action | How | +| ------ | --- | +| Go to address | `G` | +| Rename function/symbol | `N` | +| Set type or signature | `Y` | +| Add comment | `;` | +| Open Hex view | `View -> Hex` | +| Enable hex editing | Toggle the lock in the status bar | +| Reanalyze after a patch | Right-click function -> `Reanalyze` | +| Edit a register live | `dbg.set_reg_value("r1", 0x2b)` in the Python console (or right-click the register, press `E`, type hex, Enter) | +| Write a RAM string live | `dbg.write_memory(0x20080000, b"Exploit\x00")` | +| Set a breakpoint | `Debugger -> Add Hardware Breakpoint...` (hardware execute). Do **not** use `F2` — software breakpoints cannot be written to read-only flash. | +| Move a breakpoint | Remove it and set it at the new address in the GUI (command-port fallback: `rbp ` then `bp 2 hw`) | +| Confirm what is armed | The **Breakpoints** widget lists it (command-port fallback: `mdw 0xE0002000 8`, each armed breakpoint shows as ``) | +| Apply the ELF symbol map | Paste the Python snippet from Step 16 into the Python Console | + +### OpenOCD server and reset + +The server runs with `gdb_breakpoint_override hard` so that flash-writes are never attempted. Breakpoints in this lab are set in the IDA GUI through the **GDB MI** adapter (Step 12). The command-port rows below are the fallback if you use the **GDB RSP** adapter instead. + +| Action | Command | +| ------ | ------- | +| Connect to the OpenOCD prompt (fallback) | `nc 127.0.0.1 4444` (or `telnet 127.0.0.1 4444`) | +| Reset and run (command port) | `reset run` | +| Check core state (command port) | `targets` | +| Set a breakpoint in the GUI | `Debugger -> Add Hardware Breakpoint...` (hardware execute; `F2` software breakpoints do not work on flash) | +| (fallback) Add a breakpoint without the GUI | `bp 2 hw` | +| Remove one breakpoint | `rbp ` — **address only, no length, no `hw`** | +| Remove every breakpoint | `rbp all` | +| Start the server parked at `main` | macOS/Linux: `BP_ADDR=0x10000234 ./debug-server.sh` — Windows: `$env:BP_ADDR="0x10000234"; .\debug-server.ps1` (one-shot) | +| Start the server parked in the loop | macOS/Linux: `BP_ADDR=0x10000292 ./debug-server.sh` — Windows: `$env:BP_ADDR="0x10000292"; .\debug-server.ps1` | +| Break on the loop in a running target | set a hardware breakpoint in the GUI at the loop address, then **Resume** — repeatable | +| Make IDA stepping work | `rp2350.dap.core0 configure -rtos none` (already in the scripts) | +| Step without re-trapping | move the breakpoint off the current PC first, then **Step Into**/**Step Over** | +| Reset without desyncing IDA | **Detach**, `reset run` on the port, reconnect — never `reset run` while attached | + +### Every address and byte we changed + +| Project | Address | Before | After | Effect | +| ------- | ------- | ------ | ----- | ------ | +| `0x0017` | `0x1000028e` | `2a` | `2b` | `movs r1, #42` -> `#43`, prints `FAV_NUM: 43` | +| `0x0017` | `0x10000298` | `39` | `40` | `movw r1, #1337` -> `#1344`, prints `OTHER_FAV_NUM: 1344` | +| `0x0017` | `0x10003ee8` | `52 65 76 65 72 73 65 00` | `45 78 70 6c 6f 69 74 00` | LCD line 1 prints `Exploit` instead of `Reverse` | + +### The I2C/LCD memory map + +| Item | Address | Notes | +| ---- | ------- | ----- | +| `i2c1_inst` | `0x2000062c` | RAM `.data`, fixed for the life of the program | +| `i2c1_inst.hw` | `0x40098000` | I2C1 hardware register base (first word of the struct) | +| `i2c1_inst.restart_on_next` | `0x20000630` | second word of the struct, `0` (false) | +| Literal-pool word 1 | `0x100002a4` | `0x000186a0` — I2C baud rate, 100000 | +| Literal-pool word 2 | `0x100002a8` | `0x2000062c` — `&i2c1_inst` | +| Literal-pool word 3 | `0x100002ac` | `0x10003ee8` — pointer to `"Reverse"` | +| Literal-pool word 4 | `0x100002b0` | `0x10003ef0` — pointer to `"Engineering"` | +| Literal-pool word 5 | `0x100002b4` | `0x10003efc` — pointer to `"FAV_NUM: %d\r\n"` | +| Literal-pool word 6 | `0x100002b8` | `0x10003f0c` — pointer to `"OTHER_FAV_NUM: %d\r\n"` | + +### Raw image facts + +| Item | Value | +| ---- | ----- | +| Build type | `Release` | +| Load base address | `0x10000000` | +| Project size | `17980` bytes (`0x463c`) | +| Fixed `main` anchor | `0x1000018c` (reset handler middle `blx`) | +| `main` | `0x10000234` | +| `printf` call / return, `FAV_NUM` | `0x10000292` / `0x10000296` | +| `printf` call, `OTHER_FAV_NUM` | `0x1000029c` | +| `i2c1_inst` RAM address | `0x2000062c` | +| I2C1 hardware registers | `0x40098000` | +| `FAV_NUM` format string | `0x10003efc` | +| `OTHER_FAV_NUM` format string | `0x10003f0c` | +| `"Reverse"` string | `0x10003ee8` | +| `"Engineering"` string | `0x10003ef0` | +| RP2350 UF2 family ID | `0xe48bff59` | + +--- + +## Troubleshooting + +### IDA hangs or crashes when you connect (macOS 27) + +Three different causes have been seen on this setup; check them in this order. + +- **A breakpoint set before connecting.** With the **GDB MI** adapter, if the binary view already has a breakpoint, the session hangs. Start parked with `BP_ADDR`, connect, then add breakpoints (see the next entry). +- **The wrong GDB executable.** Point **Full GDB Executable Path** at the **14.2.rel1** toolchain (Step 10). The 13.3.rel1 build did **not** connect in testing. +- **The LLDB adapter.** A crash report with `libdebuggercore.dylib -> std::terminate() -> abort()` and `liblldb` in the stack is the **LLDB** adapter, not GDB MI. Avoid LLDB on this setup. + +**Use GDB MI**, with the 14.2.rel1 path above. If it still fails, fall back to plain `arm-none-eabi-gdb` against the same server — the addresses and register values are identical to the GUI steps. + +If IDA hangs, force-quit it; the connect dialog has no working Cancel. The static steps (resolve, patch, export, flash) never touch the debugger and always work. + +### The GUI refuses to set a breakpoint (GDB RSP adapter only) + +If you are on the **GDB RSP** adapter, the GUI cannot set breakpoints on this target. That adapter is IDA's own minimal RSP client and sends a **1-byte** breakpoint (`Z0,,1`); the Cortex-M33 comparators need 2 bytes, so OpenOCD answers `only breakpoints of two bytes length supported`. It affects every address, both `Toggle Breakpoint` and `Add Hardware Breakpoint`, and the dialog's **Size** field is disabled. `gdb_breakpoint_override` makes no difference. + +**Fix: use the GDB MI adapter** (Step 10). It drives real GDB, which sends the correct length, so GUI breakpoints just work. If you must stay on GDB RSP, arm breakpoints from the command port after connecting (`bp 2 hw`) — but the lab uses GDB MI and does not need that. + +### GDB MI hangs when you connect (a breakpoint already existed) + +With the **GDB MI** adapter, if IDA already has a breakpoint set when you connect, the session **hangs**. This is a IDA bug. The working order is: + +1. Start the server parked, e.g. `BP_ADDR=0x10000234 ./debug-server.sh` (Windows: `$env:BP_ADDR="0x10000234"; .\debug-server.ps1`). +2. Connect with the **GDB MI** adapter. +3. Only *then* set hardware breakpoints in the UI. + +Never have a breakpoint in the binary view before the GDB MI connection. If it hangs, quit IDA, restart the server with `BP_ADDR`, and connect again before adding any breakpoints. + +### Step Into / Step Over does nothing (PC never moves) + +Two causes have been seen on this target. + +1. **A breakpoint on the current PC re-traps the step.** OpenOCD's step-over-breakpoint logic fails with `Duplicate Breakpoint address` and the PC stays put. Fix: move the breakpoint off the current PC (in the GUI), then step. +2. **The `hwthread` RTOS (GDB RSP adapter only).** With the **GDB RSP** adapter, OpenOCD can log `fake step thread 0` and reply without stepping, because the RP2350 config's `-rtos hwthread` makes the current thread id 1 while IDA sends thread id 0. Fix: `rp2350.dap.core0 configure -rtos none` (the launcher scripts already pass this). **GDB MI does not hit this.** + +To tell them apart, turn on OpenOCD logging (`log_output /tmp/ocd.log`, then `debug_level 3` on the command port) and look for `fake step` versus `Duplicate Breakpoint`. + +### `zsh: bad CPU type in executable: cmake` + +An Intel `x86_64` tool is on your `PATH` on Apple Silicon. Run Step 2: `export PATH="/opt/homebrew/bin:$PATH"`, then `hash -r`. Add it to `~/.zshrc` to make it permanent. + +### My addresses do not match this guide + +You probably built `Debug`. This lesson is a `Release` build. Re-run Step 3 with `-DCMAKE_BUILD_TYPE=Release`. A `Debug` build moves the SDK functions and keeps `init_i2c_and_lcd` / `write_lcd_greeting` as separate calls, so `main` is not at `0x10000234`. + +### A breakpoint never fires + +First, confirm you actually set one, and that it is a **hardware** breakpoint. With the **GDB MI** adapter, `Debugger -> Add Hardware Breakpoint...` (hardware execute) should land in the **Breakpoints** widget. If nothing lands, or the core keeps running, you probably used `F2` (`Toggle Breakpoint`) — that is a software breakpoint and cannot be written to read-only flash, so it never installs. Also check you are on **GDB MI**, not **GDB RSP** (the GDB RSP adapter cannot set breakpoints on this target at all). + +Then check the order and the state: + +- **Arm it only after IDA is connected.** OpenOCD flushes every breakpoint when a client attaches, so anything armed earlier is gone. This also applies to `BP_ADDR` on the startup command line. +- **Verify it is armed:** `mdw 0xE0002000 8`. You should see your address with the low bit set (`0x10000292` -> `0x10000293`). All zeros means nothing is armed — re-read this first, because it distinguishes "not armed" from "armed but never reached". +- **Is the core running?** `poll` on the command port should not report a halt. If it is stopped, click **Resume**. +- **Does the address get reached again?** `main` runs once per reset, so use `BP_ADDR` at startup (Step 9) rather than `reset run` while attached. Loop addresses such as `0x10000292` fire on the next pass with no reset — arm them and click **Resume** in IDA. +- **With GDB MI the stop is reported as `Breakpoint`** and appears in the **Breakpoints** widget, because GDB really did set it. + +### I edit `r1` (or another register) and it reverts + +`main` reloads the value at the top of every loop iteration — `movs r1, #42` at `0x1000028e` runs right before the `printf` at `0x10000292`. So `r1` is only `0x2b` for the instant between your edit and the next pass; then it is `0x2a` again. The edit sticks only if the core is **genuinely stopped** at the breakpoint and stays stopped. + +If it keeps reverting, the core is running, which almost always means the breakpoint is not installed — usually because it is a **software** breakpoint (`F2`) that cannot be written to read-only flash. Use `Debugger -> Add Hardware Breakpoint...` (hardware execute). + +> **The Registers widget is a snapshot, not a live view.** IDA reads the registers at each stop and shows that snapshot; it does not poll the target, and there is no "refresh registers" command. So a value changed outside IDA will not appear until the next stop. + +### The LCD string hack does nothing + +The LCD is written **once**, during `lcd_i2c_init` / `write_lcd_greeting`, before the loop starts. You must break at `0x1000027c` and redirect `r0` **before** that call runs. If you already let the target run into the loop, the LCD already shows the old strings. Restart the server parked at `main` (`BP_ADDR=0x10000234`) and reconnect, then set the breakpoint at `0x1000027c` while stopped. + +Also confirm you wrote a NUL-terminated string. `lcd_puts` walks bytes until `*s == 0`; without the trailing `\x00`, it keeps sending RAM garbage to the PCF8574. + +### The compiler did not keep `const` in `.rodata` + +It is not supposed to in this build. `const int OTHER_FAV_NUM = 1337` becomes `movw r1, #1337` because the program never takes its address (`&OTHER_FAV_NUM`) and the value fits in a 16-bit immediate. A `const` only stays in `.rodata` when something forces it there — an address-taken `const`, an array, a pointer, or `volatile`. When you reverse a real binary, never assume a `const` is a memory load; check the instruction. + +### The `movw` patch did not take + +You patched the wrong byte. `movw` is a 32-bit instruction and its low immediate byte (`imm8`) is the **third** byte. The instruction starts at `0x10000296`, so the byte to change is `0x10000298` (`0x39 -> 0x40`). Patching `0x10000296` (the opcode) corrupts the instruction and the core will fault. + +### The LCD shows garbage after patching + +The replacement string is the wrong length or is missing its NUL. `"Reverse"` and `"Exploit"` are both seven characters, and the original eight-byte block is `52 65 76 65 72 73 65 00`. Write exactly `45 78 70 6c 6f 69 74 00`. A shorter string without padding runs into `"Engineering"` at `0x10003ef0`; a longer one overwrites it. + +### The serial capture is garbage on macOS + +Reading `/dev/cu.usbmodem*` with a bare `read()` returns garbage. Set **raw termios at 115200** first: clear canonical/echo flags, set `CLOCAL|CREAD`, and `B115200` on input and output. `screen /dev/cu.usbmodem* 115200` does all of this for you; a script must call `tcsetattr` itself. Once set, the capture reads clean `FAV_NUM: 42` lines. + +### It worked for a second, then stopped (IDA's view desyncs) + +This is the most common failure, and it has one main cause: **driving the core from the OpenOCD command port while IDA is connected.** + +- If you send `reset run` from the port while attached, the core resets, runs, and halts at your breakpoint — but IDA never receives the stop event. Its sidebar keeps showing the *previous* location, so **Step** and **Resume** act on a stale PC and appear to do nothing. +- If the OpenOCD process dies (or you restart it) while attached, IDA keeps believing it is connected: the sidebar stays, but the menu shows **Pause** enabled and **Resume**/**Step** disabled because IDA last saw the target *running*. + +Recovery: **Detach, then reconnect.** If Detach does nothing (the connection is already dead), restart IDA — its menu still shows a session that no longer exists. + +Prevention: + +- Stop at `main` with `BP_ADDR` on a fresh server start, not with `reset run` while attached. +- For loop addresses, set the breakpoint in the GUI and click **Resume**. Let IDA be the thing that starts the core. +- If you must reset, **Detach first**, `reset run`, then reconnect. +- Never leave a breakpoint on the PC you are about to step or resume from. + +### The target "blows past" `main` and stops at `0x10003ab4` instead + +`0x10003ab4` is inside `stdio_uart_out_flush`: + +```asm +10003ab0: 4b02 ldr r3, [pc, #8] @ (10003abc ) +10003ab2: 681a ldr r2, [r3] +10003ab4: 6993 ldr r3, [r2, #24] @ the core sits here while the UART drains +10003ab6: 071b lsls r3, r3, #28 +10003ab8: d4fc bmi.n 10003ab4 +10003aba: 4770 bx lr +10003abc: 2000086c .word 0x2000086c +``` + +That is the UART transmit-FIFO drain loop inside `printf`, so the core is running `main`'s loop and simply spends nearly all its time there. The breakpoint at `main` did not fire because `main`'s entry runs exactly **once per reset**. If you arm the breakpoint after the reset, or set it while the target is already running and just resume, the core is already past `main` and will never re-execute it. Either arm the breakpoint **before** resetting, or break inside the loop at `0x10000292`, which fires every iteration. + +**`0x10003ab4` is not a function.** It is one instruction inside `stdio_uart_out_flush`, which starts at `0x10003ab0`. If IDA has created a function at `0x10003ab4` (for example because the debugger stopped at that PC), the decompiler shows garbage. Delete that bogus function (right-click it -> `Delete Function`, or put the cursor on it and press `U` to undefine) and reanalyze. The real function is `stdio_uart_out_flush` at `0x10003ab0`. + +### The console floods with `Failed to read memory at 0xf0000000` + +Core1 is exposed. The scripts must run with `USE_CORE=0`. Stop the server, confirm only `core0` is reported, restart, then restart IDA. + +### `Connect to Remote Process` is greyed out and Pause does nothing + +IDA is in a stale session, usually because the debug server restarted while attached. Quit and reopen IDA (or the `.i64`) and connect again. + +### The decompiler still shows the old value after patching + +Right-click the function and choose `Reanalyze`. + +--- + +## Fallback: do the dynamic steps with GDB (macOS 27) + +If IDA's debugger crashes on attach on macOS 27 (see Troubleshooting), you can still do the live hack with the ARM GDB from the toolchain, against the same OpenOCD server. The addresses and register values are identical to the GUI steps. + +Start the debug server (Step 9), then in a new terminal: + +``` +arm-none-eabi-gdb +``` + +At the `(gdb)` prompt: + +``` +set architecture armv8-m.main +target extended-remote :3333 +hbreak *0x10000292 +continue +``` + +Do **not** run `monitor reset run` before `hbreak`. `0x10000292` is inside `main`'s loop, so the breakpoint fires on the next iteration with no reset. If you reset first, the core runs `main` and you will not catch it. + +GDB stops at the `printf` call. Confirm the value, change it, and let it run: + +``` +info registers pc r1 # pc = 0x10000292, r1 = 0x2a +set $r1 = 0x2b +stepi +continue +``` + +The serial monitor prints `FAV_NUM: 43` for the iteration you changed — the same temporary live hack as editing `r1` in the IDA Registers widget. When you are done, press `Ctrl-C`, then `detach` and `quit`. + +**If you specifically want to stop at `main` (`0x10000234`),** remember its entry runs only once per reset, so the breakpoint must be armed *before* the reset: + +``` +monitor reset halt +hbreak *0x10000234 +continue +``` + +If you instead set it while the target is running and just `continue`, you will "blow past" `main` and catch the core inside `printf` — in this build at `0x10003ab4`, the `stdio_uart_out_flush` UART-drain loop. + +`hbreak` sets a hardware breakpoint, which is required for read-only flash. It works from plain GDB because GDB sends the 2-byte length the Cortex-M33 comparators need. IDA's **GDB MI** adapter goes through the same GDB, so its GUI breakpoints work too; the old **GDB RSP** adapter was the one that sent a 1-byte length and could not set breakpoints here. + +## Glossary + +| Term | Definition | +| ---- | ---------- | +| **AAPCS** | ARM Architecture Procedure Call Standard — `r0`-`r3` for the first four arguments, `r0` for the return value | +| **`.bss`** | Section for uninitialized (or zero-initialized) static/global variables; zeroed by startup code | +| **`const`** | A source-level "read-only" qualifier; the compiler may still inline it as an immediate | +| **`.data`** | Section for initialized static/global variables; copied from flash to SRAM at boot | +| **`#define`** | Preprocessor text replacement performed before compilation; consumed by the compiler as a literal | +| **`.elf`** | Linked image with the symbol table; the ground truth for addresses and names | +| **`imm8`** | The low 8 bits of a `movw` immediate, stored in the third byte of the 32-bit instruction | +| **Immediate value** | A constant embedded directly in an instruction, not fetched from memory | +| **I2C** | Inter-Integrated Circuit — a two-wire (SDA/SCL) serial bus; open-drain, needs pull-ups | +| **Literal pool** | A block of 32-bit constants that Thumb-2 code reaches with PC-relative `ldr` | +| **`movs`** | 16-bit Thumb move that loads an 8-bit immediate (0-255) | +| **`movw`** | 32-bit Thumb-2 "move wide" that loads any 16-bit immediate (0-65535) | +| **Open-drain** | An output that can only pull a line LOW, not drive it HIGH; pull-ups restore HIGH | +| **PCF8574** | The I2C I/O expander on a typical 1602 LCD backpack; commonly at `0x27` | +| **`.rodata`** | Read-only section for constants and string literals; stays in flash | +| **SCL / SDA** | I2C Serial Clock and Serial Data lines | +| **Struct** | A user-defined type that groups related variables; the SDK uses one per I2C controller | +| **Thumb bit** | Bit 0 of a Cortex-M function pointer; selects Thumb instruction mode | +| **`typedef`** | Creates an alias for a type (for example `typedef struct i2c_inst i2c_inst_t`) | +| **UF2** | USB Flashing Format — the file format the Pico 2 bootloader accepts | +| **Vector table** | The first words of flash: initial stack pointer and exception vectors | + +--- + +**Remember:** the ELF tells you what every address is, and the `.bin` is what you actually patch. Prove the behavior dynamically, read `r1` at the `printf` call, resolve the names from the ELF (including the `lcd_1602.c` symbols), then patch the bytes — `0x2a -> 0x2b`, `0x39 -> 0x40`, and the eight-byte LCD string — and flash. diff --git a/WEEK07/WEEK07-IDA.pdf b/WEEK07/WEEK07-IDA.pdf new file mode 100644 index 0000000..41ca2a5 Binary files /dev/null and b/WEEK07/WEEK07-IDA.pdf differ diff --git a/WEEK09/WEEK09-IDA.md b/WEEK09/WEEK09-IDA.md new file mode 100644 index 0000000..4ed65ce --- /dev/null +++ b/WEEK09/WEEK09-IDA.md @@ -0,0 +1,1536 @@ +# Week 9-IDA: IDA Pro — Read, Hack, and Patch Operator Immediates and a DHT11 Float Scale (Raw `.bin`) + +*** + +**LEGAL DISCLAIMER:** +The information, tools, and code provided in this repository and course are strictly for educational, research, and defensive purposes only. + +You are explicitly prohibited from using any materials contained herein to access, test, modify, or exploit any device, network, or system that you do not own 100% or for which you do not have explicit, documented, and legally binding authorization to interact with. + +By using this repository and course, you acknowledge and agree that: + +1. Any illegal, unauthorized, or malicious use of this information is solely your responsibility. +2. The author(s) and contributor(s) of this repository and course shall not be held liable for any damages, legal repercussions, criminal charges, or unauthorized actions resulting from the use, misuse, or abuse of the contents herein. +3. You will comply with all applicable local, state, national, and international laws regarding cybersecurity and computer fraud. + +**IF YOU DO NOT AGREE WITH THESE TERMS, DO NOT USE THIS REPOSITORY AND COURSE.** + +*** + +## What You'll Learn This Week + +- Build the lesson project with `Release` and get both an `.elf` and a raw `.bin` +- Dump the **ELF symbol map** with `arm-none-eabi-nm` and use it as ground truth +- Load the raw `.bin` into IDA at `0x10000000` +- Read the six C operator results as **bare instruction immediates** (`movs r1, #50`, `movs r1, #5`, …) +- Read the DHT11 single-wire driver, including the inlined `gpio_*` and `time_us_32` helpers +- **Break at the arithmetic `printf` call** on live silicon and hack the printed value live +- Optionally **hack the format string live** by pointing `r0` at a RAM replacement +- **Resolve the functions in the IDA GUI** using the ELF symbol map, including the `dht11.c` symbols +- **Patch** the arithmetic immediate (`50 -> 99`) and the DHT11 scaling constant (`0.1f -> 5.0f`) +- **Rename** the printed label by patching the `"arithmetic_operator:"` string +- **Export** the patched image, convert it to UF2, and flash it + +--- + +## How This Guide Works + +The build produces two files for the project: + +| File | What it is | How we use it | +| ---- | ---------- | ------------- | +| `.elf` | The linked image with a full symbol table | Ground truth for every function address and name | +| `.bin` | The raw flash image, no headers, no symbols | The image we load into IDA and reverse | + +The `.bin` is built **from** the `.elf`, so the ELF tells you exactly what is at every address. We use the ELF symbol map to resolve functions in IDA, and we reverse-engineer the raw `.bin` the way a real extracted firmware image is reversed. + +> **Build `Release`, not `Debug`.** Every address in this guide matches the Week 9 lesson, and the Week 9 lesson is a `Release` build. `Release` optimizes the code the same way the original lesson was built: it **inlines** the `static` helpers `print_operator_results`, `compute_arithmetic_ops`, `compute_operators`, and `print_dht11_reading` straight into `main`, and it inlines the whole `dht11.c` static helper chain (`send_start_signal`, `wait_for_level`, `wait_response`, `read_bit`, `read_40_bits`, `validate_checksum`) into `dht11_read`. Every operator result is folded to a bare `movs r1, #imm` immediate. If you build `Debug`, the SDK function addresses move and the helpers stay separate calls, so nothing lines up. Always build `Release` for this lesson. + +The order is **dynamic first, static second**: + +1. Break on the live target and prove what the code does. +2. Hack it live in the debugger and watch the output change. +3. Resolve the functions in IDA using the ELF symbol map. +4. Patch the bytes, export, convert, and flash. + +| Project | Serial output | Also does | The hacks | +| ------- | ------------- | --------- | --------- | +| `0x001a_operators` | six operator lines, then `Humidity: …%, Temperature: …°C` | DHT11 single-wire sensor on GPIO 4 | `50 -> 99` (arithmetic immediate), `0.1f -> 5.0f` (DHT11 scale), and `"arithmetic_operator:" -> "hacked_operator:"` | + +> **Addresses come from your build.** Every address here is from the `Release` build produced in Step 3. Confirm against your own `.elf` with the command in Step 4. + +> **The surprise of this week is how small the operator code is.** The C source computes `x * y`, `x > y`, `x << 1`, and `x += 5` in a helper function, but `Release` folds every one of those into a compile-time constant and stores it as a one-byte immediate inside a `movs r1, #imm` instruction. There is no variable in memory to change — the answer is baked into the instruction stream. The DHT11 reading is different: it is a real measurement scaled by a `float` constant (`0.1f`) sitting in the literal pool, and *that* one is a data word you can patch. + +> **A note on the sensor reading.** The humidity/temperature numbers depend on the physical DHT11 attached to GPIO 4. This guide's ground truth is about the *code*, not the sensor: the scale constant, where `dht11_read` lives, and which register holds the reading. + +--- + +## Part 1: Build, Flash, and Get the Symbol Map + +### Step 1: Install the toolchain + +**Windows x64** + +- Install the **Raspberry Pi Pico** extension in VS Code. It installs the ARM GNU toolchain, CMake, Ninja, and the Pico SDK. +- Install **IDA Pro** and complete its license activation. +- Install **PuTTY** for the serial monitor. + +**macOS Apple Silicon** + +```bash +brew install cmake ninja +``` + +- Install **IDA Pro** and complete its license activation. +- Install the **Arm GNU Toolchain**, or let the VS Code Pico extension manage it. + +**Linux x64** + +```bash +sudo apt install cmake ninja-build gcc-arm-none-eabi libnewlib-arm-none-eabi git python3 openocd minicom +``` + +- Install **IDA Pro** and complete its license activation. + +### Step 2: Verify your tools are the right architecture (do not skip this) + +On **macOS Apple Silicon**, the most common failure is an Intel `x86_64` tool on your `PATH`: + +``` +zsh: bad CPU type in executable: cmake +``` + +You may have **two Homebrews**: the arm64 one at `/opt/homebrew` and the Intel one at `/usr/local`. If `/usr/local/bin` wins, every `brew` tool is x86_64. Check: + +```bash +file "$(which cmake)" +file "$(which ninja)" +file "$(which arm-none-eabi-gdb)" +file "$(which arm-none-eabi-nm)" +file "$(which openocd)" +file "$(which telnet)" +``` + +All must report `arm64`. If any is `x86_64`, put the Apple Silicon prefix first for the session and check again: + +```bash +export PATH="/opt/homebrew/bin:$PATH" +hash -r +file "$(which cmake)" +``` + +To make it permanent, add that `export` to `~/.zshrc`. Do not use Rosetta as a fix; OpenOCD and GDB are exactly the kind of programs where a translation layer produces failures that look like debugger bugs. + +**`telnet` is special — and optional.** The GDB MI workflow does not need it; it is only used by the command-port fallback. macOS no longer ships `telnet`, and the Homebrew build is often the Intel one, so `telnet 127.0.0.1 4444` fails with `bad CPU type in executable`. Call the Apple Silicon Homebrew explicitly: + +```bash +/opt/homebrew/bin/brew install telnet +``` + +If you would rather not install anything, macOS ships an arm64 `nc`, which can connect to the same OpenOCD port: + +```bash +nc 127.0.0.1 4444 +``` + +**Windows x64** and **Linux x64** do not have this problem. Skip to Step 3. + +### Step 3: Build the project with `Release` + +Run this inside `0x001a_operators/`: + +```bash +cmake -B build -G Ninja -DPICO_BOARD=pico2 -DPICO_PLATFORM=rp2350 -DCMAKE_BUILD_TYPE=Release +cmake --build build +``` + +**Point IDA at this repository (once).** Every console snippet below reads the repo root from `~/.embedded-hacking-repo`, so IDA never needs a database open and nothing is hardcoded. From the repo root, run once: + +**macOS / Linux:** + +```bash +pwd > ~/.embedded-hacking-repo +``` + +**Windows (PowerShell):** + +```powershell +(Get-Location).Path | Set-Content "$env:USERPROFILE\.embedded-hacking-repo" +``` + +**Then build from the IDA console**, so the whole build -> patch -> flash loop stays inside IDA. The console inherits a minimal `PATH` — on macOS just `/usr/bin:/bin:/usr/sbin:/sbin` — so it does not see Homebrew; add your package manager's `bin` first, then run plain `cmake`. + +**macOS Apple Silicon:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() +os.environ["PATH"] = "/opt/homebrew/bin:" + os.environ["PATH"] # the console's PATH omits Homebrew +proj = os.path.join(root, "0x001a_operators") +subprocess.run(["cmake", "-B", "build", "-G", "Ninja", "-DPICO_BOARD=pico2", + "-DPICO_PLATFORM=rp2350", "-DCMAKE_BUILD_TYPE=Release"], cwd=proj) +subprocess.run(["cmake", "--build", "build"], cwd=proj) +``` + +**Linux x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() +proj = os.path.join(root, "0x001a_operators") +subprocess.run(["cmake", "-B", "build", "-G", "Ninja", "-DPICO_BOARD=pico2", + "-DPICO_PLATFORM=rp2350", "-DCMAKE_BUILD_TYPE=Release"], cwd=proj) +subprocess.run(["cmake", "--build", "build"], cwd=proj) +``` + +**Windows x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() +proj = os.path.join(root, "0x001a_operators") +subprocess.run(["cmake", "-B", "build", "-G", "Ninja", "-DPICO_BOARD=pico2", + "-DPICO_PLATFORM=rp2350", "-DCMAKE_BUILD_TYPE=Release"], cwd=proj) +subprocess.run(["cmake", "--build", "build"], cwd=proj) +``` + +The build directory now contains the pair we need: + +- `0x001a_operators/build/0x001a_operators.elf` and `.bin` — the `.bin` is **17484** bytes (`0x444c`) + +If the ARM toolchain is not on your `PATH`, add `-DPICO_TOOLCHAIN_PATH=...`: + +| OS | Typical toolchain path | +| -- | ---------------------- | +| Windows x64 | `C:/Program Files/Arm GNU Toolchain arm-none-eabi/14.2 rel1/bin` | +| macOS Apple Silicon | `~/.pico-sdk/toolchain/14_2_Rel1/bin` | +| Linux x64 | `/usr` | + +> **This guide's toolchain lives at `~/.pico-sdk/toolchain/14_2_Rel1/bin`.** All of `arm-none-eabi-nm`, `arm-none-eabi-objdump`, and `arm-none-eabi-gdb` resolved in this document come from there. If your install is elsewhere, `which arm-none-eabi-nm` tells you where to point. + +### Step 4: Dump the ELF symbol map + +This is the ground truth for the whole lesson. Run `arm-none-eabi-nm` on the ELF and keep the output in a terminal or a text file: + +**macOS Apple Silicon / Linux x64:** + +```bash +arm-none-eabi-nm -n --defined-only build/0x001a_operators.elf | grep -E ' [Tt] ' +``` + +**Windows x64:** + +```powershell +arm-none-eabi-nm -n --defined-only build\0x001a_operators.elf | Select-String ' [Tt] ' +``` + +Each line is `address type name`. The `T`/`t` type is a function. Here are the functions this lesson uses. The signatures come from the ELF's DWARF debug info queried with `arm-none-eabi-gdb -batch -ex "ptype "`, so they are exact. + +**Our code and the startup chain:** + +| Address | ELF symbol | Signature | Role | +| ------- | ---------- | --------- | ---- | +| `0x1000015c` | `_reset_handler` | `void _reset_handler(void)` | reset entry | +| `0x10000186` | `platform_entry` | `void platform_entry(void)` | calls `runtime_init`, `main`, `exit` | +| `0x1000019a` | `data_cpy` | `void data_cpy(void*, void*, void*)` | copies `.data` from flash to SRAM | +| `0x100001e4` | `_init` | `void _init(void)` | runs `.init_array` | +| `0x10000210` | `frame_dummy` | `void frame_dummy(void)` | C runtime boilerplate | +| `0x10000234` | `main` | `int main(void)` | the lesson function (all four static helpers inlined) | +| `0x100002d4` | `dht11_init` | `void dht11_init(uint8_t)` | the `dht11.c` init function | +| `0x100002f4` | `dht11_read` | `bool dht11_read(float*, float*)` | the `dht11.c` read function (all six static helpers inlined) | + +**The GPIO and timer functions `main` / `dht11.c` reach:** + +| Address | ELF symbol | Signature | Role | +| ------- | ---------- | --------- | ---- | +| `0x10000440` | `gpio_set_function` | `void gpio_set_function(uint, gpio_function_t)` | SDK GPIO function select (UART pins) | +| `0x1000047c` | `gpio_set_pulls` | `void gpio_set_pulls(uint, bool, bool)` | SDK pull config (`gpio_pull_up` inlined) | +| `0x100004a4` | `gpio_init` | `void gpio_init(uint)` | SDK GPIO init (`dht11_init` calls it) | +| `0x10000f00` | `sleep_us` | `void sleep_us(uint64_t)` | SDK microsecond delay (`dht11_read` calls it) | +| `0x10000fd8` | `sleep_ms` | `void sleep_ms(uint32_t)` | SDK millisecond delay (`main`, `dht11_read`) | +| `0x100011bc` | `time_us_64` | `uint64_t time_us_64(void)` | SDK microsecond clock (`printf` path) | +| `0x100011d0` | `busy_wait_us` | `void busy_wait_us(uint64_t)` | UART timing loop | +| `0x10001250` | `uart_init` | `uint uart_init(uart_inst_t*, uint)` | SDK UART init | +| `0x10001424` | `clock_get_hz` | `unsigned long clock_get_hz(clock_handle_t)` | UART clock lookup | + +**The stdio/UART and printf chain `main` reaches:** + +| Address | ELF symbol | Signature | Role | +| ------- | ---------- | --------- | ---- | +| `0x1000313c` | `exit` | `void exit(int)` | C runtime exit | +| `0x10003144` | `runtime_init` | `void runtime_init(void)` | SDK runtime init | +| `0x10003170` | `stdio_out_chars_crlf` | `void stdio_out_chars_crlf(stdio_driver_t*, const char*, int)` | CRLF output driver | +| `0x10003280` | `stdio_put_string` | `int stdio_put_string(const char*, int, bool, bool)` | buffered string output | +| `0x1000336c` | `stdio_set_driver_enabled` | `void stdio_set_driver_enabled(stdio_driver_t*, bool)` | enable the UART driver | +| `0x10003394` | `stdio_init_all` | `bool stdio_init_all(void)` | SDK serial init | +| `0x10003424` | `__wrap_puts` | `int __wrap_puts(const char*)` | the `puts` wrapper (`DHT11 read failed`) | +| `0x10003460` | `__wrap_vprintf` | `int __wrap_vprintf(const char*, va_list)` | printf core | +| `0x10003524` | `__wrap_printf` | `int __wrap_printf(const char*, ...)` | the `printf` wrapper (all seven calls) | +| `0x100036e0` | `stdio_uart_init` | `void stdio_uart_init(void)` | SDK UART stdio init | +| `0x10003820` | `strlen` | `size_t strlen(const char*)` | C runtime string length | + +**SDK helpers the `printf` path reaches:** + +| Address | ELF symbol | Signature | Role | +| ------- | ---------- | --------- | ---- | +| `0x10001a44` | `_out_rev` | `unsigned _out_rev(out_fct_type, char*, size_t, size_t, const char*, size_t, unsigned, unsigned)` | reversed-digit output | +| `0x10001ae0` | `_ntoa_format` | `unsigned _ntoa_format(out_fct_type, char*, size_t, size_t, char*, size_t, bool, unsigned, unsigned, unsigned, unsigned)` | number formatter | +| `0x10001cb4` | `_out_char` | `void _out_char(char, void*, size_t, size_t)` | single-char sink | +| `0x100026fc` | `_vsnprintf` | `int _vsnprintf(out_fct_type, char*, size_t, const char*, va_list)` | the format dispatcher | +| `0x100030e0` | `vfctprintf` | `int vfctprintf(void (*)(char, void*), void*, const char*, va_list)` | printf format engine | + +Things in this project that have **no symbol of their own**, because the compiler inlined them: + +- `print_operator_results`, `compute_arithmetic_ops`, `compute_operators`, `print_dht11_reading` — the four `static` helpers in `0x001a_operators.c` are inlined into `main`, so their bodies appear directly inside `main`. +- `send_start_signal`, `wait_for_level`, `wait_response`, `read_bit`, `read_40_bits`, `validate_checksum` — the six `static` helpers in `dht11.c` are inlined into `dht11_read`, along with `gpio_set_dir`, `gpio_put`, `gpio_get`, and `time_us_32` from the SDK headers. You see `mcrr` (SIO writes), `ldr [.., #4]` (SIO reads), and `ldr [r0, #40]` (TIMER0 read) directly inside `dht11_read`. +- `gpio_pull_up` — `static inline` in the SDK, so `dht11_init` compiles to a direct tail-call to `gpio_set_pulls`. + +> **`dht_pin` is a `b` symbol, not a function.** `arm-none-eabi-nm -n` lists `20000b7c b dht_pin`. That lowercase `b` is a **local data** symbol: the `dht11.c` file-scope `static uint dht_pin;` is parked in RAM `.bss` at `0x20000b7c`. It holds the GPIO number (`4`) after `dht11_init(4)` runs. There is no function there; do not `Y` it with a prototype. + +### Step 5: Flash and confirm the output + +A `.bin` has no headers, so OpenOCD must be told the base address `0x10000000`. From the repository root: + +**macOS Apple Silicon / Linux x64:** + +```bash +./flash.sh 0x001a_operators/build/0x001a_operators.bin +``` + +**Windows x64 (PowerShell):** + +```powershell +.\flash.ps1 -Bin 0x001a_operators\build\0x001a_operators.bin +``` + +**Or flash from the IDA console** (the console reads the repo root from the marker file, so it works with no database open): + +**macOS Apple Silicon / Linux x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) +bin_path = os.path.join(root, "0x001a_operators", "build", "0x001a_operators.bin") +log = os.path.join(os.path.dirname(bin_path), "flash.log") +subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # free the probe first +subprocess.Popen([os.path.join(root, "flash.sh"), bin_path], + stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) +print("flashing in the background; log:", log) +``` + +**Windows x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) +bin_path = os.path.join(root, "0x001a_operators", "build", "0x001a_operators.bin") +log = os.path.join(os.path.dirname(bin_path), "flash.log") +subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"]) # free the probe first +subprocess.Popen(["powershell", "-ExecutionPolicy", "Bypass", "-File", + os.path.join(root, "flash.ps1"), "-Bin", bin_path], + stdout=open(log, "w"), stderr=subprocess.STDOUT) +print("flashing in the background; log:", log) +``` + +Wait for `wrote 17484 bytes ...` and `** Verified OK **`. Open a serial monitor at **115200** baud: + +- **Windows x64:** PuTTY -> Connection type **Serial**, the Pico's COM port, speed `115200`. +- **macOS Apple Silicon:** `screen /dev/tty.usbmodem* 115200` (quit with `Ctrl-A` then `K`). +- **Linux x64:** `minicom -D /dev/ttyACM0 -b 115200`. + +``` +arithmetic_operator: 50 +increment_operator: 5 +relational_operator: 0 +logical_operator: 0 +bitwise_operator: 10 +assignment_operator: 10 +Humidity: 51.0%, Temperature: 23.8°C +... +``` + +Two of these values are *not* what a naive reading of the source predicts, and the build is correct: + +- **`increment_operator: 5`** — `compute_arithmetic_ops` takes `x` **by value**, so the `*incr = x++;` inside the helper increments the helper's private copy. `compute_operators`' own `x` is still `5` afterwards. +- **`bitwise_operator: 10`** and **`assignment_operator: 10`** — because `x` is still `5`, `x << 1` is `10` (not `12`), and `x += 5` is `10` (not `11`). The relational and logical operators compare `5 > 10`, so both are `0`. + +The humidity and temperature lines come from the physical DHT11 and vary with your sensor. + +--- + +## Part 2: Load the Raw `.bin` into IDA + +Start from a fresh IDA state. If you already have a database for this lesson, **close it and start over**; a stale database keeps old names and patches. + +### Step 7: Bring the raw `.bin` into IDA + +A raw `.bin` has no headers, so IDA cannot know where it belongs or what architecture it is. You must supply both. If you just double-click the `.bin`, IDA may load it with a guessed architecture, and every address in this lesson will be wrong. + +#### 1.1 Open the file +1. **File ▸ Open…** (Ctrl/Cmd+O). +2. Select the `.bin` file and click **Open**. + +IDA opens the **"Load a new file"** dialog because a raw `.bin` has no header. + +#### 1.2 Set the format and processor +In the *Load a new file* dialog: +1. **Format**: leave it as **Binary file** (IDA auto-detects a headerless image). +2. **Processor type**: click the **…** button next to the processor field. In the *Processor type* dialog: + - Family: **ARM** + - Type: **ARM Little-endian** (the 32-bit ARM module). + - Click **OK**. + +> If IDA asks **"Do you want to disassemble it as 64-bit code?"** — click **No**. +> The RP2350 is 32-bit; answering *Yes* loads AArch64 and you get `X` registers / data. (This is the single most common cause of the `DCB` wall.) + +#### 1.3 Configure the ARM architecture and Thumb mode +Still in the *Load a new file* dialog, open the processor options (the **Processor options** / **Set…** button, which opens the dialog titled **ARM architecture options**): +- **ARM architecture**: choose **ARMv8-M** (this is the Cortex-M33 / RP2350 core). +- **Thumb instructions**: select **Thumb-2** (ARMv8-M is Thumb-only, so this is the correct mode). +- Leave **automatic ARM-THUMB switch** off; we want Thumb throughout. + +#### 1.4 Set the loading address +- **Loading address**: enter **`10000000`** (hex; the RP2350 XIP flash base). + IDA rejects addresses that don't look like ROM/RAM with *"The loading address should belong to RAM or ROM"* — `0x10000000` is the correct flash window. + +Leave **Manual load** and **Create segments** at their defaults. Click **OK**. + +#### 1.5 Force Thumb, then seed the code from the vector table +A raw `.bin` has no header, so IDA's loader has **no entry point** and defaults the segment to **ARM mode** (which cannot decode Thumb). Two required steps — in this order: + +**A. Set the segment to Thumb (do this first).** +- **Edit ▸ Segments ▸ Set default segment register value…** → register **`T`** = **`1`** (or press **`Alt+G`**). IDA reanalyzes the segment as Thumb automatically. + +**B. Seed the code from the vector table.** +1. **G** → `10000000`. The first two words are the initial stack pointer and the **reset vector**. +2. **Read the 4-byte word at `0x10000004`** (do **not** assume its value — it differs per build). +3. **Clear bit 0** (the ARM **Thumb** flag) → the reset handler address. +4. **G** to that address → press **C** (**MakeCode**). IDA disassembles the reset handler and follows its `bl`s into `main`. + +Once `main` shows code, the import is correct. + +**Why IDA needs this and others don't:** IDA's generic raw-binary ARM loader treats the image as flat data and waits for you to set Thumb and mark the entry point. It's an IDA quirk, not a mistake on your part. + +### Step 8: The views you will use + +- **Linear view:** the disassembly listing. You navigate, read, and patch here. +- **Graph view:** the control-flow graph of the current function. +- **Decompiler (HLIL):** the pseudo-C decompilation. +- **Hex view:** raw bytes, used for patching. +- **Function list:** the sidebar list of every detected function. + +Navigation: `G` go to address, `N` rename, `Y` set type or signature, `;` add a comment. Breakpoints are set from the GUI through the GDB MI adapter — see Step 12. + +> **macOS function keys:** the top-row `F` keys are usually mapped to system functions. Every step here uses menu paths that work without them. + +> **Optional — load the RP2350 SVD for peripheral names.** If you want IDA to label peripheral registers (TIMER0, SIO, UART0, …) instead of bare addresses, load the RP2350 SVD. It ships with Week 4, so it lives at **`WEEK04/rp2350.svd`** inside the repository — remember it is in **Week 4**, not this week. This lesson does not need it; the ELF symbol map already names every function. + +--- + +## Part 3: Dynamic — Break at the `printf` Call and Hack Live + +### Step 9: Start OpenOCD as a live debug server + +Make sure no other OpenOCD is running; a forgotten server holds port `3333`. + +**macOS / Linux:** + +```bash +ps aux | grep -i openocd +``` + +**Windows (PowerShell):** + +```powershell +Get-Process | Where-Object { $_.ProcessName -like '*openocd*' } +``` + +Stop any leftover server gracefully: + +**macOS / Linux:** + +```bash +pkill -TERM -f openocd +``` + +**Windows (PowerShell):** + +```powershell +Get-Process openocd -ErrorAction SilentlyContinue | Stop-Process +``` + +Start the server **parked at `main`**: + +**macOS Apple Silicon / Linux x64:** + +```bash +BP_ADDR=0x10000234 ./debug-server.sh +``` + +**Windows x64 (PowerShell):** + +```powershell +$env:BP_ADDR="0x10000234"; .\debug-server.ps1 +``` + +**Or start it from the IDA console**, freeing the probe first and launching the server in the background so the console returns immediately: + +**macOS Apple Silicon / Linux x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) +subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # stop any running server first +log = os.path.join(root, "openocd.log") +p = subprocess.Popen([os.path.join(root, "debug-server.sh")], cwd=root, + env=dict(os.environ, BP_ADDR="0x10000234"), + stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) +print("OpenOCD started (pid", p.pid, "); log:", log) +``` + +**Windows x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) +subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"]) # stop any running server first +log = os.path.join(root, "openocd.log") +p = subprocess.Popen(["powershell", "-ExecutionPolicy", "Bypass", "-File", + os.path.join(root, "debug-server.ps1")], cwd=root, + env=dict(os.environ, BP_ADDR="0x10000234"), + stdout=open(log, "w"), stderr=subprocess.STDOUT) +print("OpenOCD started (pid", p.pid, "); log:", log) +``` + +`Popen` returns in a few milliseconds; the server keeps running in the background. Check `openocd.log` for `Listening on port 3333`, then connect in Step 10. + +Wait for: + +``` +Info : [rp2350.dap.core0] Examination succeed +Startup breakpoint at 0x10000234 (2-byte hardware execute, one-shot). +Info : starting gdb server for rp2350.dap.core0 on 3333 +Info : Listening on port 3333 for gdb connections +``` + +> **`BP_ADDR` parks the core at `main` before any client connects.** The script arms a 2-byte hardware breakpoint and then does the startup `reset run`, so the core runs from the vector table and stops at your address with no debugger attached yet. When IDA connects a moment later, the first thing it reads is already the truth: `Stopped at 0x10000234`. This is the whole reason the lab works cleanly — you never have to drive a reset from outside the GUI. +> +> Use the address you actually want to stop at: +> +> | What you want to stop at | Address | Command | +> | --- | --- | --- | +> | `main` (once per reset) | `0x10000234` | `BP_ADDR=0x10000234 ./debug-server.sh` | +> | The **loop** — the arithmetic `printf` call, hit every iteration | `0x10000272` | `BP_ADDR=0x10000272 ./debug-server.sh` | +> +> ```bash +> BP_ADDR=0x10000234 ./debug-server.sh # park at main +> BP_ADDR=0x10000272 ./debug-server.sh # park in the loop instead +> ``` +> +> ```powershell +> $env:BP_ADDR="0x10000234"; .\debug-server.ps1 # park at main +> $env:BP_ADDR="0x10000272"; .\debug-server.ps1 # park in the loop +> ``` +> +> **This startup stop is single-use.** OpenOCD flushes breakpoints when a client connects, so this one is gone once IDA attaches — fine for `main`, which only runs once per reset. Every breakpoint after that is set from the IDA GUI (Step 12) and is repeatable. To stop at `main` again, restart the server with `BP_ADDR` and reconnect. + +> **Exactly one core.** The line must say `core0` and must **not** mention `core1`. Core1 is never started by this firmware; exposing it makes IDA read core1's reset-state registers, which are not real addresses, and OpenOCD floods the log with `Failed to read memory at 0xf0000000`. The scripts already use `USE_CORE=0`; do not change it. + +> **Windows driver note:** the Debug Probe must use the **WinUSB** driver. If OpenOCD reports `unable to open CMSIS-DAP device`, install it with [Zadig](https://zadig.akeo.ie/) (select `Debug Probe (CMSIS-DAP)` -> WinUSB). + +### Step 10: Connect IDA to the GDB server + +1. Make sure the image is open and analyzed (Part 2) and the server from Step 9 is running (parked at `main`). +2. Choose `Debugger -> Connect to Remote Process`. +3. In the **adapter** dropdown, select **GDB MI**. +4. In the **connect** settings group, set **IP Address** to `127.0.0.1` and **Port** to `3333`. +5. Set **Full GDB Executable Path** to the `arm-none-eabi-gdb` from the **Arm GNU Toolchain 14.2.rel1**. It ships for all three hosts, and the Raspberry Pi Pico VS Code extension installs that same 14.2.rel1 toolchain (including `arm-none-eabi-gdb`) on all of them: + + | OS | `arm-none-eabi-gdb` path | + | -- | ------------------------ | + | macOS Apple Silicon | `/Applications/ArmGNUToolchain/14.2.rel1/arm-none-eabi/bin/arm-none-eabi-gdb` (or the Pico extension's `~/.pico-sdk/toolchain/14_2_Rel1/bin/arm-none-eabi-gdb`) | + | Windows x64 | `%USERPROFILE%\.pico-sdk\toolchain\14_2_Rel1\bin\arm-none-eabi-gdb.exe` (Pico extension), or `C:\Program Files (x86)\Arm GNU Toolchain arm-none-eabi\14.2 rel1\bin\arm-none-eabi-gdb.exe` | + | Linux x64 | `~/.pico-sdk/toolchain/14_2_Rel1/bin/arm-none-eabi-gdb` (Pico extension), or the `bin/` directory of the extracted `arm-gnu-toolchain-14.2.rel1-x86_64-arm-none-eabi` tarball | +6. Click **Accept**. + +> **Use the GDB MI adapter.** It launches a real `arm-none-eabi-gdb --interpreter=mi2` and lets IDA drive it, so breakpoints and stepping go through real GDB — which sends the correct 2-byte breakpoint length and handles step-over itself. Verified working end to end: connect, GUI breakpoints (**Add Hardware Breakpoint...**, hardware execute), **Step Into** / **Step Over**, and register edits. Stops are reported as `Breakpoint` (not `SingleStep`). +> +> **Do NOT have any breakpoints set in IDA before you connect.** With the GDB MI adapter, attaching while IDA already has a breakpoint **hangs the session**. Start the server parked with `BP_ADDR` (Step 9), connect, and only add hardware breakpoints *after* the connection is up. This is a IDA bug; it is the single most common GDB MI failure. +> +> **The GDB executable path matters.** Use the **14.2.rel1** build on every OS (Windows, macOS, Linux). The 13.3.rel1 build did **not** connect in testing. +> +> **This step is temporary.** Vector35 plans to ship a GDB binary with the GDB MI adapter ([Vector35/debugger#929](https://github.com/Vector35/debugger/issues/929), milestone *Langara*). Once that lands, IDA provides GDB itself and you will not need to set **Full GDB Executable Path** at all. +> +> **Do not pick Corellium.** IDA's adapter dropdown also lists **Corellium**, which is for Corellium's virtual devices and expects an API token, not a local OpenOCD server. It is not the adapter for this lab. The dropdown is a combo box, so an accidental arrow-key press can land on it — always read the label back and confirm it says **GDB MI** before clicking **Accept**. + +> **The adapter and port are not saved in the `.i64`.** Every time you relaunch IDA you must re-select **GDB MI**, re-enter port `3333`, and re-set the GDB path. + +> **Watch for an off-screen error dialog.** When a connection fails, IDA pops a `IDA critical alert` window that can be positioned mostly outside the main window, which makes it look like nothing happened. If the connect seems to do nothing, check your other display. + +The target keeps running. Open the **Registers** tab (bug icon) and confirm you see live values. `pc` inside `0x10003xxx` and `sp` just below `0x20082000` are healthy. + +> **If `pc` is `0x00000088`, `0x000000ec`, or `sp` is `0xf0000000`, the session is bad.** Restart the server, then restart IDA (a server restart while attached leaves IDA in a stale session), and connect again. + +### Step 11: Find `main` without relying on its address + +`main` can move between programs, so we do not guess it. We follow the one fixed path to it. Press `G` and go to `0x10000000`: + +``` +0x10000000 0x20082000 initial stack pointer (top of SRAM) +0x10000004 0x1000015d reset vector +``` + +Bit 0 of a vector is the Thumb bit, so `0x1000015d` means "start at `0x1000015c`". That is `_reset_handler`. Follow the reset path to `0x10000186`, `platform_entry`: + +```asm +10000186: ldr r1, [pc, #80] @ (100001d8 ) +10000188: blx r1 +1000018a: ldr r1, [pc, #80] @ (100001dc ) +1000018c: blx r1 +1000018e: ldr r1, [pc, #80] @ (100001e0 ) +10000190: blx r1 +10000192: bkpt 0x0000 +10000194: b.n 10000192 +``` + +**The middle `blx` at `0x1000018c` is the call to `main`.** `platform_entry` is byte-identical in every project, so `0x1000018c` catches `main` no matter where the linker placed it. The literal pool at `0x100001dc` holds `main | 1`; clearing bit 0 gives `0x10000234`. + +### Step 12: Set a hardware breakpoint in the GUI + +With the **GDB MI** adapter, IDA sets breakpoints through real GDB, which sends the correct 2-byte length, so you set them **in the UI**. There is no command port here. + +> **Why older drafts used the command port.** IDA's **GDB RSP** adapter is its own minimal RSP client and sends a **1-byte** breakpoint (`Z0,,1`); the Cortex-M33 FPB comparators need 2 bytes, so OpenOCD rejected it with `only breakpoints of two bytes length supported`. The old workaround was to arm breakpoints by hand over telnet. **The GDB MI adapter does not have this problem** — it drives real `arm-none-eabi-gdb`, which sends the right length. So everything below is done in the GUI. The command port still exists as a fallback (see the end of this step), but you do not need it. + +#### Where you can stop + +| You want to stop at | Address | How | Repeatable? | +| --- | --- | --- | --- | +| **`main`** | `0x10000234` | The server starts parked there with `BP_ADDR=0x10000234` (Step 9), so IDA is already stopped at `main` when it connects. | No — `main` runs once per reset. | +| **The arithmetic `printf` call** | `0x10000272` | Set a hardware breakpoint in the GUI, then click **Resume**. | Yes — fires on every iteration. | +| **The second `printf` call (increment)** | `0x1000027a` | Same. | Yes. | +| **The `dht11_read` call** | `0x100002a2` | Same. | Yes. | + +#### Set the loop breakpoint in the GUI + +1. Press `G`, type the loop address (`0x10000272`), and press Enter. +2. Set a **hardware execution** breakpoint at that address, either way: + - `Debugger -> Add Hardware Breakpoint...` — a **hardware execute** (`HE`) breakpoint. **Use this one.** + - click the line and press `F2` (`Debugger -> Toggle Breakpoint`) — a **software** breakpoint. It will **not** work here: the code is in read-only flash, so GDB cannot install it and the core just keeps running. +3. Click **Resume**. The core is already running the loop, so the breakpoint fires on the next iteration. IDA stops with the PC at the loop address and reports it as a **Breakpoint** — verified: `Stopped (Breakpoint) at 0x10000272`. + +> **No breakpoints before you connect.** With GDB MI, a breakpoint set before the connection hangs the session (Step 10). Start parked with `BP_ADDR`, connect, *then* add breakpoints. + +#### Stepping + +With the target halted at the breakpoint, **Step Into** (`F7`) and **Step Over** (`F8`) run through real GDB and move the PC. Verified: `0x10000272 -> 0x10003524 -> 0x10003526 -> ...`. + +> **Step Over on the raw `.bin` steps *into* calls.** The raw image has no symbol for `__wrap_printf`, so **Step Over** at the `printf` call behaves like **Step Into**. When the lab needs to execute the call and then stop, it moves the breakpoint to the return site and clicks **Resume** instead (Step 13 shows this). + +> **Never use IDA's Restart button.** On RP2350 it resets and halts inside the boot ROM (`pc=0x88`, `sp=0xf0000000`). To reset cleanly, restart the server with `BP_ADDR` and reconnect. + +> **If you ever need the command port.** It is still there — `nc 127.0.0.1 4444`, and `bp 2 hw` still arms a breakpoint, `rbp ` / `rbp all` still remove them. It is the fallback if you switch back to the **GDB RSP** adapter, whose 1-byte breakpoints the GUI cannot set. With GDB MI you do not need it for this lab. + +### Step 13: HACK IT LIVE — change the printed `arithmetic_operator` + +`main` loads the constant `0x32` (50) into `r1` and calls `printf` on every iteration. We break on that call and change it live: + +```asm +1000026e: movs r1, #50 @ 0x32 +10000270: ldr r0, [pc, #68] @ (100002b8 ) +10000272: bl 10003524 <__wrap_printf> +10000276: movs r1, #5 +10000278: ldr r0, [pc, #64] @ (100002bc ) +1000027a: bl 10003524 <__wrap_printf> +``` + +1. Press `G`, go to `0x10000272` (the `bl __wrap_printf` for `arithmetic_operator`). +2. Set a **hardware execute** breakpoint there: `Debugger -> Add Hardware Breakpoint...`. (Do not use `F2` — that is a software breakpoint and will not work on read-only flash.) +3. Click **Resume** in IDA. The target is already running the loop, so the breakpoint fires on the next iteration. IDA stops with the program counter at `0x10000272`, `r0 = 0x100038e8`, and `r1 = 0x32`. +4. Open the **Registers** widget (bug icon -> **Registers**). +5. Find `r1`. Its value is `0x32` (50), loaded by the `movs r1, #50` at `0x1000026e`. +6. **Set `r1` to `0x63` (99).** From IDA's Python console (`Plugins -> Python Console`): + ```python + dbg.set_reg_value("r1", 0x63) + ``` + `dbg.set_reg_value(name, value)` writes one register (returns `True` on success). You can also right-click `r1` in the **Registers** widget, press `E` (edit), type `63`, and press Enter. The widget may not repaint the value, but the write reaches the target — you confirm it by the printed output in the next steps. +7. **Move the breakpoint past the call.** You want `printf` to run once and then stop, so move the breakpoint from `0x10000272` to the instruction *after* the call, `0x10000276` (the `movs r1, #5` that begins the increment half of the loop): remove the breakpoint at `0x10000272` and set a hardware breakpoint at `0x10000276`. Two reasons not to just click **Step Over** here: a breakpoint left on the current PC re-traps the step, and IDA's **Step Over** steps *into* `__wrap_printf` on this raw `.bin` because the image carries no symbol for the call. Moving the breakpoint to the return site is deterministic. +8. Click **Resume** in IDA. The core executes `bl __wrap_printf` with `r1 = 0x63`, so this iteration prints `arithmetic_operator: 99`, then stops at `0x10000276`. +9. Look at your serial monitor — the `screen` session on the Pico's USB serial port — and at the **Target** tab in IDA: + + ``` + arithmetic_operator: 99 + ``` + +You changed a running program's output without touching the binary. + +### Step 13b: HACK THE STRING LIVE — change `arithmetic_operator:` to `hacked_operator:` (optional) + +The text `"arithmetic_operator: %d\r\n"` lives in flash (`.rodata`) at `0x100038e8`, and flash is **read-only at runtime** — a debugger write there does not stick. So instead of overwriting the text in place, redirect the pointer: at the `printf` call, `r0` holds the string address, so point `r0` at a replacement string you place in RAM. + +1. Arm the breakpoint at the `printf` call and hit it, exactly as in Step 13 steps 1-3. At the stop, `r0 = 0x100038e8` and `r1 = 0x32`. +2. Put the replacement string into free RAM at `0x20080000` from IDA's **Python console** (`Plugins -> Python Console`) — no command port needed: + ```python + dbg.write_memory(0x20080000, b"hacked_operator: %d\r\n\x00") + ``` + `dbg.write_memory(address, bytes)` is IDA's debugger memory-write API; it returns `True` on success. That writes `hacked_operator: %d\r\n\0`. +3. Point `r0` at that string: + ```python + dbg.set_reg_value("r0", 0x20080000) + ``` + (Or right-click `r0` in the **Registers** widget, press `E`, type `0x20080000`, and press Enter.) +4. If you want the value hack too, set `r1` to `0x63` as in Step 13. Then move the breakpoint past the call in the GUI (remove it at `0x10000272`, set one at `0x10000276`) and click **Resume**. The core runs `printf` with `r0` pointing at your RAM string and `r1 = 0x63`, so this iteration prints: + ``` + hacked_operator: 99 + ``` + then stops at `0x10000276`. + +Like the value hack, this is **one iteration only**: the loop reloads `r0` (and `r1`) from flash on every pass, so the next line is `arithmetic_operator: 50` again. The permanent version is the static patch in Step 18c. + +### Step 14: Why the hack reverts (and why we patch next) + +Press **Resume**. The loop branches back to `0x1000026e`, which reloads `movs r1, #50`, so the next line is `arithmetic_operator: 50`. The live edit changed one iteration only. There is no variable in memory to change; the value is baked into the instruction. To make `arithmetic_operator: 99` permanent we must patch the instruction. That is the static pass. + +Press **Pause** to stop the output flood. + +### Step 15: Kill the debugger and OpenOCD + +The live hack is done. Do this **before** the static pass. + +1. In the **Debugger** sidebar, click the **X** (**Kill**) (or **`Debugger -> Kill`**) to disconnect IDA. +2. **Kill does not stop the OpenOCD process** — `debug-server.sh` started it separately, and it keeps running and holding the probe. Stop it from the IDA console: + + **macOS / Linux:** + + ```python + import subprocess + subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # stop the debug server, free the probe + ``` + + **Windows:** + + ```python + import subprocess + subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"]) # stop the debug server, free the probe + ``` + +3. Confirm nothing is left: `pgrep -fl openocd` (macOS/Linux) prints nothing. + +From a terminal it is the same: `pkill -TERM -f openocd`, or `Get-Process openocd | Stop-Process` on Windows. + +--- + +## Part 4: Static — Resolve the Functions in IDA and Patch + +### Step 16: Resolve the functions in the IDA GUI + +We now name the functions in IDA using the ELF symbol map from Step 4. IDA loaded the raw `.bin` with **no symbols**, so every function shows as `sub_` — resolving means giving each one its real name and signature. + +Three keys do all the work: + +| Key | IDA action | Use it for | +| --- | ------------------- | ---------- | +| `G` | Go to address | Jump to a function's address | +| `Y` | **Change Type** | Set the function's signature. The dialog shows the full prototype, so this sets the name *and* the type in one step. | +| `N` | Rename | Rename only, when you just want the name and not the type | + +For each function below: `G` to its address, then **`Y` (Change Type)** and type the prototype from the table. + +#### How to resolve a function in IDA (`Y`) + +`Y` is the **Change Type** key, and it is what actually resolves the function — it turns `void sub_10003394()` into `bool stdio_init_all(void)`. The Change Type dialog shows the full declaration (name and type), so typing the prototype sets both: + +1. `G` to the function's address. The cursor lands on the function. +2. Press **`Y`**. In the Change Type dialog, type the prototype from the table exactly — for example `bool stdio_init_all(void)` — and press Enter. + +The decompiler header then shows the real prototype, and calls to the function read cleanly instead of `sub_()`. `N` is only for renaming without touching the type; `Y` alone sets both the name and the type. + +If `Y` seems to do nothing, confirm the cursor is on the function, or right-click it and pick **Change Type...**. IDA parses what you type and silently keeps the old type if it does not parse, so glance at the header after each `Y`. + +#### Worked example: `main` + +1. Press `G`, type `0x10000234`, press Enter. The view jumps there; the cursor lands on `sub_10000234`. +2. Press **`Y`** (Change Type), type `int main(void)`, press Enter. That sets the name to `main` and the type to `int(void)`. + +> **IDA shows `int32_t` where Ghidra shows `int`.** After you set `int main(void)`, the decompiler header may read `int32_t main(void)`. That is the same type — on this platform `int` is 32 bits and IDA's parser normalises it to `int32_t`. Do not fight it; it is not an error. + +#### Worked example: `dht11_init` + +1. `G` -> `0x100002d4`. +2. `Y` -> `void dht11_init(uint8_t pin)`. + +This is our own `dht11.c` code. In this build the SDK's `gpio_init` and `gpio_pull_up` are called directly (`gpio_pull_up` as a tail-call to `gpio_set_pulls`), so the function is small. + +#### Worked example: `dht11_read` + +1. `G` -> `0x100002f4`. +2. `Y` -> `bool dht11_read(float* humidity, float* temperature)`. + +This is the big one: all six `dht11.c` static helpers are inlined here, along with `gpio_set_dir` / `gpio_put` / `gpio_get` / `time_us_32`, so `dht11_read` contains the entire single-wire protocol and the `0.1f` scale. + +#### Worked example: `gpio_init` + +1. `G` -> `0x100004a4`. +2. `Y` -> `void gpio_init(uint gpio)`. + +#### Worked example: `gpio_set_pulls` + +1. `G` -> `0x1000047c`. +2. `Y` -> `void gpio_set_pulls(uint gpio, bool up, bool down)`. + +This is what `gpio_pull_up(4)` in `dht11_init` compiles to. + +#### Worked example: `__wrap_printf` + +1. `G` -> `0x10003524`. +2. `Y` -> `int __wrap_printf(const char *fmt, ...)`. Keep the `...` — `printf` is variadic. + +> **`printf` in our source is `__wrap_printf` in the binary.** The SDK links our `printf` calls to its `__wrap_printf` wrapper, which forwards to `__wrap_vprintf`. Rename it `printf` if you prefer the lesson's shorthand, but `__wrap_printf` is what the ELF says. + +#### Worked example: `__wrap_puts` + +1. `G` -> `0x10003424`. +2. `Y` -> `int __wrap_puts(const char *s)`. + +This is the `else` branch of `print_dht11_reading`, which prints `"DHT11 read failed\r\n"`. (`__wrap_puts` is aliased to `stdio_puts` at the same address.) + +The rest of the chain is the same two keystrokes per function (`G`, then `Y`). This is **our code plus the library functions it actually calls** — not the whole SDK. `main` calls `stdio_init_all`, `dht11_init`, `__wrap_printf`, `dht11_read`, `__wrap_puts`, and `sleep_ms`, so we follow that chain down. + +The call chain for this project: + +``` +main +├── stdio_init_all ── stdio_uart_init ── gpio_set_function, uart_init, stdio_set_driver_enabled +│ └── uart_init ── clock_get_hz, busy_wait_us +├── dht11_init ── gpio_init, gpio_set_pulls (gpio_pull_up inlined) +├── __wrap_printf ── __wrap_vprintf ── vfctprintf ── _vsnprintf +│ │ └── _ntoa_format / _out_rev / _out_char +│ ├── stdio_out_chars_crlf +│ └── time_us_64 +├── dht11_read ── sleep_ms, sleep_us +│ └── send_start_signal / wait_for_level / wait_response / read_bit / +│ read_40_bits / validate_checksum / gpio_set_dir / gpio_put / +│ gpio_get / time_us_32 (all inlined; no calls) +└── __wrap_puts ── stdio_put_string +``` + +**Resolve every function in that chain:** + +| Address | Rename to (`N`) | Signature (`Y`) | +| ------- | --------------- | --------------- | +| `0x1000015c` | `_reset_handler` | `void _reset_handler(void)` | +| `0x10000186` | `platform_entry` | `void platform_entry(void)` | +| `0x1000019a` | `data_cpy` | `void data_cpy(void*, void*, void*)` | +| `0x100001e4` | `_init` | `void _init(void)` | +| `0x10000210` | `frame_dummy` | `void frame_dummy(void)` | +| **`0x10000234`** | **`main`** | **`int main(void)`** | +| `0x100002d4` | `dht11_init` | `void dht11_init(uint8_t)` | +| `0x100002f4` | `dht11_read` | `bool dht11_read(float*, float*)` | +| `0x10000440` | `gpio_set_function` | `void gpio_set_function(uint, gpio_function_t)` | +| `0x1000047c` | `gpio_set_pulls` | `void gpio_set_pulls(uint, bool, bool)` | +| `0x100004a4` | `gpio_init` | `void gpio_init(uint)` | +| `0x10000f00` | `sleep_us` | `void sleep_us(uint64_t)` | +| `0x10000fd8` | `sleep_ms` | `void sleep_ms(uint32_t)` | +| `0x100011bc` | `time_us_64` | `uint64_t time_us_64(void)` | +| `0x100011d0` | `busy_wait_us` | `void busy_wait_us(uint64_t)` | +| `0x10001250` | `uart_init` | `uint uart_init(uart_inst_t*, uint)` | +| `0x10001424` | `clock_get_hz` | `unsigned long clock_get_hz(clock_handle_t)` | +| `0x1000313c` | `exit` | `void exit(int)` | +| `0x10003144` | `runtime_init` | `void runtime_init(void)` | +| `0x10003170` | `stdio_out_chars_crlf` | `void stdio_out_chars_crlf(stdio_driver_t*, const char*, int)` | +| `0x10003280` | `stdio_put_string` | `int stdio_put_string(const char*, int, bool, bool)` | +| `0x1000336c` | `stdio_set_driver_enabled` | `void stdio_set_driver_enabled(stdio_driver_t*, bool)` | +| `0x10003394` | `stdio_init_all` | `bool stdio_init_all(void)` | +| `0x10003424` | `__wrap_puts` | `int __wrap_puts(const char*)` | +| `0x10003460` | `__wrap_vprintf` | `int __wrap_vprintf(const char*, va_list)` | +| `0x10003524` | `__wrap_printf` | `int __wrap_printf(const char*, ...)` | +| `0x100036e0` | `stdio_uart_init` | `void stdio_uart_init(void)` | +| `0x10003820` | `strlen` | `size_t strlen(const char*)` | + +**Resolve the SDK helpers the `printf` path reaches:** + +| Address | Rename to (`N`) | Signature (`Y`) | +| ------- | --------------- | --------------- | +| `0x10001a44` | `_out_rev` | `unsigned _out_rev(out_fct_type, char*, size_t, size_t, const char*, size_t, unsigned, unsigned)` | +| `0x10001ae0` | `_ntoa_format` | `unsigned _ntoa_format(out_fct_type, char*, size_t, size_t, char*, size_t, bool, unsigned, unsigned, unsigned, unsigned)` | +| `0x10001cb4` | `_out_char` | `void _out_char(char, void*, size_t, size_t)` | +| `0x100026fc` | `_vsnprintf` | `int _vsnprintf(out_fct_type, char*, size_t, const char*, va_list)` | +| `0x100030e0` | `vfctprintf` | `int vfctprintf(void (*)(char, void*), void*, const char*, va_list)` | + +> **A `void` return type may not stick — here is the fix.** IDA treats `void` as low-confidence, and its analysis can override it with an inferred type — most often `int32_t` on this 32-bit target. It is most visible on `_reset_handler` (a hand-written assembly entry that never returns normally), but it can happen to **any** function whose return type IDA thinks it can infer. +> +> Setting the full signature with `Y` reproduces the unwanted `int32_t`, and `fn.return_type = ...` fails too. What works is the **return-value** setter: +> +> ```python +> from binaryninja import ReturnValue, Type +> fn = bv.get_function_at(0x1000015c) +> if fn is not None: +> fn.return_value = ReturnValue(Type.void()) +> ``` +> +> That holds `_reset_handler` at `void` even after reanalysis. If it still will not stick, leave it — it does not affect the rest of the lesson. + +> **`dht_pin` is data, not a function.** `arm-none-eabi-nm -n` lists `20000b7c b dht_pin`. That lowercase `b` is a **local data** symbol: the linker parks the `dht11.c` file-scope static at RAM address `0x20000b7c`. `dht11_init(4)` stores `4` into it. There is no function there; do not `Y` it with a prototype. + +> **Shortcut — resolves name *and* type for every function.** Instead of doing `N` + `Y` by hand, paste this into IDA's Python console (`Plugins -> Python Console`). It sets each function's name and signature programmatically: +> +> ```python +> from binaryninja import Symbol, SymbolType +> # The raw .bin has no headers, so these SDK types don't exist. set_user_type() +> # re-parses each signature as C, so an undefined name raises +> # "SyntaxError: unknown type name '...'". Define them first. +> sdk = bv.parse_types_from_string(""" +> typedef unsigned int uint; +> typedef char* va_list; +> typedef unsigned long clock_handle_t; +> typedef void (*out_fct_type)(char, void*, size_t, size_t); +> struct stdio_driver; +> typedef struct stdio_driver stdio_driver_t; +> struct uart_inst; +> typedef struct uart_inst uart_inst_t; +> enum gpio_function { +> GPIO_FUNC_XIP = 0, GPIO_FUNC_SPI = 1, GPIO_FUNC_UART = 2, GPIO_FUNC_I2C = 3, +> GPIO_FUNC_PWM = 4, GPIO_FUNC_SIO = 5, GPIO_FUNC_PIO0 = 6, GPIO_FUNC_PIO1 = 7, +> GPIO_FUNC_GPCK = 8, GPIO_FUNC_USB = 9, GPIO_FUNC_NULL = 0x1f, +> }; +> typedef enum gpio_function gpio_function_t; +> """) +> for name, ty in sdk.types.items(): +> bv.define_user_type(name, ty) +> +> # address: (name, signature) +> funcs = { +> 0x1000015c: ("_reset_handler", "void _reset_handler(void)"), +> 0x10000186: ("platform_entry", "void platform_entry(void)"), +> 0x1000019a: ("data_cpy", "void data_cpy(void*, void*, void*)"), +> 0x100001e4: ("_init", "void _init(void)"), +> 0x10000210: ("frame_dummy", "void frame_dummy(void)"), +> 0x10000234: ("main", "int main(void)"), +> 0x100002d4: ("dht11_init", "void dht11_init(uint8_t)"), +> 0x100002f4: ("dht11_read", "bool dht11_read(float*, float*)"), +> 0x10000440: ("gpio_set_function", "void gpio_set_function(uint, gpio_function_t)"), +> 0x1000047c: ("gpio_set_pulls", "void gpio_set_pulls(uint, bool, bool)"), +> 0x100004a4: ("gpio_init", "void gpio_init(uint)"), +> 0x10000f00: ("sleep_us", "void sleep_us(uint64_t)"), +> 0x10000fd8: ("sleep_ms", "void sleep_ms(uint32_t)"), +> 0x100011bc: ("time_us_64", "uint64_t time_us_64(void)"), +> 0x100011d0: ("busy_wait_us", "void busy_wait_us(uint64_t)"), +> 0x10001250: ("uart_init", "uint uart_init(uart_inst_t*, uint)"), +> 0x10001424: ("clock_get_hz", "unsigned long clock_get_hz(clock_handle_t)"), +> 0x1000313c: ("exit", "void exit(int)"), +> 0x10003144: ("runtime_init", "void runtime_init(void)"), +> 0x10003170: ("stdio_out_chars_crlf", "void stdio_out_chars_crlf(stdio_driver_t*, const char*, int)"), +> 0x10003280: ("stdio_put_string", "int stdio_put_string(const char*, int, bool, bool)"), +> 0x1000336c: ("stdio_set_driver_enabled", "void stdio_set_driver_enabled(stdio_driver_t*, bool)"), +> 0x10003394: ("stdio_init_all", "bool stdio_init_all(void)"), +> 0x10003424: ("__wrap_puts", "int __wrap_puts(const char*)"), +> 0x10003460: ("__wrap_vprintf", "int __wrap_vprintf(const char*, va_list)"), +> 0x10003524: ("__wrap_printf", "int __wrap_printf(const char*, ...)"), +> 0x100036e0: ("stdio_uart_init", "void stdio_uart_init(void)"), +> 0x10003820: ("strlen", "size_t strlen(const char*)"), +> 0x10001a44: ("_out_rev", "unsigned _out_rev(out_fct_type, char*, size_t, size_t, const char*, size_t, unsigned, unsigned)"), +> 0x10001ae0: ("_ntoa_format", "unsigned _ntoa_format(out_fct_type, char*, size_t, size_t, char*, size_t, bool, unsigned, unsigned, unsigned, unsigned)"), +> 0x10001cb4: ("_out_char", "void _out_char(char, void*, size_t, size_t)"), +> 0x100026fc: ("_vsnprintf", "int _vsnprintf(out_fct_type, char*, size_t, const char*, va_list)"), +> 0x100030e0: ("vfctprintf", "int vfctprintf(void (*)(char, void*), void*, const char*, va_list)"), +> } +> for addr, (name, sig) in funcs.items(): +> bv.define_user_symbol(Symbol(SymbolType.FunctionSymbol, addr, name)) +> f = bv.get_function_at(addr) +> if f is not None: +> f.set_user_type(sig) +> ``` +> +> SDK type names (`stdio_driver_t`, `uart_inst_t`, `gpio_function_t`, plus `uint`, `va_list`, `clock_handle_t`, and `out_fct_type`) are **not** in the raw `.bin`. `set_user_type` re-parses each signature as C, so an undefined name raises `SyntaxError: unknown type name '...'` and stops the loop — it is not harmless. The `sdk` block above defines them first (an opaque `struct`/`enum`/`typedef` is enough to parse). Standard names (`uint8_t`, `uint32_t`, `uint64_t`, `bool`, `size_t`) are built in. If you add a function that uses another SDK type, add a definition for it to that block too. + +### Step 17: Read `main` in the decompiler + +Open the **Decompiler** view on `main`. Once the functions above are typed, it reads roughly: + +```c +int32_t main(void) +{ + stdio_init_all(); + dht11_init(4); + while (true) { + __wrap_printf("arithmetic_operator: %d\r\n", 0x32); // 50 + __wrap_printf("increment_operator: %d\r\n", 5); // 5 + __wrap_printf("relational_operator: %d\r\n", 0); // false + __wrap_printf("logical_operator: %d\r\n", 0); // false + __wrap_printf("bitwise_operator: %d\r\n", 0xa); // 10 + __wrap_printf("assignment_operator: %d\r\n", 0xa); // 10 + if (!dht11_read(&hum, &temp)) { + __wrap_puts("DHT11 read failed\r\n"); + } else { + __wrap_printf("Humidity: %.1f%%, Temperature: %.1f°C\r\n", hum, temp); + } + sleep_ms(2000); + } +} +``` + +The `0x32`, `5`, `0`, `0xa`, and `0xa` are the constants we will patch first. Every one is an **immediate in the instruction stream** — there is no variable in memory to change, which is why the patch edits the instruction operand. + +### Step 18: Patch 1 — change `arithmetic_operator` from 50 to 99 + +Go to `0x1000026e`: + +```asm +1000026e: 32 21 movs r1, #50 @ 0x32 +``` + +`movs r1, #imm8` is a 16-bit Thumb instruction. Its encoding is `0x21XX` (`movs r1, #imm8`), stored little-endian as **`XX 21`** — so the immediate is the byte at the instruction's **own** address, `0x1000026e`. Change `0x32` (50) to `0x63` (99). + +> **This is the opposite byte from the Week 7 `movw` patch.** For a 16-bit `movs`, the immediate is the first byte. For the 32-bit `movw`, the low immediate byte was the *third* byte. Always decode the instruction before you decide which byte to touch. + +| Project | Address | Before | After | Effect | +| ------- | ------- | ------ | ----- | ------ | +| `0x001a` | `0x1000026e` | `32` | `63` | `movs r1, #50` -> `#99`, prints `arithmetic_operator: 99` | + +**Option A — Hex view:** + +1. Switch to the **Hex** view (`View -> Hex`). +2. Toggle the lock off so editing is enabled. +3. Go to `0x1000026e` and change the byte `32` to `63`. +4. Return to the linear view, right-click the function -> `Reanalyze`. + +**Option B — Python console:** + +```python +bv.write(0x1000026e, b"\x63") +print(hex(bv.read(0x1000026e, 1)[0])) # -> 0x63 +``` + +After reanalysis the instruction reads `movs r1, #99`. + +### Step 18b: Patch 2 — change the DHT11 scale from `0.1f` to `5.0f` + +The DHT11 driver converts the integer and decimal bytes to a float and scales the decimal part: + +``` +humidity = data[0] + data[1] * 0.1f +temperature = data[2] + data[3] * 0.1f +``` + +`dht11_read` computes both with a fused multiply-add against a single `0.1f` constant. Look at the end of `dht11_read`: + +```asm +100003ee: vmov s15, r6 +100003f2: vcvt.f32.s32 s12, s15 +100003f6: vmov s15, r1 +100003fa: vcvt.f32.s32 s14, s15 +100003fe: vmov s15, r0 +10000402: vcvt.f32.s32 s13, s15 +10000406: vmov s15, r2 +1000040a: vldr s11, [pc, #44] @ 10000438 +1000040e: vcvt.f32.s32 s15, s15 +10000412: movs r0, #1 +10000414: vfma.f32 s14, s12, s11 +10000418: vfma.f32 s15, s13, s11 +1000041c: vstr s14, [r5] +10000420: vstr s15, [fp] +``` + +The constant `s11` is loaded by the `vldr s11, [pc, #44]` at `0x1000040a`, which reads the literal-pool word at `0x10000438`. That word is `0x3dcccccd` (float `0.1`), stored little-endian as `cd cc cc 3d`. Change it to `0x40a00000` (float `5.0`), bytes `00 00 a0 40`: + +| Project | Address | Before | After | Effect | +| ------- | ------- | ------ | ----- | ------ | +| `0x001a` | `0x10000438` | `cd cc cc 3d` | `00 00 a0 40` | `0.1f` -> `5.0f`; the humidity/temperature decimal parts read ~50x larger | + +``` ++-----------------------------------------------------------------+ +| IEEE-754 little-endian change | +| | +| 0.1f = 0x3dcccccd -> bytes cd cc cc 3d | +| 5.0f = 0x40a00000 -> bytes 00 00 a0 40 | +| | +| humidity = int + (decimal * 0.1f) becomes | +| humidity = int + (decimal * 5.0f) | +| | ++-----------------------------------------------------------------+ +``` + +**Option A — Hex view:** + +1. Switch to the **Hex** view (`View -> Hex`). +2. Go to `0x10000438` and change `cd cc cc 3d` to `00 00 a0 40`. +3. Return to the linear view and reanalyze. + +**Option B — Python console:** + +```python +bv.write(0x10000438, bytes.fromhex("0000a040")) +print(bv.read(0x10000438, 4).hex()) # -> 0000a040 +``` + +> **The scale is applied to both humidity and temperature.** The two `vfma.f32` instructions both read `s11`, so patching the one constant changes both readings, not just temperature. + +### Step 18c: Patch 3 — rename the printed label + +The string `"arithmetic_operator: %d\r\n"` starts at `0x100038e8`. Its first 26 bytes are: + +``` +61 72 69 74 68 6d 65 74 69 63 5f 6f 70 65 72 61 74 6f 72 3a 20 25 64 0d 0a 00 + a r i t h m e t i c _ o p e r a t o r : % d \r \n \0 +``` + +We replace it with `"hacked_operator: %d\r\n\0"`, which is **four bytes shorter**, and pad the tail with NULs: + +``` +68 61 63 6b 65 64 5f 6f 70 65 72 61 74 6f 72 3a 20 25 64 0d 0a 00 00 00 00 00 + h a c k e d _ o p e r a t o r : % d \r \n \0 +``` + +The `\0` at offset 21 terminates the string, so `printf` stops there and the four padding bytes are never read. The next format string (`"increment_operator: …"`) begins at `0x10003904`, which is 28 bytes past `0x100038e8`, so our 26-byte write cannot reach it. + +| Project | Address | Before | After | Effect | +| ------- | ------- | ------ | ----- | ------ | +| `0x001a` | `0x100038e8` | `61 72 69 74 68 6d 65 74 69 63 5f 6f 70 65 72 61 74 6f 72 3a 20 25 64 0d 0a 00` | `68 61 63 6b 65 64 5f 6f 70 65 72 61 74 6f 72 3a 20 25 64 0d 0a 00 00 00 00 00` | prints `hacked_operator:` instead of `arithmetic_operator:` | + +**Option A — Hex view:** + +1. Switch to the **Hex** view (`View -> Hex`). +2. Go to `0x100038e8` and replace the 26 bytes above. +3. Return to the linear view and reanalyze. + +**Option B — Python console:** + +```python +bv.write(0x100038e8, b"hacked_operator: %d\r\n\x00\x00\x00\x00") +print(bv.read(0x100038e8, 26)) # -> b'hacked_operator: %d\r\n\x00\x00\x00\x00' +``` + +> **Keep the NUL.** `printf` walks the format string until it hits `\0`. If you omit it, the printer runs on into the padding and then into the next string, producing garbage. The four padding bytes guarantee the terminator. + +### Step 19: Export the patched `.bin` + +```python +import os +seg = next(s for s in bv.segments if s.data_length) # the loadable image segment +data = bv.read(seg.start, seg.data_length) # base + size come from the view itself +out = os.path.join(os.path.join(root, "0x001a_operators", "build"), "0x001a_operators-h.bin") +open(out, "wb").write(data) +print(len(data), out) # -> 17484 /.../build/0x001a_operators-h.bin +``` + +Where the two numbers come from — nothing is hardcoded: + +- **`seg.start`** is the image base IDA loaded the `.bin` at (`0x10000000`), the same value you pass to `uf2conv --base`. +- **`seg.data_length`** is the segment's size in the file (`0x444c` = 17484). Exactly one segment carries data (the image); every peripheral and synthetic segment has `data_length == 0`, so `next(...)` picks the image. +- Reading `seg.start` for `seg.data_length` bytes therefore grabs exactly the image. + +Two gotchas this avoids: + +- **No relative path.** IDA's Python console runs with a read-only working directory (inside the app bundle), so `open("0x001a_operators-h.bin", "wb")` fails with `OSError: [Errno 30] Read-only file system`. `root` (from `~/.embedded-hacking-repo`, Step 3) is the repo, so the file is written into the project's `build/` — no machine-specific path and no database needed. +- **Read the image, not the whole view.** `bv.read(bv.start, bv.length)` spans the entire mapped range, which is not the image. The segment's `data_length` is the image size. + +A different size means you exported a partial view. + +### Step 20: Convert to UF2 + +Run from the project directory: + +**macOS Apple Silicon / Linux x64:** + +```bash +python3 ../uf2conv.py 0x001a_operators-h.bin \ + --base 0x10000000 --family 0xe48bff59 --output hacked.uf2 +``` + +**Windows x64:** + +```cmd +python ..\uf2conv.py 0x001a_operators-h.bin ^ + --base 0x10000000 --family 0xe48bff59 --output hacked.uf2 +``` + +> **Or convert from the IDA console** — it is a normal Python interpreter, so you never have to leave the app. `chdir` to a writable directory first (the default one is read-only), then run the script: +> +> ```python +> import os, sys, runpy +> os.chdir(os.path.join(root, "0x001a_operators", "build")) # the project build dir (writable) +> sys.argv = ["uf2conv.py", "0x001a_operators-h.bin", +> "--base", "0x10000000", "--family", "0xe48bff59", "--output", "hacked.uf2"] +> runpy.run_path("../../uf2conv.py", run_name="__main__") # path to your uf2conv.py +> ``` +> +> This writes `hacked.uf2` next to the `.bin`, ready to drag onto the Pico. + +### Step 21: Flash and verify + +Hold **BOOTSEL**, plug in the Pico 2, and drag `hacked.uf2` onto the **`RP2350`** drive. Open the serial monitor: + +``` +hacked_operator: 99 +increment_operator: 5 +relational_operator: 0 +logical_operator: 0 +bitwise_operator: 10 +assignment_operator: 10 +Humidity: 255.0%, Temperature: 119.0°C +... +``` + +- The first line now reads **`hacked_operator: 99`**. +- The humidity/temperature decimals are scaled by **5.0** instead of **0.1**, so the readings are roughly 50x larger (exact numbers depend on your sensor). + +**All three changes — one instruction byte, one float word, and one string — with no source code.** + +> **Faster: flash over the Debug Probe (no BOOTSEL).** The repo's `flash.sh` writes the raw `.bin` straight into XIP flash over SWD (`program 0x10000000 verify reset exit`), so you never touch BOOTSEL or a UF2. Run it from a terminal (`./flash.sh `), or from the IDA console **without freezing it** — use `subprocess.Popen`, which returns immediately, and send OpenOCD's output to a log file. (`subprocess.run` blocks the console until the flash finishes; do not use it here.) +> +> ```python +> import os, subprocess +> root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() +> bin_path = os.path.join(os.path.join(root, "0x001a_operators", "build"), "0x001a_operators-h.bin") +> log = os.path.join(os.path.join(root, "0x001a_operators", "build"), "flash.log") +> subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # free the probe first +> p = subprocess.Popen([os.path.join(root, "flash.sh"), bin_path], +> stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) +> print("flashing in the background; log:", log) +> ``` +> +> The `pkill` frees the probe first; on Windows use `subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"])`. +> +> The console is free the moment this returns. Check it with `print(p.poll())` (`None` = still running, `0` = done) or read `flash.log` — success ends with `** Verified OK **`. +> +> The same non-blocking form without the script: +> +> ```python +> import os, subprocess +> ocd = os.path.expanduser("~/.pico-sdk/openocd/0.12.0+dev") +> bin_path = os.path.join(os.path.join(root, "0x001a_operators", "build"), "0x001a_operators-h.bin") +> log = os.path.join(os.path.join(root, "0x001a_operators", "build"), "flash.log") +> subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # free the probe first +> p = subprocess.Popen([f"{ocd}/openocd", "-s", f"{ocd}/scripts", +> "-f", "interface/cmsis-dap.cfg", "-f", "target/rp2350.cfg", +> "-c", "adapter speed 5000", +> "-c", f"program {bin_path} 0x10000000 verify reset exit"], +> stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) +> print("flashing in the background; log:", log) +> ``` +> +> **The Debug Probe is single-owner.** If IDA is still attached (the `debug-server.sh` OpenOCD is running), the flash cannot grab the probe. Detach in IDA and stop that OpenOCD first: +> +> ```bash +> # macOS / Linux +> pkill -TERM -f openocd +> ``` +> ```powershell +> # Windows +> Get-Process openocd -ErrorAction SilentlyContinue | Stop-Process +> ``` +> +> Success looks like `Programming Finished` -> `Verified OK` -> `Resetting Target`. On Windows use `flash.ps1` (`.\flash.ps1 -Bin `) the same way. + +--- + +## Cheatsheet + +### IDA GUI actions + +| Action | How | +| ------ | --- | +| Go to address | `G` | +| Rename function/symbol | `N` | +| Set type or signature | `Y` | +| Add comment | `;` | +| Open Hex view | `View -> Hex` | +| Enable hex editing | Toggle the lock in the status bar | +| Reanalyze after a patch | Right-click function -> `Reanalyze` | +| Edit a register live | `dbg.set_reg_value("r1", 0x63)` in the Python console (or right-click the register, press `E`, type hex, Enter) | +| Write a RAM string live | `dbg.write_memory(0x20080000, b"hacked_operator: %d\r\n\x00")` | +| Set a breakpoint | `Debugger -> Add Hardware Breakpoint...` (hardware execute). Do **not** use `F2` — software breakpoints cannot be written to read-only flash. | +| Move a breakpoint | Remove it and set it at the new address in the GUI (command-port fallback: `rbp ` then `bp 2 hw`) | +| Confirm what is armed | The **Breakpoints** widget lists it (command-port fallback: `mdw 0xE0002000 8`, each armed breakpoint shows as ``) | +| Apply the ELF symbol map | Paste the Python snippet from Step 16 into the Python Console | +| Load peripheral names (optional) | Load the RP2350 SVD — it lives at **`WEEK04/rp2350.svd`** | + +### OpenOCD server and reset + +The server runs with `gdb_breakpoint_override hard` so that flash-writes are never attempted. Breakpoints in this lab are set in the IDA GUI through the **GDB MI** adapter (Step 12). The command-port rows below are the fallback if you use the **GDB RSP** adapter instead. + +| Action | Command | +| ------ | ------- | +| Connect to the OpenOCD prompt (fallback) | `nc 127.0.0.1 4444` (or `telnet 127.0.0.1 4444`) | +| Reset and run (command port) | `reset run` | +| Check core state (command port) | `targets` | +| Set a breakpoint in the GUI | `Debugger -> Add Hardware Breakpoint...` (hardware execute; `F2` software breakpoints do not work on flash) | +| (fallback) Add a breakpoint without the GUI | `bp 2 hw` | +| Remove one breakpoint | `rbp ` — **address only, no length, no `hw`** | +| Remove every breakpoint | `rbp all` | +| Start the server parked at `main` | macOS/Linux: `BP_ADDR=0x10000234 ./debug-server.sh` — Windows: `$env:BP_ADDR="0x10000234"; .\debug-server.ps1` (one-shot) | +| Start the server parked in the loop | macOS/Linux: `BP_ADDR=0x10000272 ./debug-server.sh` — Windows: `$env:BP_ADDR="0x10000272"; .\debug-server.ps1` | +| Break on the loop in a running target | set a hardware breakpoint in the GUI at the loop address, then **Resume** — repeatable | +| Make IDA stepping work | `rp2350.dap.core0 configure -rtos none` (already in the scripts) | +| Step without re-trapping | move the breakpoint off the current PC first, then **Step Into**/**Step Over** | +| Reset without desyncing IDA | **Detach**, `reset run` on the port, reconnect — never `reset run` while attached | + +### Every address and byte we changed + +| Project | Address | Before | After | Effect | +| ------- | ------- | ------ | ----- | ------ | +| `0x001a` | `0x1000026e` | `32` | `63` | `movs r1, #50` -> `#99`, prints `arithmetic_operator: 99` | +| `0x001a` | `0x10000438` | `cd cc cc 3d` | `00 00 a0 40` | DHT11 scale `0.1f` -> `5.0f`, readings ~50x larger | +| `0x001a` | `0x100038e8` | `61 72 69 74 68 6d 65 74 69 63 5f 6f 70 65 72 61 74 6f 72 3a 20 25 64 0d 0a 00` | `68 61 63 6b 65 64 5f 6f 70 65 72 61 74 6f 72 3a 20 25 64 0d 0a 00 00 00 00 00` | prints `hacked_operator:` instead of `arithmetic_operator:` | + +### The operator / DHT11 memory map + +| Item | Address | Notes | +| ---- | ------- | ----- | +| `dht_pin` | `0x20000b7c` | RAM `.bss`, the `dht11.c` static holding the GPIO number (`4`) | +| Literal-pool word — humidity/temp format | `0x100002b4` | `0x10003988` — `"Humidity: %.1f%%, Temperature: %.1f°C\r\n"` | +| Literal-pool word — arithmetic format | `0x100002b8` | `0x100038e8` — `"arithmetic_operator: %d\r\n"` | +| Literal-pool word — increment format | `0x100002bc` | `0x10003904` — `"increment_operator: %d\r\n"` | +| Literal-pool word — relational format | `0x100002c0` | `0x10003920` — `"relational_operator: %d\r\n"` | +| Literal-pool word — logical format | `0x100002c4` | `0x1000393c` — `"logical_operator: %d\r\n"` | +| Literal-pool word — bitwise format | `0x100002c8` | `0x10003954` — `"bitwise_operator: %d\r\n"` | +| Literal-pool word — assignment format | `0x100002cc` | `0x1000396c` — `"assignment_operator: %d\r\n"` | +| Literal-pool word — failure string | `0x100002d0` | `0x100039b4` — `"DHT11 read failed\r\n"` | +| `dht11_read` literal-pool word | `0x10000434` | `0x400b0000` — TIMER0 base, used by the inlined `time_us_32` | +| DHT11 scale constant | `0x10000438` | `0x3dcccccd` — `0.1f` | +| `dht11_read` literal-pool word | `0x1000043c` | `0x20000b7c` — `&dht_pin` | + +### Raw image facts + +| Item | Value | +| ---- | ----- | +| Build type | `Release` | +| Load base address | `0x10000000` | +| Project size | `17484` bytes (`0x444c`) | +| Fixed `main` anchor | `0x1000018c` (reset handler middle `blx`) | +| `main` | `0x10000234` | +| `dht11_init` | `0x100002d4` | +| `dht11_read` | `0x100002f4` | +| `printf` call / return, `arithmetic_operator` | `0x10000272` / `0x10000276` | +| `arithmetic_operator` format string | `0x100038e8` | +| `increment_operator` format string | `0x10003904` | +| `relational_operator` format string | `0x10003920` | +| `logical_operator` format string | `0x1000393c` | +| `bitwise_operator` format string | `0x10003954` | +| `assignment_operator` format string | `0x1000396c` | +| Humidity/Temperature format string | `0x10003988` | +| `"DHT11 read failed\r\n"` string | `0x100039b4` | +| DHT11 scale constant | `0x10000438` | +| DHT11 GPIO pin | `4` | +| RP2350 UF2 family ID | `0xe48bff59` | + +--- + +## Troubleshooting + +### My operator values are 12 and 11, not 10 and 10 + +You are reading the original Week 9 text, not this build. In `0x001a_operators.c`, `compute_arithmetic_ops` receives `x` **by value**, so its `*incr = x++;` never touches `compute_operators`' `x`. That `x` stays `5`, so `x << 1` is `10` and `x += 5` is `10`. Confirm it on your own ELF in Step 4: the immediates in `main` are `#50`, `#5`, `#0`, `#0`, `#10`, `#10`. + +### IDA hangs or crashes when you connect (macOS 27) + +Three different causes have been seen on this setup; check them in this order. + +- **A breakpoint set before connecting.** With the **GDB MI** adapter, if the binary view already has a breakpoint, the session hangs. Start parked with `BP_ADDR`, connect, then add breakpoints (see the next entry). +- **The wrong GDB executable.** Point **Full GDB Executable Path** at the **14.2.rel1** toolchain (Step 10). The 13.3.rel1 build did **not** connect in testing. +- **The LLDB adapter.** A crash report with `libdebuggercore.dylib -> std::terminate() -> abort()` and `liblldb` in the stack is the **LLDB** adapter, not GDB MI. Avoid LLDB on this setup. + +**Use GDB MI**, with the 14.2.rel1 path above. If it still fails, fall back to plain `arm-none-eabi-gdb` against the same server — the addresses and register values are identical to the GUI steps. + +If IDA hangs, force-quit it; the connect dialog has no working Cancel. The static steps (resolve, patch, export, flash) never touch the debugger and always work. + +### The GUI refuses to set a breakpoint (GDB RSP adapter only) + +If you are on the **GDB RSP** adapter, the GUI cannot set breakpoints on this target. That adapter is IDA's own minimal RSP client and sends a **1-byte** breakpoint (`Z0,,1`); the Cortex-M33 comparators need 2 bytes, so OpenOCD answers `only breakpoints of two bytes length supported`. It affects every address, both `Toggle Breakpoint` and `Add Hardware Breakpoint`, and the dialog's **Size** field is disabled. `gdb_breakpoint_override` makes no difference. + +**Fix: use the GDB MI adapter** (Step 10). It drives real GDB, which sends the correct length, so GUI breakpoints just work. If you must stay on GDB RSP, arm breakpoints from the command port after connecting (`bp 2 hw`) — but the lab uses GDB MI and does not need that. + +### GDB MI hangs when you connect (a breakpoint already existed) + +With the **GDB MI** adapter, if IDA already has a breakpoint set when you connect, the session **hangs**. This is a IDA bug. The working order is: + +1. Start the server parked, e.g. `BP_ADDR=0x10000234 ./debug-server.sh` (Windows: `$env:BP_ADDR="0x10000234"; .\debug-server.ps1`). +2. Connect with the **GDB MI** adapter. +3. Only *then* set hardware breakpoints in the UI. + +Never have a breakpoint in the binary view before the GDB MI connection. If it hangs, quit IDA, restart the server with `BP_ADDR`, and connect again before adding any breakpoints. + +### Step Into / Step Over does nothing (PC never moves) + +Two causes have been seen on this target. + +1. **A breakpoint on the current PC re-traps the step.** OpenOCD's step-over-breakpoint logic fails with `Duplicate Breakpoint address` and the PC stays put. Fix: move the breakpoint off the current PC (in the GUI), then step. +2. **The `hwthread` RTOS (GDB RSP adapter only).** With the **GDB RSP** adapter, OpenOCD can log `fake step thread 0` and reply without stepping, because the RP2350 config's `-rtos hwthread` makes the current thread id 1 while IDA sends thread id 0. Fix: `rp2350.dap.core0 configure -rtos none` (the launcher scripts already pass this). **GDB MI does not hit this.** + +To tell them apart, turn on OpenOCD logging (`log_output /tmp/ocd.log`, then `debug_level 3` on the command port) and look for `fake step` versus `Duplicate Breakpoint`. + +### `zsh: bad CPU type in executable: cmake` + +An Intel `x86_64` tool is on your `PATH` on Apple Silicon. Run Step 2: `export PATH="/opt/homebrew/bin:$PATH"`, then `hash -r`. Add it to `~/.zshrc` to make it permanent. + +### My addresses do not match this guide + +You probably built `Debug`. This lesson is a `Release` build. Re-run Step 3 with `-DCMAKE_BUILD_TYPE=Release`. A `Debug` build moves the SDK functions and keeps `print_operator_results`, `compute_operators`, and the `dht11.c` helpers as separate calls, so `main` is not at `0x10000234` and the operator results are not bare immediates. + +### A breakpoint never fires + +First, confirm you actually set one, and that it is a **hardware** breakpoint. With the **GDB MI** adapter, `Debugger -> Add Hardware Breakpoint...` (hardware execute) should land in the **Breakpoints** widget. If nothing lands, or the core keeps running, you probably used `F2` (`Toggle Breakpoint`) — that is a software breakpoint and cannot be written to read-only flash, so it never installs. Also check you are on **GDB MI**, not **GDB RSP** (the GDB RSP adapter cannot set breakpoints on this target at all). + +Then check the order and the state: + +- **Arm it only after IDA is connected.** OpenOCD flushes every breakpoint when a client attaches, so anything armed earlier is gone. This also applies to `BP_ADDR` on the startup command line. +- **Verify it is armed:** `mdw 0xE0002000 8`. You should see your address with the low bit set (`0x10000272` -> `0x10000273`). All zeros means nothing is armed — re-read this first, because it distinguishes "not armed" from "armed but never reached". +- **Is the core running?** `poll` on the command port should not report a halt. If it is stopped, click **Resume**. +- **Does the address get reached again?** `main` runs once per reset, so use `BP_ADDR` at startup (Step 9) rather than `reset run` while attached. Loop addresses such as `0x10000272` fire on the next pass with no reset — arm them and click **Resume** in IDA. +- **With GDB MI the stop is reported as `Breakpoint`** and appears in the **Breakpoints** widget, because GDB really did set it. + +### I edit `r1` (or another register) and it reverts + +`main` reloads the value at the top of every loop iteration — `movs r1, #50` at `0x1000026e` runs right before the `printf` at `0x10000272`. So `r1` is only `0x63` for the instant between your edit and the next pass; then it is `0x32` again. The edit sticks only if the core is **genuinely stopped** at the breakpoint and stays stopped. + +If it keeps reverting, the core is running, which almost always means the breakpoint is not installed — usually because it is a **software** breakpoint (`F2`) that cannot be written to read-only flash. Use `Debugger -> Add Hardware Breakpoint...` (hardware execute). + +> **The Registers widget is a snapshot, not a live view.** IDA reads the registers at each stop and shows that snapshot; it does not poll the target, and there is no "refresh registers" command. So a value changed outside IDA will not appear until the next stop. + +### The string hack does nothing + +The live version needs to run **before** the `printf` call, which means breaking at `0x10000272` and redirecting `r0` while stopped. If you let it resume, the loop reloads `r0` from the literal pool on the next pass and the hack is gone. + +Also confirm you wrote a NUL-terminated string. `printf` walks bytes until `*r0 == 0`; without the trailing `\x00`, it keeps reading RAM garbage. + +### The patched instruction still shows the old value + +Right-click the function and choose `Reanalyze`. IDA caches the disassembly text; a byte edit does not always trigger a re-lift by itself. + +### The arith patch corrupts the instruction + +You patched the wrong byte. `movs r1, #imm8` is 16-bit and its immediate is the **first** byte: the instruction starts at `0x1000026e`, so the byte to change is `0x1000026e` (`0x32 -> 0x63`). Patching `0x1000026f` (the `0x21` opcode) corrupts the instruction and the core will fault. + +### The DHT11 reading did not change + +Confirm you patched the right word. The scale is the literal loaded by `vldr s11, [pc, #44]` at `0x1000040a`; that literal lives at `0x10000438` and is `cd cc cc 3d` (`0.1f`). Change it to `00 00 a0 40` (`5.0f`). If your sensor is not connected or not answering, `dht11_read` returns `false` and the firmware prints `DHT11 read failed` instead — the scale patch only matters when a reading succeeds. + +### The `arithmetic_operator` string hack overran + +The replacement must be NUL-terminated. `"hacked_operator: %d\r\n"` is 21 characters; write it plus a `\0` (22 bytes) and pad the remaining four bytes with `00`. The next format string begins at `0x10003904`, 28 bytes past `0x100038e8`, so a 26-byte write stays clear of it. A longer write overwrites `"increment_operator: …"`. + +### The serial capture is garbage on macOS + +Reading `/dev/cu.usbmodem*` with a bare `read()` returns garbage. Set **raw termios at 115200** first: clear canonical/echo flags, set `CLOCAL|CREAD`, and `B115200` on input and output. `screen /dev/cu.usbmodem* 115200` does all of this for you; a script must call `tcsetattr` itself. Once set, the capture reads clean `arithmetic_operator: 50` lines. + +### It worked for a second, then stopped (IDA's view desyncs) + +This is the most common failure, and it has one main cause: **driving the core from the OpenOCD command port while IDA is connected.** + +- If you send `reset run` from the port while attached, the core resets, runs, and halts at your breakpoint — but IDA never receives the stop event. Its sidebar keeps showing the *previous* location, so **Step** and **Resume** act on a stale PC and appear to do nothing. +- If the OpenOCD process dies (or you restart it) while attached, IDA keeps believing it is connected: the sidebar stays, but the menu shows **Pause** enabled and **Resume**/**Step** disabled because IDA last saw the target *running*. + +Recovery: **Detach, then reconnect.** If Detach does nothing (the connection is already dead), restart IDA — its menu still shows a session that no longer exists. + +Prevention: + +- Stop at `main` with `BP_ADDR` on a fresh server start, not with `reset run` while attached. +- For loop addresses, set the breakpoint in the GUI and click **Resume**. Let IDA be the thing that starts the core. +- If you must reset, **Detach first**, `reset run`, then reconnect. +- Never leave a breakpoint on the PC you are about to step or resume from. + +### The target "blows past" `main` and stops at `0x10003648` instead + +`0x10003648` is `stdio_uart_out_flush`, the UART transmit-FIFO drain loop inside `printf`: + +```asm +10003648: 4b02 ldr r3, [pc, #8] @ (10003654 ) +1000364a: 681a ldr r2, [r3] +1000364c: 6993 ldr r3, [r2, #24] +1000364e: 071b lsls r3, r3, #28 +10003650: d4fc bmi.n 1000364c +10003652: 4770 bx lr +``` + +That is where the core sits while the UART drains, so the core is running `main`'s loop and simply spends nearly all its time there. The breakpoint at `main` did not fire because `main`'s entry runs exactly **once per reset**. If you arm the breakpoint after the reset, or set it while the target is already running and just resume, the core is already past `main` and will never re-execute it. Either arm the breakpoint **before** resetting, or break inside the loop at `0x10000272`, which fires every iteration. + +### The console floods with `Failed to read memory at 0xf0000000` + +Core1 is exposed. The scripts must run with `USE_CORE=0`. Stop the server, confirm only `core0` is reported, restart, then restart IDA. + +### `Connect to Remote Process` is greyed out and Pause does nothing + +IDA is in a stale session, usually because the debug server restarted while attached. Quit and reopen IDA (or the `.i64`) and connect again. + +### The decompiler still shows the old value after patching + +Right-click the function and choose `Reanalyze`. + +--- + +## Fallback: do the dynamic steps with GDB (macOS 27) + +If IDA's debugger crashes on attach on macOS 27 (see Troubleshooting), you can still do the live hack with the ARM GDB from the toolchain, against the same OpenOCD server. The addresses and register values are identical to the GUI steps. + +Start the debug server (Step 9), then in a new terminal: + +``` +arm-none-eabi-gdb +``` + +At the `(gdb)` prompt: + +``` +set architecture armv8-m.main +target extended-remote :3333 +hbreak *0x10000272 +continue +``` + +Do **not** run `monitor reset run` before `hbreak`. `0x10000272` is inside `main`'s loop, so the breakpoint fires on the next iteration with no reset. If you reset first, the core runs `main` and you will not catch it. + +GDB stops at the `printf` call. Confirm the value, change it, and let it run: + +``` +info registers pc r0 r1 # pc = 0x10000272, r0 = 0x100038e8, r1 = 0x32 +set $r1 = 0x63 +stepi +continue +``` + +The serial monitor prints `arithmetic_operator: 99` for the iteration you changed — the same temporary live hack as editing `r1` in the IDA Registers widget. When you are done, press `Ctrl-C`, then `detach` and `quit`. + +**If you specifically want to stop at `main` (`0x10000234`),** remember its entry runs only once per reset, so the breakpoint must be armed *before* the reset: + +``` +monitor reset halt +hbreak *0x10000234 +continue +``` + +If you instead set it while the target is running and just `continue`, you will "blow past" `main` and catch the core inside `printf` — in this build at `0x10003648`, the `stdio_uart_out_flush` UART-drain loop. + +`hbreak` sets a hardware breakpoint, which is required for read-only flash. It works from plain GDB because GDB sends the 2-byte length the Cortex-M33 comparators need. IDA's **GDB MI** adapter goes through the same GDB, so its GUI breakpoints work too; the old **GDB RSP** adapter was the one that sent a 1-byte length and could not set breakpoints here. + +## Glossary + +| Term | Definition | +| ---- | ---------- | +| **AAPCS** | ARM Architecture Procedure Call Standard — `r0`-`r3` for the first four arguments, `r0` for the return value | +| **Arithmetic operator** | C operators for math (`+`, `-`, `*`, `/`, `%`); here `x * y` folds to `#50` | +| **Assignment operator** | Compound assignment (`+=`, `-=`, …); here `x += 5` folds to `#10` | +| **Bitwise operator** | Operators on individual bits (`<<`, `>>`, `&`, `\|`, `^`); here `x << 1` folds to `#10` | +| **`.bss`** | Section for uninitialized (or zero-initialized) static/global variables; `dht_pin` lives here | +| **`.data`** | Section for initialized static/global variables; copied from flash to SRAM at boot | +| **DHT11** | Low-cost single-wire digital humidity and temperature sensor | +| **`.elf`** | Linked image with the symbol table; the ground truth for addresses and names | +| **Fused multiply-add** | `vfma.f32 Sd, Sn, Sm` computes `Sd = Sd + (Sn * Sm)` in one operation | +| **Immediate value** | A constant embedded directly in an instruction, not fetched from memory | +| **Increment operator** | `x++` (post) or `++x` (pre); here `x++` returns the old value, `5` | +| **IEEE-754** | Standard for floating-point representation; `0.1f` is `0x3dcccccd` | +| **Literal pool** | A block of 32-bit constants that Thumb-2 code reaches with PC-relative `ldr` | +| **Logical operator** | Operators combining conditions (`&&`, `\|\|`, `!`); here `false` | +| **`movs`** | 16-bit Thumb move that loads an 8-bit immediate (0-255); immediate is the first byte | +| **`movw`** | 32-bit Thumb-2 "move wide" that loads a 16-bit immediate; low imm8 is the third byte | +| **PCF8574** | An I2C I/O expander; not used this week (that was the LCD, Week 7) | +| **Relational operator** | Comparison operators (`<`, `>`, `==`, `!=`); here `5 > 10` is `false` | +| **`.rodata`** | Read-only section for constants and string literals; stays in flash | +| **SIO** | Single-cycle I/O block; `gpio_set_dir` / `gpio_put` write it with `mcrr`, `gpio_get` reads it | +| **SVD** | System View Description file — register names for a peripheral; the RP2350 one is at **`WEEK04/rp2350.svd`** | +| **Thumb bit** | Bit 0 of a Cortex-M function pointer; selects Thumb instruction mode | +| **TIMER0** | RP2350 timer block at `0x400b0000`; `time_us_32` reads its `TIMERAWL` register (`+0x28`) | +| **UF2** | USB Flashing Format — the file format the Pico 2 bootloader accepts | +| **Vector table** | The first words of flash: initial stack pointer and exception vectors | + +--- + +**Remember:** the ELF tells you what every address is, and the `.bin` is what you actually patch. Prove the behavior dynamically, read `r1` at the arithmetic `printf` call, resolve the names from the ELF (including the `dht11.c` symbols), then patch the bytes — the `movs` immediate (`0x32 -> 0x63`), the DHT11 float word (`0.1f -> 5.0f`), and the format string (`arithmetic_operator:` -> `hacked_operator:`) — and flash. diff --git a/WEEK09/WEEK09-IDA.pdf b/WEEK09/WEEK09-IDA.pdf new file mode 100644 index 0000000..45ac9c8 Binary files /dev/null and b/WEEK09/WEEK09-IDA.pdf differ diff --git a/WEEK10/WEEK10-IDA.md b/WEEK10/WEEK10-IDA.md new file mode 100644 index 0000000..7d4200d --- /dev/null +++ b/WEEK10/WEEK10-IDA.md @@ -0,0 +1,1890 @@ +# Week 10-IDA: IDA Pro — Hack Static & Dynamic Conditionals with the SG90 Servo (Raw `.bin`) + +*** + +**LEGAL DISCLAIMER:** +The information, tools, and code provided in this repository and course are strictly for educational, research, and defensive purposes only. + +You are explicitly prohibited from using any materials contained herein to access, test, modify, or exploit any device, network, or system that you do not own 100% or for which you do not have explicit, documented, and legally binding authorization to interact with. + +By using this repository and course, you acknowledge and agree that: + +1. Any illegal, unauthorized, or malicious use of this information is solely your responsibility. +2. The author(s) and contributor(s) of this repository and course shall not be held liable for any damages, legal repercussions, criminal charges, or unauthorized actions resulting from the use, misuse, or abuse of the contents herein. +3. You will comply with all applicable local, state, national, and international laws regarding cybersecurity and computer fraud. + +**IF YOU DO NOT AGREE WITH THESE TERMS, DO NOT USE THIS REPOSITORY AND COURSE.** + +*** + +## What You'll Learn This Week + +- Build both lesson projects with `Release` and get an `.elf` and a raw `.bin` for each +- Dump the **ELF symbol map** with `arm-none-eabi-nm` and use it as ground truth +- Load each raw `.bin` into IDA at `0x10000000` +- **Break at `main`** on live silicon, even though `main` can move between programs +- **Hack each running target live** from IDA's Registers widget and Python console +- **Resolve the functions in the IDA GUI** using the ELF symbol map +- **Patch** the bytes that control behavior — strings, an IEEE-754 float, an immediate delay, and two `beq` targets — export, convert, and flash +- Understand how a **static** conditional is optimized away while a **dynamic** conditional must keep its `cmp`/`beq`/`bne` branches + +--- + +## How This Guide Works + +Each project builds two files: + +| File | What it is | How we use it | +| ---- | ---------- | ------------- | +| `.elf` | The linked image with a full symbol table and DWARF | Ground truth for every function address and signature | +| `.bin` | The raw flash image, no headers, no symbols | The image we load into IDA and reverse | + +The `.bin` is built **from** the `.elf`, so the ELF tells you exactly what is at every address. We reverse-engineer the raw `.bin` the way a real extracted firmware image is reversed. + +> **Build `Release`, not `Debug`.** Every address in this guide matches the current `Release` builds. `Release` folds the `static` helpers (`print_if_else`, `print_switch`, `sweep_servo`, `eval_if_else`, `process_servo_command`) into `main` and keeps the code layout stable. If you build `Debug`, the SDK function addresses move and the helpers stay separate, so nothing lines up. Always build `Release` for this lesson. + +The order is **dynamic first, static second**, twice — once per project: + +1. Break on the live target and prove what the code does. +2. Hack it live in the debugger and watch the behavior change. +3. Resolve the functions in IDA using the ELF symbol map. +4. Patch the bytes, export, convert, and flash. + +| Project | Prints | Also does | The hack | +| ------- | ------ | --------- | -------- | +| `0x001d_static-conditionals` | `1`, then `one`, forever | sweeps the SG90 servo 0° → 180° | angle `180` → `30`, delay `500` → `100`, string `1` → `2`, `one` → `fun` | +| `0x0020_dynamic-conditionals` | `1`+`one` or `2`+`two` from the keyboard | sweeps the servo on `1` / `2` | keys `1`/`2` → `x`/`y`, angle `180` → `30`, skip the prints to go stealth | + +> **Two conditionals, two fates.** In Project 1 the `choice` value is hard-coded (`int choice = 1;`), so the compiler proves the condition at compile time and **deletes the `cmp` and the dead branches** — that is a *static* conditional. In Project 2 `choice = getchar()`, so the value is only known at run time and the compiler must emit the `cmp`/`beq`/`bne` chain — that is a *dynamic* conditional. You will see both in the disassembly. + +> **Addresses come from your build.** Every address here is from the `Release` build produced in Step 3 and was verified against the current `.elf` files with `arm-none-eabi-nm` and `arm-none-eabi-objdump`. Confirm against your own `.elf` with the command in Step 4. + +> **The SVD file lives in `WEEK04`.** If you want the RP2350 peripheral register map for the PWM/UART side of the lab, it is `Embedded-Hacking/WEEK04/rp2350.svd` — it is **not** in `WEEK10`. + +### Background: PWM and the SG90 in one paragraph + +A servo wants a **50 Hz** signal (a 20 ms frame). The RP2350 system clock is **150 MHz**; the `servo.c` driver divides that down to a **1 MHz** tick (1 tick = 1 µs) and wraps the counter at **20,000**, giving a 20 ms frame. The pulse width picks the angle: **1000 µs = 0°**, **1500 µs = 90°**, **2000 µs = 180°**. `servo_set_angle(float)` clamps the angle, maps it to a pulse in `[1000, 2000]`, and writes the PWM compare level. The float travels in a **general-purpose register (`r0`)**, not `s0` — you will see `vmov s14, r0` at the top of `servo_set_angle`. That is why the live angle hack edits `r0`. + +--- + +## Part 1: Build, Flash, and Get the Symbol Map + +### Step 1: Install the toolchain + +**Windows x64** + +- Install the **Raspberry Pi Pico** extension in VS Code. It installs the ARM GNU toolchain, CMake, Ninja, and the Pico SDK. +- Install **IDA Pro** and complete its license activation. +- Install **PuTTY** for the serial monitor. + +**macOS Apple Silicon** + +```bash +brew install cmake ninja +``` + +- Install **IDA Pro** and complete its license activation. +- Install the **Arm GNU Toolchain**, or let the VS Code Pico extension manage it. + +**Linux x64** + +```bash +sudo apt install cmake ninja-build gcc-arm-none-eabi libnewlib-arm-none-eabi git python3 openocd minicom +``` + +- Install **IDA Pro** and complete its license activation. + +### Step 2: Verify your tools are the right architecture (do not skip this) + +On **macOS Apple Silicon**, the most common failure is an Intel `x86_64` tool on your `PATH`: + +``` +zsh: bad CPU type in executable: cmake +``` + +You may have **two Homebrews**: the arm64 one at `/opt/homebrew` and the Intel one at `/usr/local`. If `/usr/local/bin` wins, every `brew` tool is x86_64. Check: + +```bash +file "$(which cmake)" +file "$(which ninja)" +file "$(which arm-none-eabi-gdb)" +file "$(which arm-none-eabi-nm)" +file "$(which openocd)" +``` + +All must report `arm64`. If any is `x86_64`, put the Apple Silicon prefix first for the session and check again: + +```bash +export PATH="/opt/homebrew/bin:$PATH" +hash -r +file "$(which cmake)" +``` + +To make it permanent, add that `export` to `~/.zshrc`. Do not use Rosetta as a fix; OpenOCD and GDB are exactly the kind of programs where a translation layer produces failures that look like debugger bugs. + +**Windows x64** and **Linux x64** do not have this problem. Skip to Step 3. + +### Step 3: Build the two projects with `Release` + +Run this once inside `0x001d_static-conditionals/` and once inside `0x0020_dynamic-conditionals/`: + +```bash +cmake -B build -G Ninja -DPICO_BOARD=pico2 -DPICO_PLATFORM=rp2350 -DCMAKE_BUILD_TYPE=Release +cmake --build build +``` + +**Point IDA at this repository (once).** Every console snippet below reads the repo root from `~/.embedded-hacking-repo`, so IDA never needs a database open and nothing is hardcoded. From the repo root, run once: + +**macOS / Linux:** + +```bash +pwd > ~/.embedded-hacking-repo +``` + +**Windows (PowerShell):** + +```powershell +(Get-Location).Path | Set-Content "$env:USERPROFILE\.embedded-hacking-repo" +``` + +**Then build from the IDA console**, so the whole build → patch → flash loop stays inside IDA. The console inherits a minimal `PATH` — on macOS just `/usr/bin:/bin:/usr/sbin:/sbin` — so it does not see Homebrew; add your package manager's `bin` first, then run plain `cmake`. + +**macOS Apple Silicon:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() +os.environ["PATH"] = "/opt/homebrew/bin:" + os.environ["PATH"] # the console's PATH omits Homebrew +for name in ("0x001d_static-conditionals", "0x0020_dynamic-conditionals"): + proj = os.path.join(root, name) + subprocess.run(["cmake", "-B", "build", "-G", "Ninja", "-DPICO_BOARD=pico2", + "-DPICO_PLATFORM=rp2350", "-DCMAKE_BUILD_TYPE=Release"], cwd=proj) + subprocess.run(["cmake", "--build", "build"], cwd=proj) +``` + +**Linux x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() +for name in ("0x001d_static-conditionals", "0x0020_dynamic-conditionals"): + proj = os.path.join(root, name) + subprocess.run(["cmake", "-B", "build", "-G", "Ninja", "-DPICO_BOARD=pico2", + "-DPICO_PLATFORM=rp2350", "-DCMAKE_BUILD_TYPE=Release"], cwd=proj) + subprocess.run(["cmake", "--build", "build"], cwd=proj) +``` + +**Windows x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() +for name in ("0x001d_static-conditionals", "0x0020_dynamic-conditionals"): + proj = os.path.join(root, name) + subprocess.run(["cmake", "-B", "build", "-G", "Ninja", "-DPICO_BOARD=pico2", + "-DPICO_PLATFORM=rp2350", "-DCMAKE_BUILD_TYPE=Release"], cwd=proj) + subprocess.run(["cmake", "--build", "build"], cwd=proj) +``` + +Each build directory now contains the pair we need: + +- `0x001d_static-conditionals/build/0x001d_static-conditionals.elf` and `.bin` — `.bin` is **8084** bytes (`0x1f94`) +- `0x0020_dynamic-conditionals/build/0x0020_dynamic-conditionals.elf` and `.bin` — `.bin` is **16188** bytes (`0x3f3c`) + +If the ARM toolchain is not on your `PATH`, add `-DPICO_TOOLCHAIN_PATH=...`: + +| OS | Typical toolchain path | +| -- | ---------------------- | +| Windows x64 | `C:/Program Files/Arm GNU Toolchain arm-none-eabi/14.2 rel1/bin` | +| macOS Apple Silicon | `/Applications/ArmGNUToolchain/14.2.rel1/arm-none-eabi/bin` | +| Linux x64 | `/usr` | + +### Step 4: Dump the ELF symbol map + +This is the ground truth for the whole lesson. Run `arm-none-eabi-nm` on each ELF and keep the output in a terminal or a text file: + +**macOS Apple Silicon / Linux x64:** + +```bash +arm-none-eabi-nm -n --defined-only build/0x001d_static-conditionals.elf | grep -E ' [Tt] ' +arm-none-eabi-nm -n --defined-only build/0x0020_dynamic-conditionals.elf | grep -E ' [Tt] ' +``` + +**Windows x64:** + +```powershell +arm-none-eabi-nm -n --defined-only build\0x001d_static-conditionals.elf | Select-String ' [Tt] ' +arm-none-eabi-nm -n --defined-only build\0x0020_dynamic-conditionals.elf | Select-String ' [Tt] ' +``` + +Each line is `address type name`. The `T`/`t` type is a function. The signatures below come from the ELF's DWARF debug info queried with `arm-none-eabi-gdb -batch -ex "ptype "`, so they are exact. + +**Project 1 — our code and the startup chain:** + +| Address | ELF symbol | Signature | Role | +| ------- | ---------- | --------- | ---- | +| `0x1000015c` | `_reset_handler` | `void _reset_handler(void)` | reset entry | +| `0x10000186` | `platform_entry` | `void platform_entry(void)` | calls `runtime_init`, `main`, `exit` | +| `0x1000019a` | `data_cpy` | `void data_cpy(void*, void*, void*)` | copies `.data` from flash to SRAM | +| `0x100001e4` | `_init` | `void _init(void)` | runs `.init_array` | +| `0x10000210` | `frame_dummy` | `void frame_dummy(void)` | C runtime boilerplate | +| `0x10000234` | `main` | `int main(void)` | the lesson function (all three `static` helpers inlined) | +| `0x1000027c` | `servo_init` | `void servo_init(uint8_t)` | the `servo.c` init function | +| `0x10000318` | `servo_set_angle` | `void servo_set_angle(float)` | the `servo.c` angle setter (clamp + PWM level, all helpers inlined) | + +**Project 1 — the GPIO, timer, stdio, and `puts` chain `main` reaches:** + +| Address | ELF symbol | Signature | Role | +| ------- | ---------- | --------- | ---- | +| `0x100003d8` | `gpio_set_function` | `void gpio_set_function(uint, gpio_function_t)` | SDK GPIO function select | +| `0x10000e28` | `sleep_ms` | `void sleep_ms(uint32_t)` | SDK millisecond delay | +| `0x1000100c` | `time_us_64` | `uint64_t time_us_64(void)` | SDK microsecond clock | +| `0x10001020` | `busy_wait_us` | `void busy_wait_us(uint64_t)` | UART timing loop | +| `0x100010a0` | `uart_init` | `uint uart_init(uart_inst_t*, uint)` | SDK UART init | +| `0x10001274` | `clock_get_hz` | `unsigned long clock_get_hz(clock_handle_t)` | UART/servo clock lookup | +| `0x10001604` | `exit` | `void exit(int)` | C runtime exit | +| `0x1000160c` | `runtime_init` | `void runtime_init(void)` | SDK runtime init | +| `0x10001638` | `stdio_out_chars_crlf` | `void stdio_out_chars_crlf(stdio_driver_t*, const char*, int)` | CRLF output driver | +| `0x100016e8` | `stdio_put_string` | `int stdio_put_string(const char*, int, bool, bool)` | buffered string output | +| `0x100017d4` | `stdio_set_driver_enabled` | `void stdio_set_driver_enabled(stdio_driver_t*, bool)` | enable the UART driver | +| `0x100017fc` | `stdio_init_all` | `bool stdio_init_all(void)` | SDK serial init | +| `0x1000188c` | `__wrap_puts` | `int __wrap_puts(const char*)` | the `puts` wrapper (both prints) | +| `0x10001a68` | `stdio_uart_init` | `void stdio_uart_init(void)` | SDK UART stdio init | +| `0x10001ba8` | `strlen` | `size_t strlen(const char*)` | C runtime string length | + +**Project 2 — our code and the startup chain:** + +| Address | ELF symbol | Signature | Role | +| ------- | ---------- | --------- | ---- | +| `0x1000015c` | `_reset_handler` | `void _reset_handler(void)` | reset entry | +| `0x10000186` | `platform_entry` | `void platform_entry(void)` | calls `runtime_init`, `main`, `exit` | +| `0x1000019a` | `data_cpy` | `void data_cpy(void*, void*, void*)` | copies `.data` from flash to SRAM | +| `0x100001e4` | `_init` | `void _init(void)` | runs `.init_array` | +| `0x10000210` | `frame_dummy` | `void frame_dummy(void)` | C runtime boilerplate | +| `0x10000234` | `main` | `int main(void)` | the lesson function (both `static` helpers inlined) | +| `0x100002dc` | `servo_init` | `void servo_init(uint8_t)` | the `servo.c` init function | +| `0x10000378` | `servo_set_angle` | `void servo_set_angle(float)` | the `servo.c` angle setter (all helpers inlined) | + +**Project 2 — the GPIO, timer, stdio, `printf`, `puts`, and `getchar` chain `main` reaches:** + +| Address | ELF symbol | Signature | Role | +| ------- | ---------- | --------- | ---- | +| `0x10000438` | `gpio_set_function` | `void gpio_set_function(uint, gpio_function_t)` | SDK GPIO function select | +| `0x10000e88` | `sleep_ms` | `void sleep_ms(uint32_t)` | SDK millisecond delay | +| `0x1000106c` | `time_us_64` | `uint64_t time_us_64(void)` | SDK microsecond clock | +| `0x10001080` | `busy_wait_us` | `void busy_wait_us(uint64_t)` | UART timing loop | +| `0x10001100` | `uart_init` | `uint uart_init(uart_inst_t*, uint)` | SDK UART init | +| `0x100012d4` | `clock_get_hz` | `unsigned long clock_get_hz(clock_handle_t)` | UART/servo clock lookup | +| `0x10002f90` | `vfctprintf` | `int vfctprintf(void (*)(char, void*), void*, const char*, va_list)` | printf format engine | +| `0x10002fec` | `exit` | `void exit(int)` | C runtime exit | +| `0x10002ff4` | `runtime_init` | `void runtime_init(void)` | SDK runtime init | +| `0x10003020` | `stdio_out_chars_crlf` | `void stdio_out_chars_crlf(stdio_driver_t*, const char*, int)` | CRLF output driver | +| `0x10003130` | `stdio_put_string` | `int stdio_put_string(const char*, int, bool, bool)` | buffered string output | +| `0x1000321c` | `stdio_set_driver_enabled` | `void stdio_set_driver_enabled(stdio_driver_t*, bool)` | enable the UART driver | +| `0x10003244` | `stdio_init_all` | `bool stdio_init_all(void)` | SDK serial init | +| `0x10003250` | `__wrap_getchar` | `int __wrap_getchar(void)` | the `getchar` wrapper (reads the UART) | +| `0x10003344` | `__wrap_puts` | `int __wrap_puts(const char*)` | the `puts` wrapper | +| `0x10003380` | `__wrap_vprintf` | `int __wrap_vprintf(const char*, va_list)` | printf core | +| `0x10003444` | `__wrap_printf` | `int __wrap_printf(const char*, ...)` | the `printf` wrapper (`%s` calls) | +| `0x10003600` | `stdio_uart_init` | `void stdio_uart_init(void)` | SDK UART stdio init | +| `0x10003740` | `strlen` | `size_t strlen(const char*)` | C runtime string length | + +> **`main` is `0x10000234` in both projects.** In Project 1 the three `static` helpers are inlined into `main`; in Project 2 `eval_if_else` and `process_servo_command` are inlined, and `sweep_servo` with them. That is why both projects put `main` at the same address. In a `Debug` build the helpers stay separate and `main` moves — another reason to build `Release`. + +> **`printf` in our source is `__wrap_printf` in the binary.** The SDK links our `printf` calls to its `__wrap_printf` wrapper, which forwards to `__wrap_vprintf`. Project 1 has no `printf` at all: the compiler replaced every `printf("...")` with a `__wrap_puts` because the strings have no format specifiers. + +### Step 5: Flash Project 1 and confirm `1` / `one` + servo sweep + +A `.bin` has no headers, so OpenOCD must be told the base address `0x10000000`. From the repository root: + +**macOS Apple Silicon / Linux x64:** + +```bash +./flash.sh 0x001d_static-conditionals/build/0x001d_static-conditionals.bin +``` + +**Windows x64 (PowerShell):** + +```powershell +.\flash.ps1 -Bin 0x001d_static-conditionals\build\0x001d_static-conditionals.bin +``` + +**Or flash from the IDA console:** + +**macOS Apple Silicon / Linux x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) +bin_path = os.path.join(root, "0x001d_static-conditionals", "build", "0x001d_static-conditionals.bin") +log = os.path.join(os.path.dirname(bin_path), "flash.log") +subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # free the probe first +subprocess.Popen([os.path.join(root, "flash.sh"), bin_path], + stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) +print("flashing in the background; log:", log) +``` + +**Windows x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) +bin_path = os.path.join(root, "0x001d_static-conditionals", "build", "0x001d_static-conditionals.bin") +log = os.path.join(os.path.dirname(bin_path), "flash.log") +subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"]) # free the probe first +subprocess.Popen(["powershell", "-ExecutionPolicy", "Bypass", "-File", + os.path.join(root, "flash.ps1"), "-Bin", bin_path], + stdout=open(log, "w"), stderr=subprocess.STDOUT) +print("flashing in the background; log:", log) +``` + +Wait for `wrote 8084 bytes ...` and `** Verified OK **`. Open a serial monitor at **115200** baud: + +- **Windows x64:** PuTTY → Connection type **Serial**, the Pico's COM port, speed `115200`. +- **macOS Apple Silicon:** `screen /dev/tty.usbmodem* 115200` (quit with `Ctrl-A` then `K`). +- **Linux x64:** `minicom -D /dev/ttyACM0 -b 115200`. + +``` +1 +one +1 +one +1 +one +... +``` + +The servo sweeps **0° → 180° → 0°** once per second, and because `choice` is hard-coded the same two lines repeat forever. + +### Step 6: Flash Project 2 and confirm the dynamic behavior + +```bash +# macOS / Linux +./flash.sh 0x0020_dynamic-conditionals/build/0x0020_dynamic-conditionals.bin +``` +```powershell +# Windows +.\flash.ps1 -Bin 0x0020_dynamic-conditionals\build\0x0020_dynamic-conditionals.bin +``` + +**Or flash from the IDA console** (same form, pointing at the Project 2 `.bin`): + +**macOS / Linux:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) +bin_path = os.path.join(root, "0x0020_dynamic-conditionals", "build", "0x0020_dynamic-conditionals.bin") +log = os.path.join(os.path.dirname(bin_path), "flash.log") +subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # free the probe first +subprocess.Popen([os.path.join(root, "flash.sh"), bin_path], + stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) +print("flashing in the background; log:", log) +``` + +**Windows:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) +bin_path = os.path.join(root, "0x0020_dynamic-conditionals", "build", "0x0020_dynamic-conditionals.bin") +log = os.path.join(os.path.dirname(bin_path), "flash.log") +subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"]) # free the probe first +subprocess.Popen(["powershell", "-ExecutionPolicy", "Bypass", "-File", + os.path.join(root, "flash.ps1"), "-Bin", bin_path], + stdout=open(log, "w"), stderr=subprocess.STDOUT) +print("flashing in the background; log:", log) +``` + +Wait for `wrote 16188 bytes ...`. Nothing prints until you type. In the serial monitor: + +- type `1` → the Pico prints `1` then `one`, and the servo sweeps **0° → 180°**; +- type `2` → it prints `2` then `two`, and the servo sweeps **180° → 0°**; +- type anything else → it prints `??` twice and waits for another key. + +--- + +## Part 2: Load the Raw `.bin` into IDA + +Start from a fresh IDA state. If you already have a database for this lesson, **close it and start over**; a stale database keeps old names and patches. + +### Step 7: Bring the raw `.bin` into IDA + +A raw `.bin` has no headers, so IDA cannot know where it belongs or what architecture it is. You must supply both. If you just double-click the `.bin`, IDA may load it with a guessed architecture, and every address in this lesson will be wrong. + +#### 1.1 Open the file +1. **File ▸ Open…** (Ctrl/Cmd+O). +2. Select the `.bin` file and click **Open**. + +IDA opens the **"Load a new file"** dialog because a raw `.bin` has no header. + +#### 1.2 Set the format and processor +In the *Load a new file* dialog: +1. **Format**: leave it as **Binary file** (IDA auto-detects a headerless image). +2. **Processor type**: click the **…** button next to the processor field. In the *Processor type* dialog: + - Family: **ARM** + - Type: **ARM Little-endian** (the 32-bit ARM module). + - Click **OK**. + +> If IDA asks **"Do you want to disassemble it as 64-bit code?"** — click **No**. +> The RP2350 is 32-bit; answering *Yes* loads AArch64 and you get `X` registers / data. (This is the single most common cause of the `DCB` wall.) + +#### 1.3 Configure the ARM architecture and Thumb mode +Still in the *Load a new file* dialog, open the processor options (the **Processor options** / **Set…** button, which opens the dialog titled **ARM architecture options**): +- **ARM architecture**: choose **ARMv8-M** (this is the Cortex-M33 / RP2350 core). +- **Thumb instructions**: select **Thumb-2** (ARMv8-M is Thumb-only, so this is the correct mode). +- Leave **automatic ARM-THUMB switch** off; we want Thumb throughout. + +#### 1.4 Set the loading address +- **Loading address**: enter **`10000000`** (hex; the RP2350 XIP flash base). + IDA rejects addresses that don't look like ROM/RAM with *"The loading address should belong to RAM or ROM"* — `0x10000000` is the correct flash window. + +Leave **Manual load** and **Create segments** at their defaults. Click **OK**. + +#### 1.5 Force Thumb, then seed the code from the vector table +A raw `.bin` has no header, so IDA's loader has **no entry point** and defaults the segment to **ARM mode** (which cannot decode Thumb). Two required steps — in this order: + +**A. Set the segment to Thumb (do this first).** +- **Edit ▸ Segments ▸ Set default segment register value…** → register **`T`** = **`1`** (or press **`Alt+G`**). IDA reanalyzes the segment as Thumb automatically. + +**B. Seed the code from the vector table.** +1. **G** → `10000000`. The first two words are the initial stack pointer and the **reset vector**. +2. **Read the 4-byte word at `0x10000004`** (do **not** assume its value — it differs per build). +3. **Clear bit 0** (the ARM **Thumb** flag) → the reset handler address. +4. **G** to that address → press **C** (**MakeCode**). IDA disassembles the reset handler and follows its `bl`s into `main`. + +Once `main` shows code, the import is correct. + +**Why IDA needs this and others don't:** IDA's generic raw-binary ARM loader treats the image as flat data and waits for you to set Thumb and mark the entry point. It's an IDA quirk, not a mistake on your part. + +### Step 8: Save it as a IDA database (`.i64`) + +IDA never writes back into the `.bin`. Your names, comments, types, and patches live in a separate **`.i64`** database. Save one now, before you make any changes: + +1. Choose `File -> Save As...`. +2. Save it next to the image as `0x001d_static-conditionals.i64`. +3. From now on, save with `File -> Save` (`Cmd+S` on macOS, `Ctrl+S` on Windows/Linux) whenever you rename or patch. + +| File | Role | +| ---- | ---- | +| `0x001d_static-conditionals.bin` | the raw firmware image; IDA never modifies it | +| `0x001d_static-conditionals.i64` | your analysis database: names, types, comments, and patches | + +When you come back later, **open the `.i64`**, not the `.bin`; that restores all your work. You export the patched image out of this view later, in Step 19. + +### Step 9: The views you will use + +- **Linear view:** the disassembly listing. You navigate, read, and patch here. +- **Graph view:** the control-flow graph of the current function. +- **Decompiler (HLIL):** the pseudo-C decompilation. +- **Hex view:** raw bytes, used for patching. +- **Function list:** the sidebar list of every detected function. + +Navigation: `G` go to address, `N` rename, `Y` set type or signature, `;` add a comment. Breakpoints are set from the GUI through the GDB MI adapter — see Step 13. + +> **macOS function keys:** the top-row `F` keys are usually mapped to system functions. Every step here uses menu paths that work without them. + +--- + +## Part 3: Dynamic — Break at `main` and Hack Live (Project 1) + +### Step 10: Start OpenOCD as a live debug server + +Make sure no other OpenOCD is running; a forgotten server holds port `3333`. + +**macOS / Linux:** + +```bash +ps aux | grep -i openocd +``` + +**Windows (PowerShell):** + +```powershell +Get-Process | Where-Object { $_.ProcessName -like '*openocd*' } +``` + +Stop any leftover server gracefully: + +**macOS / Linux:** + +```bash +pkill -TERM -f openocd +``` + +**Windows (PowerShell):** + +```powershell +Get-Process openocd -ErrorAction SilentlyContinue | Stop-Process +``` + +Start the server **parked at `main`**: + +**macOS Apple Silicon / Linux x64:** + +```bash +BP_ADDR=0x10000234 ./debug-server.sh +``` + +**Windows x64 (PowerShell):** + +```powershell +$env:BP_ADDR="0x10000234"; .\debug-server.ps1 +``` + +**Or start it from the IDA console**, freeing the probe first and launching the server in the background so the console returns immediately: + +**macOS Apple Silicon / Linux x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) +subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # stop any running server first +log = os.path.join(root, "openocd.log") +p = subprocess.Popen([os.path.join(root, "debug-server.sh")], cwd=root, + env=dict(os.environ, BP_ADDR="0x10000234"), + stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) +print("OpenOCD started (pid", p.pid, "); log:", log) +``` + +**Windows x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) +subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"]) # stop any running server first +log = os.path.join(root, "openocd.log") +p = subprocess.Popen(["powershell", "-ExecutionPolicy", "Bypass", "-File", + os.path.join(root, "debug-server.ps1")], cwd=root, + env=dict(os.environ, BP_ADDR="0x10000234"), + stdout=open(log, "w"), stderr=subprocess.STDOUT) +print("OpenOCD started (pid", p.pid, "); log:", log) +``` + +`Popen` returns in a few milliseconds; the server keeps running in the background. Check `openocd.log` for `Listening on port 3333`, then connect in Step 11. + +Wait for: + +``` +Info : [rp2350.dap.core0] Examination succeed +Startup breakpoint at 0x10000234 (2-byte hardware execute, one-shot). +Info : starting gdb server for rp2350.dap.core0 on 3333 +Info : Listening on port 3333 for gdb connections +``` + +> **`BP_ADDR` parks the core at `main` before any client connects.** The script arms a 2-byte hardware breakpoint and then does the startup `reset run`, so the core runs from the vector table and stops at your address with no debugger attached yet. When IDA connects a moment later, the first thing it reads is already the truth: `Stopped at 0x10000234`. + +> **This startup stop is single-use.** OpenOCD flushes breakpoints when a client connects, so this one is gone once IDA attaches — fine for `main`, which only runs once per reset. Every breakpoint after that is set from the IDA GUI (Step 13) and is repeatable. To stop at `main` again, restart the server with `BP_ADDR` and reconnect. + +> **Exactly one core.** The line must say `core0` and must **not** mention `core1`. Core1 is never started by this firmware; exposing it makes IDA read core1's reset-state registers, which are not real addresses, and OpenOCD floods the log with `Failed to read memory at 0xf0000000`. The scripts already use `USE_CORE=0`; do not change it. + +> **Windows driver note:** the Debug Probe must use the **WinUSB** driver. If OpenOCD reports `unable to open CMSIS-DAP device`, install it with [Zadig](https://zadig.akeo.ie/) (select `Debug Probe (CMSIS-DAP)` → WinUSB). + +### Step 11: Connect IDA to the GDB server + +1. Make sure the image is open and analyzed (Part 2) and the server from Step 10 is running (parked at `main`). +2. Choose `Debugger -> Connect to Remote Process`. +3. In the **adapter** dropdown, select **GDB MI**. +4. In the **connect** settings group, set **IP Address** to `127.0.0.1` and **Port** to `3333`. +5. Set **Full GDB Executable Path** to the `arm-none-eabi-gdb` from the **Arm GNU Toolchain 14.2.rel1**. It ships for all three hosts, and the Raspberry Pi Pico VS Code extension installs that same 14.2.rel1 toolchain (including `arm-none-eabi-gdb`) on all of them: + + | OS | `arm-none-eabi-gdb` path | + | -- | ------------------------ | + | macOS Apple Silicon | `/Applications/ArmGNUToolchain/14.2.rel1/arm-none-eabi/bin/arm-none-eabi-gdb` (or the Pico extension's `~/.pico-sdk/toolchain/14_2_Rel1/bin/arm-none-eabi-gdb`) | + | Windows x64 | `%USERPROFILE%\.pico-sdk\toolchain\14_2_Rel1\bin\arm-none-eabi-gdb.exe` (Pico extension), or `C:\Program Files (x86)\Arm GNU Toolchain arm-none-eabi\14.2 rel1\bin\arm-none-eabi-gdb.exe` | + | Linux x64 | `~/.pico-sdk/toolchain/14_2_Rel1/bin/arm-none-eabi-gdb` (Pico extension), or the `bin/` directory of the extracted `arm-gnu-toolchain-14.2.rel1-x86_64-arm-none-eabi` tarball | +6. Click **Accept**. + +> **Use the GDB MI adapter.** It launches a real `arm-none-eabi-gdb --interpreter=mi2` and lets IDA drive it, so breakpoints and stepping go through real GDB — which sends the correct 2-byte breakpoint length. Verified working end to end: connect, GUI breakpoints (**Add Hardware Breakpoint...**, hardware execute), **Step Into** / **Step Over**, and register edits. + +> **Do NOT have any breakpoints set in IDA before you connect.** With the GDB MI adapter, attaching while IDA already has a breakpoint **hangs the session**. Start the server parked with `BP_ADDR` (Step 10), connect, and only add hardware breakpoints *after* the connection is up. This is a IDA bug; it is the single most common GDB MI failure. + +> **The GDB executable path matters.** Use the **14.2.rel1** build on every OS (Windows, macOS, Linux). The 13.3.rel1 build did **not** connect in testing. +> +> **This step is temporary.** Vector35 plans to ship a GDB binary with the GDB MI adapter ([Vector35/debugger#929](https://github.com/Vector35/debugger/issues/929), milestone *Langara*). Once that lands, IDA provides GDB itself and you will not need to set **Full GDB Executable Path** at all. + +> **Do not pick Corellium.** IDA's adapter dropdown also lists **Corellium**, which is for Corellium's virtual devices and expects an API token, not a local OpenOCD server. Always read the label back and confirm it says **GDB MI** before clicking **Accept**. + +> **The adapter and port are not saved in the `.i64`.** Every time you relaunch IDA you must re-select **GDB MI**, re-enter port `3333`, and re-set the GDB path. + +The target keeps running. Open the **Registers** tab (bug icon) and confirm you see live values. `pc` inside `0x10003xxx` and `sp` just below `0x20082000` are healthy. + +> **If `pc` is `0x00000088`, `0x000000ec`, or `sp` is `0xf0000000`, the session is bad.** Restart the server, then restart IDA (a server restart while attached leaves IDA in a stale session), and connect again. + +### Step 12: Find `main` without relying on its address + +`main` can move between programs, so we do not guess it. We follow the one fixed path to it. Press `G` and go to `0x10000000`: + +``` +0x10000000 0x20082000 initial stack pointer (top of SRAM) +0x10000004 0x1000015d reset vector +``` + +Bit 0 of a vector is the Thumb bit, so `0x1000015d` means "start at `0x1000015c`". That is `_reset_handler`. Follow the reset path to `0x10000186`, `platform_entry`: + +```asm +10000186 : +10000186: ldr r1, [pc, #80] +10000188: blx r1 +1000018a: ldr r1, [pc, #80] +1000018c: blx r1 +1000018e: ldr r1, [pc, #80] +10000190: blx r1 +10000192: bkpt 0x0000 +``` + +**The middle `blx` at `0x1000018c` is the call to `main`.** `platform_entry` is byte-identical in both projects, so `0x1000018c` catches `main` no matter where the linker placed it. The literal pool at `0x100001dc` holds `main | 1`; clearing bit 0 gives `0x10000234`. + +### Step 13: Set a hardware breakpoint in the GUI + +With the **GDB MI** adapter, IDA sets breakpoints through real GDB, which sends the correct 2-byte length, so you set them **in the UI**. There is no command port here. + +#### Where you can stop + +| You want to stop at | Project 1 address | How | Repeatable? | +| --- | --- | --- | --- | +| **`main`** | `0x10000234` | The server starts parked there with `BP_ADDR=0x10000234` (Step 10), so IDA is already stopped at `main` when it connects. | No — `main` runs once per reset. | +| **First `puts` (`"1\r\n"`)** | `0x10000246` | Set a hardware breakpoint in the GUI, then click **Resume**. | Yes — fires on every iteration. | +| **Second `puts` (`"one\r"`)** | `0x1000024c` | Same. | Yes. | +| **`servo_set_angle(0.0f)`** | `0x10000252` | Same. | Yes. | +| **`servo_set_angle(180.0f)`** | `0x10000260` | Same — this is the angle we hack. | Yes. | + +#### Set a breakpoint in the GUI + +1. Press `G`, type the address (for example `0x10000260`), and press Enter. +2. Set a **hardware execution** breakpoint at that address, either way: + - `Debugger -> Add Hardware Breakpoint...` — a **hardware execute** (`HE`) breakpoint. **Use this one.** + - click the line and press `F2` (`Debugger -> Toggle Breakpoint`) — a **software** breakpoint. It will **not** work here: the code is in read-only flash, so GDB cannot install it and the core just keeps running. +3. Click **Resume**. The core is already running the loop, so the breakpoint fires on the next iteration. IDA stops with the PC at the address and reports it as a **Breakpoint**. + +> **No breakpoints before you connect.** With GDB MI, a breakpoint set before the connection hangs the session (Step 11). Start parked with `BP_ADDR`, connect, *then* add breakpoints. + +> **Step Over on the raw `.bin` steps *into* calls.** The raw image has no symbol for `__wrap_puts` or `servo_set_angle`, so **Step Over** at a `bl` behaves like **Step Into**. When the lab needs to execute the call and then stop, it moves the breakpoint to the return site and clicks **Resume** instead (Step 14 shows this). + +> **Never use IDA's Restart button.** On RP2350 it resets and halts inside the boot ROM (`pc=0x88`, `sp=0xf0000000`). To reset cleanly, restart the server with `BP_ADDR` and reconnect. + +### Step 14: HACK IT LIVE — change the servo angle from 180° to 30° + +`main` loads the constant `0x43340000` (180.0f) into `r4` once, before the loop, then copies it into `r0` at `0x1000025e` right before the `servo_set_angle` call at `0x10000260`. We break on that call and change the angle live. + +1. Press `G`, go to `0x10000260` (the `bl servo_set_angle` for 180.0°). +2. Set a **hardware execute** breakpoint there: `Debugger -> Add Hardware Breakpoint...`. (Do not use `F2` — that is a software breakpoint and will not work on read-only flash.) +3. Click **Resume** in IDA. The target is already running the loop, so the breakpoint fires on the next pass. IDA stops with the program counter at `0x10000260` and `r0 = 0x43340000` — the `mov r0, r4` at `0x1000025e` just loaded the 180.0f literal into `r0`. +4. Open the **Registers** widget (bug icon → **Registers**). +5. Find `r0`. Its value is `0x43340000`. +6. **Set `r0` to `0x41f00000` (30.0f).** From IDA's Python console (`Plugins -> Python Console`): + ```python + dbg.set_reg_value("r0", 0x41f00000) # 30.0f + ``` + `dbg.set_reg_value(name, value)` writes one register (returns `True` on success). You can also right-click `r0` in the **Registers** widget, press `E` (edit), type `41f00000`, and press Enter. The widget may not repaint the value, but the write reaches the target. +7. **Move the breakpoint past the call.** Remove the breakpoint at `0x10000260` and set a hardware breakpoint at `0x10000264` (the `mov.w r0, #500` right after the call). Two reasons not to just click **Step Over**: a breakpoint left on the current PC re-traps the step, and IDA's **Step Over** steps *into* `servo_set_angle` on this raw `.bin`. +8. Click **Resume**. The core executes `bl servo_set_angle` with `r0 = 0x41f00000`, so this sweep ends at **30°** instead of 180°, then stops at `0x10000264`. Watch the servo arm. + +> **`r4` is the real source — and it never reloads inside the loop.** `r4` is loaded once at `0x10000242` (before the loop starts at `0x10000244`) from the literal at `0x10000270`, so if you set `r4 = 0x41f00000` instead of `r0`, *every* pass uses 30° until the next reset. Editing `r0` changes only the current sweep because the next pass reloads `r0` from `r4`. Both edits are useful: `r0` shows a one-shot live change; `r4` shows a sticky one. + +### Step 14b: HACK THE STRING LIVE — change `one` to `fun` + +The text `"one\r"` lives in flash (`.rodata`) at `0x10001c64`, and flash is **read-only at runtime** — a debugger write there does not stick. So you cannot overwrite the text in place. Instead you redirect the pointer: at the `puts` call, `r0` holds the string address, so you point `r0` at a replacement string you place in RAM. + +1. Press `G`, go to `0x1000024c` (the second `bl __wrap_puts`) and set a **hardware execute** breakpoint. Resume; the loop hits it next pass. At the stop, `r0 = 0x10001c64` — the `ldr r0, [pc, #44]` at `0x1000024a` just loaded the `"one\r"` pointer from the literal at `0x10000278`. +2. Put the replacement string into free RAM at `0x20080000` from IDA's **Python console**: + ```python + dbg.write_memory(0x20080000, b"fun\r\x00") # puts appends the newline + ``` + `dbg.write_memory(address, bytes)` is IDA's debugger memory-write API; it returns `True` on success. The bytes are `66 75 6e 0d 00` = `"fun\r\0"`. We keep the `\r` and let `puts` add the `\n`, exactly as the compiler does for the original `"one\r"`. +3. Point `r0` at that string: + ```python + dbg.set_reg_value("r0", 0x20080000) + ``` + (Or right-click `r0` in the **Registers** widget, press `E`, type `20080000`, and press Enter.) +4. Move the breakpoint past the call (remove it at `0x1000024c`, set one at `0x10000250`) and click **Resume**. The core runs `puts` with `r0` pointing at your RAM string, so this iteration prints: + ``` + fun + ``` + then stops at `0x10000250`. + +Like the angle hack, this is **one iteration only**: the loop reloads `r0` from the literal pool on every pass, so the next line is `one` again. The permanent version is the static patch in Step 18. + +### Step 15: Why the hack reverts (and why we patch next) + +Press **Resume**. The loop branches back to `0x10000244`, which reloads `r0` from `0x10001c64` and `0x1000025e` reloads `r0` from `r4`, so the next line is `one` and the next sweep ends at 180° again. The live edits changed one iteration only; nothing in RAM controls these values. To make the changes permanent we must patch the bytes — the static pass. + +Press **Pause** to stop the output flood. + +### Step 15b: Kill the debugger and OpenOCD + +The live hack is done. Do this **before** the static pass. + +1. In the **Debugger** sidebar, click the **X** (**Kill**) (or **`Debugger -> Kill`**) to disconnect IDA. +2. **Kill does not stop the OpenOCD process** — `debug-server.sh` started it separately, and it keeps running and holding the probe. Stop it from the IDA console: + + **macOS / Linux:** + + ```python + import subprocess + subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # stop the debug server, free the probe + ``` + + **Windows:** + + ```python + import subprocess + subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"]) # stop the debug server, free the probe + ``` + +3. Confirm nothing is left: `pgrep -fl openocd` (macOS/Linux) prints nothing. + +--- + +## Part 4: Static — Resolve the Functions in IDA and Patch (Project 1) + +### Step 16: Resolve the functions in the IDA GUI + +We now name the functions in IDA using the ELF symbol map from Step 4. IDA loaded the raw `.bin` with **no symbols**, so every function shows as `sub_` — resolving means giving each one its real name and signature. + +Three keys do all the work: + +| Key | IDA action | Use it for | +| --- | --- | --- | +| `G` | Go to address | Jump to a function's address | +| `Y` | **Change Type** | Set the function's signature. The dialog shows the full prototype, so this sets the name *and* the type in one step. | +| `N` | Rename | Rename only, when you just want the name and not the type | + +For each function below: `G` to its address, then **`Y` (Change Type)** and type the prototype from the table. + +#### How to resolve a function in IDA (`Y`) + +`Y` is the **Change Type** key, and it is what actually resolves the function — it turns `void sub_100017fc()` into `bool stdio_init_all(void)`. The Change Type dialog shows the full declaration (name and type), so typing the prototype sets both: + +1. `G` to the function's address. The cursor lands on the function. +2. Press **`Y`**. In the Change Type dialog, type the prototype from the table exactly — for example `bool stdio_init_all(void)` — and press Enter. + +If `Y` seems to do nothing, confirm the cursor is on the function, or right-click it and pick **Change Type...**. IDA parses what you type and silently keeps the old type if it does not parse, so glance at the header after each `Y`. + +#### Worked example: `main` + +1. Press `G`, type `0x10000234`, press Enter. The cursor lands on `sub_10000234`. +2. Press **`Y`** (Change Type), type `int main(void)`, press Enter. + +> **IDA shows `int32_t` where Ghidra shows `int`.** After you set `int main(void)`, the decompiler header may read `int32_t main(void)`. That is the same type — on this platform `int` is 32 bits and IDA's parser normalises it to `int32_t`. Do not fight it; it is not an error. + +#### Worked example: `servo_init` + +1. `G` -> `0x1000027c`. +2. `Y` -> `void servo_init(uint8_t pin)`. + +It takes a `uint8_t` pin number; `main` calls it with `6` (`movs r0, #6`). + +#### Worked example: `servo_set_angle` + +1. `G` -> `0x10000318`. +2. `Y` -> `void servo_set_angle(float degrees)`. + +The float arrives in **`r0`** (soft-float ABI), not `s0`. The function opens with `vmov s14, r0` and then clamps the resulting pulse to `[1000, 2000]` — you can see `cmp.w r3, #2000` and `cmp.w r3, #1000` inside it. + +#### Worked example: `__wrap_puts` + +1. `G` -> `0x1000188c`. +2. `Y` -> `int __wrap_puts(const char *s)`. + +Both prints in `main` land here. `printf("1\r\n")` has no format specifiers, so the compiler replaced it with `puts`; the `\n` was trimmed out of the string because `puts` adds one. + +#### Worked example: `stdio_init_all` + +1. `G` -> `0x100017fc`. +2. `Y` -> `bool stdio_init_all(void)`. + +It returns **`bool`**, not `void` — the ELF says `_Bool stdio_init_all(void)`. Our `main` ignores the return value, so the decompiler still reads cleanly. + +#### Worked example: `sleep_ms` + +1. `G` -> `0x10000e28`. +2. `Y` -> `void sleep_ms(uint32_t ms)`. + +Both delay instructions load `r0 = 0x1f4` (500) immediately before calling it. + +The rest of the chain is the same two keystrokes per function (`G`, then `Y`). This is **our code plus the library functions it actually calls** — not the whole SDK. + +The call chain for this project: + +``` +main +├── stdio_init_all ── stdio_uart_init ── gpio_set_function, uart_init, stdio_set_driver_enabled +│ └── uart_init ── clock_get_hz, busy_wait_us +├── servo_init ── gpio_set_function, clock_get_hz +├── __wrap_puts ── strlen, stdio_put_string ── time_us_64, strlen +└── servo_set_angle, sleep_ms +``` + +**Project 1 — resolve every function in that chain:** + +| Address | Rename to (`N`) | Signature (`Y`) | +| ------- | --------------- | --------------- | +| `0x1000015c` | `_reset_handler` | `void _reset_handler(void)` | +| `0x10000186` | `platform_entry` | `void platform_entry(void)` | +| `0x1000019a` | `data_cpy` | `void data_cpy(void*, void*, void*)` | +| `0x100001e4` | `_init` | `void _init(void)` | +| `0x10000210` | `frame_dummy` | `void frame_dummy(void)` | +| **`0x10000234`** | **`main`** | **`int main(void)`** | +| `0x1000027c` | `servo_init` | `void servo_init(uint8_t)` | +| `0x10000318` | `servo_set_angle` | `void servo_set_angle(float)` | +| `0x100003d8` | `gpio_set_function` | `void gpio_set_function(uint, gpio_function_t)` | +| `0x10000e28` | `sleep_ms` | `void sleep_ms(uint32_t)` | +| `0x1000100c` | `time_us_64` | `uint64_t time_us_64(void)` | +| `0x10001020` | `busy_wait_us` | `void busy_wait_us(uint64_t)` | +| `0x100010a0` | `uart_init` | `uint uart_init(uart_inst_t*, uint)` | +| `0x10001274` | `clock_get_hz` | `unsigned long clock_get_hz(clock_handle_t)` | +| `0x10001604` | `exit` | `void exit(int)` | +| `0x1000160c` | `runtime_init` | `void runtime_init(void)` | +| `0x10001638` | `stdio_out_chars_crlf` | `void stdio_out_chars_crlf(stdio_driver_t*, const char*, int)` | +| `0x100016e8` | `stdio_put_string` | `int stdio_put_string(const char*, int, bool, bool)` | +| `0x100017d4` | `stdio_set_driver_enabled` | `void stdio_set_driver_enabled(stdio_driver_t*, bool)` | +| `0x100017fc` | `stdio_init_all` | `bool stdio_init_all(void)` | +| `0x1000188c` | `__wrap_puts` | `int __wrap_puts(const char*)` | +| `0x10001a68` | `stdio_uart_init` | `void stdio_uart_init(void)` | +| `0x10001ba8` | `strlen` | `size_t strlen(const char*)` | + +> **A `void` return type may not stick — here is the fix.** IDA treats `void` as low-confidence, and its analysis can override it with an inferred type — most often `int32_t` on this 32-bit target. It is most visible on `_reset_handler` (a hand-written assembly entry that never returns normally), but it can happen to **any** function whose return type IDA thinks it can infer. +> +> Setting the full signature with `Y` reproduces the unwanted `int32_t`, and `fn.return_type = ...` fails too. What works is the **return-value** setter: +> +> ```python +> from binaryninja import ReturnValue, Type +> fn = bv.get_function_at(0x1000015c) +> if fn is not None: +> fn.return_value = ReturnValue(Type.void()) +> ``` +> +> That holds `_reset_handler` at `void` even after reanalysis. If it still will not stick, leave it — it does not affect the rest of the lesson. + +> **Shortcut — resolves name *and* type for every function.** Instead of doing `N` + `Y` by hand, paste this into IDA's Python console (`Plugins -> Python Console`). It sets each function's name and signature programmatically: +> +> ```python +> from binaryninja import Symbol, SymbolType +> # The raw .bin has no headers, so these SDK types don't exist. set_user_type() +> # re-parses each signature as C, so an undefined name raises +> # "SyntaxError: unknown type name '...'". Define them first. +> sdk = bv.parse_types_from_string(""" +> typedef unsigned int uint; +> typedef char* va_list; +> typedef unsigned long clock_handle_t; +> struct stdio_driver; +> typedef struct stdio_driver stdio_driver_t; +> struct uart_inst; +> typedef struct uart_inst uart_inst_t; +> enum gpio_function { +> GPIO_FUNC_XIP = 0, GPIO_FUNC_SPI = 1, GPIO_FUNC_UART = 2, GPIO_FUNC_I2C = 3, +> GPIO_FUNC_PWM = 4, GPIO_FUNC_SIO = 5, GPIO_FUNC_PIO0 = 6, GPIO_FUNC_PIO1 = 7, +> GPIO_FUNC_GPCK = 8, GPIO_FUNC_USB = 9, GPIO_FUNC_NULL = 0x1f, +> }; +> typedef enum gpio_function gpio_function_t; +> """) +> for name, ty in sdk.types.items(): +> bv.define_user_type(name, ty) +> +> # address: (name, signature) +> funcs = { +> 0x1000015c: ("_reset_handler", "void _reset_handler(void)"), +> 0x10000186: ("platform_entry", "void platform_entry(void)"), +> 0x1000019a: ("data_cpy", "void data_cpy(void*, void*, void*)"), +> 0x100001e4: ("_init", "void _init(void)"), +> 0x10000210: ("frame_dummy", "void frame_dummy(void)"), +> 0x10000234: ("main", "int main(void)"), +> 0x1000027c: ("servo_init", "void servo_init(uint8_t)"), +> 0x10000318: ("servo_set_angle", "void servo_set_angle(float)"), +> 0x100003d8: ("gpio_set_function", "void gpio_set_function(uint, gpio_function_t)"), +> 0x10000e28: ("sleep_ms", "void sleep_ms(uint32_t)"), +> 0x1000100c: ("time_us_64", "uint64_t time_us_64(void)"), +> 0x10001020: ("busy_wait_us", "void busy_wait_us(uint64_t)"), +> 0x100010a0: ("uart_init", "uint uart_init(uart_inst_t*, uint)"), +> 0x10001274: ("clock_get_hz", "unsigned long clock_get_hz(clock_handle_t)"), +> 0x10001604: ("exit", "void exit(int)"), +> 0x1000160c: ("runtime_init", "void runtime_init(void)"), +> 0x10001638: ("stdio_out_chars_crlf", "void stdio_out_chars_crlf(stdio_driver_t*, const char*, int)"), +> 0x100016e8: ("stdio_put_string", "int stdio_put_string(const char*, int, bool, bool)"), +> 0x100017d4: ("stdio_set_driver_enabled", "void stdio_set_driver_enabled(stdio_driver_t*, bool)"), +> 0x100017fc: ("stdio_init_all", "bool stdio_init_all(void)"), +> 0x1000188c: ("__wrap_puts", "int __wrap_puts(const char*)"), +> 0x10001a68: ("stdio_uart_init", "void stdio_uart_init(void)"), +> 0x10001ba8: ("strlen", "size_t strlen(const char*)"), +> } +> for addr, (name, sig) in funcs.items(): +> bv.define_user_symbol(Symbol(SymbolType.FunctionSymbol, addr, name)) +> f = bv.get_function_at(addr) +> if f is not None: +> f.set_user_type(sig) +> ``` +> +> SDK type names (`stdio_driver_t`, `uart_inst_t`, `gpio_function_t`, plus `uint`, `va_list`, `clock_handle_t`) are **not** in the raw `.bin`. `set_user_type` re-parses each signature as C, so an undefined name raises `SyntaxError: unknown type name '...'` and stops the loop — it is not harmless. The `sdk` block above defines them first. Standard names (`uint8_t`, `uint32_t`, `uint64_t`, `bool`, `size_t`) are built in. + +### Step 17: Read `main` in the decompiler + +Open the **Decompiler** view on `main`: + +```asm +10000234
: +10000234: push {r3, r4, r5, lr} +10000236: bl 100017fc +1000023a: movs r0, #6 +1000023c: bl 1000027c +10000240: movs r5, #0 +10000242: ldr r4, [pc, #44] +10000244: ldr r0, [pc, #44] +10000246: bl 1000188c <__wrap_puts> +1000024a: ldr r0, [pc, #44] +1000024c: bl 1000188c <__wrap_puts> +10000250: mov r0, r5 +10000252: bl 10000318 +10000256: mov.w r0, #500 +1000025a: bl 10000e28 +1000025e: mov r0, r4 +10000260: bl 10000318 +10000264: mov.w r0, #500 +10000268: bl 10000e28 +1000026c: b.n 10000244 +1000026e: nop +10000270: .word 0x43340000 +10000274: .word 0x10001c5c +10000278: .word 0x10001c64 +``` + +The whole program is one loop because the three `static` helpers were inlined: + +- **No `cmp` anywhere.** `choice` is the constant `1`, so the compiler folded `if (choice == 1)` to always-true, deleted `else if (choice == 2)` and `else`, and left only the `1` and `one` prints. That is the static conditional. +- `r5 = 0` (`movs r5, #0` at `0x10000240`) is the `0.0f` angle; `r4` holds `0x43340000` (180.0f) from the literal pool at `0x10000270`. +- `0x10000274` and `0x10000278` point at `"1\r\n"` and `"one\r"` in `.rodata`. + +The decompiler reads roughly: + +```c +int32_t main(void) +{ + stdio_init_all(); + servo_init(6); + do + { + __wrap_puts("1\r\n"); + __wrap_puts("one\r"); + servo_set_angle(0.0f); + sleep_ms(0x1f4); + servo_set_angle(180.0f); + sleep_ms(0x1f4); + } while (true); +} +``` + +### Step 18: Patch 1 — change the strings `1` to `2` and `one` to `fun` + +The strings live in `.rodata`: + +```asm +10000270: .word 0x43340000 +10000274: .word 0x10001c5c +10000278: .word 0x10001c64 +``` + +`0x10001c5c` holds `31 0d 00` = `"1\r"`, and `0x10001c64` holds `6f 6e 65 0d 00` = `"one\r"`. Change the first byte of each string in the **Hex** view (`View -> Hex`, lock off) or the Python console: + +```python +bv.write(0x10001c5c, b"\x32") # "1" -> "2" +bv.write(0x10001c64, b"fun") # "one" -> "fun" +print(bv.read(0x10001c5c, 4)) # -> b'2\r\x00\x00' +print(bv.read(0x10001c64, 6)) # -> b'fun\r\x00\x00' +``` + +Keep the replacement lengths identical: `"1"` is one byte, `"one"` is three. A shorter string must be padded and a longer one would run into the next string. + +### Step 18b: Patch 2 — change the angle from 180.0f to 30.0f + +The 180.0f literal sits at `0x10000270`: + +```asm +10000270: .word 0x43340000 +``` + +It is loaded into `r4` at `0x10000242` and copied into `r0` before the second `servo_set_angle`. IEEE-754: + +- `0x43340000` = 180.0f → little-endian bytes `00 00 34 43` +- `0x41f00000` = 30.0f → little-endian bytes `00 00 f0 41` + +**Option A — Hex view:** go to `0x10000270` and change `00 00 34 43` to `00 00 f0 41`, then reanalyze. + +**Option B — Python console:** + +```python +bv.write(0x10000270, bytes.fromhex("0000f041")) +print(bv.read(0x10000270, 4).hex(" ")) # -> 00 00 f0 41 +``` + +`30.0 = 1.875 × 2^4`; sign `0`, exponent `127 + 4 = 131 = 0x83`, mantissa `0.875 = 0x700000` → `0x41f00000`. + +### Step 18c: Patch 3 — speed up the sweep from 500 ms to 100 ms + +The compiler packed `500` directly into two 32-bit Thumb-2 `mov.w` instructions: + +```asm +10000256: mov.w r0, #500 +1000025a: bl 10000e28 +10000264: mov.w r0, #500 +10000268: bl 10000e28 +``` + +Each `mov.w r0, #500` is the four bytes `4f f4 fa 70`. The four bytes for `mov.w r0, #100` are `4f f0 64 00` (verified by assembling `mov.w r0, #100` with `arm-none-eabi-as`). Change both: + +```python +for addr in (0x10000256, 0x10000264): + bv.write(addr, bytes.fromhex("4ff06400")) # mov.w r0, #100 +``` + +> **Why the bytes change shape.** `500` does not fit in an 8-bit rotated immediate, so the encoder uses the `f4 4f`-family form `4f f4 fa 70`. `100` (`0x64`) does fit, so the encoder uses the `f04f`/`f0 4f` form `4f f0 64 00`. Same instruction, different immediate encoding. Both are exactly 4 bytes. + +Verify all five patches: + +```python +for addr in (0x10001c5c, 0x10001c64, 0x10000270, 0x10000256, 0x10000264): + print(hex(addr), bv.read(addr, 4).hex(" ")) +# -> 0x10001c5c 32 0d 00 00 +# -> 0x10001c64 66 75 6e 0d +# -> 0x10000270 00 00 f0 41 +# -> 0x10000256 4f f0 64 00 +# -> 0x10000264 4f f0 64 00 +``` + +### Step 19: Export the patched `.bin` + +```python +import os +seg = next(s for s in bv.segments if s.data_length) # the loadable image segment +data = bv.read(seg.start, seg.data_length) # base + size come from the view itself +out = os.path.join(os.path.join(root, "0x001d_static-conditionals", "build"), "0x001d_static-conditionals-h.bin") +open(out, "wb").write(data) +print(len(data), out) # -> 8084 /.../build/0x001d_static-conditionals-h.bin +``` + +Where the two numbers come from — nothing is hardcoded: + +- **`seg.start`** is the image base IDA loaded the `.bin` at (`0x10000000`), the same value you pass to `uf2conv --base`. +- **`seg.data_length`** is the segment's size in the file (`0x1f94` = 8084). Exactly one segment carries data (the image); every peripheral and synthetic segment has `data_length == 0`, so `next(...)` picks the image. + +> **No relative path.** IDA's Python console runs with a read-only working directory (inside the app bundle), so a relative `open(...)` fails with `OSError: [Errno 30] Read-only file system`. `root` (from `~/.embedded-hacking-repo`, Step 3) is the repo, so the file is written into the project's `build/`. + +### Step 20: Convert to UF2 + +Run from the project directory: + +**macOS Apple Silicon / Linux x64:** + +```bash +python3 ../uf2conv.py 0x001d_static-conditionals-h.bin \ + --base 0x10000000 --family 0xe48bff59 --output hacked.uf2 +``` + +**Windows x64:** + +```cmd +python ..\uf2conv.py 0x001d_static-conditionals-h.bin ^ + --base 0x10000000 --family 0xe48bff59 --output hacked.uf2 +``` + +> **Or convert from the IDA console** — `chdir` to a writable directory first (the default one is read-only), then run the script: +> +> ```python +> import os, sys, runpy +> os.chdir(os.path.join(root, "0x001d_static-conditionals", "build")) # the project build dir (writable) +> sys.argv = ["uf2conv.py", "0x001d_static-conditionals-h.bin", +> "--base", "0x10000000", "--family", "0xe48bff59", "--output", "hacked.uf2"] +> runpy.run_path("../../uf2conv.py", run_name="__main__") +> ``` + +### Step 21: Flash and verify + +Hold **BOOTSEL**, plug in the Pico 2, and drag `hacked.uf2` onto the **`RP2350`** drive. Or flash the `.bin` over the Debug Probe with SWD — no BOOTSEL — from the console (stop any running OpenOCD first, and use `Popen`, not `run`, so the console is not blocked): + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() +bin_path = os.path.join(os.path.join(root, "0x001d_static-conditionals", "build"), "0x001d_static-conditionals-h.bin") +log = os.path.join(os.path.join(root, "0x001d_static-conditionals", "build"), "flash.log") +subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # free the probe first +p = subprocess.Popen([os.path.join(root, "flash.sh"), bin_path], + stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) +print("flashing in the background; log:", log) +``` + +Open the serial monitor: + +``` +2 +fun +2 +fun +2 +fun +... +``` + +The servo now sweeps **0° → 30°** and does it **5× faster**. **Five bytes changed, no source code.** + +--- + +## Part 5: Reflash Project 2 and Load It into IDA + +### Step 22: Reflash Project 2 and restart the session + +Part 4 left the Pico running the patched Project 1 image. Put the original Project 2 back and start a fresh session. + +1. Stop any running debug server so the flash script can use the probe: + + ```bash + # macOS / Linux + pkill -TERM -f openocd + ``` + ```powershell + # Windows + Get-Process openocd -ErrorAction SilentlyContinue | Stop-Process + ``` + +2. Flash the original Project 2 image: + + ```bash + # macOS / Linux + ./flash.sh 0x0020_dynamic-conditionals/build/0x0020_dynamic-conditionals.bin + ``` + ```powershell + # Windows + .\flash.ps1 -Bin 0x0020_dynamic-conditionals\build\0x0020_dynamic-conditionals.bin + ``` + + **Or do steps 1–2 from the IDA console:** + + **macOS / Linux:** + + ```python + import os, subprocess + root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) + bin_path = os.path.join(root, "0x0020_dynamic-conditionals", "build", "0x0020_dynamic-conditionals.bin") + log = os.path.join(os.path.dirname(bin_path), "flash.log") + subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # free the probe first + subprocess.Popen([os.path.join(root, "flash.sh"), bin_path], + stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) + print("flashing Project 2 in the background; log:", log) + ``` + + **Windows:** + + ```python + import os, subprocess + root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) + bin_path = os.path.join(root, "0x0020_dynamic-conditionals", "build", "0x0020_dynamic-conditionals.bin") + log = os.path.join(os.path.dirname(bin_path), "flash.log") + subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"]) # free the probe first + subprocess.Popen(["powershell", "-ExecutionPolicy", "Bypass", "-File", + os.path.join(root, "flash.ps1"), "-Bin", bin_path], + stdout=open(log, "w"), stderr=subprocess.STDOUT) + print("flashing Project 2 in the background; log:", log) + ``` + +3. Load Project 2 and save its database — see Step 22b. + +Confirm the Pico responds to `1` / `2` again. + +### Step 22b: Load Project 2 into IDA and save the database + +Exactly like Steps 7–8, but for Project 2. **Use `File -> Open with Options...`** (not plain `File -> Open`), select `0x0020_dynamic-conditionals/build/0x0020_dynamic-conditionals.bin`, and set: + +- **Architecture:** `thumb2` +- **Platform:** `thumb2` +- **Base Address:** `0x10000000` + +Click **Open**. Then press `G`, type `0x10000000`, and confirm the first two words: + +``` +0x10000000 0x20082000 initial stack pointer +0x10000004 0x1000015d reset vector (bit 0 = Thumb) +``` + +If you see data at `0x00000000`, close the tab and redo it with `Open with Options`. + +Save it with `File -> Save As...` as `0x0020_dynamic-conditionals.i64` (next to the `.bin`). From now on open the `.i64`, not the `.bin`; save with `Cmd+S` / `Ctrl+S` after every rename or patch. + +> **Console equivalent:** +> ```python +> load("0x0020_dynamic-conditionals/build/0x0020_dynamic-conditionals.bin", +> options={"loader.imageBase": 0x10000000, "loader.platform": "thumb2"}) +> ``` + +--- + +## Part 6: Dynamic — Break at `main` and Hack Live (Project 2) + +### Step 23: Break at `main` + +`main` is at `0x10000234` in this project too. Start the server parked at `main` (Step 10 form) and connect with the **GDB MI** adapter (Step 11): + +1. Restart the server parked at `main`: + + **macOS / Linux:** + + ```bash + BP_ADDR=0x10000234 ./debug-server.sh + ``` + ```powershell + # Windows + $env:BP_ADDR="0x10000234"; .\debug-server.ps1 + ``` + + **Or restart it from the IDA console:** + + **macOS / Linux:** + + ```python + import os, subprocess + root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() + log = os.path.join(root, "openocd.log") + subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # kill any running server first + subprocess.Popen([os.path.join(root, "debug-server.sh")], cwd=root, + env=dict(os.environ, BP_ADDR="0x10000234"), + stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) + print("OpenOCD restarted parked at main; log:", log) + ``` + + **Windows:** + + ```python + import os, subprocess + root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() + log = os.path.join(root, "openocd.log") + subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"]) # kill any running server first + subprocess.Popen(["powershell", "-ExecutionPolicy", "Bypass", "-File", + os.path.join(root, "debug-server.ps1")], cwd=root, + env=dict(os.environ, BP_ADDR="0x10000234"), + stdout=open(log, "w"), stderr=subprocess.STDOUT) + print("OpenOCD restarted parked at main; log:", log) + ``` +2. Connect IDA (Step 11): adapter **GDB MI**, IP `127.0.0.1`, port `3333`. + +The target is already halted at `main` when IDA connects, and the sidebar reads `Stopped at 0x10000234`. + +### Step 24: Read `main` and find the dynamic conditional + +The whole loop is one function because both helpers were inlined. Notice the `cmp`/`beq`/`bne` chain the compiler had to keep this time: + +```asm +10000234
: +10000234: push {r3, r4, r5, lr} +10000236: bl 10003244 +1000023a: movs r0, #6 +1000023c: bl 100002dc +10000240: movs r4, #0 +10000242: ldr r5, [pc, #124] +10000244: bl 10003250 <__wrap_getchar> +10000248: uxtb r0, r0 +1000024a: cmp r0, #49 +1000024c: beq.n 10000268 +1000024e: cmp r0, #50 +10000250: beq.n 10000294 +10000252: ldr r0, [pc, #112] +10000254: bl 10003344 <__wrap_puts> +10000258: ldr r0, [pc, #104] +1000025a: bl 10003344 <__wrap_puts> +1000025e: bl 10003250 <__wrap_getchar> +10000262: uxtb r0, r0 +10000264: cmp r0, #49 +10000266: bne.n 1000024e +10000268: ldr r0, [pc, #92] +1000026a: bl 10003344 <__wrap_puts> +1000026e: ldr r1, [pc, #92] +10000270: ldr r0, [pc, #92] +10000272: bl 10003444 <__wrap_printf> +10000276: mov r0, r4 +10000278: bl 10000378 +1000027c: mov.w r0, #500 +10000280: bl 10000e88 +10000284: mov r0, r5 +10000286: bl 10000378 +1000028a: mov.w r0, #500 +1000028e: bl 10000e88 +10000292: b.n 10000244 +10000294: ldr r0, [pc, #60] +10000296: bl 10003344 <__wrap_puts> +1000029a: ldr r1, [pc, #60] +1000029c: ldr r0, [pc, #48] +1000029e: bl 10003444 <__wrap_printf> +100002a2: mov r0, r5 +100002a4: bl 10000378 +100002a8: mov.w r0, #500 +100002ac: bl 10000e88 +100002b0: mov r0, r4 +100002b2: bl 10000378 +100002b6: mov.w r0, #500 +100002ba: bl 10000e88 +100002be: b.n 10000244 +100002c0: .word 0x43340000 +100002c4: .word 0x1000381c +100002c8: .word 0x10003800 +100002cc: .word 0x10003808 +100002d0: .word 0x1000380c +100002d4: .word 0x10003814 +100002d8: .word 0x10003818 +``` + +Because `choice` is now `getchar()` and can be anything, the compiler cannot fold the condition. It emits the comparisons at `0x1000024a` (`cmp r0, #49` = `0x31` = `'1'`) and `0x1000024e` (`cmp r0, #50` = `0x32` = `'2'`), each followed by a `beq.n`. That is the dynamic conditional. + +The string map, read straight from `.rodata`: + +| Literal | Points at | String | +| ------- | --------- | ------ | +| `0x100002c4` | `0x1000381c` | `"??\r"` (the `else` / `default` prints) | +| `0x100002c8` | `0x10003800` | `"1\r\n"` (the `'1'` print) | +| `0x100002cc` | `0x10003808` | `"one"` (the `printf` argument) | +| `0x100002d0` | `0x1000380c` | `"%s\r\n"` (the `printf` format) | +| `0x100002d4` | `0x10003814` | `"2\r\n"` (the `'2'` print) | +| `0x100002d8` | `0x10003818` | `"two"` (the `printf` argument) | + +> **Why the `else` path has two `puts` and a second `getchar`.** The compiler inlined both `eval_if_else` and `process_servo_command`; both have a "default" that prints `"??\r\n"`, and the shared string is emitted twice (`0x10000252` and `0x10000258`). The second `getchar` at `0x1000025e` is the compiler's rotated loop back-edge. The observable behavior is what matters: `1` → `1`+`one`, `2` → `2`+`two`, anything else → `??` twice. + +### Step 25: HACK IT LIVE — drive the branch with `r0` + +`getchar` blocks until you press a key, so this breakpoint fires exactly when a key arrives. We stop right after the read and overwrite the value so the program takes whichever branch we want. + +1. Press `G`, go to `0x1000024a` (the first `cmp r0, #49`). Set a **hardware execute** breakpoint: `Debugger -> Add Hardware Breakpoint...`. +2. Click **Resume** and type any key in the serial monitor — for example `a`. `getchar` returns, the `uxtb` at `0x10000248` runs, and the breakpoint fires at `0x1000024a` with `r0 = 0x61` (`'a'`). +3. **Set `r0` to `0x31` (`'1'`)** from the Python console: + ```python + dbg.set_reg_value("r0", 0x31) # force the '1' branch + ``` + (Or right-click `r0` in the **Registers** widget, press `E`, type `31`, and press Enter.) +4. Remove the breakpoint at `0x1000024a` and click **Resume**. The core runs `cmp r0, #49`, sees the forced `0x31`, and takes the `'1'` branch — so even though you typed `a`, the Pico prints: + ``` + 1 + one + ``` + and sweeps the servo **0° → 180°**. + +> **Change the branch, not the register, if you prefer.** Setting `r0 = 0x32` instead forces the `'2'` path (`2`, `two`, servo 180° → 0°). Setting `r0` to anything else drops into the `??` path. One live register write steers the whole control-flow chain. + +### Step 25b: HACK THE STRING LIVE — change `1` to `7` + +The `'1'` print uses the string at `0x10003800` (`"1\r\n"`). Exactly like Project 1, redirect `r0` to a RAM string at the `puts` call. + +1. Press `G`, go to `0x10000268` (the `bl __wrap_puts` on the `'1'` path) and set a hardware execute breakpoint. Resume and type `1`. At the stop, `r0 = 0x10003800` — the `ldr r0, [pc, #92]` at `0x10000268` loaded the `"1\r\n"` pointer. +2. Write the replacement to RAM and repoint `r0`: + ```python + dbg.write_memory(0x20080000, b"7\r\x00") # puts appends the newline + dbg.set_reg_value("r0", 0x20080000) + ``` +3. Remove the breakpoint at `0x10000268`, set one at `0x1000026a`, and click **Resume**. This iteration prints: + ``` + 7 + one + ``` + One iteration only — the loop reloads `r0` from the literal pool each pass. The permanent version is the static patch in Step 27b. + +### Step 25c: Kill the debugger and OpenOCD + +Same as Step 15b: click the **X** (**Kill**) in the **Debugger** sidebar (or **`Debugger -> Kill`**), then stop OpenOCD from the IDA console: + +**macOS / Linux:** + +```python +import subprocess +subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # stop the debug server, free the probe +``` + +**Windows:** + +```python +import subprocess +subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"]) # stop the debug server, free the probe +``` + +--- + +## Part 7: Static — Resolve the Functions and Patch (Project 2) + +### Step 26: Resolve the functions in the IDA GUI + +Same two keys as Step 16 — `G` to the address, then `Y` (Change Type) to set the prototype — using the Project 2 ELF symbol map from Step 4. + +#### Worked example: `main` + +1. `G` -> `0x10000234`. +2. `Y` -> `int main(void)` (IDA shows `int32_t main(void)` — the same 32-bit `int`). + +#### Worked example: `__wrap_getchar` + +1. `G` -> `0x10003250`. +2. `Y` -> `int __wrap_getchar(void)`. + +`getchar` returns an `int` in `r0`; `main` immediately narrows it with `uxtb r0, r0` before comparing. + +#### Worked example: `__wrap_printf` + +1. `G` -> `0x10003444`. +2. `Y` -> `int __wrap_printf(const char *fmt, ...)`. Keep the `...` — `printf` is variadic. It forwards to `__wrap_vprintf`. + +#### Worked example: `__wrap_puts` + +1. `G` -> `0x10003344`. +2. `Y` -> `int __wrap_puts(const char *s)`. + +#### Worked example: `servo_set_angle` + +1. `G` -> `0x10000378`. +2. `Y` -> `void servo_set_angle(float degrees)`. + +The clamp constants are inside it: + +```asm +100003ba: cmp.w r3, #2000 +100003be: it cs +100003c0: movcs.w r3, #2000 +100003c4: cmp.w r3, #1000 +100003c8: it cc +100003ca: movcc.w r3, #1000 +``` + +`0x7d0` is the 2000 µs maximum pulse and `0x3e8` is the 1000 µs minimum. + +The call chain for this project: + +``` +main +├── stdio_init_all ── stdio_uart_init ── gpio_set_function, uart_init, stdio_set_driver_enabled +│ └── uart_init ── clock_get_hz, busy_wait_us +├── servo_init ── gpio_set_function, clock_get_hz +├── __wrap_getchar ── busy_wait_us +├── __wrap_puts ── strlen, stdio_put_string ── time_us_64, strlen +├── __wrap_printf ── __wrap_vprintf ── vfctprintf, stdio_out_chars_crlf, time_us_64 +└── servo_set_angle, sleep_ms +``` + +**Project 2 — resolve every function in that chain:** + +| Address | Rename to (`N`) | Signature (`Y`) | +| ------- | --------------- | --------------- | +| `0x1000015c` | `_reset_handler` | `void _reset_handler(void)` | +| `0x10000186` | `platform_entry` | `void platform_entry(void)` | +| `0x1000019a` | `data_cpy` | `void data_cpy(void*, void*, void*)` | +| `0x100001e4` | `_init` | `void _init(void)` | +| `0x10000210` | `frame_dummy` | `void frame_dummy(void)` | +| **`0x10000234`** | **`main`** | **`int main(void)`** | +| `0x100002dc` | `servo_init` | `void servo_init(uint8_t)` | +| `0x10000378` | `servo_set_angle` | `void servo_set_angle(float)` | +| `0x10000438` | `gpio_set_function` | `void gpio_set_function(uint, gpio_function_t)` | +| `0x10000e88` | `sleep_ms` | `void sleep_ms(uint32_t)` | +| `0x1000106c` | `time_us_64` | `uint64_t time_us_64(void)` | +| `0x10001080` | `busy_wait_us` | `void busy_wait_us(uint64_t)` | +| `0x10001100` | `uart_init` | `uint uart_init(uart_inst_t*, uint)` | +| `0x100012d4` | `clock_get_hz` | `unsigned long clock_get_hz(clock_handle_t)` | +| `0x10002f90` | `vfctprintf` | `int vfctprintf(void (*)(char, void*), void*, const char*, va_list)` | +| `0x10002fec` | `exit` | `void exit(int)` | +| `0x10002ff4` | `runtime_init` | `void runtime_init(void)` | +| `0x10003020` | `stdio_out_chars_crlf` | `void stdio_out_chars_crlf(stdio_driver_t*, const char*, int)` | +| `0x10003130` | `stdio_put_string` | `int stdio_put_string(const char*, int, bool, bool)` | +| `0x1000321c` | `stdio_set_driver_enabled` | `void stdio_set_driver_enabled(stdio_driver_t*, bool)` | +| `0x10003244` | `stdio_init_all` | `bool stdio_init_all(void)` | +| `0x10003250` | `__wrap_getchar` | `int __wrap_getchar(void)` | +| `0x10003344` | `__wrap_puts` | `int __wrap_puts(const char*)` | +| `0x10003380` | `__wrap_vprintf` | `int __wrap_vprintf(const char*, va_list)` | +| `0x10003444` | `__wrap_printf` | `int __wrap_printf(const char*, ...)` | +| `0x10003600` | `stdio_uart_init` | `void stdio_uart_init(void)` | +| `0x10003740` | `strlen` | `size_t strlen(const char*)` | + +> **Shortcut — resolves name *and* type for every function.** Paste this into IDA's Python console: +> +> ```python +> from binaryninja import Symbol, SymbolType +> # The raw .bin has no headers, so these SDK types don't exist. set_user_type() +> # re-parses each signature as C, so an undefined name raises +> # "SyntaxError: unknown type name '...'". Define them first. +> sdk = bv.parse_types_from_string(""" +> typedef unsigned int uint; +> typedef char* va_list; +> typedef unsigned long clock_handle_t; +> struct stdio_driver; +> typedef struct stdio_driver stdio_driver_t; +> struct uart_inst; +> typedef struct uart_inst uart_inst_t; +> enum gpio_function { +> GPIO_FUNC_XIP = 0, GPIO_FUNC_SPI = 1, GPIO_FUNC_UART = 2, GPIO_FUNC_I2C = 3, +> GPIO_FUNC_PWM = 4, GPIO_FUNC_SIO = 5, GPIO_FUNC_PIO0 = 6, GPIO_FUNC_PIO1 = 7, +> GPIO_FUNC_GPCK = 8, GPIO_FUNC_USB = 9, GPIO_FUNC_NULL = 0x1f, +> }; +> typedef enum gpio_function gpio_function_t; +> """) +> for name, ty in sdk.types.items(): +> bv.define_user_type(name, ty) +> +> # address: (name, signature) +> funcs = { +> 0x1000015c: ("_reset_handler", "void _reset_handler(void)"), +> 0x10000186: ("platform_entry", "void platform_entry(void)"), +> 0x1000019a: ("data_cpy", "void data_cpy(void*, void*, void*)"), +> 0x100001e4: ("_init", "void _init(void)"), +> 0x10000210: ("frame_dummy", "void frame_dummy(void)"), +> 0x10000234: ("main", "int main(void)"), +> 0x100002dc: ("servo_init", "void servo_init(uint8_t)"), +> 0x10000378: ("servo_set_angle", "void servo_set_angle(float)"), +> 0x10000438: ("gpio_set_function", "void gpio_set_function(uint, gpio_function_t)"), +> 0x10000e88: ("sleep_ms", "void sleep_ms(uint32_t)"), +> 0x1000106c: ("time_us_64", "uint64_t time_us_64(void)"), +> 0x10001080: ("busy_wait_us", "void busy_wait_us(uint64_t)"), +> 0x10001100: ("uart_init", "uint uart_init(uart_inst_t*, uint)"), +> 0x100012d4: ("clock_get_hz", "unsigned long clock_get_hz(clock_handle_t)"), +> 0x10002f90: ("vfctprintf", "int vfctprintf(void (*)(char, void*), void*, const char*, va_list)"), +> 0x10002fec: ("exit", "void exit(int)"), +> 0x10002ff4: ("runtime_init", "void runtime_init(void)"), +> 0x10003020: ("stdio_out_chars_crlf", "void stdio_out_chars_crlf(stdio_driver_t*, const char*, int)"), +> 0x10003130: ("stdio_put_string", "int stdio_put_string(const char*, int, bool, bool)"), +> 0x1000321c: ("stdio_set_driver_enabled", "void stdio_set_driver_enabled(stdio_driver_t*, bool)"), +> 0x10003244: ("stdio_init_all", "bool stdio_init_all(void)"), +> 0x10003250: ("__wrap_getchar", "int __wrap_getchar(void)"), +> 0x10003344: ("__wrap_puts", "int __wrap_puts(const char*)"), +> 0x10003380: ("__wrap_vprintf", "int __wrap_vprintf(const char*, va_list)"), +> 0x10003444: ("__wrap_printf", "int __wrap_printf(const char*, ...)"), +> 0x10003600: ("stdio_uart_init", "void stdio_uart_init(void)"), +> 0x10003740: ("strlen", "size_t strlen(const char*)"), +> } +> for addr, (name, sig) in funcs.items(): +> bv.define_user_symbol(Symbol(SymbolType.FunctionSymbol, addr, name)) +> f = bv.get_function_at(addr) +> if f is not None: +> f.set_user_type(sig) +> ``` + +### Step 27: Patch 1 — change the servo angle from 180.0f to 30.0f + +The 180.0f literal sits at `0x100002c0`, loaded into `r5` at `0x10000242`: + +```asm +100002c0: .word 0x43340000 +``` + +Change the four bytes exactly as in Project 1: + +```python +bv.write(0x100002c0, bytes.fromhex("0000f041")) # 180.0f -> 30.0f +print(bv.read(0x100002c0, 4).hex(" ")) # -> 00 00 f0 41 +``` + +Both servo paths (`0x10000284`/`0x100002a2` use `r5`, `0x10000276`/`0x100002b0` use `r4` = 0.0f) now cap at 30°. + +### Step 27b: Patch 2 — rewrite the secret keys `1` → `x` and `2` → `y` + +The two key comparisons are at `0x1000024a` and `0x1000024e`: + +```asm +1000024a: cmp r0, #49 +1000024e: cmp r0, #50 +``` + +The immediate is the low byte of the 16-bit `cmp` encoding: `0x31` at `0x1000024a` and `0x32` at `0x1000024e`. Change them to `x` (`0x78`) and `y` (`0x79`): + +```python +bv.write(0x1000024a, b"\x78") # cmp r0, #0x78 ('x') +bv.write(0x1000024e, b"\x79") # cmp r0, #0x79 ('y') +print(bv.read(0x1000024a, 2).hex(" ")) # -> 78 28 +print(bv.read(0x1000024e, 2).hex(" ")) # -> 79 28 +``` + +Now `x` takes the old `1` path and `y` takes the old `2` path. + +### Step 27c (optional): Patch 3 — make `x` and `y` stealth (skip the prints) + +The original `1`/`2` paths print before moving the servo. To make the new `x`/`y` keys silent, redirect the two `beq.n` targets straight to the servo code, skipping both prints. The current targets are `0x10000268` (the `1` print block) and `0x10000294` (the `2` print block); the servo code starts at `0x10000276` (`mov r0, r4`) and `0x100002a2` (`mov r0, r5`). + +| Address | Instruction | Before | After | New target | +| ------- | ----------- | ------ | ----- | ---------- | +| `0x1000024c` | `beq.n` | `0c d0` | `13 d0` | `0x10000276` (skip `1`/`one` prints) | +| `0x10000250` | `beq.n` | `20 d0` | `27 d0` | `0x100002a2` (skip `2`/`two` prints) | + +```python +bv.write(0x1000024c, bytes.fromhex("13d0")) # beq.n -> 0x10000276 +bv.write(0x10000250, bytes.fromhex("27d0")) # beq.n -> 0x100002a2 +``` + +> **How the encoding was chosen.** A 16-bit conditional branch is `1101 cond imm8`; the target is `PC + 4 + (imm8 << 1)`. For `0x1000024c` → `0x10000276`: `(0x276 - 0x250) / 2 = 0x13`. For `0x10000250` → `0x100002a2`: `(0x2a2 - 0x254) / 2 = 0x27`. Both were verified by patching a copy of the raw `.bin` and disassembling it with `arm-none-eabi-objdump`. This patch is optional; the key rewrite in Step 27b works without it (it just still prints). + +### Step 28: Export, convert, and flash + +```python +import os +seg = next(s for s in bv.segments if s.data_length) # the loadable image segment +data = bv.read(seg.start, seg.data_length) # base + size from the view itself +out = os.path.join(os.path.join(root, "0x0020_dynamic-conditionals", "build"), "0x0020_dynamic-conditionals-h.bin") +open(out, "wb").write(data) +print(len(data), out) # -> 16188 /.../build/0x0020_dynamic-conditionals-h.bin +``` + +`seg.data_length` is the image size (`0x3f3c` = 16188) read from the view — nothing hardcoded. + +**macOS Apple Silicon / Linux x64:** + +```bash +python3 ../uf2conv.py 0x0020_dynamic-conditionals-h.bin \ + --base 0x10000000 --family 0xe48bff59 --output hacked.uf2 +``` + +**Windows x64:** + +```cmd +python ..\uf2conv.py 0x0020_dynamic-conditionals-h.bin ^ + --base 0x10000000 --family 0xe48bff59 --output hacked.uf2 +``` + +Or run the conversion from the IDA console, exactly as in Step 20 (`os.chdir` to the build dir, then `runpy.run_path("../../uf2conv.py", run_name="__main__")` with `sys.argv` set to the arguments above). + +Hold **BOOTSEL**, plug in the Pico 2, drag `hacked.uf2` onto the **`RP2350`** drive. Or flash the `.bin` over the Debug Probe with SWD — no BOOTSEL — from the console, exactly as in Step 21. + +### Step 29: Verify + +Open the serial monitor: + +- type `x` → with Step 27c applied, **no output** and the servo sweeps silently; without it, `x` prints `x`… actually it prints the original strings `1` / `one` because only the comparison changed (the print strings are untouched). With Step 27c applied the prints are skipped entirely — a **stealth command**. +- type `y` → likewise silent (Step 27c), and the servo sweeps the other way. +- the servo's maximum angle is now **30°**, not 180°. +- the original `1` and `2` keys no longer match the comparisons. + +**We changed the servo angle and hid two secret keys, with a handful of bytes and no source code.** + +--- + +## Cheatsheet + +### IDA GUI actions + +| Action | How | +| ------ | --- | +| Go to address | `G` | +| Rename function/symbol | `N` | +| Set type or signature | `Y` | +| Add comment | `;` | +| Open Hex view | `View -> Hex` | +| Enable hex editing | Toggle the lock in the status bar | +| Reanalyze after a patch | Right-click function -> `Reanalyze` | +| Edit a register live | `dbg.set_reg_value("r0", 0x41f00000)` in the Python console (or right-click the register, press `E`, type hex, Enter) | +| Write debugger memory | `dbg.write_memory(0x20080000, b"fun\r\x00")` | +| Set a breakpoint | `Debugger -> Add Hardware Breakpoint...` (hardware execute). Do **not** use `F2` — software breakpoints cannot be written to read-only flash. | +| Move a breakpoint | Remove it and set it at the new address in the GUI | +| Confirm what is armed | The **Breakpoints** widget lists it | +| Apply the ELF symbol map | Paste the Python snippet from Step 16 / 26 into the Python Console | + +### OpenOCD server and reset + +The server runs with `gdb_breakpoint_override hard` so that flash-writes are never attempted. Breakpoints in this lab are set in the IDA GUI through the **GDB MI** adapter (Step 13). + +| Action | Command | +| ------ | ------- | +| Start the server parked at `main` | macOS/Linux: `BP_ADDR=0x10000234 ./debug-server.sh` — Windows: `$env:BP_ADDR="0x10000234"; .\debug-server.ps1` (one-shot) | +| Break on a loop address in a running target | set a hardware breakpoint in the GUI, then **Resume** — repeatable | +| Kill the debugger | click **X** in the **Debugger** sidebar, or `Debugger -> Kill` | +| Stop OpenOCD | macOS/Linux: `pkill -TERM -f openocd` — Windows: `taskkill /F /IM openocd.exe` | +| Make IDA stepping work | `rp2350.dap.core0 configure -rtos none` (already in the scripts) | +| Step without re-trapping | move the breakpoint off the current PC first, then **Step Into**/**Step Over** | +| Reset without desyncing IDA | **Detach**, `reset run`, reconnect — never `reset run` while attached | + +### Where you can stop + +| Stop at | Project 1 `0x001d` | Project 2 `0x0020` | +| ------- | ------------------ | ------------------ | +| `main` (once per reset) | `0x10000234` | `0x10000234` | +| First `puts` | `0x10000246` (`"1\r\n"`) | `0x10000268` (`"1\r\n"`) | +| Second `puts` | `0x1000024c` (`"one\r"`) | — | +| `getchar` return (dynamic key) | — | `0x1000024a` (`cmp r0, #0x31`) | +| `servo_set_angle(0.0f)` | `0x10000252` | `0x10000276` / `0x100002a2` | +| `servo_set_angle(180.0f)` | `0x10000260` | `0x10000284` / `0x100002b0` | + +### Every address and byte we changed + +| Project | Address | Before | After | Effect | +| ------- | ------- | ------ | ----- | ------ | +| `0x001d` | `0x10001c5c` | `31` | `32` | prints `2` instead of `1` | +| `0x001d` | `0x10001c64` | `6f 6e 65` | `66 75 6e` | prints `fun` instead of `one` | +| `0x001d` | `0x10000270` | `00 00 34 43` | `00 00 f0 41` | servo max angle `180.0f` → `30.0f` | +| `0x001d` | `0x10000256` | `4f f4 fa 70` | `4f f0 64 00` | first `sleep_ms` `500` → `100` | +| `0x001d` | `0x10000264` | `4f f4 fa 70` | `4f f0 64 00` | second `sleep_ms` `500` → `100` | +| `0x0020` | `0x1000024a` | `31` | `78` | compare `'1'` → `'x'` | +| `0x0020` | `0x1000024e` | `32` | `79` | compare `'2'` → `'y'` | +| `0x0020` | `0x100002c0` | `00 00 34 43` | `00 00 f0 41` | servo max angle `180.0f` → `30.0f` | +| `0x0020` | `0x1000024c` | `0c` | `13` | `beq.n` skips the `1`/`one` prints (optional) | +| `0x0020` | `0x10000250` | `20` | `27` | `beq.n` skips the `2`/`two` prints (optional) | + +### Raw image facts + +| Item | Value | +| ---- | ----- | +| Build type | `Release` | +| Load base address | `0x10000000` | +| Project 1 size | `8084` bytes | +| Project 2 size | `16188` bytes | +| Initial stack pointer (both) | `0x20082000` | +| Reset vector (both) | `0x1000015d` | +| Fixed `main` anchor (both) | `0x1000018c` | +| `main` (both) | `0x10000234` | +| `servo_set_angle`, Project 1 | `0x10000318` | +| `servo_set_angle`, Project 2 | `0x10000378` | +| Project 1 `180.0f` literal | `0x10000270` | +| Project 2 `180.0f` literal | `0x100002c0` | +| Project 1 `one` string | `0x10001c64` | +| Project 2 `one` string | `0x10003808` | +| RP2350 UF2 family ID | `0xe48bff59` | + +--- + +## Troubleshooting + +### IDA hangs or crashes when you connect (macOS 27) + +Three different causes have been seen on this setup; check them in this order. + +- **A breakpoint set before connecting.** With the **GDB MI** adapter, if the binary view already has a breakpoint, the session hangs. Start parked with `BP_ADDR`, connect, then add breakpoints. +- **The wrong GDB executable.** Point **Full GDB Executable Path** at the **14.2.rel1** toolchain (Step 11). The 13.3.rel1 build did not connect in testing. +- **The LLDB adapter.** A crash report with `libdebuggercore.dylib -> std::terminate() -> abort()` and `liblldb` in the stack is the **LLDB** adapter, not GDB MI. Avoid LLDB on this setup. + +If IDA hangs, force-quit it; the connect dialog has no working Cancel. The static steps (resolve, patch, export, flash) never touch the debugger and always work. + +### GDB MI hangs when you connect (a breakpoint already existed) + +With the **GDB MI** adapter, if IDA already has a breakpoint set when you connect, the session **hangs**. The working order is: + +1. Start the server parked, e.g. `BP_ADDR=0x10000234 ./debug-server.sh` (Windows: `$env:BP_ADDR="0x10000234"; .\debug-server.ps1`). +2. Connect with the **GDB MI** adapter. +3. Only *then* set hardware breakpoints in the UI. + +### Step Into / Step Over does nothing (PC never moves) + +Two causes have been seen on this target. + +1. **A breakpoint on the current PC re-traps the step.** OpenOCD's step-over-breakpoint logic fails with `Duplicate Breakpoint address` and the PC stays put. Fix: move the breakpoint off the current PC (in the GUI), then step. +2. **The `hwthread` RTOS (GDB RSP adapter only).** With the **GDB RSP** adapter, OpenOCD can log `fake step thread 0` and reply without stepping. Fix: `rp2350.dap.core0 configure -rtos none`. **GDB MI does not hit this.** + +### `zsh: bad CPU type in executable: cmake` + +An Intel `x86_64` tool is on your `PATH` on Apple Silicon. Run Step 2: `export PATH="/opt/homebrew/bin:$PATH"`, then `hash -r`. + +### My addresses do not match this guide + +You probably built `Debug`. This lesson is a `Release` build. Re-run Step 3 with `-DCMAKE_BUILD_TYPE=Release`. A `Debug` build moves the SDK functions and keeps the `static` helpers separate. + +### A breakpoint never fires + +First, confirm you actually set one, and that it is a **hardware** breakpoint. `Debugger -> Add Hardware Breakpoint...` (hardware execute) should land in the **Breakpoints** widget. If nothing lands, or the core keeps running, you probably used `F2` (`Toggle Breakpoint`) — a software breakpoint cannot be written to read-only flash. + +Then check the order and the state: + +- **Arm it only after IDA is connected.** OpenOCD flushes every breakpoint when a client attaches, so anything armed earlier is gone. This also applies to `BP_ADDR` on the startup command line. +- **Is the core running?** If it is stopped, click **Resume**. +- **Does the address get reached again?** `main` runs once per reset, so use `BP_ADDR` at startup rather than `reset run` while attached. Loop addresses such as `0x10000260` fire on the next pass with no reset. For Project 2's `0x1000024a` you must also press a key, because it sits right after the blocking `getchar`. + +### I edit `r0` (or another register) and it reverts + +For the Project 1 angle, `mov r0, r4` at `0x1000025e` reloads `r0` on every pass, so the edit is visible for one sweep unless you stop the core again. Editing `r4` instead makes it stick, because `r4` is loaded once before the loop. For Project 2, `getchar` reloads `r0` on every key press. The edit sticks only while the core is **genuinely stopped** at the breakpoint. + +> **The Registers widget is a snapshot, not a live view.** IDA reads the registers at each stop and shows that snapshot; it does not poll the target. A value changed outside IDA will not appear until the next stop. + +### The string hack does nothing (or prints garbage) + +Pick a RAM address that is free — `0x20080000` is safe here (well above the `.data`/`.bss` end at about `0x2000062c`). Write a NUL-terminated string, and remember `__wrap_puts` appends its own `\n`, so keep the `\r` but not the `\n` (write `b"fun\r\x00"`). Then set `r0`, not `r1`. + +### The patched string shifted `printf` output + +In Project 1 both prints are `puts`, so only whole-string replacement matters. Keep `"one"` → `"fun"` exactly three bytes; a longer string would overwrite the `\r` terminator and a shorter one would leave a stray character. + +### `mov.w r0, #100` corrupts the instruction + +Use the four bytes `4f f0 64 00`, not the first two bytes of the `500` encoding. `500` needs the `4f f4 …` form; `100` uses the `4f f0 …` form. Both are 4 bytes. Verify with `arm-none-eabi-objdump` (Step 20/21 context) or by re-reading the bytes in IDA. + +### Project 2's `x`/`y` still print + +Step 27b only changes the *comparison* values. To make the keys silent you must also apply the optional `beq` redirects in Step 27c. If the servo moves but the terminal still shows `1`/`one`, you applied 27b but not 27c. + +### The optional `beq` redirect sends execution somewhere wrong + +Recompute from the ELF: `target = PC + 4 + (imm8 << 1)`. For `0x1000024c` the servo code is at `0x10000276` (imm8 `0x13`); for `0x10000250` it is at `0x100002a2` (imm8 `0x27`). Confirm the byte pair you write is little-endian (`13 d0`, `27 d0`). + +### The serial capture is garbage on macOS + +Reading `/dev/cu.usbmodem*` with a bare `read()` returns garbage. Set **raw termios at 115200** first, or just use `screen /dev/cu.usbmodem* 115200`, which does it for you. + +### It worked for a second, then stopped (IDA's view desyncs) + +The main cause is **driving the core from the OpenOCD command port while IDA is connected**. If you must reset, **Detach first**, reset, then reconnect. Never leave a breakpoint on the PC you are about to step or resume from. + +### The console floods with `Failed to read memory at 0xf0000000` + +Core1 is exposed. The scripts must run with `USE_CORE=0`. Stop the server, confirm only `core0` is reported, restart, then restart IDA. + +### The decompiler still shows the old value after patching + +Right-click the function and choose `Reanalyze`. + +--- + +## Fallback: do the dynamic steps with GDB (macOS 27) + +If IDA's debugger crashes on attach on macOS 27, you can still do the live hacks with the ARM GDB from the toolchain, against the same OpenOCD server. The addresses and register values are identical to the GUI steps. + +Start the debug server (Step 10), then in a new terminal: + +``` +arm-none-eabi-gdb +``` + +At the `(gdb)` prompt: + +``` +set architecture armv8-m.main +target extended-remote :3333 +hbreak *0x10000260 +continue +``` + +Do **not** run `monitor reset run` before `hbreak`. `0x10000260` is inside `main`'s loop, so the breakpoint fires on the next iteration with no reset. GDB stops at the `servo_set_angle` call: + +``` +info registers pc r0 # pc = 0x10000260, r0 = 0x43340000 +set $r0 = 0x41f00000 +continue +``` + +The servo's next sweep ends at 30° — the same temporary live hack as editing `r0` in the IDA Registers widget. For the string hack, break at `0x1000024c`, then `set {char[5]}0x20080000 = "fun\r"` and `set $r0 = 0x20080000`. + +Project 2 is the same with the other call site and value: + +``` +hbreak *0x1000024a +continue +info registers pc r0 # r0 holds the key you typed +set $r0 = 0x31 +continue +``` + +`hbreak` sets a hardware breakpoint, which is required for read-only flash. It works from plain GDB because GDB sends the 2-byte length the Cortex-M33 comparators need. IDA's **GDB MI** adapter goes through the same GDB, so its GUI breakpoints work too. + +## Glossary + +| Term | Definition | +| ---- | ---------- | +| **`beq`** | Branch if Equal — ARM conditional jump, taken when the Z flag is set | +| **`bne`** | Branch if Not Equal — ARM conditional jump, taken when the Z flag is clear | +| **`.bss`** | Section for uninitialized global variables; zeroed by startup code | +| **`.data`** | Section for initialized global variables; copied from flash to SRAM at boot | +| **Dynamic conditional** | A condition whose value is only known at run time (e.g. `getchar()`), so the compiler must emit the comparisons and branches | +| **`.elf`** | Linked image with the symbol table; the ground truth for addresses and names | +| **GPIO** | General Purpose Input/Output — controllable pins on the microcontroller | +| **Hardware breakpoint** | A breakpoint serviced by the CPU comparators, required for read-only flash | +| **Inlining** | The optimizer replacing a function call with the function body; why the `static` helpers disappear from `main` in `Release` | +| **Literal pool** | A block of 32-bit constants that Thumb-2 code reaches with PC-relative `ldr` | +| **PWM** | Pulse Width Modulation — a variable pulse-width signal; 50 Hz for the SG90 | +| **`.rodata`** | Read-only section for constants and string literals; stays in flash | +| **SG90** | A common 0°–180° hobby servo driven by a 1–2 ms pulse every 20 ms | +| **SIO** | Single-cycle I/O — the fast GPIO block in the RP2350, at `0xd0000000` | +| **Static conditional** | A condition whose value is known at compile time, so the compiler folds it and deletes dead branches | +| **Thumb bit** | Bit 0 of a Cortex-M function pointer; selects Thumb instruction mode | +| **UF2** | USB Flashing Format — the file format the Pico 2 bootloader accepts | +| **Vector table** | The first words of flash: initial stack pointer and exception vectors | + +--- + +**Remember:** the ELF tells you what every address is, and the `.bin` is what you actually patch. Prove the behavior dynamically, resolve the names from the ELF, then patch the bytes and flash. diff --git a/WEEK10/WEEK10-IDA.pdf b/WEEK10/WEEK10-IDA.pdf new file mode 100644 index 0000000..e413f43 Binary files /dev/null and b/WEEK10/WEEK10-IDA.pdf differ diff --git a/WEEK11/WEEK11-IDA.md b/WEEK11/WEEK11-IDA.md new file mode 100644 index 0000000..2e82c20 --- /dev/null +++ b/WEEK11/WEEK11-IDA.md @@ -0,0 +1,1900 @@ +# Week 11-IDA: IDA Pro — Hack Structs & Functions with the NEC IR Remote (Raw `.bin`) + +*** + +**LEGAL DISCLAIMER:** +The information, tools, and code provided in this repository and course are strictly for educational, research, and defensive purposes only. + +You are explicitly prohibited from using any materials contained herein to access, test, modify, or exploit any device, network, or system that you do not own 100% or for which you do not have explicit, documented, and legally binding authorization to interact with. + +By using this repository and course, you acknowledge and agree that: + +1. Any illegal, unauthorized, or malicious use of this information is solely your responsibility. +2. The author(s) and contributor(s) of this repository and course shall not be held liable for any damages, legal repercussions, criminal charges, or unauthorized actions resulting from the use, misuse, or abuse of the contents herein. +3. You will comply with all applicable local, state, national, and international laws regarding cybersecurity and computer fraud. + +**IF YOU DO NOT AGREE WITH THESE TERMS, DO NOT USE THIS REPOSITORY AND COURSE.** + +*** + +## What You'll Learn This Week + +- Build the two lesson projects with `Release` and get an `.elf` and a raw `.bin` for each +- Dump the **ELF symbol map** with `arm-none-eabi-nm` and use it as ground truth +- Load each raw `.bin` into IDA at `0x10000000` +- **Break at `main`** on live silicon, even though `main` can move between programs +- **Hack each running target live** by editing a register and redirecting a string in IDA +- **Resolve the functions in the IDA GUI** using the ELF symbol map +- See how the compiler **flattens a C struct into hard-coded immediates** and **inlines every helper function** +- **Patch** the LED pin immediates and the NEC format string, export, convert, and flash +- Understand the security lesson: **the log says one thing while the hardware does another** + +--- + +## How This Guide Works + +Each project builds two files: + +| File | What it is | How we use it | +| ---- | ---------- | ------------- | +| `.elf` | The linked image with a full symbol table and DWARF | Ground truth for every function address and signature | +| `.bin` | The raw flash image, no headers, no symbols | The image we load into IDA and reverse | + +The `.bin` is built **from** the `.elf`, so the ELF tells you exactly what is at every address. We reverse-engineer the raw `.bin` the way a real extracted firmware image is reversed. + +> **Build `Release`, not `Debug`.** Every address in this guide matches the current `Release` builds. `Release` flattens the LED struct into plain immediates and inlines every `static` helper (`make_default_leds`, `init_led_gpios`, `process_ir_key`, `poll_ir`, and in Project 2 `ir_to_led_number`, `get_led_pin`, `leds_all_off`, `blink_led`, `process_ir_led_command`, `handle_ir_key`, `poll_and_handle_ir`) into `main`. If you build `Debug`, the SDK function addresses move and the helpers stay separate, so nothing lines up. Always build `Release` for this lesson. + +The order is **dynamic first, static second**, twice — once per project: + +1. Break on the live target and prove what the code does. +2. Hack it live in the debugger and watch the behavior change. +3. Resolve the functions in IDA using the ELF symbol map. +4. Patch the bytes, export, convert, and flash. + +| Project | Prints | Also does | The hacks | +| ------- | ------ | --------- | --------- | +| `0x0023_structures` | `IR receiver on GPIO 5 ready`, then `NEC command: 0xNN` per key | lights LED1/2/3 on GPIO 16/17/18 from the flattened struct | move LED1 to GPIO 18 live; swap LED1↔LED3 pins; rename the `NEC` string | +| `0x0026_functions` | the same, plus `LED N activated on GPIO P` | blinks the mapped LED 3× then holds it | forge the decoded key live; swap LED1↔LED3 pins (log desync); rename the `NEC` string | + +> **The struct disappears.** `simple_led_ctrl_t` has six members (three `uint8_t` pins and three `bool` states), but the optimizer proves it never escapes `main`, so it is never placed in memory. `leds.led1_pin` becomes the literal `16`, `leds.led2_pin` becomes `17`, `leds.led3_pin` becomes `18`, and the `bool` states become register values. That is why you patch **immediates**, not a struct field. + +> **The functions disappear too.** Every `static` helper is inlined, so there is no `process_ir_key` or `blink_led` symbol to rename. You see their bodies directly inside `main`. The only real functions `main` calls are the SDK routines and `ir_init`/`ir_getkey`. + +> **The SVD file lives in `WEEK04`.** If you want the RP2350 peripheral register map for the SIO/GPIO side of the lab, it is `Embedded-Hacking/WEEK04/rp2350.svd` — it is **not** in `WEEK11`. + +### Background: the NEC IR remote in one paragraph + +An IR receiver on **GPIO 5** demodulates a 38 kHz carrier and presents the NEC frame as a digital mark/space train. `ir_getkey()` waits for the 9 ms leader + 4.5 ms space, samples 32 bits by timing the marks, then validates that the address and command pairs are bitwise inverses. It returns the **command byte** (`0x0C`, `0x18`, or `0x5E` for buttons 1, 2, 3) or `-1`. `main` maps that byte to one of three LEDs on **GPIO 16 (red), 17 (green), 18 (yellow)**. Because the struct is flattened, that mapping is a set of hard-coded pin numbers in the loop — exactly what we patch. + +--- + +## Part 1: Build, Flash, and Get the Symbol Map + +### Step 1: Install the toolchain + +**Windows x64** + +- Install the **Raspberry Pi Pico** extension in VS Code. It installs the ARM GNU toolchain, CMake, Ninja, and the Pico SDK. +- Install **IDA Pro** and complete its license activation. +- Install **PuTTY** for the serial monitor. + +**macOS Apple Silicon** + +```bash +brew install cmake ninja +``` + +- Install **IDA Pro** and complete its license activation. +- Install the **Arm GNU Toolchain**, or let the VS Code Pico extension manage it. + +**Linux x64** + +```bash +sudo apt install cmake ninja-build gcc-arm-none-eabi libnewlib-arm-none-eabi git python3 openocd minicom +``` + +- Install **IDA Pro** and complete its license activation. + +### Step 2: Verify your tools are the right architecture (do not skip this) + +On **macOS Apple Silicon**, the most common failure is an Intel `x86_64` tool on your `PATH`: + +``` +zsh: bad CPU type in executable: cmake +``` + +You may have **two Homebrews**: the arm64 one at `/opt/homebrew` and the Intel one at `/usr/local`. If `/usr/local/bin` wins, every `brew` tool is x86_64. Check: + +```bash +file "$(which cmake)" +file "$(which ninja)" +file "$(which arm-none-eabi-gdb)" +file "$(which arm-none-eabi-nm)" +file "$(which openocd)" +``` + +All must report `arm64`. If any is `x86_64`, put the Apple Silicon prefix first for the session and check again: + +```bash +export PATH="/opt/homebrew/bin:$PATH" +hash -r +file "$(which cmake)" +``` + +To make it permanent, add that `export` to `~/.zshrc`. Do not use Rosetta as a fix; OpenOCD and GDB are exactly the kind of programs where a translation layer produces failures that look like debugger bugs. + +**Windows x64** and **Linux x64** do not have this problem. Skip to Step 3. + +### Step 3: Build the two projects with `Release` + +Run this once inside `0x0023_structures/` and once inside `0x0026_functions/`: + +```bash +cmake -B build -G Ninja -DPICO_BOARD=pico2 -DPICO_PLATFORM=rp2350 -DCMAKE_BUILD_TYPE=Release +cmake --build build +``` + +**Point IDA at this repository (once).** Every console snippet below reads the repo root from `~/.embedded-hacking-repo`, so IDA never needs a database open and nothing is hardcoded. From the repo root, run once: + +**macOS / Linux:** + +```bash +pwd > ~/.embedded-hacking-repo +``` + +**Windows (PowerShell):** + +```powershell +(Get-Location).Path | Set-Content "$env:USERPROFILE\.embedded-hacking-repo" +``` + +**Then build from the IDA console**, so the whole build -> patch -> flash loop stays inside IDA. The console inherits a minimal `PATH` — on macOS just `/usr/bin:/bin:/usr/sbin:/sbin` — so it does not see Homebrew; add your package manager's `bin` first, then run plain `cmake`. + +**macOS Apple Silicon:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() +os.environ["PATH"] = "/opt/homebrew/bin:" + os.environ["PATH"] # the console's PATH omits Homebrew +for name in ("0x0023_structures", "0x0026_functions"): + proj = os.path.join(root, name) + subprocess.run(["cmake", "-B", "build", "-G", "Ninja", "-DPICO_BOARD=pico2", + "-DPICO_PLATFORM=rp2350", "-DCMAKE_BUILD_TYPE=Release"], cwd=proj) + subprocess.run(["cmake", "--build", "build"], cwd=proj) +``` + +**Linux x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() +for name in ("0x0023_structures", "0x0026_functions"): + proj = os.path.join(root, name) + subprocess.run(["cmake", "-B", "build", "-G", "Ninja", "-DPICO_BOARD=pico2", + "-DPICO_PLATFORM=rp2350", "-DCMAKE_BUILD_TYPE=Release"], cwd=proj) + subprocess.run(["cmake", "--build", "build"], cwd=proj) +``` + +**Windows x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() +for name in ("0x0023_structures", "0x0026_functions"): + proj = os.path.join(root, name) + subprocess.run(["cmake", "-B", "build", "-G", "Ninja", "-DPICO_BOARD=pico2", + "-DPICO_PLATFORM=rp2350", "-DCMAKE_BUILD_TYPE=Release"], cwd=proj) + subprocess.run(["cmake", "--build", "build"], cwd=proj) +``` + +Each build directory now contains the pair we need: + +- `0x0023_structures/build/0x0023_structures.elf` and `.bin` — `.bin` is **16372** bytes (`0x3ff4`) +- `0x0026_functions/build/0x0026_functions.elf` and `.bin` — `.bin` is **16476** bytes (`0x405c`) + +If the ARM toolchain is not on your `PATH`, add `-DPICO_TOOLCHAIN_PATH=...`: + +| OS | Typical toolchain path | +| -- | ---------------------- | +| Windows x64 | `C:/Program Files/Arm GNU Toolchain arm-none-eabi/14.2 rel1/bin` | +| macOS Apple Silicon | `/Applications/ArmGNUToolchain/14.2.rel1/arm-none-eabi/bin` | +| Linux x64 | `/usr` | + +### Step 4: Dump the ELF symbol map + +This is the ground truth for the whole lesson. Run `arm-none-eabi-nm` on each ELF and keep the output in a terminal or a text file: + +**macOS Apple Silicon / Linux x64:** + +```bash +arm-none-eabi-nm -n --defined-only build/0x0023_structures.elf | grep -E ' [Tt] ' +arm-none-eabi-nm -n --defined-only build/0x0026_functions.elf | grep -E ' [Tt] ' +``` + +**Windows x64:** + +```powershell +arm-none-eabi-nm -n --defined-only build\0x0023_structures.elf | Select-String ' [Tt] ' +arm-none-eabi-nm -n --defined-only build\0x0026_functions.elf | Select-String ' [Tt] ' +``` + +Each line is `address type name`. The `T`/`t` type is a function. The signatures below come from the ELF's DWARF debug info queried with `arm-none-eabi-gdb -batch -ex "ptype "`, so they are exact. + +**Project 1 — `0x0023_structures` — our code and the startup chain:** + +| Address | ELF symbol | Signature | Role | +| ------- | ---------- | --------- | ---- | +| `0x1000015c` | `_reset_handler` | `void _reset_handler(void)` | reset entry | +| `0x10000186` | `platform_entry` | `void platform_entry(void)` | calls `runtime_init`, `main`, `exit` | +| `0x1000019a` | `data_cpy` | `void data_cpy(void*, void*, void*)` | copies `.data` from flash to SRAM | +| `0x100001e4` | `_init` | `void _init(void)` | runs `.init_array` | +| `0x10000210` | `frame_dummy` | `void frame_dummy(void)` | C runtime boilerplate | +| `0x10000234` | `main` | `int main(void)` | the lesson function (struct flattened, all helpers inlined) | +| `0x100002cc` | `ir_init` | `void ir_init(uint8_t)` | the `ir.c` receiver init | +| `0x100002f4` | `ir_getkey` | `int ir_getkey(void)` | the blocking NEC decoder (timing helpers inlined) | + +**Project 1 — the GPIO, UART, stdio, and `printf` chain `main` reaches:** + +| Address | ELF symbol | Signature | Role | +| ------- | ---------- | --------- | ---- | +| `0x100004e8` | `gpio_set_function` | `void gpio_set_function(uint, gpio_function_t)` | SDK GPIO function select | +| `0x10000524` | `gpio_set_pulls` | `void gpio_set_pulls(uint, bool, bool)` | SDK pull-up/down (used by `ir_init`) | +| `0x1000054c` | `gpio_init` | `void gpio_init(uint)` | SDK GPIO init | +| `0x10000fa8` | `sleep_ms` | `void sleep_ms(uint32_t)` | SDK millisecond delay | +| `0x1000118c` | `time_us_64` | `uint64_t time_us_64(void)` | SDK microsecond clock (NEC timing) | +| `0x100011a0` | `busy_wait_us` | `void busy_wait_us(uint64_t)` | UART timing loop | +| `0x10001220` | `uart_init` | `uint uart_init(uart_inst_t*, uint)` | SDK UART init | +| `0x100013f4` | `clock_get_hz` | `unsigned long clock_get_hz(clock_handle_t)` | UART clock lookup | +| `0x1000310c` | `exit` | `void exit(int)` | C runtime exit | +| `0x10003114` | `runtime_init` | `void runtime_init(void)` | SDK runtime init | +| `0x10003140` | `stdio_out_chars_crlf` | `void stdio_out_chars_crlf(stdio_driver_t*, const char*, int)` | CRLF output driver | +| `0x10003250` | `stdio_put_string` | `int stdio_put_string(const char*, int, bool, bool)` | buffered string output | +| `0x1000333c` | `stdio_set_driver_enabled` | `void stdio_set_driver_enabled(stdio_driver_t*, bool)` | enable the UART driver | +| `0x10003364` | `stdio_init_all` | `bool stdio_init_all(void)` | SDK serial init | +| `0x100033f4` | `__wrap_puts` | `int __wrap_puts(const char*)` | the `puts` wrapper (adjacent stdio family) | +| `0x10003430` | `__wrap_vprintf` | `int __wrap_vprintf(const char*, va_list)` | printf core | +| `0x100034f4` | `__wrap_printf` | `int __wrap_printf(const char*, ...)` | the `printf` wrapper (both prints) | +| `0x100036b0` | `stdio_uart_init` | `void stdio_uart_init(void)` | SDK UART stdio init | +| `0x100037f0` | `strlen` | `size_t strlen(const char*)` | C runtime string length | + +**Project 2 — `0x0026_functions` — our code and the startup chain:** + +| Address | ELF symbol | Signature | Role | +| ------- | ---------- | --------- | ---- | +| `0x1000015c` | `_reset_handler` | `void _reset_handler(void)` | reset entry | +| `0x10000186` | `platform_entry` | `void platform_entry(void)` | calls `runtime_init`, `main`, `exit` | +| `0x1000019a` | `data_cpy` | `void data_cpy(void*, void*, void*)` | copies `.data` from flash to SRAM | +| `0x100001e4` | `_init` | `void _init(void)` | runs `.init_array` | +| `0x10000210` | `frame_dummy` | `void frame_dummy(void)` | C runtime boilerplate | +| `0x10000234` | `main` | `int main(void)` | the lesson function (struct flattened, all helpers inlined) | +| `0x10000318` | `ir_init` | `void ir_init(uint8_t)` | the `ir.c` receiver init | +| `0x10000340` | `ir_getkey` | `int ir_getkey(void)` | the blocking NEC decoder (timing helpers inlined) | + +**Project 2 — the GPIO, UART, stdio, and `printf` chain `main` reaches:** + +| Address | ELF symbol | Signature | Role | +| ------- | ---------- | --------- | ---- | +| `0x10000534` | `gpio_set_function` | `void gpio_set_function(uint, gpio_function_t)` | SDK GPIO function select | +| `0x10000570` | `gpio_set_pulls` | `void gpio_set_pulls(uint, bool, bool)` | SDK pull-up/down (used by `ir_init`) | +| `0x10000598` | `gpio_init` | `void gpio_init(uint)` | SDK GPIO init | +| `0x10000ff0` | `sleep_ms` | `void sleep_ms(uint32_t)` | SDK millisecond delay | +| `0x100011d4` | `time_us_64` | `uint64_t time_us_64(void)` | SDK microsecond clock (NEC timing) | +| `0x100011e8` | `busy_wait_us` | `void busy_wait_us(uint64_t)` | UART timing loop | +| `0x10001268` | `uart_init` | `uint uart_init(uart_inst_t*, uint)` | SDK UART init | +| `0x1000143c` | `clock_get_hz` | `unsigned long clock_get_hz(clock_handle_t)` | UART clock lookup | +| `0x10003154` | `exit` | `void exit(int)` | C runtime exit | +| `0x1000315c` | `runtime_init` | `void runtime_init(void)` | SDK runtime init | +| `0x10003188` | `stdio_out_chars_crlf` | `void stdio_out_chars_crlf(stdio_driver_t*, const char*, int)` | CRLF output driver | +| `0x10003298` | `stdio_put_string` | `int stdio_put_string(const char*, int, bool, bool)` | buffered string output | +| `0x10003384` | `stdio_set_driver_enabled` | `void stdio_set_driver_enabled(stdio_driver_t*, bool)` | enable the UART driver | +| `0x100033ac` | `stdio_init_all` | `bool stdio_init_all(void)` | SDK serial init | +| `0x1000343c` | `__wrap_puts` | `int __wrap_puts(const char*)` | the `puts` wrapper (adjacent stdio family) | +| `0x10003478` | `__wrap_vprintf` | `int __wrap_vprintf(const char*, va_list)` | printf core | +| `0x1000353c` | `__wrap_printf` | `int __wrap_printf(const char*, ...)` | the `printf` wrapper (all three prints) | +| `0x100036f8` | `stdio_uart_init` | `void stdio_uart_init(void)` | SDK UART stdio init | +| `0x10003838` | `strlen` | `size_t strlen(const char*)` | C runtime string length | + +> **`main` is `0x10000234` in both projects.** Both programs put `main` at the same address because the startup code and the linker layout are identical; only the body of `main` and the functions after it move. In a `Debug` build the helpers stay separate and `main` moves — another reason to build `Release`. + +> **`printf` in our source is `__wrap_printf` in the binary.** The SDK links our `printf` calls to its `__wrap_printf` wrapper, which forwards to `__wrap_vprintf`. The `__wrap_puts` symbol exists in the image (the stdio family always does), but our `printf` path does not call it. + +### Step 5: Flash Project 1 and confirm the NEC/LED behavior + +A `.bin` has no headers, so OpenOCD must be told the base address `0x10000000`. From the repository root: + +**macOS Apple Silicon / Linux x64:** + +```bash +./flash.sh 0x0023_structures/build/0x0023_structures.bin +``` + +**Windows x64 (PowerShell):** + +```powershell +.\flash.ps1 -Bin 0x0023_structures\build\0x0023_structures.bin +``` + +**Or flash from the IDA console:** + +**macOS Apple Silicon / Linux x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) +bin_path = os.path.join(root, "0x0023_structures", "build", "0x0023_structures.bin") +log = os.path.join(os.path.dirname(bin_path), "flash.log") +subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # free the probe first +subprocess.Popen([os.path.join(root, "flash.sh"), bin_path], + stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) +print("flashing in the background; log:", log) +``` + +**Windows x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) +bin_path = os.path.join(root, "0x0023_structures", "build", "0x0023_structures.bin") +log = os.path.join(os.path.dirname(bin_path), "flash.log") +subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"]) # free the probe first +subprocess.Popen(["powershell", "-ExecutionPolicy", "Bypass", "-File", + os.path.join(root, "flash.ps1"), "-Bin", bin_path], + stdout=open(log, "w"), stderr=subprocess.STDOUT) +print("flashing in the background; log:", log) +``` + +Wait for `wrote 16372 bytes ...` and `** Verified OK **`. Open a serial monitor at **115200** baud: + +- **Windows x64:** PuTTY -> Connection type **Serial**, the Pico's COM port, speed `115200`. +- **macOS Apple Silicon:** `screen /dev/tty.usbmodem* 115200` (quit with `Ctrl-A` then `K`). +- **Linux x64:** `minicom -D /dev/ttyACM0 -b 115200`. + +On reset it prints the banner once, then a line for every button press: + +``` +IR receiver on GPIO 5 ready +NEC command: 0x0C <- button "1" -> red LED (GPIO 16) +NEC command: 0x18 <- button "2" -> green LED (GPIO 17) +NEC command: 0x5E <- button "3" -> yellow LED (GPIO 18) +``` + +### Step 6: Flash Project 2 and confirm the blink behavior + +```bash +# macOS / Linux +./flash.sh 0x0026_functions/build/0x0026_functions.bin +``` +```powershell +# Windows +.\flash.ps1 -Bin 0x0026_functions\build\0x0026_functions.bin +``` + +**Or flash from the IDA console** (same form, pointing at the Project 2 `.bin`): + +**macOS / Linux:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) +bin_path = os.path.join(root, "0x0026_functions", "build", "0x0026_functions.bin") +log = os.path.join(os.path.dirname(bin_path), "flash.log") +subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # free the probe first +subprocess.Popen([os.path.join(root, "flash.sh"), bin_path], + stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) +print("flashing in the background; log:", log) +``` + +**Windows:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) +bin_path = os.path.join(root, "0x0026_functions", "build", "0x0026_functions.bin") +log = os.path.join(os.path.dirname(bin_path), "flash.log") +subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"]) # free the probe first +subprocess.Popen(["powershell", "-ExecutionPolicy", "Bypass", "-File", + os.path.join(root, "flash.ps1"), "-Bin", bin_path], + stdout=open(log, "w"), stderr=subprocess.STDOUT) +print("flashing in the background; log:", log) +``` + +Wait for `wrote 16476 bytes ...`. The serial monitor shows the banner, then for each button: + +``` +IR receiver on GPIO 5 ready +NEC command: 0x0C +LED 1 activated on GPIO 16 <- red LED blinks 3x, then holds on +NEC command: 0x18 +LED 2 activated on GPIO 17 <- green LED blinks 3x, then holds on +NEC command: 0x5E +LED 3 activated on GPIO 18 <- yellow LED blinks 3x, then holds on +``` + +> **Watch the two lines together.** The `LED N activated on GPIO P` line is built from the struct's *pin constants*, which the compiler hard-coded. Later we change the pin the loop actually drives but leave the print constant alone — that is the **log desynchronization** this week is about. + +--- + +## Part 2: Load the Raw `.bin` into IDA + +Start from a fresh IDA state. If you already have a database for this lesson, **close it and start over**; a stale database keeps old names and patches. + +### Step 7: Bring the raw `.bin` into IDA + +A raw `.bin` has no headers, so IDA cannot know where it belongs or what architecture it is. You must supply both. If you just double-click the `.bin`, IDA may load it with a guessed architecture, and every address in this lesson will be wrong. + +#### 1.1 Open the file +1. **File ▸ Open…** (Ctrl/Cmd+O). +2. Select the `.bin` file and click **Open**. + +IDA opens the **"Load a new file"** dialog because a raw `.bin` has no header. + +#### 1.2 Set the format and processor +In the *Load a new file* dialog: +1. **Format**: leave it as **Binary file** (IDA auto-detects a headerless image). +2. **Processor type**: click the **…** button next to the processor field. In the *Processor type* dialog: + - Family: **ARM** + - Type: **ARM Little-endian** (the 32-bit ARM module). + - Click **OK**. + +> If IDA asks **"Do you want to disassemble it as 64-bit code?"** — click **No**. +> The RP2350 is 32-bit; answering *Yes* loads AArch64 and you get `X` registers / data. (This is the single most common cause of the `DCB` wall.) + +#### 1.3 Configure the ARM architecture and Thumb mode +Still in the *Load a new file* dialog, open the processor options (the **Processor options** / **Set…** button, which opens the dialog titled **ARM architecture options**): +- **ARM architecture**: choose **ARMv8-M** (this is the Cortex-M33 / RP2350 core). +- **Thumb instructions**: select **Thumb-2** (ARMv8-M is Thumb-only, so this is the correct mode). +- Leave **automatic ARM-THUMB switch** off; we want Thumb throughout. + +#### 1.4 Set the loading address +- **Loading address**: enter **`10000000`** (hex; the RP2350 XIP flash base). + IDA rejects addresses that don't look like ROM/RAM with *"The loading address should belong to RAM or ROM"* — `0x10000000` is the correct flash window. + +Leave **Manual load** and **Create segments** at their defaults. Click **OK**. + +#### 1.5 Force Thumb, then seed the code from the vector table +A raw `.bin` has no header, so IDA's loader has **no entry point** and defaults the segment to **ARM mode** (which cannot decode Thumb). Two required steps — in this order: + +**A. Set the segment to Thumb (do this first).** +- **Edit ▸ Segments ▸ Set default segment register value…** → register **`T`** = **`1`** (or press **`Alt+G`**). IDA reanalyzes the segment as Thumb automatically. + +**B. Seed the code from the vector table.** +1. **G** → `10000000`. The first two words are the initial stack pointer and the **reset vector**. +2. **Read the 4-byte word at `0x10000004`** (do **not** assume its value — it differs per build). +3. **Clear bit 0** (the ARM **Thumb** flag) → the reset handler address. +4. **G** to that address → press **C** (**MakeCode**). IDA disassembles the reset handler and follows its `bl`s into `main`. + +Once `main` shows code, the import is correct. + +**Why IDA needs this and others don't:** IDA's generic raw-binary ARM loader treats the image as flat data and waits for you to set Thumb and mark the entry point. It's an IDA quirk, not a mistake on your part. + +### Step 8: Save it as a IDA database (`.i64`) + +IDA never writes back into the `.bin`. Your names, comments, types, and patches live in a separate **`.i64`** database. Save one now, before you make any changes: + +1. Choose `File -> Save As...`. +2. Save it next to the image as `0x0023_structures.i64`. +3. From now on, save with `File -> Save` (`Cmd+S` on macOS, `Ctrl+S` on Windows/Linux) whenever you rename or patch. + +| File | Role | +| ---- | ---- | +| `0x0023_structures.bin` | the raw firmware image; IDA never modifies it | +| `0x0023_structures.i64` | your analysis database: names, types, comments, and patches | + +When you come back later, **open the `.i64`**, not the `.bin`; that restores all your work. You export the patched image out of this view later, in Step 19. + +### Step 9: The views you will use + +- **Linear view:** the disassembly listing. You navigate, read, and patch here. +- **Graph view:** the control-flow graph of the current function. +- **Decompiler (HLIL):** the pseudo-C decompilation. +- **Hex view:** raw bytes, used for patching. +- **Function list:** the sidebar list of every detected function. + +Navigation: `G` go to address, `N` rename, `Y` set type or signature, `;` add a comment. Breakpoints are set from the GUI through the GDB MI adapter — see Step 13. + +> **macOS function keys:** the top-row `F` keys are usually mapped to system functions. Every step here uses menu paths that work without them. + +--- + +## Part 3: Dynamic — Break at `main` and Hack Live (Project 1) + +### Step 10: Start OpenOCD as a live debug server + +Make sure no other OpenOCD is running; a forgotten server holds port `3333`. + +**macOS / Linux:** + +```bash +ps aux | grep -i openocd +``` + +**Windows (PowerShell):** + +```powershell +Get-Process | Where-Object { $_.ProcessName -like '*openocd*' } +``` + +Stop any leftover server gracefully: + +**macOS / Linux:** + +```bash +pkill -TERM -f openocd +``` + +**Windows (PowerShell):** + +```powershell +Get-Process openocd -ErrorAction SilentlyContinue | Stop-Process +``` + +Start the server **parked at `main`**: + +**macOS Apple Silicon / Linux x64:** + +```bash +BP_ADDR=0x10000234 ./debug-server.sh +``` + +**Windows x64 (PowerShell):** + +```powershell +$env:BP_ADDR="0x10000234"; .\debug-server.ps1 +``` + +**Or start it from the IDA console**, freeing the probe first and launching the server in the background so the console returns immediately: + +**macOS Apple Silicon / Linux x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) +subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # stop any running server first +log = os.path.join(root, "openocd.log") +p = subprocess.Popen([os.path.join(root, "debug-server.sh")], cwd=root, + env=dict(os.environ, BP_ADDR="0x10000234"), + stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) +print("OpenOCD started (pid", p.pid, "); log:", log) +``` + +**Windows x64:** + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) +subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"]) # stop any running server first +log = os.path.join(root, "openocd.log") +p = subprocess.Popen(["powershell", "-ExecutionPolicy", "Bypass", "-File", + os.path.join(root, "debug-server.ps1")], cwd=root, + env=dict(os.environ, BP_ADDR="0x10000234"), + stdout=open(log, "w"), stderr=subprocess.STDOUT) +print("OpenOCD started (pid", p.pid, "); log:", log) +``` + +`Popen` returns in a few milliseconds; the server keeps running in the background. Check `openocd.log` for `Listening on port 3333`, then connect in Step 11. + +Wait for: + +``` +Info : [rp2350.dap.core0] Examination succeed +Startup breakpoint at 0x10000234 (2-byte hardware execute, one-shot). +Info : starting gdb server for rp2350.dap.core0 on 3333 +Info : Listening on port 3333 for gdb connections +``` + +> **`BP_ADDR` parks the core at `main` before any client connects.** The script arms a 2-byte hardware breakpoint and then does the startup `reset run`, so the core runs from the vector table and stops at your address with no debugger attached yet. When IDA connects a moment later, the first thing it reads is already the truth: `Stopped at 0x10000234`. + +> **This startup stop is single-use.** OpenOCD flushes breakpoints when a client connects, so this one is gone once IDA attaches — fine for `main`, which only runs once per reset. Every breakpoint after that is set from the IDA GUI (Step 13) and is repeatable. To stop at `main` again, restart the server with `BP_ADDR` and reconnect. + +> **Exactly one core.** The line must say `core0` and must **not** mention `core1`. Core1 is never started by this firmware; exposing it makes IDA read core1's reset-state registers, which are not real addresses, and OpenOCD floods the log with `Failed to read memory at 0xf0000000`. The scripts already use `USE_CORE=0`; do not change it. + +> **Windows driver note:** the Debug Probe must use the **WinUSB** driver. If OpenOCD reports `unable to open CMSIS-DAP device`, install it with [Zadig](https://zadig.akeo.ie/) (select `Debug Probe (CMSIS-DAP)` -> WinUSB). + +### Step 11: Connect IDA to the GDB server + +1. Make sure the image is open and analyzed (Part 2) and the server from Step 10 is running (parked at `main`). +2. Choose `Debugger -> Connect to Remote Process`. +3. In the **adapter** dropdown, select **GDB MI**. +4. In the **connect** settings group, set **IP Address** to `127.0.0.1` and **Port** to `3333`. +5. Set **Full GDB Executable Path** to the `arm-none-eabi-gdb` from the **Arm GNU Toolchain 14.2.rel1**. It ships for all three hosts, and the Raspberry Pi Pico VS Code extension installs that same 14.2.rel1 toolchain (including `arm-none-eabi-gdb`) on all of them: + + | OS | `arm-none-eabi-gdb` path | + | -- | ------------------------ | + | macOS Apple Silicon | `/Applications/ArmGNUToolchain/14.2.rel1/arm-none-eabi/bin/arm-none-eabi-gdb` (or the Pico extension's `~/.pico-sdk/toolchain/14_2_Rel1/bin/arm-none-eabi-gdb`) | + | Windows x64 | `%USERPROFILE%\.pico-sdk\toolchain\14_2_Rel1\bin\arm-none-eabi-gdb.exe` (Pico extension), or `C:\Program Files (x86)\Arm GNU Toolchain arm-none-eabi\14.2 rel1\bin\arm-none-eabi-gdb.exe` | + | Linux x64 | `~/.pico-sdk/toolchain/14_2_Rel1/bin/arm-none-eabi-gdb` (Pico extension), or the `bin/` directory of the extracted `arm-gnu-toolchain-14.2.rel1-x86_64-arm-none-eabi` tarball | +6. Click **Accept**. + +> **Use the GDB MI adapter.** It launches a real `arm-none-eabi-gdb --interpreter=mi2` and lets IDA drive it, so breakpoints and stepping go through real GDB — which sends the correct 2-byte breakpoint length. Verified working end to end: connect, GUI breakpoints (**Add Hardware Breakpoint...**, hardware execute), **Step Into** / **Step Over**, and register edits. + +> **Do NOT have any breakpoints set in IDA before you connect.** With the GDB MI adapter, attaching while IDA already has a breakpoint **hangs the session**. Start the server parked with `BP_ADDR` (Step 10), connect, and only add hardware breakpoints *after* the connection is up. This is a IDA bug; it is the single most common GDB MI failure. + +> **The GDB executable path matters.** Use the **14.2.rel1** build on every OS (Windows, macOS, Linux). The 13.3.rel1 build did **not** connect in testing. +> +> **This step is temporary.** Vector35 plans to ship a GDB binary with the GDB MI adapter ([Vector35/debugger#929](https://github.com/Vector35/debugger/issues/929), milestone *Langara*). Once that lands, IDA provides GDB itself and you will not need to set **Full GDB Executable Path** at all. + +> **Do not pick Corellium.** IDA's adapter dropdown also lists **Corellium**, which is for Corellium's virtual devices and expects an API token, not a local OpenOCD server. Always read the label back and confirm it says **GDB MI** before clicking **Accept**. + +> **The adapter and port are not saved in the `.i64`.** Every time you relaunch IDA you must re-select **GDB MI**, re-enter port `3333`, and re-set the GDB path. + +The target keeps running. Open the **Registers** tab (bug icon) and confirm you see live values. `pc` inside `0x10003xxx` and `sp` just below `0x20082000` are healthy. + +> **If `pc` is `0x00000088`, `0x000000ec`, or `sp` is `0xf0000000`, the session is bad.** Restart the server, then restart IDA (a server restart while attached leaves IDA in a stale session), and connect again. + +### Step 12: Find `main` without relying on its address + +`main` can move between programs, so we do not guess it. We follow the one fixed path to it. Press `G` and go to `0x10000000`: + +``` +0x10000000 0x20082000 initial stack pointer (top of SRAM) +0x10000004 0x1000015d reset vector +``` + +Bit 0 of a vector is the Thumb bit, so `0x1000015d` means "start at `0x1000015c`". That is `_reset_handler`. Follow the reset path to `0x10000186`, `platform_entry`: + +```asm +10000186 : +10000186: 4914 ldr r1, [pc, #80] +10000188: 4788 blx r1 +1000018a: 4914 ldr r1, [pc, #80] +1000018c: 4788 blx r1 +1000018e: 4914 ldr r1, [pc, #80] +10000190: 4788 blx r1 +10000192: be00 bkpt 0x0000 +``` + +**The middle `blx` at `0x1000018c` is the call to `main`.** `platform_entry` is byte-identical in both projects, so `0x1000018c` catches `main` no matter where the linker placed it. The literal pool at `0x100001dc` holds `main | 1`; clearing bit 0 gives `0x10000234`. + +### Step 13: Set a hardware breakpoint in the GUI + +With the **GDB MI** adapter, IDA sets breakpoints through real GDB, which sends the correct 2-byte length, so you set them **in the UI**. There is no command port here. + +#### Where you can stop + +| You want to stop at | Project 1 address | How | Repeatable? | +| --- | --- | --- | --- | +| **`main`** | `0x10000234` | The server starts parked there with `BP_ADDR=0x10000234` (Step 10), so IDA is already stopped at `main` when it connects. | No — `main` runs once per reset. | +| **First `printf` (`IR receiver...`)** | `0x1000026c` | Set a hardware breakpoint in the GUI, then click **Resume**. | No — runs once before the loop. | +| **Loop `printf` (`NEC command...`)** | `0x1000027c` | Same. | Yes — fires on every key press. | +| **First `gpio_put` (`mcrr`)** | `0x1000028a` | Same — this is where LED1's pin is written. | Yes — fires on every key press. | +| **`ir_getkey` return** | `0x10000274` | Same. | Yes. | + +#### Set a breakpoint in the GUI + +1. Press `G`, type the address (for example `0x1000028a`), and press Enter. +2. Set a **hardware execution** breakpoint at that address, either way: + - `Debugger -> Add Hardware Breakpoint...` — a **hardware execute** (`HE`) breakpoint. **Use this one.** + - click the line and press `F2` (`Debugger -> Toggle Breakpoint`) — a **software** breakpoint. It will **not** work here: the code is in read-only flash, so GDB cannot install it and the core just keeps running. +3. Click **Resume**. The core is already running the loop, so the breakpoint fires on the next key press. IDA stops with the PC at the address and reports it as a **Breakpoint**. + +> **No breakpoints before you connect.** With GDB MI, a breakpoint set before the connection hangs the session (Step 11). Start parked with `BP_ADDR`, connect, *then* add breakpoints. + +> **Step Over on the raw `.bin` steps *into* calls.** The raw image has no symbol for `__wrap_printf`, `ir_getkey`, or `sleep_ms`, so **Step Over** at a `bl` behaves like **Step Into**. When the lab needs to execute the call and then stop, it moves the breakpoint to the return site and clicks **Resume** instead (Step 14 shows this). + +> **Never use IDA's Restart button.** On RP2350 it resets and halts inside the boot ROM (`pc=0x88`, `sp=0xf0000000`). To reset cleanly, restart the server with `BP_ADDR` and reconnect. + +### Step 14: HACK IT LIVE — move LED1 from GPIO 16 to GPIO 18 + +`main` loads the constant `16` into `r5` once at `0x10000240`, before the loop, and the loop's first `mcrr` at `0x1000028a` writes the LED1 state to the pin in `r5`. Because `r5` is **never reloaded inside the loop**, changing it once is sticky for every later key press. We break on that `mcrr` and change it live. + +1. Press `G`, go to `0x1000028a` (the first `mcrr`, `gpio_put(r5, ...)` for LED1). +2. Set a **hardware execute** breakpoint there: `Debugger -> Add Hardware Breakpoint...`. (Do not use `F2` — that is a software breakpoint and will not work on read-only flash.) +3. Click **Resume** in IDA, then press **"1"** on the IR remote. The `ir_getkey` call returns, the `printf` at `0x1000027c` prints `NEC command: 0x0C`, and the breakpoint fires at `0x1000028a`. +4. Open the **Registers** widget (bug icon -> **Registers**). Find `r5`. Its value is `16` (`0x10`) — LED1's pin. +5. **Set `r5` to `18` (`0x12`).** From IDA's Python console (`Plugins -> Python Console`): + ```python + dbg.set_reg_value("r5", 0x12) # LED1 now drives GPIO 18 + ``` + `dbg.set_reg_value(name, value)` writes one register (returns `True` on success). You can also right-click `r5` in the **Registers** widget, press `E` (edit), type `12`, and press Enter. The widget may not repaint the value, but the write reaches the target. +6. Remove the breakpoint at `0x1000028a` and click **Resume**. The core executes the `mcrr` with `r5 = 18`, so pressing **"1"** now lights the **yellow** LED on GPIO 18 instead of the red LED on GPIO 16. + +Because `r5` is set once and never reloaded, the change sticks for every subsequent key press until you reset. Press **"1"** again: the yellow LED lights again, while the terminal still says `NEC command: 0x0C`. + +> **`r5` is the sticky register here.** If you instead edit `r3` (the state, computed by the `clz` trick) or `r2`, the next iteration recomputes them, so the edit lasts one pass. `r5` is the pin, loaded once, so it is the one worth moving. + +### Step 14b: HACK THE STRING LIVE — change `NEC` to `HACKED` + +The text `"NEC command: 0x%02X\n"` lives in flash (`.rodata`) at `0x100038d0`, and flash is **read-only at runtime** — a debugger write there does not stick. So you cannot overwrite the text in place. Instead you redirect the pointer: at the loop `printf` call, `r0` holds the format-string address, so you point `r0` at a replacement string you place in RAM. + +1. Press `G`, go to `0x1000027c` (the loop `bl __wrap_printf`) and set a **hardware execute** breakpoint. Resume and press **"1"** on the remote. At the stop, `r0 = 0x100038d0` (the `ldr r0, [pc, #76]` at `0x1000027a` just loaded the `"NEC command: 0x%02X\n"` pointer) and `r1 = 0x0C`. +2. Put the replacement string into free RAM at `0x20080000` from the **Python console**: + ```python + dbg.write_memory(0x20080000, b"HACKED: 0x%02X\n\x00") # one %02X, same argument + ``` + `dbg.write_memory(address, bytes)` is IDA's debugger memory-write API; it returns `True` on success. Keep exactly one `%02X` so `printf` still consumes the key in `r1`. +3. Point `r0` at that string: + ```python + dbg.set_reg_value("r0", 0x20080000) + ``` + (Or right-click `r0` in the **Registers** widget, press `E`, type `20080000`, and press Enter.) +4. Move the breakpoint past the call in the GUI (remove it at `0x1000027c`, set one at `0x10000280`) and click **Resume**. The core runs `printf` with `r0` pointing at your RAM string and `r1 = 0x0C`, so this iteration prints: + ``` + HACKED: 0x0C + ``` + then stops at `0x10000280`. + +Like the pin hack, this is **one iteration only**: the loop reloads `r0` from the literal pool on every pass, so the next key prints `NEC command: ...` again. The permanent version is the static patch in Step 18b. + +### Step 15: Why the hack reverts (and why we patch next) + +Press **Resume**. The loop branches back to `0x10000270`, reloads `r0` from `0x100038d0` at `0x1000027a`, and `r5` stays at `18` only until the next reset (it is loaded once at `0x10000240`). The string edit was one iteration; the pin edit was sticky but lives only in a register. To make the behavior permanent we must patch the bytes — the static pass. + +Press **Pause** to stop the output flood. + +### Step 15b: Kill the debugger and OpenOCD + +The live hack is done. Do this **before** the static pass. + +1. In the **Debugger** sidebar, click the **X** (**Kill**) (or **`Debugger -> Kill`**) to disconnect IDA. +2. **Kill does not stop the OpenOCD process** — `debug-server.sh` started it separately, and it keeps running and holding the probe. Stop it from the IDA console: + + **macOS / Linux:** + + ```python + import subprocess + subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # stop the debug server, free the probe + ``` + + **Windows:** + + ```python + import subprocess + subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"]) # stop the debug server, free the probe + ``` + +3. Confirm nothing is left: `pgrep -fl openocd` (macOS/Linux) prints nothing. + +From a terminal it is the same: `pkill -TERM -f openocd`, or `Get-Process openocd | Stop-Process` on Windows. + +--- + +## Part 4: Static — Resolve the Functions in IDA and Patch (Project 1) + +### Step 16: Resolve the functions in the IDA GUI + +We now name the functions in IDA using the ELF symbol map from Step 4. IDA loaded the raw `.bin` with **no symbols**, so every function shows as `sub_` — resolving means giving each one its real name and signature. + +Three keys do all the work: + +| Key | IDA action | Use it for | +| --- | --- | --- | +| `G` | Go to address | Jump to a function's address | +| `Y` | **Change Type** | Set the function's signature. The dialog shows the full prototype, so this sets the name *and* the type in one step. | +| `N` | Rename | Rename only, when you just want the name and not the type | + +For each function below: `G` to its address, then **`Y` (Change Type)** and type the prototype from the table. + +#### How to resolve a function in IDA (`Y`) + +`Y` is the **Change Type** key, and it is what actually resolves the function — it turns `void sub_10003364()` into `bool stdio_init_all(void)`. The Change Type dialog shows the full declaration (name and type), so typing the prototype sets both: + +1. `G` to the function's address. The cursor lands on the function. +2. Press **`Y`**. In the Change Type dialog, type the prototype from the table exactly — for example `bool stdio_init_all(void)` — and press Enter. + +If `Y` seems to do nothing, confirm the cursor is on the function, or right-click it and pick **Change Type...**. IDA parses what you type and silently keeps the old type if it does not parse, so glance at the header after each `Y`. + +#### Worked example: `main` + +1. Press `G`, type `0x10000234`, press Enter. The cursor lands on `sub_10000234`. +2. Press **`Y`** (Change Type), type `int main(void)`, press Enter. + +> **IDA shows `int32_t` where Ghidra shows `int`.** After you set `int main(void)`, the decompiler header may read `int32_t main(void)`. That is the same type — on this platform `int` is 32 bits and IDA's parser normalises it to `int32_t`. Do not fight it; it is not an error. + +#### Worked example: `ir_init` + +1. `G` -> `0x100002cc`. +2. `Y` -> `void ir_init(uint8_t pin)`. + +It takes a `uint8_t` pin; `main` calls it with `5` (`movs r0, #5`). It opens with `gpio_init(pin)`, then writes the direction and calls `gpio_set_pulls` for the pull-up. + +#### Worked example: `ir_getkey` + +1. `G` -> `0x100002f4`. +2. `Y` -> `int ir_getkey(void)`. + +It returns `-1` on timeout and the command byte otherwise. The NEC timing helpers (`wait_for_level`, `wait_leader`, `read_nec_bit`, `read_32_bits`, `validate_nec_frame`) are all `static` and **inlined** into it, so you will not find them as separate functions. + +#### Worked example: `gpio_init` + +1. `G` -> `0x1000054c`. +2. `Y` -> `void gpio_init(uint gpio)`. + +`main` calls it three times with `16`, `17`, `18` — the flattened struct pins. + +#### Worked example: `stdio_init_all` + +1. `G` -> `0x10003364`. +2. `Y` -> `bool stdio_init_all(void)`. + +It returns **`bool`**, not `void` — the ELF says `_Bool stdio_init_all(void)`. Our `main` ignores the return value, so the decompiler still reads cleanly. + +#### Worked example: `__wrap_printf` + +1. `G` -> `0x100034f4`. +2. `Y` -> `int __wrap_printf(const char *fmt, ...)`. Keep the `...` — `printf` is variadic. + +> **`printf` in our source is `__wrap_printf` in the binary.** The SDK links our `printf` calls to its `__wrap_printf` wrapper. + +The rest of the chain is the same two keystrokes per function (`G`, then `Y`). This is **our code plus the library functions it actually calls** — not the whole SDK. The call chain for this project: + +``` +main +├── stdio_init_all ── stdio_uart_init ── gpio_set_function, uart_init +│ │ └── uart_init ── clock_get_hz, busy_wait_us +│ ├── stdio_set_driver_enabled +│ ├── stdio_out_chars_crlf +│ └── stdio_put_string ── strlen, time_us_64 +├── gpio_init +├── ir_init ── gpio_init, gpio_set_pulls +├── ir_getkey ── time_us_64 (the NEC timing helpers are inlined) +└── __wrap_printf ── __wrap_vprintf +``` + +**Project 1 — resolve every function in that chain:** + +| Address | Rename to (`N`) | Signature (`Y`) | +| ------- | --------------- | --------------- | +| `0x1000015c` | `_reset_handler` | `void _reset_handler(void)` | +| `0x10000186` | `platform_entry` | `void platform_entry(void)` | +| `0x1000019a` | `data_cpy` | `void data_cpy(void*, void*, void*)` | +| `0x100001e4` | `_init` | `void _init(void)` | +| `0x10000210` | `frame_dummy` | `void frame_dummy(void)` | +| **`0x10000234`** | **`main`** | **`int main(void)`** | +| `0x100002cc` | `ir_init` | `void ir_init(uint8_t)` | +| `0x100002f4` | `ir_getkey` | `int ir_getkey(void)` | +| `0x100004e8` | `gpio_set_function` | `void gpio_set_function(uint, gpio_function_t)` | +| `0x10000524` | `gpio_set_pulls` | `void gpio_set_pulls(uint, bool, bool)` | +| `0x1000054c` | `gpio_init` | `void gpio_init(uint)` | +| `0x10000fa8` | `sleep_ms` | `void sleep_ms(uint32_t)` | +| `0x1000118c` | `time_us_64` | `uint64_t time_us_64(void)` | +| `0x100011a0` | `busy_wait_us` | `void busy_wait_us(uint64_t)` | +| `0x10001220` | `uart_init` | `uint uart_init(uart_inst_t*, uint)` | +| `0x100013f4` | `clock_get_hz` | `unsigned long clock_get_hz(clock_handle_t)` | +| `0x1000310c` | `exit` | `void exit(int)` | +| `0x10003114` | `runtime_init` | `void runtime_init(void)` | +| `0x10003140` | `stdio_out_chars_crlf` | `void stdio_out_chars_crlf(stdio_driver_t*, const char*, int)` | +| `0x10003250` | `stdio_put_string` | `int stdio_put_string(const char*, int, bool, bool)` | +| `0x1000333c` | `stdio_set_driver_enabled` | `void stdio_set_driver_enabled(stdio_driver_t*, bool)` | +| `0x10003364` | `stdio_init_all` | `bool stdio_init_all(void)` | +| `0x100033f4` | `__wrap_puts` | `int __wrap_puts(const char*)` | +| `0x10003430` | `__wrap_vprintf` | `int __wrap_vprintf(const char*, va_list)` | +| `0x100034f4` | `__wrap_printf` | `int __wrap_printf(const char*, ...)` | +| `0x100036b0` | `stdio_uart_init` | `void stdio_uart_init(void)` | +| `0x100037f0` | `strlen` | `size_t strlen(const char*)` | + +> **A `void` return type may not stick — here is the fix.** IDA treats `void` as low-confidence, and its analysis can override it with an inferred type — most often `int32_t` on this 32-bit target. It is most visible on `_reset_handler` (a hand-written assembly entry that never returns normally), but it can happen to **any** function whose return type IDA thinks it can infer. +> +> Setting the full signature with `Y` reproduces the unwanted `int32_t`, and `fn.return_type = ...` fails too. What works is the **return-value** setter: +> +> ```python +> from binaryninja import ReturnValue, Type +> fn = bv.get_function_at(0x1000015c) +> if fn is not None: +> fn.return_value = ReturnValue(Type.void()) +> ``` +> +> That holds `_reset_handler` at `void` even after reanalysis. If it still will not stick, leave it — it does not affect the rest of the lesson. + +> **Shortcut — resolves name *and* type for every function.** Instead of doing `N` + `Y` by hand, paste this into IDA's Python console (`Plugins -> Python Console`). It sets each function's name and signature programmatically: +> +> ```python +> from binaryninja import Symbol, SymbolType +> # The raw .bin has no headers, so these SDK types don't exist. set_user_type() +> # re-parses each signature as C, so an undefined name raises +> # "SyntaxError: unknown type name '...'". Define them first. +> sdk = bv.parse_types_from_string(""" +> typedef unsigned int uint; +> typedef char* va_list; +> typedef unsigned long clock_handle_t; +> struct stdio_driver; +> typedef struct stdio_driver stdio_driver_t; +> struct uart_inst; +> typedef struct uart_inst uart_inst_t; +> enum gpio_function { +> GPIO_FUNC_XIP = 0, GPIO_FUNC_SPI = 1, GPIO_FUNC_UART = 2, GPIO_FUNC_I2C = 3, +> GPIO_FUNC_PWM = 4, GPIO_FUNC_SIO = 5, GPIO_FUNC_PIO0 = 6, GPIO_FUNC_PIO1 = 7, +> GPIO_FUNC_GPCK = 8, GPIO_FUNC_USB = 9, GPIO_FUNC_NULL = 0x1f, +> }; +> typedef enum gpio_function gpio_function_t; +> """) +> for name, ty in sdk.types.items(): +> bv.define_user_type(name, ty) +> +> # address: (name, signature) +> funcs = { +> 0x1000015c: ("_reset_handler", "void _reset_handler(void)"), +> 0x10000186: ("platform_entry", "void platform_entry(void)"), +> 0x1000019a: ("data_cpy", "void data_cpy(void*, void*, void*)"), +> 0x100001e4: ("_init", "void _init(void)"), +> 0x10000210: ("frame_dummy", "void frame_dummy(void)"), +> 0x10000234: ("main", "int main(void)"), +> 0x100002cc: ("ir_init", "void ir_init(uint8_t)"), +> 0x100002f4: ("ir_getkey", "int ir_getkey(void)"), +> 0x100004e8: ("gpio_set_function", "void gpio_set_function(uint, gpio_function_t)"), +> 0x10000524: ("gpio_set_pulls", "void gpio_set_pulls(uint, bool, bool)"), +> 0x1000054c: ("gpio_init", "void gpio_init(uint)"), +> 0x10000fa8: ("sleep_ms", "void sleep_ms(uint32_t)"), +> 0x1000118c: ("time_us_64", "uint64_t time_us_64(void)"), +> 0x100011a0: ("busy_wait_us", "void busy_wait_us(uint64_t)"), +> 0x10001220: ("uart_init", "uint uart_init(uart_inst_t*, uint)"), +> 0x100013f4: ("clock_get_hz", "unsigned long clock_get_hz(clock_handle_t)"), +> 0x1000310c: ("exit", "void exit(int)"), +> 0x10003114: ("runtime_init", "void runtime_init(void)"), +> 0x10003140: ("stdio_out_chars_crlf", "void stdio_out_chars_crlf(stdio_driver_t*, const char*, int)"), +> 0x10003250: ("stdio_put_string", "int stdio_put_string(const char*, int, bool, bool)"), +> 0x1000333c: ("stdio_set_driver_enabled", "void stdio_set_driver_enabled(stdio_driver_t*, bool)"), +> 0x10003364: ("stdio_init_all", "bool stdio_init_all(void)"), +> 0x100033f4: ("__wrap_puts", "int __wrap_puts(const char*)"), +> 0x10003430: ("__wrap_vprintf", "int __wrap_vprintf(const char*, va_list)"), +> 0x100034f4: ("__wrap_printf", "int __wrap_printf(const char*, ...)"), +> 0x100036b0: ("stdio_uart_init", "void stdio_uart_init(void)"), +> 0x100037f0: ("strlen", "size_t strlen(const char*)"), +> } +> for addr, (name, sig) in funcs.items(): +> bv.define_user_symbol(Symbol(SymbolType.FunctionSymbol, addr, name)) +> f = bv.get_function_at(addr) +> if f is not None: +> f.set_user_type(sig) +> ``` +> +> SDK type names (`stdio_driver_t`, `uart_inst_t`, `gpio_function_t`, `clock_handle_t`, plus `uint`, `va_list`) are **not** in the raw `.bin`. `set_user_type` re-parses each signature as C, so an undefined name raises `SyntaxError: unknown type name '...'` and stops the loop — it is not harmless. The `sdk` block above defines them first. Standard names (`uint8_t`, `uint32_t`, `uint64_t`, `bool`, `size_t`) are built in. + +### Step 17: Read `main` in the decompiler + +Open the **Decompiler** view on `main`. The whole program is one function because every `static` helper was inlined: + +```asm +10000234
: +10000234: b508 push {r3, lr} +10000236: f003 f895 bl 10003364 +1000023a: 2010 movs r0, #16 +1000023c: f000 f986 bl 1000054c +10000240: 2510 movs r5, #16 +10000242: f04f 0401 mov.w r4, #1 +10000246: ec44 5044 mcrr 0, 4, r5, r4, cr4 +1000024a: 2011 movs r0, #17 +1000024c: f000 f97e bl 1000054c +10000250: 2311 movs r3, #17 +10000252: ec44 3044 mcrr 0, 4, r3, r4, cr4 +10000256: 2012 movs r0, #18 +10000258: f000 f978 bl 1000054c +1000025c: 2312 movs r3, #18 +1000025e: ec44 3044 mcrr 0, 4, r3, r4, cr4 +10000262: 2005 movs r0, #5 +10000264: f000 f832 bl 100002cc +10000268: 2105 movs r1, #5 +1000026a: 4816 ldr r0, [pc, #88] +1000026c: f003 f942 bl 100034f4 <__wrap_printf> +10000270: f000 f840 bl 100002f4 +10000274: 1e04 subs r4, r0, #0 +10000276: db21 blt.n 100002bc +10000278: 4621 mov r1, r4 +1000027a: 4813 ldr r0, [pc, #76] +1000027c: f003 f93a bl 100034f4 <__wrap_printf> +10000280: f1a4 030c sub.w r3, r4, #12 +10000284: fab3 f383 clz r3, r3 +10000288: 095b lsrs r3, r3, #5 +1000028a: ec43 5040 mcrr 0, 4, r5, r3, cr0 +1000028e: f1a4 0218 sub.w r2, r4, #24 +10000292: fab2 f282 clz r2, r2 +10000296: 2311 movs r3, #17 +10000298: 0952 lsrs r2, r2, #5 +1000029a: ec42 3040 mcrr 0, 4, r3, r2, cr0 +1000029e: f1a4 045e sub.w r4, r4, #94 +100002a2: fab4 f484 clz r4, r4 +100002a6: 2312 movs r3, #18 +100002a8: 0964 lsrs r4, r4, #5 +100002aa: ec44 3040 mcrr 0, 4, r3, r4, cr0 +100002ae: 200a movs r0, #10 +100002b0: f000 fe7a bl 10000fa8 +100002b4: f000 f81e bl 100002f4 +100002b8: 1e04 subs r4, r0, #0 +100002ba: dadd bge.n 10000278 +100002bc: 2001 movs r0, #1 +100002be: f000 fe73 bl 10000fa8 +100002c2: e7d5 b.n 10000270 +100002c4: 100038b0 .word 0x100038b0 +100002c8: 100038d0 .word 0x100038d0 +``` + +The decompiler reads roughly: + +```c +int32_t main(void) +{ + stdio_init_all(); + gpio_init(0x10); gpio_set_dir(0x10, 1); // led1_pin = 16 + gpio_init(0x11); gpio_set_dir(0x11, 1); // led2_pin = 17 + gpio_init(0x12); gpio_set_dir(0x12, 1); // led3_pin = 18 + ir_init(5); + __wrap_printf("IR receiver on GPIO %d ready\n", 5); + do + { + int32_t key = ir_getkey(); + if (key >= 0) + { + __wrap_printf("NEC command: 0x%02X\n", key); + mcrr(0x10, key == 0x0c); // led1_pin = 16 + mcrr(0x11, key == 0x18); // led2_pin = 17 + mcrr(0x12, key == 0x5e); // led3_pin = 18 + sleep_ms(10); + } + else + { + sleep_ms(1); + } + } while (true); +} +``` + +- **There is no struct.** `16`, `17`, `18` are immediates; `led1_state` etc. are the `clz`-computed register values. +- The `clz`/`lsrs` pair is how the compiler turns `(key == 0x0C)` into a `0`/`1` without a branch: `sub.w r3, r4, #12` sets the flags, `clz r3, r3` counts leading zeros, `lsrs r3, r3, #5` reduces it to `0` or `1`. +- `0x100002c4` and `0x100002c8` point at `"IR receiver on GPIO %d ready\n"` (`0x100038b0`) and `"NEC command: 0x%02X\n"` (`0x100038d0`) in `.rodata`. + +### Step 18: Patch 1 — swap LED1 and LED3 pins + +The original lesson swaps LED pin assignments. LED1 is the red LED on GPIO 16 and LED3 is the yellow LED on GPIO 18. Swap them so button **"1"** lights yellow and button **"3"** lights red. The two pins are hard-coded immediates: + +| Address | Instruction | Bytes before | Bytes after | Role | +| ------- | ----------- | ------------ | ----------- | ---- | +| `0x10000240` | `movs r5, #16` | `10 25` | `12 25` | LED1's pin (`r5`) 16 -> 18 | +| `0x100002a6` | `movs r3, #18` | `12 23` | `10 23` | LED3's pin (`r3`) 18 -> 16 | + +In the **Hex** view (`View -> Hex`, lock off) change the low byte of each, then right-click `main` -> `Reanalyze`. Or in the Python console: + +```python +bv.write(0x10000240, b"\x12") # movs r5, #18 (LED1 -> GPIO 18) +bv.write(0x100002a6, b"\x10") # movs r3, #16 (LED3 -> GPIO 16) +print(bv.read(0x10000240, 2).hex(" ")) # -> 12 25 +print(bv.read(0x100002a6, 2).hex(" ")) # -> 10 23 +``` + +After reanalysis the loop reads `movs r5, #18` and `movs r3, #16`, so button **"1"** drives GPIO 18 (yellow) and button **"3"** drives GPIO 16 (red). The `NEC command:` log still prints the *command byte*, so the log and the physical LED mapping no longer agree — the log desynchronization. + +### Step 18b: Patch 2 — rename the `NEC` string to `PWN` + +The format string `"NEC command: 0x%02X\n"` starts at `0x100038d0`. Its first three bytes are `4e 45 43` (`NEC`). Change them to `50 57 4e` (`PWN`), leaving the ` command: 0x%02X\n` tail untouched, so the line prints `PWN command: 0x0C`. + +**Option A — Hex view:** go to `0x100038d0` and change the three bytes `4e 45 43` to `50 57 4e`, then reanalyze. + +**Option B — Python console:** + +```python +bv.write(0x100038d0, b"PWN") +print(bv.read(0x100038d0, 20)) # -> b'PWN command: 0x%02X\n\x00' +``` + +Keep the replacement exactly three bytes. If you use a shorter string you must pad it, or `%02X` shifts and `printf` reads the wrong argument. A longer string would overwrite the ` command:` tail. + +### Step 19: Export the patched `.bin` + +```python +import os +seg = next(s for s in bv.segments if s.data_length) # the loadable image segment +data = bv.read(seg.start, seg.data_length) # base + size come from the view itself +out = os.path.join(os.path.join(root, "0x0023_structures", "build"), "0x0023_structures-h.bin") +open(out, "wb").write(data) +print(len(data), out) # -> 16372 /.../build/0x0023_structures-h.bin +``` + +Where the two numbers come from — nothing is hardcoded: + +- **`seg.start`** is the image base IDA loaded the `.bin` at (`0x10000000`), the same value you pass to `uf2conv --base`. +- **`seg.data_length`** is the segment's size in the file (`0x3ff4` = 16372). Exactly one segment carries data (the image); every peripheral and synthetic segment has `data_length == 0`, so `next(...)` picks the image. + +> **No relative path.** IDA's Python console runs with a read-only working directory (inside the app bundle), so a relative `open(...)` fails with `OSError: [Errno 30] Read-only file system`. `root` (from `~/.embedded-hacking-repo`, Step 3) is the repo, so the file is written into the project's `build/`. + +### Step 20: Convert to UF2 + +Run from the project directory: + +**macOS Apple Silicon / Linux x64:** + +```bash +python3 ../uf2conv.py 0x0023_structures-h.bin \ + --base 0x10000000 --family 0xe48bff59 --output hacked.uf2 +``` + +**Windows x64:** + +```cmd +python ..\uf2conv.py 0x0023_structures-h.bin ^ + --base 0x10000000 --family 0xe48bff59 --output hacked.uf2 +``` + +> **Or convert from the IDA console** — `chdir` to a writable directory first (the default one is read-only), then run the script: +> +> ```python +> import os, sys, runpy +> os.chdir(os.path.join(root, "0x0023_structures", "build")) # the project build dir (writable) +> sys.argv = ["uf2conv.py", "0x0023_structures-h.bin", +> "--base", "0x10000000", "--family", "0xe48bff59", "--output", "hacked.uf2"] +> runpy.run_path("../../uf2conv.py", run_name="__main__") # path to your uf2conv.py +> ``` + +### Step 21: Flash and verify the swapped LEDs + +Hold **BOOTSEL**, plug in the Pico 2, and drag `hacked.uf2` onto the **`RP2350`** drive. Or flash the `.bin` over the Debug Probe with SWD — no BOOTSEL — from the console (stop any running OpenOCD first, and use `Popen`, not `run`, so the console is not blocked): + +```python +import os, subprocess +root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() +bin_path = os.path.join(os.path.join(root, "0x0023_structures", "build"), "0x0023_structures-h.bin") +log = os.path.join(os.path.join(root, "0x0023_structures", "build"), "flash.log") +subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # free the probe first +p = subprocess.Popen([os.path.join(root, "flash.sh"), bin_path], + stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) +print("flashing in the background; log:", log) +``` + +Open the serial monitor and press the buttons: + +``` +PWN command: 0x0C <- button "1" now lights the YELLOW LED (GPIO 18) +PWN command: 0x18 <- button "2" still lights the green LED (GPIO 17) +PWN command: 0x5E <- button "3" now lights the RED LED (GPIO 16) +``` + +**Two bytes swapped the LEDs and three bytes renamed the log — no source code.** + +--- + +## Part 5: Reflash Project 2 and Load It into IDA + +### Step 22: Reflash Project 2 and restart the session + +Part 4 left the Pico running the patched Project 1 image. Put the original Project 2 back and start a fresh session. + +1. Stop any running debug server so the flash script can use the probe: + + ```bash + # macOS / Linux + pkill -TERM -f openocd + ``` + ```powershell + # Windows + Get-Process openocd -ErrorAction SilentlyContinue | Stop-Process + ``` + +2. Flash the original Project 2 image: + + ```bash + # macOS / Linux + ./flash.sh 0x0026_functions/build/0x0026_functions.bin + ``` + ```powershell + # Windows + .\flash.ps1 -Bin 0x0026_functions\build\0x0026_functions.bin + ``` + + **Or do steps 1–2 from the IDA console:** + + **macOS / Linux:** + + ```python + import os, subprocess + root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) + bin_path = os.path.join(root, "0x0026_functions", "build", "0x0026_functions.bin") + log = os.path.join(os.path.dirname(bin_path), "flash.log") + subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # free the probe first + subprocess.Popen([os.path.join(root, "flash.sh"), bin_path], + stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) + print("flashing Project 2 in the background; log:", log) + ``` + + **Windows:** + + ```python + import os, subprocess + root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() # set once (Step 3) + bin_path = os.path.join(root, "0x0026_functions", "build", "0x0026_functions.bin") + log = os.path.join(os.path.dirname(bin_path), "flash.log") + subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"]) # free the probe first + subprocess.Popen(["powershell", "-ExecutionPolicy", "Bypass", "-File", + os.path.join(root, "flash.ps1"), "-Bin", bin_path], + stdout=open(log, "w"), stderr=subprocess.STDOUT) + print("flashing Project 2 in the background; log:", log) + ``` + +3. Load Project 2 and save its database — see Step 22b. + +Confirm the Pico responds to `1` / `2` / `3` again. + +### Step 22b: Load Project 2 into IDA and save the database + +Exactly like Steps 7–8, but for Project 2. **Use `File -> Open with Options...`** (not plain `File -> Open`), select `0x0026_functions/build/0x0026_functions.bin`, and set: + +- **Architecture:** `thumb2` +- **Platform:** `thumb2` +- **Base Address:** `0x10000000` + +Click **Open**. Then press `G`, type `0x10000000`, and confirm the first two words: + +``` +0x10000000 0x20082000 initial stack pointer +0x10000004 0x1000015d reset vector (bit 0 = Thumb) +``` + +If you see data at `0x00000000`, close the tab and redo it with `Open with Options`. + +Save it with `File -> Save As...` as `0x0026_functions.i64` (next to the `.bin`). From now on open the `.i64`, not the `.bin`; save with `Cmd+S` / `Ctrl+S` after every rename or patch. + +> **Console equivalent:** +> ```python +> load("0x0026_functions/build/0x0026_functions.bin", +> options={"loader.imageBase": 0x10000000, "loader.platform": "thumb2"}) +> ``` + +--- + +## Part 6: Dynamic — Break at `main` and Hack Live (Project 2) + +### Step 23: Break at `main` + +`main` is at `0x10000234` in this project too. Start the server parked at `main` (Step 10 form) and connect with the **GDB MI** adapter (Step 11): + +1. Restart the server parked at `main`: + + **macOS / Linux:** + + ```bash + BP_ADDR=0x10000234 ./debug-server.sh + ``` + ```powershell + # Windows + $env:BP_ADDR="0x10000234"; .\debug-server.ps1 + ``` + + **Or restart it from the IDA console:** + + **macOS / Linux:** + + ```python + import os, subprocess + root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() + log = os.path.join(root, "openocd.log") + subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # kill any running server first + subprocess.Popen([os.path.join(root, "debug-server.sh")], cwd=root, + env=dict(os.environ, BP_ADDR="0x10000234"), + stdout=open(log, "w"), stderr=subprocess.STDOUT, start_new_session=True) + print("OpenOCD restarted parked at main; log:", log) + ``` + + **Windows:** + + ```python + import os, subprocess + root = open(os.path.expanduser("~/.embedded-hacking-repo")).read().strip() + log = os.path.join(root, "openocd.log") + subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"]) # kill any running server first + subprocess.Popen(["powershell", "-ExecutionPolicy", "Bypass", "-File", + os.path.join(root, "debug-server.ps1")], cwd=root, + env=dict(os.environ, BP_ADDR="0x10000234"), + stdout=open(log, "w"), stderr=subprocess.STDOUT) + print("OpenOCD restarted parked at main; log:", log) + ``` +2. Connect IDA (Step 11): adapter **GDB MI**, IP `127.0.0.1`, port `3333`. + +The target is already halted at `main` when IDA connects, and the sidebar reads `Stopped at 0x10000234`. + +### Step 24: Read `main` and find the inlined function bodies + +The whole loop is one function because every helper was inlined. The key difference from Project 1 is the extra `printf` and the blink loop that carries the LED pin in `r5`: + +```asm +10000234
: +10000234: b580 push {r7, lr} +10000236: f003 f8b9 bl 100033ac +1000023a: 2010 movs r0, #16 +1000023c: f000 f9ac bl 10000598 +10000240: f04f 0701 mov.w r7, #1 +10000244: 2310 movs r3, #16 +10000246: ec47 3044 mcrr 0, 4, r3, r7, cr4 +1000024a: 2011 movs r0, #17 +1000024c: f000 f9a4 bl 10000598 +10000250: 2311 movs r3, #17 +10000252: ec47 3044 mcrr 0, 4, r3, r7, cr4 +10000256: 2012 movs r0, #18 +10000258: f000 f99e bl 10000598 +1000025c: 2312 movs r3, #18 +1000025e: ec47 3044 mcrr 0, 4, r3, r7, cr4 +10000262: 2005 movs r0, #5 +10000264: f000 f858 bl 10000318 +10000268: 2105 movs r1, #5 +1000026a: 4828 ldr r0, [pc, #160] +1000026c: f003 f966 bl 1000353c <__wrap_printf> +10000270: f04f 0600 mov.w r6, #0 +10000274: f000 f864 bl 10000340 +10000278: 1e04 subs r4, r0, #0 +1000027a: db19 blt.n 100002b0 +1000027c: 4621 mov r1, r4 +1000027e: 4824 ldr r0, [pc, #144] +10000280: f003 f95c bl 1000353c <__wrap_printf> +10000284: 2510 movs r5, #16 +10000286: ec46 5040 mcrr 0, 4, r5, r6, cr0 +1000028a: 2311 movs r3, #17 +1000028c: ec46 3040 mcrr 0, 4, r3, r6, cr0 +10000290: 2212 movs r2, #18 +10000292: ec46 2040 mcrr 0, 4, r2, r6, cr0 +10000296: 2c0c cmp r4, #12 +10000298: d00e beq.n 100002b8 +1000029a: 2c18 cmp r4, #24 +1000029c: d02e beq.n 100002fc +1000029e: 2c5e cmp r4, #94 +100002a0: d030 beq.n 10000304 +100002a2: 200a movs r0, #10 +100002a4: f000 fea4 bl 10000ff0 +100002a8: f000 f84a bl 10000340 +100002ac: 1e04 subs r4, r0, #0 +100002ae: dae5 bge.n 1000027c +100002b0: 2001 movs r0, #1 +100002b2: f000 fe9d bl 10000ff0 +100002b6: e7dd b.n 10000274 +100002b8: f04f 0801 mov.w r8, #1 +100002bc: 2403 movs r4, #3 +100002be: ec47 5040 mcrr 0, 4, r5, r7, cr0 +100002c2: 2032 movs r0, #50 +100002c4: f000 fe94 bl 10000ff0 +100002c8: ec46 5040 mcrr 0, 4, r5, r6, cr0 +100002cc: 2032 movs r0, #50 +100002ce: f000 fe8f bl 10000ff0 +100002d2: 1e63 subs r3, r4, #1 +100002d4: f013 04ff ands.w r4, r3, #255 +100002d8: d1f1 bne.n 100002be +100002da: ec47 5040 mcrr 0, 4, r5, r7, cr0 +100002de: f1b8 0f01 cmp.w r8, #1 +100002e2: d009 beq.n 100002f8 +100002e4: f1b8 0f02 cmp.w r8, #2 +100002e8: bf14 ite ne +100002ea: 2212 movne r2, #18 +100002ec: 2211 moveq r2, #17 +100002ee: 4641 mov r1, r8 +100002f0: 4808 ldr r0, [pc, #32] +100002f2: f003 f923 bl 1000353c <__wrap_printf> +100002f6: e7d4 b.n 100002a2 +100002f8: 2210 movs r2, #16 +100002fa: e7f8 b.n 100002ee +100002fc: 461d mov r5, r3 +100002fe: f04f 0802 mov.w r8, #2 +10000302: e7db b.n 100002bc +10000304: 4615 mov r5, r2 +10000306: f04f 0803 mov.w r8, #3 +1000030a: e7d7 b.n 100002bc +1000030c: 100038f8 .word 0x100038f8 +10000310: 10003918 .word 0x10003918 +10000314: 10003930 .word 0x10003930 +``` + +What the inlining produced: + +- **`leds_all_off(&leds)`** is the three `mcrr` writes at `0x10000286`, `0x1000028c`, `0x10000292`, all using `r6 = 0` (`mov.w r6, #0` at `0x10000270`). +- **`ir_to_led_number`** is the `cmp`/`beq` chain at `0x10000296`–`0x100002a0` (`12`, `24`, `94`). +- **`get_led_pin`** is the `mov r5, r3` at `0x100002fc` (key 24 -> pin 17) and the `mov r5, r2` at `0x10000304` (key 94 -> pin 18); for key 12, `r5` keeps the `16` loaded at `0x10000284`. +- **`blink_led`** is the loop at `0x100002be`–`0x100002d8`; `r4` counts 3 down to 0, `r5` is the pin, `r7 = 1` and `r6 = 0` drive it on/off. +- **`get_led_pin` in the final print** is `movs r2, #16` at `0x100002f8` (key 1), `moveq r2, #17` at `0x100002ec` (key 2), and `movne r2, #18` at `0x100002ea` (key 3). These are the constants that will **lie** after we patch the loop pins. + +The string map, read straight from `.rodata`: + +| Literal | Points at | String | +| ------- | --------- | ------ | +| `0x1000030c` | `0x100038f8` | `"IR receiver on GPIO %d ready\n"` | +| `0x10000310` | `0x10003918` | `"NEC command: 0x%02X\n"` | +| `0x10000314` | `0x10003930` | `"LED %d activated on GPIO %d\n"` | + +### Step 25: HACK IT LIVE — forge the decoded NEC key + +`ir_getkey` returns the command byte in `r0`; `main` copies it into `r4` at `0x10000278`. We stop right after the read and overwrite `r4` so the program takes a different button's path — even though the operator pressed a different button. + +1. Press `G`, go to `0x1000027c` (the `mov r1, r4` right after the `blt.n`, inside the `key >= 0` block). Set a **hardware execute** breakpoint: `Debugger -> Add Hardware Breakpoint...`. +2. Click **Resume** and press **"1"** on the IR remote. `ir_getkey` returns, `subs r4, r0, #0` at `0x10000278` runs, and the breakpoint fires at `0x1000027c` with `r4 = 0x0C` (12). +3. **Set `r4` to `0x5E` (94)** from the Python console: + ```python + dbg.set_reg_value("r4", 0x5E) # pretend button "3" was pressed + ``` + (Or right-click `r4` in the **Registers** widget, press `E`, type `5e`, and press Enter.) +4. Remove the breakpoint at `0x1000027c` and click **Resume**. The core runs `mov r1, r4`, so the `printf` prints `NEC command: 0x5E`, the `cmp` chain takes the key-94 branch at `0x10000304`, and the Pico blinks the **yellow** LED on GPIO 18 — although you pressed **"1"**. + +> **The pin variant.** If you prefer to move the pin instead of the key, break at `0x10000286` (the first `mcrr`, after `movs r5, #16` at `0x10000284`) and set `r5 = 0x12`. LED1's blink then drives GPIO 18, but `r5` is reloaded at `0x10000284` on the next key, so it is a one-key change. The `r4` edit above is the same idea one step earlier in the pipeline. + +### Step 25b: HACK THE STRING LIVE — change `NEC` to `HACKED` + +The `"NEC command: 0x%02X\n"` format is at `0x10003918`; redirect `r0` to a RAM string at the `printf` call. + +1. Press `G`, go to `0x10000280` (the `bl __wrap_printf` on the key path) and set a **hardware execute** breakpoint. Resume and press **"1"**. At the stop, `r0 = 0x10003918` — the `ldr r0, [pc, #144]` at `0x1000027e` loaded the pointer — and `r1 = 0x0C`. +2. Write the replacement to RAM and repoint `r0`: + ```python + dbg.write_memory(0x20080000, b"HACKED: 0x%02X\n\x00") # keep one %02X + dbg.set_reg_value("r0", 0x20080000) + ``` +3. Remove the breakpoint at `0x10000280`, set one at `0x10000284`, and click **Resume**. This iteration prints: + ``` + HACKED: 0x0C + ``` + One iteration only — the loop reloads `r0` from the literal pool each pass. The permanent version is the static patch in Step 27b. + +### Step 25c: Kill the debugger and OpenOCD + +Same as Step 15b: click the **X** (**Kill**) in the **Debugger** sidebar (or **`Debugger -> Kill`**), then stop OpenOCD from the IDA console: + +**macOS / Linux:** + +```python +import subprocess +subprocess.run(["pkill", "-TERM", "-f", "openocd"]) # stop the debug server, free the probe +``` + +**Windows:** + +```python +import subprocess +subprocess.run(["taskkill", "/F", "/IM", "openocd.exe"]) # stop the debug server, free the probe +``` + +--- + +## Part 7: Static — Resolve the Functions and Patch (Project 2) + +### Step 26: Resolve the functions in the IDA GUI + +Same two keys as Step 16 — `G` to the address, then `Y` (Change Type) to set the prototype — using the Project 2 ELF symbol map from Step 4. + +#### Worked example: `main` + +1. `G` -> `0x10000234`. +2. `Y` -> `int main(void)` (IDA shows `int32_t main(void)` — the same 32-bit `int`). + +#### Worked example: `ir_init` + +1. `G` -> `0x10000318`. +2. `Y` -> `void ir_init(uint8_t pin)`. + +#### Worked example: `ir_getkey` + +1. `G` -> `0x10000340`. +2. `Y` -> `int ir_getkey(void)`. + +#### Worked example: `gpio_init` + +1. `G` -> `0x10000598`. +2. `Y` -> `void gpio_init(uint gpio)`. + +`main` calls it three times with `16`, `17`, `18` — the flattened struct pins. + +#### Worked example: `__wrap_printf` + +1. `G` -> `0x1000353c`. +2. `Y` -> `int __wrap_printf(const char *fmt, ...)`. Keep the `...` — `printf` is variadic. It forwards to `__wrap_vprintf`. + +#### Worked example: `sleep_ms` + +1. `G` -> `0x10000ff0`. +2. `Y` -> `void sleep_ms(uint32_t ms)`. + +The blink loop and the idle path both load `10` or `50` immediately before calling it. + +The call chain for this project is the same as Project 1, plus the extra `printf` and the blink loop: + +``` +main +├── stdio_init_all ── stdio_uart_init ── gpio_set_function, uart_init +│ │ └── uart_init ── clock_get_hz, busy_wait_us +│ ├── stdio_set_driver_enabled +│ ├── stdio_out_chars_crlf +│ └── stdio_put_string ── strlen, time_us_64 +├── gpio_init +├── ir_init ── gpio_init, gpio_set_pulls +├── ir_getkey ── time_us_64 (the NEC timing helpers are inlined) +├── __wrap_printf ── __wrap_vprintf (NEC line and LED line) +└── sleep_ms +``` + +**Project 2 — resolve every function in that chain:** + +| Address | Rename to (`N`) | Signature (`Y`) | +| ------- | --------------- | --------------- | +| `0x1000015c` | `_reset_handler` | `void _reset_handler(void)` | +| `0x10000186` | `platform_entry` | `void platform_entry(void)` | +| `0x1000019a` | `data_cpy` | `void data_cpy(void*, void*, void*)` | +| `0x100001e4` | `_init` | `void _init(void)` | +| `0x10000210` | `frame_dummy` | `void frame_dummy(void)` | +| **`0x10000234`** | **`main`** | **`int main(void)`** | +| `0x10000318` | `ir_init` | `void ir_init(uint8_t)` | +| `0x10000340` | `ir_getkey` | `int ir_getkey(void)` | +| `0x10000534` | `gpio_set_function` | `void gpio_set_function(uint, gpio_function_t)` | +| `0x10000570` | `gpio_set_pulls` | `void gpio_set_pulls(uint, bool, bool)` | +| `0x10000598` | `gpio_init` | `void gpio_init(uint)` | +| `0x10000ff0` | `sleep_ms` | `void sleep_ms(uint32_t)` | +| `0x100011d4` | `time_us_64` | `uint64_t time_us_64(void)` | +| `0x100011e8` | `busy_wait_us` | `void busy_wait_us(uint64_t)` | +| `0x10001268` | `uart_init` | `uint uart_init(uart_inst_t*, uint)` | +| `0x1000143c` | `clock_get_hz` | `unsigned long clock_get_hz(clock_handle_t)` | +| `0x10003154` | `exit` | `void exit(int)` | +| `0x1000315c` | `runtime_init` | `void runtime_init(void)` | +| `0x10003188` | `stdio_out_chars_crlf` | `void stdio_out_chars_crlf(stdio_driver_t*, const char*, int)` | +| `0x10003298` | `stdio_put_string` | `int stdio_put_string(const char*, int, bool, bool)` | +| `0x10003384` | `stdio_set_driver_enabled` | `void stdio_set_driver_enabled(stdio_driver_t*, bool)` | +| `0x100033ac` | `stdio_init_all` | `bool stdio_init_all(void)` | +| `0x1000343c` | `__wrap_puts` | `int __wrap_puts(const char*)` | +| `0x10003478` | `__wrap_vprintf` | `int __wrap_vprintf(const char*, va_list)` | +| `0x1000353c` | `__wrap_printf` | `int __wrap_printf(const char*, ...)` | +| `0x100036f8` | `stdio_uart_init` | `void stdio_uart_init(void)` | +| `0x10003838` | `strlen` | `size_t strlen(const char*)` | + +> **Shortcut — resolves name *and* type for every function.** Paste this into IDA's Python console: +> +> ```python +> from binaryninja import Symbol, SymbolType +> # The raw .bin has no headers, so these SDK types don't exist. set_user_type() +> # re-parses each signature as C, so an undefined name raises +> # "SyntaxError: unknown type name '...'". Define them first. +> sdk = bv.parse_types_from_string(""" +> typedef unsigned int uint; +> typedef char* va_list; +> typedef unsigned long clock_handle_t; +> struct stdio_driver; +> typedef struct stdio_driver stdio_driver_t; +> struct uart_inst; +> typedef struct uart_inst uart_inst_t; +> enum gpio_function { +> GPIO_FUNC_XIP = 0, GPIO_FUNC_SPI = 1, GPIO_FUNC_UART = 2, GPIO_FUNC_I2C = 3, +> GPIO_FUNC_PWM = 4, GPIO_FUNC_SIO = 5, GPIO_FUNC_PIO0 = 6, GPIO_FUNC_PIO1 = 7, +> GPIO_FUNC_GPCK = 8, GPIO_FUNC_USB = 9, GPIO_FUNC_NULL = 0x1f, +> }; +> typedef enum gpio_function gpio_function_t; +> """) +> for name, ty in sdk.types.items(): +> bv.define_user_type(name, ty) +> +> # address: (name, signature) +> funcs = { +> 0x1000015c: ("_reset_handler", "void _reset_handler(void)"), +> 0x10000186: ("platform_entry", "void platform_entry(void)"), +> 0x1000019a: ("data_cpy", "void data_cpy(void*, void*, void*)"), +> 0x100001e4: ("_init", "void _init(void)"), +> 0x10000210: ("frame_dummy", "void frame_dummy(void)"), +> 0x10000234: ("main", "int main(void)"), +> 0x10000318: ("ir_init", "void ir_init(uint8_t)"), +> 0x10000340: ("ir_getkey", "int ir_getkey(void)"), +> 0x10000534: ("gpio_set_function", "void gpio_set_function(uint, gpio_function_t)"), +> 0x10000570: ("gpio_set_pulls", "void gpio_set_pulls(uint, bool, bool)"), +> 0x10000598: ("gpio_init", "void gpio_init(uint)"), +> 0x10000ff0: ("sleep_ms", "void sleep_ms(uint32_t)"), +> 0x100011d4: ("time_us_64", "uint64_t time_us_64(void)"), +> 0x100011e8: ("busy_wait_us", "void busy_wait_us(uint64_t)"), +> 0x10001268: ("uart_init", "uint uart_init(uart_inst_t*, uint)"), +> 0x1000143c: ("clock_get_hz", "unsigned long clock_get_hz(clock_handle_t)"), +> 0x10003154: ("exit", "void exit(int)"), +> 0x1000315c: ("runtime_init", "void runtime_init(void)"), +> 0x10003188: ("stdio_out_chars_crlf", "void stdio_out_chars_crlf(stdio_driver_t*, const char*, int)"), +> 0x10003298: ("stdio_put_string", "int stdio_put_string(const char*, int, bool, bool)"), +> 0x10003384: ("stdio_set_driver_enabled", "void stdio_set_driver_enabled(stdio_driver_t*, bool)"), +> 0x100033ac: ("stdio_init_all", "bool stdio_init_all(void)"), +> 0x1000343c: ("__wrap_puts", "int __wrap_puts(const char*)"), +> 0x10003478: ("__wrap_vprintf", "int __wrap_vprintf(const char*, va_list)"), +> 0x1000353c: ("__wrap_printf", "int __wrap_printf(const char*, ...)"), +> 0x100036f8: ("stdio_uart_init", "void stdio_uart_init(void)"), +> 0x10003838: ("strlen", "size_t strlen(const char*)"), +> } +> for addr, (name, sig) in funcs.items(): +> bv.define_user_symbol(Symbol(SymbolType.FunctionSymbol, addr, name)) +> f = bv.get_function_at(addr) +> if f is not None: +> f.set_user_type(sig) +> ``` + +### Step 27: Patch 1 — swap LED1 and LED3 pins + +The original lesson swaps LED 1 and LED 3. LED1 is the red LED on GPIO 16 and LED3 is the yellow LED on GPIO 18. In the loop the pins are `movs r5, #16` at `0x10000284` (LED1) and `movs r2, #18` at `0x10000290` (LED3). Swap the two immediates: + +| Address | Instruction | Bytes before | Bytes after | Role | +| ------- | ----------- | ------------ | ----------- | ---- | +| `0x10000284` | `movs r5, #16` | `10 25` | `12 25` | LED1's pin (`r5`) 16 -> 18 | +| `0x10000290` | `movs r2, #18` | `12 22` | `10 22` | LED3's pin (`r2`) 18 -> 16 | + +```python +bv.write(0x10000284, b"\x12") # movs r5, #18 (LED1 -> GPIO 18) +bv.write(0x10000290, b"\x10") # movs r2, #16 (LED3 -> GPIO 16) +print(bv.read(0x10000284, 2).hex(" ")) # -> 12 25 +print(bv.read(0x10000290, 2).hex(" ")) # -> 10 22 +``` + +Now button **"1"** blinks GPIO 18 (yellow) and button **"3"** blinks GPIO 16 (red). The `LED N activated on GPIO P` prints are **not** changed, so they still say `GPIO 16` and `GPIO 18` — **the log no longer matches the hardware.** That mismatch is the security lesson: the operator's console shows the old, expected mapping while the pins do something else. + +> **Optional consistency patch.** If you want the print to tell the truth instead, also change `movs r2, #16` at `0x100002f8` to `#18` (and the key-3 print constant `movne r2, #18` at `0x100002ea` to `#16`). For this lesson we leave them alone on purpose, so the desynchronization is visible. +> +> | Address | Instruction | Bytes before | Bytes after | Role | +> | ------- | ----------- | ------------ | ----------- | ---- | +> | `0x100002f8` | `movs r2, #16` | `10 22` | `12 22` | optional: key-1 print now says GPIO 18 | + +### Step 27b: Patch 2 — rename the `NEC` string to `PWN` + +The format string starts at `0x10003918`; change its first three bytes `4e 45 43` (`NEC`) to `50 57 4e` (`PWN`): + +```python +bv.write(0x10003918, b"PWN") +print(bv.read(0x10003918, 20)) # -> b'PWN command: 0x%02X\n\x00' +``` + +Exactly three bytes, same rule as Project 1: a shorter string must be padded, a longer one overwrites the ` command:` tail. + +### Step 28: Export, convert, and flash + +```python +import os +seg = next(s for s in bv.segments if s.data_length) # the loadable image segment +data = bv.read(seg.start, seg.data_length) # base + size from the view itself +out = os.path.join(os.path.join(root, "0x0026_functions", "build"), "0x0026_functions-h.bin") +open(out, "wb").write(data) +print(len(data), out) # -> 16476 /.../build/0x0026_functions-h.bin +``` + +`seg.data_length` is the image size (`0x405c` = 16476) read from the view — nothing hardcoded. + +**macOS Apple Silicon / Linux x64:** + +```bash +python3 ../uf2conv.py 0x0026_functions-h.bin \ + --base 0x10000000 --family 0xe48bff59 --output hacked.uf2 +``` + +**Windows x64:** + +```cmd +python ..\uf2conv.py 0x0026_functions-h.bin ^ + --base 0x10000000 --family 0xe48bff59 --output hacked.uf2 +``` + +Or run the conversion from the IDA console, exactly as in Step 20 (`os.chdir` to the build dir, then `runpy.run_path("../../uf2conv.py", run_name="__main__")` with `sys.argv` set to the arguments above). + +Hold **BOOTSEL**, plug in the Pico 2, drag `hacked.uf2` onto the **`RP2350`** drive. Or flash the `.bin` over the Debug Probe with SWD — no BOOTSEL — from the console, exactly as in Step 21. + +### Step 29: Verify + +Open the serial monitor: + +- press **"1"** -> the **YELLOW** LED on GPIO 18 blinks (it used to be the red LED on GPIO 16), and the terminal still prints `LED 1 activated on GPIO 16` — **wrong**, it is actually GPIO 18; +- press **"3"** -> the **RED** LED on GPIO 16 blinks (it used to be the yellow LED on GPIO 18), and the terminal still prints `LED 3 activated on GPIO 18` — **wrong**, it is actually GPIO 16; +- press **"2"** -> the green LED on GPIO 17 is unchanged; +- every `NEC command:` line now reads `PWN command:`. + +**The log says one thing, the hardware does another — with two bytes and no source code.** + +--- + +## Cheatsheet + +### IDA GUI actions + +| Action | How | +| ------ | --- | +| Go to address | `G` | +| Rename function/symbol | `N` | +| Set type or signature | `Y` | +| Add comment | `;` | +| Open Hex view | `View -> Hex` | +| Enable hex editing | Toggle the lock in the status bar | +| Reanalyze after a patch | Right-click function -> `Reanalyze` | +| Edit a register live | `dbg.set_reg_value("r4", 0x5E)` in the Python console (or right-click the register, press `E`, type hex, Enter) | +| Write debugger memory | `dbg.write_memory(0x20080000, b"HACKED: 0x%02X\n\x00")` | +| Set a breakpoint | `Debugger -> Add Hardware Breakpoint...` (hardware execute). Do **not** use `F2` — software breakpoints cannot be written to read-only flash. | +| Move a breakpoint | Remove it and set it at the new address in the GUI (command-port fallback: `rbp ` then `bp 2 hw`) | +| Confirm what is armed | The **Breakpoints** widget lists it (command-port fallback: `mdw 0xE0002000 8`, each armed breakpoint shows as ``) | +| Apply the ELF symbol map | Paste the Python snippet from Step 16 / 26 into the Python Console | + +### OpenOCD server and reset + +The server runs with `gdb_breakpoint_override hard` so that flash-writes are never attempted. Breakpoints in this lab are set in the IDA GUI through the **GDB MI** adapter (Step 13). The command-port rows below are the fallback if you use the **GDB RSP** adapter instead. + +| Action | Command | +| ------ | ------- | +| Connect to the OpenOCD prompt (fallback) | `nc 127.0.0.1 4444` (or `telnet 127.0.0.1 4444`) | +| Reset and run (command port) | `reset run` | +| Check core state (command port) | `targets` | +| Set a breakpoint in the GUI | `Debugger -> Add Hardware Breakpoint...` (hardware execute; `F2` software breakpoints do not work on flash) | +| (fallback) Add a breakpoint without the GUI | `bp 2 hw` | +| Remove one breakpoint | `rbp ` — **address only, no length, no `hw`** | +| Remove every breakpoint | `rbp all` | +| Start the server parked at `main` | macOS/Linux: `BP_ADDR=0x10000234 ./debug-server.sh` — Windows: `$env:BP_ADDR="0x10000234"; .\debug-server.ps1` (one-shot) | +| Break on the loop in a running target | set a hardware breakpoint in the GUI at the loop address, then **Resume** — repeatable | +| Make IDA stepping work | `rp2350.dap.core0 configure -rtos none` (already in the scripts) | +| Step without re-trapping | move the breakpoint off the current PC first, then **Step Into**/**Step Over** | +| Reset without desyncing IDA | **Detach**, `reset run` on the port, reconnect — never `reset run` while attached | +| Kill the debugger | click **X** in the **Debugger** sidebar, or `Debugger -> Kill` | +| Stop OpenOCD | macOS/Linux: `pkill -TERM -f openocd` — Windows: `taskkill /F /IM openocd.exe` | + +### Where you can stop + +| Stop at | Project 1 `0x0023` | Project 2 `0x0026` | +| ------- | ------------------ | ------------------ | +| `main` (once per reset) | `0x10000234` | `0x10000234` | +| `ir_getkey` return | `0x10000274` | `0x10000274` | +| Loop `printf` (`NEC command`) | `0x1000027c` | `0x10000280` | +| First `gpio_put` (`mcrr`, LED1 pin) | `0x1000028a` | `0x10000286` | +| LED3 `gpio_put` (`mcrr`) | `0x100002aa` | `0x10000292` | + +### Every address and byte we changed + +| Project | Address | Before | After | Effect | +| ------- | ------- | ------ | ----- | ------ | +| `0x0023` | `0x10000240` | `10` | `12` | LED1 pin 16 -> 18 | +| `0x0023` | `0x100002a6` | `12` | `10` | LED3 pin 18 -> 16 | +| `0x0023` | `0x100038d0` | `4e 45 43` | `50 57 4e` | prints `PWN` instead of `NEC` | +| `0x0026` | `0x10000284` | `10` | `12` | LED1 pin 16 -> 18 | +| `0x0026` | `0x10000290` | `12` | `10` | LED3 pin 18 -> 16 | +| `0x0026` | `0x100002f8` | `10` | `12` | optional: key-1 print says GPIO 18 | +| `0x0026` | `0x10003918` | `4e 45 43` | `50 57 4e` | prints `PWN` instead of `NEC` | + +### Raw image facts + +| Item | Value | +| ---- | ----- | +| Build type | `Release` | +| Load base address | `0x10000000` | +| Project 1 size | `16372` bytes (`0x3ff4`) | +| Project 2 size | `16476` bytes (`0x405c`) | +| Initial stack pointer (both) | `0x20082000` | +| Reset vector (both) | `0x1000015d` | +| Fixed `main` anchor (both) | `0x1000018c` | +| `main` (both) | `0x10000234` | +| `ir_init`, Project 1 | `0x100002cc` | +| `ir_init`, Project 2 | `0x10000318` | +| `ir_getkey`, Project 1 | `0x100002f4` | +| `ir_getkey`, Project 2 | `0x10000340` | +| Project 1 `IR receiver` string | `0x100038b0` | +| Project 1 `NEC command` string | `0x100038d0` | +| Project 2 `IR receiver` string | `0x100038f8` | +| Project 2 `NEC command` string | `0x10003918` | +| Project 2 `LED activated` string | `0x10003930` | +| RP2350 UF2 family ID | `0xe48bff59` | + +--- + +## Troubleshooting + +### IDA hangs or crashes when you connect (macOS 27) + +Three different causes have been seen on this setup; check them in this order. + +- **A breakpoint set before connecting.** With the **GDB MI** adapter, if the binary view already has a breakpoint, the session hangs. Start parked with `BP_ADDR`, connect, then add breakpoints. +- **The wrong GDB executable.** Point **Full GDB Executable Path** at the **14.2.rel1** toolchain (Step 11). The 13.3.rel1 build did not connect in testing. +- **The LLDB adapter.** A crash report with `libdebuggercore.dylib -> std::terminate() -> abort()` and `liblldb` in the stack is the **LLDB** adapter, not GDB MI. Avoid LLDB on this setup. + +If IDA hangs, force-quit it; the connect dialog has no working Cancel. The static steps (resolve, patch, export, flash) never touch the debugger and always work. + +### GDB MI hangs when you connect (a breakpoint already existed) + +With the **GDB MI** adapter, if IDA already has a breakpoint set when you connect, the session **hangs**. The working order is: + +1. Start the server parked, e.g. `BP_ADDR=0x10000234 ./debug-server.sh` (Windows: `$env:BP_ADDR="0x10000234"; .\debug-server.ps1`). +2. Connect with the **GDB MI** adapter. +3. Only *then* set hardware breakpoints in the UI. + +### Step Into / Step Over does nothing (PC never moves) + +Two causes have been seen on this target. + +1. **A breakpoint on the current PC re-traps the step.** OpenOCD's step-over-breakpoint logic fails with `Duplicate Breakpoint address` and the PC stays put. Fix: move the breakpoint off the current PC (in the GUI), then step. +2. **The `hwthread` RTOS (GDB RSP adapter only).** With the **GDB RSP** adapter, OpenOCD can log `fake step thread 0` and reply without stepping. Fix: `rp2350.dap.core0 configure -rtos none`. **GDB MI does not hit this.** + +### `zsh: bad CPU type in executable: cmake` + +An Intel `x86_64` tool is on your `PATH` on Apple Silicon. Run Step 2: `export PATH="/opt/homebrew/bin:$PATH"`, then `hash -r`. Add it to `~/.zshrc` to make it permanent. + +### My addresses do not match this guide + +You probably built `Debug`. This lesson is a `Release` build. Re-run Step 3 with `-DCMAKE_BUILD_TYPE=Release`. A `Debug` build moves the SDK functions and keeps the `static` helpers separate, so `main` is not at `0x10000234`. + +### A breakpoint never fires + +First, confirm you actually set one, and that it is a **hardware** breakpoint. `Debugger -> Add Hardware Breakpoint...` (hardware execute) should land in the **Breakpoints** widget. If nothing lands, or the core keeps running, you probably used `F2` (`Toggle Breakpoint`) — a software breakpoint cannot be written to read-only flash. Also check you are on **GDB MI**, not **GDB RSP** (the GDB RSP adapter cannot set breakpoints on this target at all). + +Then check the order and the state: + +- **Arm it only after IDA is connected.** OpenOCD flushes every breakpoint when a client attaches, so anything armed earlier is gone. This also applies to `BP_ADDR` on the startup command line. +- **Is the core running?** If it is stopped, click **Resume**. +- **Does the address get reached again?** `main` runs once per reset, so use `BP_ADDR` at startup rather than `reset run` while attached. Loop addresses such as `0x1000028a` (P1) and `0x10000286` (P2) fire on the next key press with no reset. For the `NEC` print addresses (`0x1000027c` / `0x10000280`) you must also press a remote button, because they sit inside the `if (key >= 0)` block. + +### I edit `r4` / `r5` and it reverts + +For Project 2's key forgery, `subs r4, r0, #0` reloads `r4` from `ir_getkey` on every key press, so the edit is visible for one key. For Project 1's `r5` pin edit, `r5` is loaded once at `0x10000240` and never reloaded, so it sticks until reset. For Project 2's `r5` pin edit, `movs r5, #16` at `0x10000284` reloads it on every key. The edit sticks only while the core is **genuinely stopped** at the breakpoint. + +> **The Registers widget is a snapshot, not a live view.** IDA reads the registers at each stop and shows that snapshot; it does not poll the target. A value changed outside IDA will not appear until the next stop. + +### The string hack does nothing (or prints garbage) + +Pick a RAM address that is free — `0x20080000` is safe here (well above the `.data`/`.bss` end at about `0x20000810`). Write a NUL-terminated string, and keep exactly the format specifiers the call consumes: the NEC format has one `%02X`, so the replacement must keep one `%02X`. Then set `r0`, not `r1`. + +### The patched string shifted `printf` output + +The `NEC command: 0x%02X\n` format has one `%02X`. Keep the replacement exactly three bytes (`NEC` -> `PWN`); a longer string would overwrite the ` command:` tail and a shorter one would leave a stray character. In the live hack you write a whole new NUL-terminated string to RAM, so any length is fine as long as it keeps one `%02X`. + +### The struct is not in memory — where is it? + +It is not. `Release` proved `simple_led_ctrl_t` never escapes `main`, so the compiler **flattened** it: the three `uint8_t` pins became the immediates `16`, `17`, `18` and the three `bool` states became register values. There is no `sub sp` for the struct and no memory address to inspect. You patch the immediates instead. If you need to see the struct in memory, build `Debug`, but then none of the addresses in this guide apply. + +### Project 2's `LED N activated on GPIO P` line is wrong after the patch + +That is the point. Step 27 swaps the pins the loop *drives* but leaves the print constants (`0x100002f8`, `0x100002ea`, `0x100002ec`) untouched, so the log shows the old mapping. If you want the print to match, apply the optional consistency patch in Step 27. + +### The serial capture is garbage on macOS + +Reading `/dev/cu.usbmodem*` with a bare `read()` returns garbage. Set **raw termios at 115200** first, or just use `screen /dev/cu.usbmodem* 115200`, which does it for you. + +### It worked for a second, then stopped (IDA's view desyncs) + +The main cause is **driving the core from the OpenOCD command port while IDA is connected**. If you must reset, **Detach first**, reset, then reconnect. Never leave a breakpoint on the PC you are about to step or resume from. + +### The console floods with `Failed to read memory at 0xf0000000` + +Core1 is exposed. The scripts must run with `USE_CORE=0`. Stop the server, confirm only `core0` is reported, restart, then restart IDA. + +### The decompiler still shows the old value after patching + +Right-click the function and choose `Reanalyze`. + +--- + +## Fallback: do the dynamic steps with GDB (macOS 27) + +If IDA's debugger crashes on attach on macOS 27, you can still do the live hacks with the ARM GDB from the toolchain, against the same OpenOCD server. The addresses and register values are identical to the GUI steps. + +Start the debug server (Step 10), then in a new terminal: + +``` +arm-none-eabi-gdb +``` + +At the `(gdb)` prompt for Project 1: + +``` +set architecture armv8-m.main +target extended-remote :3333 +hbreak *0x1000028a +continue +``` + +Do **not** run `monitor reset run` before `hbreak`. `0x1000028a` is inside `main`'s loop, so the breakpoint fires on the next key press with no reset. Press **"1"** on the remote, then: + +``` +info registers pc r5 # pc = 0x1000028a, r5 = 0x10 +set $r5 = 0x12 +continue +``` + +The next LED1 write drives GPIO 18 — the same temporary live hack as editing `r5` in the IDA Registers widget. For the string hack, break at `0x1000027c`, then `set {char[19]}0x20080000 = "HACKED: 0x%02X\n"` and `set $r0 = 0x20080000`. + +Project 2 is the same with the other call site and value: + +``` +hbreak *0x1000027c +continue +info registers pc r4 # r4 holds the decoded key you pressed +set $r4 = 0x5E +continue +``` + +`hbreak` sets a hardware breakpoint, which is required for read-only flash. It works from plain GDB because GDB sends the 2-byte length the Cortex-M33 comparators need. IDA's **GDB MI** adapter goes through the same GDB, so its GUI breakpoints work too. + +## Glossary + +| Term | Definition | +| ---- | ---------- | +| **`.bss`** | Section for uninitialized global variables; zeroed by startup code | +| **`.data`** | Section for initialized global variables; copied from flash to SRAM at boot | +| **`.elf`** | Linked image with the symbol table; the ground truth for addresses and names | +| **Flattening** | The optimizer replacing struct member accesses with the member's constant value; why `simple_led_ctrl_t` disappears | +| **GPIO** | General Purpose Input/Output — controllable pins on the microcontroller | +| **Hardware breakpoint** | A breakpoint serviced by the CPU comparators, required for read-only flash | +| **Inlining** | The optimizer replacing a function call with the function body; why every `static` helper disappears from `main` | +| **Literal pool** | A block of 32-bit constants that Thumb-2 code reaches with PC-relative `ldr` | +| **`mcrr`** | Move to coprocessor from two registers — how the SIO GPIO writes are encoded | +| **NEC** | A common IR protocol: 9 ms leader + 4.5 ms space, then 32 data bits (address, ~address, command, ~command) | +| **`.rodata`** | Read-only section for constants and string literals; stays in flash | +| **SIO** | Single-cycle I/O — the fast GPIO block in the RP2350, at `0xd0000000` | +| **Thumb bit** | Bit 0 of a Cortex-M function pointer; selects Thumb instruction mode | +| **UF2** | USB Flashing Format — the file format the Pico 2 bootloader accepts | +| **Vector table** | The first words of flash: initial stack pointer and exception vectors | + +--- + +**Remember:** the ELF tells you what every address is, and the `.bin` is what you actually patch. Prove the behavior dynamically, resolve the names from the ELF, then patch the bytes and flash. \ No newline at end of file diff --git a/WEEK11/WEEK11-IDA.pdf b/WEEK11/WEEK11-IDA.pdf new file mode 100644 index 0000000..27cb09e Binary files /dev/null and b/WEEK11/WEEK11-IDA.pdf differ