Claude f19a52b779 Run CCPLEX CPU0 so hwtest's PCIe probe completes, and speed up the core
hwtest-rcm's Wi-Fi probe hands PCIe to an AArch64 stub on CPU0, because
PCIe and MSELECT answer a CPU-complex master only. The emulator had no
CCPLEX, so the stub never reported; and the sweep never got that far
anyway, because it hung in the fan test.

CPU0 (t210/ccplex.cpp)
- A second Unicorn engine, AArch64, Cortex-A57, sharing IRAM, DRAM, TZRAM
  and every peripheral model with the BPMP. It starts when
  RST_CPUG_CMPLX_CLR releases CPU0 with every precondition of bdk's
  ccplex_boot_cpu0() met: CPU rail (MAX77621 + MAX77620 GPIO5 on Erista,
  MAX77812 EN_M4 on Mariko), CRAIL/C0NC/CE0, CPUG clock, PLLX, MSELECT,
  RAM repair, an AArch64 vector in SB_AA64_RESET_LOW/HIGH. A release that
  misses one is refused and the reason printed.
- Entered at EL3, MMU off, like silicon. Unicorn builds its ARM64 core at
  EL1 and neither a PSTATE write (stale hflags) nor an exception (never
  delivered) moves it, so a one-instruction ERET trampoline does.
- Its own clock (1 ns/instruction, 250 ns/bus access), run in 250 us
  lockstep slices behind the BPMP; WFE/WFI park it to the slice end.
- PCIe is master-aware: the BPMP still reads all ones, CPU0 is served.
  MSELECT, AFI_PCIE_CONFIG, LNKSTA, the endpoint class/BAR, the PCIE
  partition, PEX_L1 pinmux and PMC_GLB_AMAP_CFG take their measured values.

hwtest now runs its whole sweep and reports "WLAN core enumerated on the
PCIe bus" / "Wireless : pass", matching the healthy-console capture in
its README.

Performance
- No per-instruction hooks. Three UC_HOOK_CODE callbacks (one registered
  twice, one doing a uc_mem_read per instruction) are replaced by a block
  hook that counts each block's instructions once (cached), credited when
  it has run - the same totals, so the clock is unchanged.
- Peripherals are uc_mmio_map() windows instead of memory hooks, which
  had forced every guest load/store onto Unicorn's slow path; the register
  cache is a paged array instead of a std::map.
- The display reads the framebuffer straight from host DRAM, reuses its
  buffers, skips unchanged frames, and no renderer uses PRESENTVSYNC (a
  vsync'd present could stall the emulated CPU for a whole frame).
Reaching hwtest's fan test: 2.7 s -> 0.8 s; whole sweep ~3 s.

Reliability
- TIMERUS poll pacing: bdk's fan_get_speed() waits for TIMERUS to EQUAL a
  deadline (int - u32 is unsigned, so `> 0` is `!= 0`), and the dilated
  clock stepped past it, so the loop spun until TIMERUS wrapped. Polls at
  most 200 instructions apart now advance the clock by at most 1 us.
- MAX77621/MAX77812 are register files: bdk's hw_init() disabling the
  Erista CPU/GPU bucks used to be ignored and read back as enabled.
- Mariko reads FUSE_RESERVED_ODM28_B01 bit 0 set, so bdk addresses the
  retail MAX77812 at 0x33 instead of the NAK'd 0x31.
- Windows: disk images are opened O_BINARY (MinGW defaults to text mode,
  corrupting sectors) and rawnand chunks are sized with _fstati64.
- Soft reboot resets CPU0 and the PCIe root complex; the payload is
  loaded once, size-checked; an empty/unreadable payload is rejected; the
  NOP-slide check no longer trips on a counter that never reset; the M/C
  windows fall back to a software renderer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb
2026-09-25 15:55:48 +00:00
2026-05-02 00:52:26 +02:00

RCM-Emulator

Hekate running in the emulator

A host-side emulator for Nintendo Switch RCM (Recovery Mode) payloads. Loads a precompiled .bin (Hekate, Lockpick_RCM, TegraExplorer, custom payloads) and executes its ARM32 code on an emulated Tegra X1 (T210) environment, with a windowed framebuffer and keyboard input mapped to the Switch hardware buttons.

It is not a console emulator. Only the BPMP (Boot and Power Management Processor) bootloader stage is modelled. You will not boot Horizon, run NSPs, or load games. The intended use is payload development and scripted verification, plus security research where iterating on real hardware would be slow or destructive.

What it can do

  • Run Hekate (CTCaer) through the IPL (Initial Program Loader) warning into the Nyx GUI.
  • Run Lockpick_RCM through key derivation. The --prod-keys shortcut bypasses the parts of the chain that aren't fully modelled.
  • Run TegraExplorer, including .te script execution from an emulated SD card.
  • Replay deterministic button sequences via --auto-pin-recovery or --auto-te-script, so a payload flow can be exercised from a CI run or a one-shot script.
  • Tweak emulated hardware live (battery, charger, thermal, USB-PD, PMIC, fuses, SD insertion) from a side window. See Live hardware tweaks.
  • Inspect each Tegra UART port (TX history) and inject keystrokes into the payload's RX FIFO from a separate console window. See UART console.
  • Read real eMMC (embedded MMC) dumps (BOOT0, multi-part rawnand.bin.NN) and decrypt them with XTS-AES-128 (XEX-based Tweaked-codebook with ciphertext stealing) against keys from prod.keys.
  • Serve a real FAT32 SD image to the payload (--sd sd.img).

Quick start

Build (Linux / WSL)

sudo apt-get install -y build-essential libunicorn-dev libsdl2-dev
make

Build (Docker)

docker build -t rcm-emulator .
docker run --rm -v "$(pwd):/work" rcm-emulator

Build an SD image

make_sd.py packages a source folder into a FAT32 image you can pass to --sd. It uses Docker (alpine + dosfstools + mtools), so no sudo or loop mounts are needed.

python3 make_sd.py --src ./sd_root --out sd.img --size-mb 512

./sd_root is your usual SD card layout (bootloader/, switch/, etc.). The result drops in directly as --sd sd.img.

Build the SD from scratch (HATS + Parental-PIN-RCM)

This produces a fully populated sd_root (Hekate + TegraExplorer + the PIN-recovery script) and bakes it into sd.img:

# 1. Pull the latest HATS release from sthetix.
HATS_URL=$(curl -s https://api.github.com/repos/sthetix/HATS/releases/latest \
    | grep -oE '"browser_download_url": "[^"]+\.zip"' \
    | head -1 | cut -d'"' -f4)
curl -L -o hats.zip "$HATS_URL"
mkdir -p sd_root
unzip -q hats.zip -d sd_root

# 2. Drop the recover_pin.te script into the path TegraExplorer reads
#    (HATS puts it at sd:/scripts/).
git clone --depth 1 https://github.com/Creased/Parental-PIN-RCM
mkdir -p sd_root/scripts
cp Parental-PIN-RCM/recover_pin.te sd_root/scripts/

# 3. Bake everything into a FAT32 image.
python3 make_sd.py --src ./sd_root --out sd.img --size-mb 512

HATS already ships TegraExplorer.bin under bootloader/payloads/, so no extra payload download is needed.

Demo: PIN recovery

The screenshot below shows a full parental-PIN recovery run inside the emulator. Setup:

  • sd.img was built from a HATS-by-sthetix archive (extracted, then packaged with make_sd.py).
  • The recover_pin.te script under scripts/ on that SD comes from Creased/Parental-PIN-RCM.
  • backup/BOOT0 and backup/rawnand.bin.NN are an eMMC dump produced by Hekate (Tools, Backup eMMC).
  • backup/prod.keys is the keyfile produced by running Lockpick_RCM on the same console.

Boot Hekate, then chain-load TegraExplorer from the SD and run the script:

./rcm_emu ./hekate_ctcaer_6.5.2.bin \
    --sd         ./sd.img \
    --boot0      ./backup/BOOT0 \
    --rawnand    ./backup/rawnand.bin \
    --prod-keys  ./backup/prod.keys

In the Nyx GUI: Tools, Launch payload, pick TegraExplorer.bin. From the TE main menu: Scripts, recover_pin.te, Recover from sysmmc. The PIN appears in green:

PIN recovery demo

Running without arguments

Starting the emulator with no payload opens a small window that takes a dropped .bin, or press O for the system file dialog (zenity or kdialog on Linux). Dragging a payload onto the executable itself still works and skips the picker - it arrives as argv[1].

Build (Windows)

Cross-compiled from Linux in a container, because neither dependency has a MinGW package: SDL2 ships a devel tarball and unicorn has to be compiled.

docker build -f Dockerfile.windows -t rcm_emu_win .
docker run --rm -v "$PWD:/work" rcm_emu_win     # produces rcm_emu.exe

The result is statically linked - one rcm_emu.exe with no DLLs beside it. Audio goes to WASAPI on Windows and ALSA/PulseAudio on Linux; SDL picks the backend, so nothing in the emulator cares which. RCM_EMU_NO_AUDIO=1 skips playback entirely, which is what CI uses since a runner has no sound device.

Live hardware tweaks

Press M in the main window to open a second window that exposes the values the payload reads from the emulated chips. Edits apply on the next register read, with no restart and no recompile. Use it to exercise payload code that branches on hardware state (low-battery warnings, thermal throttling, charger detect, SD eject, OEM-specific PMIC forks, and similar) without needing the state to occur on real hardware.

Live hardware-config window

What's tweakable, grouped by chip:

Chip Bus / addr Tweakable
MAX17050 fuel gauge I2C_1 @ 0x36 SOC %, VCELL, OCV, Temp, Current, RepCap, FullCAP, DesignCap, V_empty, Min/Max volt, Age, Cycles
TMP451 thermal I2C_1 @ 0x4C SoC die temp, PCB temp
BQ24193 charger I2C_1 @ 0x6B VBUS, charge state, power-good, input current/voltage limit, system min, fast-charge current, charge voltage limit, thermal regulation
BM92T36 USB-PD I2C_1 @ 0x18 Cable-inserted, PDO voltage, PDO amperage
MAX77620 main PMIC I2C_5 @ 0x3C OTP (Erista / Mariko), silicon revision
MAX77621 CPU/GPU PMIC I2C_5 @ 0x1B Chip ID
Tegra fuses FUSE 0x7000F800 30+ fuse offsets: PRODUCTION/SKU/IDDQ/SPEEDO, OPT_FT/CP_REV, RESERVED_SW, RESERVED_ODM0..ODM7 (incl. anti-downgrade presets for HOS 13.2.1 / 22.0.0), VENDOR/FAB/LOT/WAFER, GPU_IDDQ, PK0..7, SBK + DK
DRAM modules EMC 0xEC (MR5-8) Vendor (MR5), Rev ID 1/2 (MR6/MR7), per-die density (MR8 5:2)
GPIO Port Z bit 1 SD card insert / eject
Display EmuState Backlight, rotation override
Emulation EmuState Pause / resume, button visualization

A few example tweaks:

  • Drag SOC % down to 5%. The Hekate "low battery" branch fires.
  • Drop SoC temp to 95 °C. The thermal-throttle path triggers.
  • Toggle VBUS to None and Power good off. Hekate flips to the "no charger" state.
  • Set Charge voltage limit to 4096 mV. The Battery Info screen reflects it on the next poll.
  • Toggle SD card inserted off mid-boot. The SD-detect path sees no card, which is useful for testing failure handling.
  • Switch PMIC OTP to Mariko (0x53). The OEM-detection branch prints "Mariko OTP" instead of "Erista OTP".

The full layout (sliders, combos, hex inputs for fuses) lives in display/config_window.cpp. Encoding logic that maps each user-facing decoded value back to the chip's raw register format is in t210/mmio.cpp. Each encoder mirrors a corresponding *_get_property() formula in the Hekate bdk/power/ tree.

UART console

Press C in the main window to open a third SDL window that exposes the Tegra UART block. It lets you:

  • Pick which port (UART_A..UART_E) to inspect from a combo box. The TX history pane shows every byte the payload has written to that port's THR (Transmit Holding Register), auto-scrolled.
  • Type bytes into the input line and "Send" them; they land in the emulator's RX FIFO so the next CPU-side uart_recv() returns them. Useful for paged probes that ask the user for input over UART (e.g. hwtest's pager keys n / p / r / s / q and the CR / LF shortcut buttons next to the input field).

Implementation in display/console_window.cpp. Per-port TX log + RX FIFO storage lives in emu_state.h::EmuState. Both the CPU emulation and ImGui rendering run on the main thread between SDL polls, so no locking is needed.

Controls

Key Switch button / action
↑ / ↓ VOL+ / VOL–
Enter POWER
Mouse click Touch (Nyx, TE menus)
M Open / close hardware-config window (see Live hardware tweaks)
C Open / close UART console window (see UART console)
R Soft reboot
P Pause or resume emulation
Ctrl+R / Ctrl+Shift+R Cycle display rotation CW / CCW
S Cycle swizzle override
Esc Quit

Command-line flags

Flag Argument Purpose
--sd sd.img Back the SD card (SDMMC1) with this raw FAT32 image.
--boot0 BOOT0 eMMC BOOT0 partition file (SDMMC4).
--rawnand rawnand.bin eMMC GPP partition prefix (auto-detects .00, .01, …).
--prod-keys prod.keys Override BIS keys from a Lockpick-style key file.
--oem erista | mariko Switch SoC generation. Drives APB_MISC_GP_HIDREV so Hekate's h_cfg.t210b01 matches and pkg1 identification skips the right OEM header. Default erista.
--bt-radio healthy | faulty | absent Broadcom CYW4356 behaviour on UART-D. healthy powers up on the BT_REG_ON edge, holds BT_HOST_WAKE high, asserts RTS_N and answers HCI; faulty reproduces the 2110-1118 console (module fitted, never leaves POR); absent additionally leaves BT_UART_RXD in a break condition. Overrides [bluetooth] radio in the ini. Default healthy.
--wifi-radio healthy | faulty | absent The WLAN half of the same CYW4356: a PCI Express endpoint on root port 1. healthy trains the link, enumerates as 14E4:43EC and answers a ChipCommon ChipID read with 0x4356; faulty still trains and enumerates but reads all ones on the backplane (live PCIe front-end, dead radio die); absent never leaves detect. The model also enforces the datasheet's power-up ordering, so a payload that releases PERST# too early gets a link that stays down and a [pcie] line naming the reason. Overrides [wifi] radio in the ini. Default healthy.
--auto-pin-recovery (none) Drive the Lockpick PIN-recovery menu without user input.
--auto-te-script (none) Drive recover_pin.te in TegraExplorer without input.

Repo layout

flowchart LR
    root["RCM-Emulator/"]
    root --> top["main.cpp<br/>emu_state.h<br/>Makefile<br/>Dockerfile<br/>README.md / DESIGN.md"]
    root --> t210["t210/<br/>(SoC peripheral models)"]
    root --> display["display/"]

    t210 --> mmio["mmio.{h,cpp}<br/>memory_map.h<br/>tegra_bl.h"]
    t210 --> sdmmc["sdmmc.{h,cpp}<br/>SDMMC1 / SDMMC4"]
    t210 --> se["se_engine.{h,cpp}<br/>AES-128, SHA-256"]
    t210 --> i2c["i2c3.{h,cpp}<br/>STMFTS / FTS4 touch"]

    display --> sdl["sdl_display.{h,cpp}<br/>block-linear de-swizzle<br/>+ SDL2"]

For implementation details, see DESIGN.md.

Limitations

  • BPMP only. Horizon and Atmosphère need A57 core emulation. This only models the ARM7 bootloader environment.
  • Subset of MMIO (Memory-Mapped I/O). Peripherals are modelled to the depth required by the payloads above. New payloads may exercise registers that fall through to the default catch-all and need handlers added.
  • Key derivation chain is partial. The TSEC (Tegra Security Co-processor) firmware and the full master-key unwrapping flow are not faithfully emulated. --prod-keys is a pragmatic shortcut: when Lockpick writes a derived BIS (Boot Image Storage) key into a keyslot, the value from the user-supplied key file is substituted. RSA, RNG, and chunked SHA are stubs.
  • Single-threaded. The CPU runs in batches on the main thread between SDL event polls. Tight host CPU loops will starve the display refresh.

Acknowledgements

Heavy reliance on the work of:

S
Description
No description provided
Readme
748 KiB
0 Stars 2 Watchers 0 Forks
Languages
C++ 86.1%
C 7.9%
Shell 2.9%
Python 1.5%
Makefile 0.7%
Other 0.8%