mirror of
https://github.com/Creased/RCM-Emulator.git
synced 2026-12-06 02:48:11 +01:00
Initial commit
This commit is contained in:
commit
d0d7a38fa3
22 files changed
+5107
No files matched your search
+22
@@ -0,0 +1,22 @@
|
||||
# Build artifacts
|
||||
rcm_emu
|
||||
*.o
|
||||
*.d
|
||||
|
||||
# Runtime captures
|
||||
last_fb.rgba
|
||||
last_fb.meta
|
||||
last_fb*.png
|
||||
out.log
|
||||
emu_run*.log
|
||||
|
||||
# User data — never commit dumps or keys
|
||||
*.img
|
||||
*.bin
|
||||
|
||||
# Editor / OS
|
||||
.vscode/
|
||||
.idea/
|
||||
.DS_Store
|
||||
__pycache__/
|
||||
*.pyc
|
||||
@@ -0,0 +1,251 @@
|
||||
# RCM-Emulator Design
|
||||
|
||||
This document explains how the emulator is structured, which Tegra X1 (T210)
|
||||
subsystems are modelled, and the non-obvious decisions or workarounds behind
|
||||
them. Read [README.md](README.md) first for usage.
|
||||
|
||||
## High-level architecture
|
||||
|
||||
```mermaid
|
||||
flowchart TB
|
||||
main["<b>main.cpp</b><br/>arg parsing, payload load, CLI<br/>emulation loop, auto-script state"]
|
||||
|
||||
main -->|uc_emu_start| uc["<b>Unicorn Engine</b><br/>ARM32, T210<br/>IRAM / DRAM / MMIO"]
|
||||
main -->|sdl_display_*| sdl["<b>display/sdl_display</b><br/>block-linear de-swizzle<br/>rotate, blit"]
|
||||
|
||||
uc -->|MMIO trap| mmio["<b>t210/mmio.cpp</b><br/>central read/write dispatch<br/>by address range"]
|
||||
|
||||
mmio --> sdmmc["<b>sdmmc</b><br/>SDMMC1 / SDMMC4<br/>CMD0..18, EXT_CSD, ADMA2"]
|
||||
mmio --> se["<b>se_engine</b><br/>AES-128, SHA-256<br/>BIS keyslot override"]
|
||||
mmio --> i2c["<b>i2c3</b><br/>STMFTS / FTS4 touch"]
|
||||
mmio --> stubs["<b>inline stubs</b><br/>GPIO, PMC, TSEC, KFUSE,<br/>PWM, DC, CLK, TMR, FUSE, UART"]
|
||||
```
|
||||
|
||||
`EmuState` (`emu_state.h`) is the single shared struct. It holds button atomics,
|
||||
touchscreen atomics, framebuffer parameters from the display controller, file
|
||||
descriptors for SD and eMMC images, and a deterministic `emu_usec` counter used
|
||||
for auto-script timing.
|
||||
|
||||
## Boot flow (Hekate as the example)
|
||||
|
||||
1. The payload is loaded into IRAM (Internal RAM) at `0x40010000` via
|
||||
`uc_mem_write`.
|
||||
2. PC is set to `0x40010000`, SP to `IPL_STACK_ADDR`. CPSR enters ARM mode.
|
||||
3. The IPL (Initial Program Loader) initialises clocks, fuses and the display,
|
||||
then blocks at a `btn_wait` site. In Hekate 6.5.2 this PC is `0x4000D14E`.
|
||||
Depending on build it may be a "press any key" prompt, the Nyx fallback
|
||||
warning, or a similar one-tap gate. `main.cpp` watches for that PC and
|
||||
spoofs a POWER press for ~100 ticks so the run advances without manual
|
||||
input. If you load a different Hekate version and boot stalls forever,
|
||||
capture the PC where it loops and update the constant.
|
||||
4. Hekate self-relocates into DRAM (`0xC0000000+`) and continues. The display
|
||||
pipeline resamples its DRAM-side framebuffer parameters.
|
||||
5. Nyx (the LVGL graphics stack) initialises and draws into a separate FB. The
|
||||
DC (Display Controller) `WINDOW_HEADER` register tracks the currently
|
||||
primary surface. The display code follows that pointer.
|
||||
|
||||
## Memory map
|
||||
|
||||
Mapped explicitly in `setup_emulation()`:
|
||||
|
||||
| Range | Size | Purpose |
|
||||
| --------------------------- | ------- | ----------------------------------- |
|
||||
| `0x40000000 – 0x40040000` | 256 KB | IRAM (payload + IPL stack) |
|
||||
| `0x80000000 – 0x90000000` | 256 MB | DRAM low |
|
||||
| `0xC0000000 – 0xFFFFFFFF` | 1 GB | DRAM high (covers FB at 0xF5A00000) |
|
||||
| `0x00000000 – 0x01000000` | 16 MB | low scratch (some null derefs) |
|
||||
| Various MMIO pages | 4 KB ea | trapped via UC hooks |
|
||||
|
||||
MMIO (Memory-Mapped I/O) ranges are added as plain mapped pages with read and
|
||||
write hooks. The actual register modelling lives in `t210/mmio.cpp`.
|
||||
|
||||
## Subsystems
|
||||
|
||||
### SDMMC1 (SD) and SDMMC4 (eMMC)
|
||||
|
||||
Implemented in `t210/sdmmc.cpp` plus inline handlers in `t210/mmio.cpp`. Enough
|
||||
of the spec is modelled for the Hekate, Lockpick and TE init paths:
|
||||
|
||||
- CMD0 GO_IDLE, CMD1 SEND_OP_COND, CMD2 ALL_SEND_CID, CMD3 SEND_RELATIVE_ADDR,
|
||||
CMD6 SWITCH, CMD7 SELECT_CARD, CMD8 SEND_EXT_CSD (eMMC) or SEND_IF_COND (SD),
|
||||
CMD9 SEND_CSD, CMD13 SEND_STATUS, CMD16 SET_BLOCKLEN, CMD17 and CMD18
|
||||
READ_(MULTI_)BLOCK, CMD55 APP_CMD.
|
||||
- ADMA2 (Advanced DMA 2) with 64-bit descriptors, multi-block reads chunked
|
||||
into the host file IO via `pread`-style calls.
|
||||
- `--rawnand` opens the matching `rawnand.bin.NN` chunks and `fstat`s the first
|
||||
one to derive the per-chunk size automatically. Typical dumps are 2 GB or
|
||||
4 GB chunks.
|
||||
|
||||
#### Gotchas
|
||||
|
||||
- **CMD3 R6 vs R1.** Hekate expects an SD R6 (RCA, Relative Card Address, in
|
||||
the upper half). eMMC reads it as R1 status. R1 with bit 16 set
|
||||
(`CID_CSD_OVERWRITE`) makes Lockpick bail before `CMD9`. The handler splits
|
||||
on the controller base.
|
||||
- **CMD9 mmca_vsn.** Hekate left-shifts the CSD response by 8 (CRC strip), so
|
||||
bits 18..21 of `rsp[3]` need to encode 4. The handler hardcodes
|
||||
`rsp[3] = 0x16504000`.
|
||||
- **CMD8 EXT_CSD.** TE polls `TRANSFER_COMPLETE` until it sees DMA-delivered
|
||||
data. The handler synthesises a 512-byte payload (REV=7, CARD_TYPE=0x57, fake
|
||||
sec_cnt) and writes it via the configured ADMA2 descriptor before raising
|
||||
the IRQ.
|
||||
|
||||
### Security Engine (`t210/se_engine.cpp`)
|
||||
|
||||
Models the SE (Security Engine) register block at `0x70012000`. Supports:
|
||||
|
||||
- **AES-128 ECB, CBC, CTR, CMAC.** The compact public-domain TinyAES core
|
||||
([kokke/tiny-AES-c](https://github.com/kokke/tiny-AES-c)) drives one block
|
||||
at a time, with chaining state taken from `IV_ORIGINAL` or `IV_UPDATED` per
|
||||
slot and `xor_pos` from `CRYPTO_CONFIG`.
|
||||
- **SHA-256.** Implemented because the TE function `save_process_header`
|
||||
validates the save container hash. Without it, `readsave()` returns
|
||||
`Error: Save header is invalid!`. Oneshot only: one IN_LL buffer at a time,
|
||||
written into the `HASH_RESULT` registers as 8 big-endian dwords (the BDK
|
||||
driver byte-swaps on read).
|
||||
- **DST_KEYTABLE unwrap path.** When the destination is another keyslot, the
|
||||
result of a single block is written into the destination `KEYS_0_3` or
|
||||
`KEYS_4_7` register pair.
|
||||
- **`--prod-keys` BIS override.** When Lockpick writes the last word of a
|
||||
derived BIS (Boot Image Storage) key into slots 0..5, the value from the
|
||||
user-supplied key file is substituted. This sidesteps the
|
||||
TSEC-firmware to `master_kek` to `master_key` derivation chain that is not
|
||||
fully modelled. For other keyslots, the SE behaves normally.
|
||||
|
||||
The 16 keyslots are stored in a flat `Keyslot ks_table[16]` with
|
||||
`key[32] / iv_orig[16] / iv_upd[16]`. RSA, RNG, and chunked SHA are stubbed.
|
||||
They return `OP_DONE` without producing data, which is enough for current
|
||||
payloads.
|
||||
|
||||
### Touchscreen (`t210/i2c3.cpp`)
|
||||
|
||||
Stub of the STMFTS controller at I²C address `0x49` on I²C3. SDL mouse events
|
||||
are translated into FTS4 `MULTI_TOUCH_ENTER`, `MOTION` and `LEAVE` records
|
||||
with a 1-indexed finger ID, then queued via the atomic flags in `EmuState`.
|
||||
The CPU thread drains them on the next I²C read.
|
||||
|
||||
### GPIO buttons and MAX77620 PMIC
|
||||
|
||||
`btn_vol_up`, `btn_vol_down` and `btn_power` are atomic bools updated by the
|
||||
SDL keyboard handler. The MMIO read handlers map them onto:
|
||||
|
||||
- VOL+ and VOL– map to GPIO X6 and X7 (active-low) on port X.
|
||||
- POWER routes through the MAX77620 PMIC (Power Management IC), reported via
|
||||
`ONOFFSTAT.EN0` over I²C5.
|
||||
|
||||
### Display pipeline (`display/sdl_display.cpp`)
|
||||
|
||||
Hekate and Nyx draw into a block-linear surface. One block-height row covers
|
||||
16 GOBs (Group Of Bytes, NVIDIA's 64 by 8 pixel tile). The display thread:
|
||||
|
||||
1. Reads DC `WINDOW_HEADER` to follow the active surface (Window A, B, C or
|
||||
D).
|
||||
2. Looks up the FB pointer, stride and GOB block height latched from
|
||||
`DC_WIN_x_SURFACE_KIND`.
|
||||
3. De-swizzles into a linear RGBA buffer using a per-pixel address calc.
|
||||
4. Optionally rotates 0, 90, 180 or 270 degrees to match the panel orientation
|
||||
detected from window dimensions, with an `R` or `Shift+R` manual override.
|
||||
5. Blits to an SDL_Texture at the host window current size.
|
||||
|
||||
The de-swizzle is the hottest path. It is inlined and operates on `u32`
|
||||
units. A blit cache keys on `(addr, w, h, stride, sw, rot, bh)` so identical
|
||||
frames don't re-touch the surface.
|
||||
|
||||
### UART
|
||||
|
||||
`UART_A` at `0x70006000`. Writes to `THR` (Transmit Holding Register) are
|
||||
buffered into a 512-byte line and flushed on `\n`, `\r`, or buffer overflow as
|
||||
a single `[uart] …` host stdout line. Bytes outside the printable range
|
||||
`0x20..0x7E` (typically Joy-Con HID frames Hekate also drives over UART) are
|
||||
dropped to keep the log readable.
|
||||
|
||||
For TE, `gfx_putc` was patched in TE source to mirror each FB-bound character
|
||||
to `UART_A`, so script `print` and `println` calls show up directly in
|
||||
`out.log` without needing to OCR the framebuffer. That patch lives in the
|
||||
TegraExplorer tree, not this repo.
|
||||
|
||||
### Other peripherals (mostly stubs)
|
||||
|
||||
- **PLLs.** Reads on `PLL_BASE` registers return `ENABLE | LOCK` for any of
|
||||
the PLLs Minerva polls during DRAM training.
|
||||
- **KFUSE.** `STATE` returns `DONE | CRCPASS` immediately so the BDK function
|
||||
`kfuse_wait_ready` doesn't hang.
|
||||
- **TSEC.** `DMATRFCMD_IDLE` is reported set, and the keygen status word is
|
||||
hardcoded to `0xB0B0B0B0` (the success magic from AMS, the Atmosphère
|
||||
keygen). No firmware is actually executed.
|
||||
- **Timer and RTC.** Backed by `EmuState::emu_usec`, incremented per CPU
|
||||
batch by a fixed amount so timing is deterministic across runs. The
|
||||
auto-script feature relies on this.
|
||||
|
||||
## Determinism and the auto-script flag
|
||||
|
||||
`emu_usec` advances by a constant per Unicorn batch, never by host wall-clock.
|
||||
That makes the entire run reproducible: a payload at PC X always sees timer
|
||||
value Y, regardless of how busy the host machine is.
|
||||
|
||||
The `--auto-pin-recovery` and `--auto-te-script` flags exploit this. A real
|
||||
interactive run was captured by logging every keyboard up and down event with
|
||||
the matching `emu_usec`, then the same schedule was re-applied verbatim in
|
||||
`main.cpp`:
|
||||
|
||||
```cpp
|
||||
struct InputEv { uint64_t at_us; char btn; bool down; };
|
||||
static const InputEv te_events[] = {
|
||||
{3480000, 'P', true}, {3640000, 'P', false},
|
||||
{10080000, 'D', true}, {10460000, 'D', false},
|
||||
/* …32 events total… */
|
||||
};
|
||||
while (te_idx < n && state.emu_usec >= te_events[te_idx].at_us) {
|
||||
apply event;
|
||||
}
|
||||
```
|
||||
|
||||
Because `emu_usec` is deterministic, the same timestamps land at the same UI
|
||||
states across runs. Adding a new automated flow is "press the buttons once
|
||||
with `[input]` logging on, copy the timestamps".
|
||||
|
||||
## Bug history
|
||||
|
||||
These are baked into the current source. Listed here so future maintainers
|
||||
don't repeat the diagnosis:
|
||||
|
||||
- **Minerva DRAM training** hangs in a `PLL_BASE.LOCK` poll. Fix: always
|
||||
report `LOCK | ENABLE`.
|
||||
- **`kfuse_wait_ready`** loops on `STATE.DONE`. Fix: stub `DONE | CRCPASS`.
|
||||
- **AMS keygen** retries `tsec_query` 15 times until timeout. Fix: stub
|
||||
`STATUS = 0xB0B0B0B0`.
|
||||
- **CMD3 over eMMC** must emit R1 status, not R6, and must not raise
|
||||
`CID_CSD_OVERWRITE`. Lockpick bails out before `CMD9` otherwise.
|
||||
- **CSD `mmca_vsn`** has to compensate for the Hekate `<< 8` shift on the
|
||||
response word. Bits 18..21 of `rsp[3]` need to encode `4`.
|
||||
- **CMD8 SEND_EXT_CSD** never fires `TRANSFER_COMPLETE` if no DMA payload is
|
||||
written. Lockpick polls forever, then falls through with `initialized = 0`,
|
||||
silently failing every subsequent `sdmmc_storage_read`.
|
||||
- **GPP chunk size** was hardcoded to 4 GB initially and broke 2 GB dumps.
|
||||
Now `fstat`-derived from `rawnand.bin.00`.
|
||||
- **Save header SHA-256** rejected by TE because the SE only modelled AES.
|
||||
Hence the SHA-256 path in `se_engine.cpp`.
|
||||
|
||||
See `git log` for the commit-by-commit diagnosis trail if you want more
|
||||
detail on any of them.
|
||||
|
||||
## Adding a new peripheral
|
||||
|
||||
1. Decide on an MMIO range and add a new `else if` branch in `mmio_read` or
|
||||
`mmio_write` (or a dedicated module like `i2c3.cpp`).
|
||||
2. If the device participates in the boot fence (status registers polled by
|
||||
the BDK), make sure the read returns the "ready" or "done" state. Silent
|
||||
`0` returns are the most common cause of hangs.
|
||||
3. If it consumes data via DMA, model the LL descriptor at `IN_LL_ADDR` or
|
||||
`OUT_LL_ADDR` and use `uc_mem_read` and `uc_mem_write` to move guest
|
||||
memory.
|
||||
4. Add logging behind `printf` with a clear prefix (`[se]`, `[sdmmc]`, etc.)
|
||||
so `out.log` stays greppable.
|
||||
|
||||
## Adding a new auto-script
|
||||
|
||||
1. Run interactively with `[input]` logging enabled (already on by default).
|
||||
2. Tail the resulting `out.log` for `^\[input\]` lines to extract
|
||||
`(emu_usec, button, edge)` triples.
|
||||
3. Drop them into a new array beside `te_events[]` in `main.cpp` and gate it
|
||||
behind a new CLI flag.
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
FROM ubuntu:24.04
|
||||
|
||||
# Build environment for RCM Payload Emulator
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
build-essential \
|
||||
pkg-config \
|
||||
libunicorn-dev \
|
||||
libsdl2-dev \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
WORKDIR /work
|
||||
|
||||
# Build command: docker run --rm -v $(pwd):/work rcm_emu make
|
||||
CMD ["make"]
|
||||
@@ -0,0 +1,40 @@
|
||||
# RCM Payload Emulator
|
||||
# ARM32 emulator for Switch RCM payloads using Unicorn Engine + SDL2
|
||||
|
||||
SRC_DIR = . t210 display
|
||||
SRCS = $(foreach dir,$(SRC_DIR),$(wildcard $(dir)/*.cpp))
|
||||
OBJS = $(SRCS:.cpp=.o)
|
||||
|
||||
OUTPUT = rcm_emu
|
||||
|
||||
CXX = g++
|
||||
CXXFLAGS = -Wall -g -O2 -std=c++17 -I.
|
||||
LDFLAGS =
|
||||
LIBS = -lunicorn -lSDL2 -lpthread
|
||||
|
||||
# pkg-config for SDL2 if available
|
||||
SDL2_CFLAGS := $(shell pkg-config --cflags sdl2 2>/dev/null)
|
||||
SDL2_LIBS := $(shell pkg-config --libs sdl2 2>/dev/null)
|
||||
|
||||
ifneq ($(SDL2_CFLAGS),)
|
||||
CXXFLAGS += $(SDL2_CFLAGS)
|
||||
LIBS = -lunicorn $(SDL2_LIBS) -lpthread
|
||||
endif
|
||||
|
||||
.PHONY: all clean
|
||||
|
||||
all: $(OUTPUT)
|
||||
|
||||
$(OUTPUT): $(OBJS)
|
||||
$(CXX) $(LDFLAGS) -o $@ $^ $(LIBS)
|
||||
|
||||
# Header dependencies
|
||||
main.o: main.cpp emu_state.h t210/memory_map.h t210/mmio.h display/sdl_display.h
|
||||
t210/mmio.o: t210/mmio.cpp t210/mmio.h t210/memory_map.h t210/tegra_bl.h emu_state.h
|
||||
display/sdl_display.o: display/sdl_display.cpp display/sdl_display.h emu_state.h t210/tegra_bl.h
|
||||
|
||||
%.o: %.cpp
|
||||
$(CXX) $(CXXFLAGS) -c -o $@ $<
|
||||
|
||||
clean:
|
||||
rm -f $(OUTPUT) $(OBJS)
|
||||
@@ -0,0 +1,186 @@
|
||||
# RCM-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.
|
||||
- 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)
|
||||
|
||||
```bash
|
||||
sudo apt-get install -y build-essential libunicorn-dev libsdl2-dev
|
||||
make
|
||||
```
|
||||
|
||||
### Build (Docker)
|
||||
|
||||
```bash
|
||||
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.
|
||||
|
||||
```bash
|
||||
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`:
|
||||
|
||||
```bash
|
||||
# 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](https://github.com/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:
|
||||
|
||||
```bash
|
||||
./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:
|
||||
|
||||

|
||||
|
||||
## Controls
|
||||
|
||||
| Key | Switch button / action |
|
||||
| -------------- | ------------------------------- |
|
||||
| `↑` / `↓` | VOL+ / VOL– |
|
||||
| `Enter` | POWER |
|
||||
| Mouse click | Touch (Nyx, TE menus) |
|
||||
| `R` / `Shift+R`| Cycle display rotation CW / CCW |
|
||||
| `P` | Pause or resume emulation |
|
||||
| `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. |
|
||||
| `--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
|
||||
|
||||
```mermaid
|
||||
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](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:
|
||||
|
||||
- [Unicorn Engine](https://www.unicorn-engine.org/) for CPU emulation.
|
||||
- [Hekate / BDK](https://github.com/CTCaer/hekate) as peripheral and
|
||||
key-derivation reference.
|
||||
- [Lockpick_RCM](https://github.com/shchmue/Lockpick_RCM) for keyslot
|
||||
semantics.
|
||||
- [TegraExplorer](https://github.com/suchmememanyskill/TegraExplorer) for the
|
||||
`.te` script harness.
|
||||
- TinyAES (kokke) for the AES-128 reference implementation.
|
||||
@@ -0,0 +1,504 @@
|
||||
#include "sdl_display.h"
|
||||
#include "../emu_state.h"
|
||||
#include "../t210/memory_map.h"
|
||||
|
||||
#include <SDL2/SDL.h>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
static SDL_Window *window = nullptr;
|
||||
static SDL_Renderer *renderer = nullptr;
|
||||
static SDL_Texture *texture = nullptr;
|
||||
static int g_swizzle_override =
|
||||
-1; // -1 = Auto, 0 = Pitch Linear, 2 = Block Linear
|
||||
|
||||
bool sdl_display_init() {
|
||||
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) < 0)
|
||||
return false;
|
||||
window = SDL_CreateWindow("RCM Payload Emulator", SDL_WINDOWPOS_CENTERED,
|
||||
SDL_WINDOWPOS_CENTERED, 720, 1280,
|
||||
SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);
|
||||
if (!window)
|
||||
return false;
|
||||
renderer = SDL_CreateRenderer(
|
||||
window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
|
||||
if (!renderer)
|
||||
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_SOFTWARE);
|
||||
if (!renderer)
|
||||
return false;
|
||||
printf("[display] SDL2 simple compositor initialized\n");
|
||||
return true;
|
||||
}
|
||||
|
||||
void sdl_display_update(EmuState *state, uc_engine *uc) {
|
||||
if (!renderer)
|
||||
return;
|
||||
|
||||
uint32_t width = state->fb_width, height = state->fb_height,
|
||||
stride = state->fb_stride;
|
||||
if (width < 16 || height < 16)
|
||||
return;
|
||||
|
||||
// If the current fb_addr is empty but we have a saved Window A with
|
||||
// content, prefer the Window A surface. This handles the case where
|
||||
// Hekate's TUI renders to IPL_FB (0xF5A00000) but the DC was repointed
|
||||
// to NYX_FB (0xF6200000) by a failed Nyx init sequence.
|
||||
uint64_t eff_addr = state->fb_addr;
|
||||
if (state->winA_addr && state->winA_addr != eff_addr) {
|
||||
// Quick check: sample a few dwords from fb_addr.
|
||||
uint32_t sample[4] = {0};
|
||||
uc_mem_read(uc, eff_addr, sample, sizeof(sample));
|
||||
bool empty = (sample[0] == 0 && sample[1] == 0 &&
|
||||
sample[2] == 0 && sample[3] == 0);
|
||||
if (empty) {
|
||||
// Check if winA_addr has content.
|
||||
uc_mem_read(uc, state->winA_addr, sample, sizeof(sample));
|
||||
if (sample[0] != 0 || sample[1] != 0 ||
|
||||
sample[2] != 0 || sample[3] != 0) {
|
||||
eff_addr = state->winA_addr;
|
||||
width = state->winA_w;
|
||||
height = state->winA_h;
|
||||
stride = state->winA_stride;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Helper: is the address inside the IPL framebuffer carveout?
|
||||
auto addr_in_ipl_fb = [](uint64_t a) -> bool {
|
||||
return a >= FB_BASE && a < FB_BASE + FB_SIZE;
|
||||
};
|
||||
|
||||
int rot = state->rotation_override;
|
||||
|
||||
uint32_t sw = state->fb_swizzle;
|
||||
uint32_t eff_stride = stride;
|
||||
uint32_t bpp = 4;
|
||||
uint32_t bh = state->fb_bh ? state->fb_bh : 16; // Block height in GOBs
|
||||
|
||||
// --- OVERRIDES & AUTO-DETECTS ---
|
||||
constexpr uint64_t kNyxFbBase = 0xF6200000ULL;
|
||||
|
||||
if (g_swizzle_override != -1) {
|
||||
sw = (uint32_t)g_swizzle_override; // Manual User Override (S Key)
|
||||
} else if (eff_addr == kNyxFbBase) {
|
||||
// Nyx GUI uses VIC to rotate its 1280x720 landscape UI into 720x1280 portrait mode (NYX_FB_ADDRESS).
|
||||
// Our emulator's mock VIC only memcpys the data, so 0xF6200000 actually holds a 1280x720 landscape image!
|
||||
// Since the DC is programmed for 720x1280, it will scramble it.
|
||||
// We override the display geometry here to render the raw 1280x720 memory correctly.
|
||||
sw = 0;
|
||||
width = 1280;
|
||||
height = 720;
|
||||
eff_stride = 1280 * 4; // 32-bit XRGB
|
||||
rot = 0;
|
||||
bh = 4;
|
||||
} else if (eff_addr == FB_BASE && sw == 0 && width == 720u &&
|
||||
height == 1280u && eff_stride == width * 4u) {
|
||||
// Hekate TUI or static bootlogo: natively rendered as 720x1280 pitch-linear portrait.
|
||||
// Do not apply any automatic layout overrides.
|
||||
sw = 0;
|
||||
rot = 0; // The UI is drawn sideways in memory to appear upright on a landscape physical Switch screen.
|
||||
// On PC, we want to view it rotated so it resembles the physical landscape Switch!
|
||||
} else if (addr_in_ipl_fb(eff_addr) && sw == 0) {
|
||||
// IPL carveout with Sw=0: Hekate writes block-linear data but the DC
|
||||
// surface kind says pitch. Detect when the stride/dimensions don't
|
||||
// match a coherent pitch-linear layout and force block-linear decode.
|
||||
bool coherent_pitch =
|
||||
width > 0 && (eff_stride == width * 4u || eff_stride == width * 2u);
|
||||
bool portrait_stride_mismatch =
|
||||
height == 1280u && width == 720u && eff_stride != width * 4u;
|
||||
bool known_menu_stride = (eff_stride == 2624u && !coherent_pitch);
|
||||
|
||||
// crop_portrait only forces BL when stride is incoherent — if stride
|
||||
// matches width*bpp, the data may already be VIC-de-swizzled pitch.
|
||||
bool crop_portrait_incoherent =
|
||||
height == 1280u && width < 720u && width >= 640u && !coherent_pitch;
|
||||
|
||||
if (!coherent_pitch || portrait_stride_mismatch || known_menu_stride ||
|
||||
crop_portrait_incoherent) {
|
||||
sw = 2; // Force block-linear decode
|
||||
bh = 4; // Hekate menu uses BH=4
|
||||
}
|
||||
}
|
||||
|
||||
// Final heuristic: NEVER auto-rotate 720x1280 portrait buffers to landscape!
|
||||
if (rot == -1) {
|
||||
if (width == 720 && height == 1280) {
|
||||
rot = 0; // Hekate already drew it sideways for physical portrait, so rot=0 makes it look like a phone on PC monitor!
|
||||
// Actually wait: if drawn upright in memory (row-by-row), then rot=0 produces a tall 720x1280 window on PC where it is perfectly upright!
|
||||
// The user wants the white lines to be horizontal. This means we MUST let the window be 720x1280!
|
||||
} else {
|
||||
rot = (height > width) ? 1 : 0; // Legacy heuristic for other stuff
|
||||
}
|
||||
}
|
||||
|
||||
// Manual rotation override always wins. The auto-detect branches above set
|
||||
// rot = 0 for Nyx and Hekate TUI surfaces; if the user pressed R/Shift+R
|
||||
// they expect the rotation to actually change, regardless of what the
|
||||
// auto-detect picked. -1 means "use auto-detect", anything else overrides.
|
||||
if (state->rotation_override != -1)
|
||||
rot = state->rotation_override & 3;
|
||||
|
||||
// --- Compute GOB stride for block-linear ---
|
||||
uint32_t sw_gobs = (width * bpp + 63) / 64;
|
||||
if (sw == 2) {
|
||||
// For IPL carveout portrait surfaces, Hekate allocates a full 720px-wide
|
||||
// BL surface even when the DC window is cropped to 656px.
|
||||
if (addr_in_ipl_fb(state->fb_addr) && state->fb_addr != kNyxFbBase &&
|
||||
bpp == 4 && height == 1280u && width >= 640u && width <= 720u) {
|
||||
uint32_t sw_720 = (720u * bpp + 63) / 64u;
|
||||
if (sw_gobs < sw_720)
|
||||
sw_gobs = sw_720;
|
||||
}
|
||||
// If DC provides a stride that's GOB-aligned, prefer it
|
||||
if (eff_stride >= 64u && (eff_stride % 64u) == 0u) {
|
||||
uint32_t stride_gobs = eff_stride / 64u;
|
||||
if (stride_gobs > sw_gobs)
|
||||
sw_gobs = stride_gobs;
|
||||
}
|
||||
}
|
||||
|
||||
uint32_t out_w = (rot & 1) ? height : width;
|
||||
uint32_t out_h = (rot & 1) ? width : height;
|
||||
|
||||
// Cache the effective rotation and output dims so the SDL event handler can
|
||||
// invert the framebuffer→window transform when mapping mouse → panel coords.
|
||||
state->last_rot.store((uint32_t)((rot < 0) ? 0 : (rot & 3)));
|
||||
state->last_out_w.store(out_w);
|
||||
state->last_out_h.store(out_h);
|
||||
|
||||
static uint32_t last_w = 0, last_h = 0;
|
||||
if (!texture || out_w != last_w || out_h != last_h) {
|
||||
if (texture)
|
||||
SDL_DestroyTexture(texture);
|
||||
// Use ARGB8888: natively matches Tegra's BGRA memory layout on Little
|
||||
// Endian
|
||||
texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888,
|
||||
SDL_TEXTUREACCESS_STREAMING, out_w, out_h);
|
||||
last_w = out_w;
|
||||
last_h = out_h;
|
||||
SDL_SetWindowSize(window, out_w, out_h);
|
||||
}
|
||||
|
||||
static uint32_t last_log_p[6] = {0}; // Addr, W, H, Rot, Sw, BH
|
||||
if (state->fb_addr != last_log_p[0] || width != last_log_p[1] ||
|
||||
height != last_log_p[2] || (uint32_t)rot != last_log_p[3] ||
|
||||
sw != last_log_p[4] || bh != last_log_p[5]) {
|
||||
printf("[display] LATCH: 0x%X (%dx%d), Rot: %d (Manual: %d), Sw: %d, "
|
||||
"GOBs: %u, BH: %u, BPP: %u\n",
|
||||
(uint32_t)state->fb_addr, width, height, rot,
|
||||
state->rotation_override, sw, sw_gobs, bh, bpp * 8);
|
||||
last_log_p[0] = state->fb_addr;
|
||||
last_log_p[1] = width;
|
||||
last_log_p[2] = height;
|
||||
last_log_p[3] = rot;
|
||||
last_log_p[4] = sw;
|
||||
last_log_p[5] = bh;
|
||||
}
|
||||
|
||||
eff_addr =
|
||||
(eff_addr ? eff_addr : FB_BASE) +
|
||||
(uint64_t)(int64_t)state->manual_offset;
|
||||
|
||||
// Compute framebuffer byte size
|
||||
size_t fb_size = (sw == 2) ? ((size_t)sw_gobs * ((height + 7) / 8) * 512)
|
||||
: ((size_t)eff_stride * height);
|
||||
if (fb_size < 1024)
|
||||
return;
|
||||
if (sw != 2 && eff_stride < 16)
|
||||
return; // Pitch-linear sanity check only
|
||||
if (fb_size > 32 * 1024 * 1024)
|
||||
fb_size = 32 * 1024 * 1024;
|
||||
|
||||
std::vector<uint8_t> buf(fb_size);
|
||||
if (uc_mem_read(uc, eff_addr, buf.data(), fb_size) == UC_ERR_OK) {
|
||||
std::vector<uint32_t> proc(out_w * out_h,
|
||||
0xFF000000); // Initialize opaque black
|
||||
|
||||
for (uint32_t sy = 0; sy < height; sy++) {
|
||||
for (uint32_t sx = 0; sx < width; sx++) {
|
||||
uint32_t off = 0;
|
||||
if (sw == 2) {
|
||||
if (bpp == 4) {
|
||||
// Use tegra_bl_byte_off_rgba8888 formula inline for 32bpp
|
||||
uint32_t gob_x = sx / 16u;
|
||||
uint32_t pixel_x = sx % 16u;
|
||||
uint32_t gob_y = sy / 8u;
|
||||
uint32_t line_y = sy % 8u;
|
||||
uint32_t block_y = gob_y / bh;
|
||||
uint32_t gob_in_block_y = gob_y % bh;
|
||||
|
||||
uint32_t idx =
|
||||
(block_y * sw_gobs * bh * 128u) + (gob_x * bh * 128u) +
|
||||
(gob_in_block_y * 128u) + (pixel_x & 3u) +
|
||||
((line_y & 1u) << 2) + ((pixel_x & 4u) << 1) +
|
||||
((line_y & 2u) << 3) + ((pixel_x & 8u) << 2) +
|
||||
((line_y & 4u) << 4);
|
||||
off = idx; // Already in uint32 units
|
||||
} else {
|
||||
// 16bpp block-linear (Nyx RGB565)
|
||||
uint32_t byte_x = sx * bpp;
|
||||
uint32_t gx = byte_x / 64;
|
||||
uint32_t px_in = byte_x % 64;
|
||||
uint32_t gy = sy / 8;
|
||||
uint32_t ly = sy % 8;
|
||||
uint32_t gob_off = ((ly >> 1) << 7) + ((px_in >> 4) << 5) +
|
||||
((ly & 1) << 4) + (px_in & 0xF);
|
||||
uint32_t gob_idx =
|
||||
(gy / bh) * (sw_gobs * bh) + gx * bh + (gy % bh);
|
||||
uint32_t byte_off = gob_idx * 512 + gob_off;
|
||||
// Read 16-bit pixel and expand to 32-bit ARGB
|
||||
if (byte_off + 2 <= fb_size) {
|
||||
uint16_t u16 = *(uint16_t *)&buf[byte_off];
|
||||
uint32_t p = (((u16 >> 11) & 0x1F) << 19) |
|
||||
(((u16 >> 5) & 0x3F) << 10) |
|
||||
((u16 & 0x1F) << 3) | 0xFF000000;
|
||||
uint32_t dx = sx, dy = sy;
|
||||
switch (rot) {
|
||||
case 1: dx = height - 1 - sy; dy = sx; break;
|
||||
case 2: dx = width - 1 - sx; dy = height - 1 - sy; break;
|
||||
case 3: dx = sy; dy = width - 1 - sx; break;
|
||||
default: break;
|
||||
}
|
||||
if (dx < out_w && dy < out_h)
|
||||
proc[dy * out_w + dx] = p;
|
||||
}
|
||||
continue; // Skip the common 32bpp path below
|
||||
}
|
||||
} else {
|
||||
off = (sy * eff_stride + sx * bpp) / 4;
|
||||
}
|
||||
|
||||
if (off < fb_size / 4) {
|
||||
uint32_t p = ((uint32_t *)buf.data())[off];
|
||||
uint32_t dx = sx, dy = sy;
|
||||
|
||||
switch (rot) {
|
||||
case 1:
|
||||
dx = height - 1 - sy;
|
||||
dy = sx;
|
||||
break;
|
||||
case 2:
|
||||
dx = width - 1 - sx;
|
||||
dy = height - 1 - sy;
|
||||
break;
|
||||
case 3:
|
||||
dx = sy;
|
||||
dy = width - 1 - sx;
|
||||
break;
|
||||
default:
|
||||
break; // 0
|
||||
}
|
||||
if (dx < out_w && dy < out_h) {
|
||||
// Native BGRA to ARGB8888 conversion mapping (forces A to 0xFF)
|
||||
proc[dy * out_w + dx] = p | 0xFF000000;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
SDL_UpdateTexture(texture, nullptr, proc.data(), out_w * 4);
|
||||
|
||||
// Snapshot for PNG conversion — save periodically (~1s) so the last
|
||||
// written file always reflects the most recent frame content.
|
||||
static int snap_counter = 0;
|
||||
if (++snap_counter >= 60) { // ~1 second at 60 FPS
|
||||
snap_counter = 0;
|
||||
FILE *f = fopen("last_fb.rgba", "wb");
|
||||
if (f) {
|
||||
fwrite(proc.data(), 1, proc.size() * 4, f);
|
||||
fclose(f);
|
||||
FILE *fm = fopen("last_fb.meta", "w");
|
||||
if (fm) {
|
||||
fprintf(fm, "%u %u\n", out_w, out_h);
|
||||
fclose(fm);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SDL_RenderClear(renderer);
|
||||
SDL_RenderCopy(renderer, texture, nullptr, nullptr);
|
||||
SDL_RenderPresent(renderer);
|
||||
state->display_initialized = true;
|
||||
}
|
||||
|
||||
// Map SDL window mouse coords to FTS4 panel-raw coords by inverting the
|
||||
// framebuffer→window rotation pipeline. Returns false if the rendered output
|
||||
// has not been measured yet (no display update happened).
|
||||
static bool window_to_panel(EmuState *state, int mx, int my,
|
||||
uint16_t *panel_x, uint16_t *panel_y) {
|
||||
uint32_t out_w = state->last_out_w.load();
|
||||
uint32_t out_h = state->last_out_h.load();
|
||||
if (out_w == 0 || out_h == 0) return false;
|
||||
|
||||
// Scale window pixel coords to texture pixel coords (window may be resized).
|
||||
int win_w = 0, win_h = 0;
|
||||
SDL_GetWindowSize(window, &win_w, &win_h);
|
||||
if (win_w <= 0 || win_h <= 0) return false;
|
||||
double tx_d = (double)mx * (double)out_w / (double)win_w;
|
||||
double ty_d = (double)my * (double)out_h / (double)win_h;
|
||||
if (tx_d < 0) tx_d = 0;
|
||||
if (ty_d < 0) ty_d = 0;
|
||||
uint32_t tx = (uint32_t)tx_d;
|
||||
uint32_t ty = (uint32_t)ty_d;
|
||||
if (tx >= out_w) tx = out_w - 1;
|
||||
if (ty >= out_h) ty = out_h - 1;
|
||||
|
||||
// The rendered SDL view always represents the physical Switch screen in its
|
||||
// intended orientation (post-rotation, post-de-swizzle). Whatever the
|
||||
// framebuffer's in-memory layout, what the user sees is what they would see
|
||||
// looking at a Switch held landscape (long axis horizontal). The FTS4 panel
|
||||
// sits behind that physical screen with its long axis (panel_x) along the
|
||||
// long dimension and its short axis (panel_y) along the short.
|
||||
//
|
||||
// So we map the texture coord to panel coords by aspect: whichever of (tx,
|
||||
// ty) lives on the longer rendered axis is the long-axis sample.
|
||||
bool landscape = (out_w >= out_h);
|
||||
uint32_t long_pix = landscape ? tx : ty;
|
||||
uint32_t long_max = landscape ? out_w : out_h;
|
||||
uint32_t short_pix = landscape ? ty : tx;
|
||||
uint32_t short_max = landscape ? out_h : out_w;
|
||||
if (long_max == 0) long_max = 1;
|
||||
if (short_max == 0) short_max = 1;
|
||||
|
||||
uint32_t px = (long_pix * 1264u) / long_max; // FTS4 X_REAL_MAX = 1264
|
||||
uint32_t py = (short_pix * 704u) / short_max; // FTS4 Y_REAL_MAX = 704
|
||||
if (px > 1264) px = 1264;
|
||||
if (py > 704) py = 704;
|
||||
*panel_x = (uint16_t)px;
|
||||
*panel_y = (uint16_t)py;
|
||||
(void)state; // last_rot still cached for future use; current mapping is rotation-agnostic
|
||||
return true;
|
||||
}
|
||||
|
||||
bool sdl_display_poll_events(EmuState *state, uc_engine *uc) {
|
||||
(void)uc; // Available for future use (e.g. raw FB dump on F8)
|
||||
SDL_Event event;
|
||||
while (SDL_PollEvent(&event)) {
|
||||
if (event.type == SDL_QUIT) {
|
||||
state->running = false;
|
||||
return false;
|
||||
}
|
||||
// ---- Mouse → FTS4 touchscreen events ----
|
||||
if (event.type == SDL_MOUSEBUTTONDOWN && event.button.button == SDL_BUTTON_LEFT) {
|
||||
uint16_t px = 0, py = 0;
|
||||
if (window_to_panel(state, event.button.x, event.button.y, &px, &py)) {
|
||||
state->tc_x.store(px);
|
||||
state->tc_y.store(py);
|
||||
state->tc_pressed.store(true);
|
||||
state->tc_event_op.store(0x03); // FTS4_EV_MULTI_TOUCH_ENTER
|
||||
state->tc_event_pending.store(true);
|
||||
printf("[touch] DOWN win=(%d,%d) panel=(%u,%u)\n",
|
||||
event.button.x, event.button.y, px, py);
|
||||
}
|
||||
}
|
||||
if (event.type == SDL_MOUSEBUTTONUP && event.button.button == SDL_BUTTON_LEFT) {
|
||||
uint16_t px = 0, py = 0;
|
||||
if (window_to_panel(state, event.button.x, event.button.y, &px, &py)) {
|
||||
state->tc_x.store(px);
|
||||
state->tc_y.store(py);
|
||||
state->tc_pressed.store(false);
|
||||
state->tc_event_op.store(0x04); // FTS4_EV_MULTI_TOUCH_LEAVE
|
||||
state->tc_event_pending.store(true);
|
||||
printf("[touch] UP win=(%d,%d) panel=(%u,%u)\n",
|
||||
event.button.x, event.button.y, px, py);
|
||||
}
|
||||
}
|
||||
if (event.type == SDL_MOUSEMOTION && state->tc_pressed.load()) {
|
||||
uint16_t px = 0, py = 0;
|
||||
if (window_to_panel(state, event.motion.x, event.motion.y, &px, &py)) {
|
||||
state->tc_x.store(px);
|
||||
state->tc_y.store(py);
|
||||
state->tc_event_op.store(0x05); // FTS4_EV_MULTI_TOUCH_MOTION
|
||||
state->tc_event_pending.store(true);
|
||||
}
|
||||
}
|
||||
if (event.type == SDL_KEYDOWN) {
|
||||
bool shift = (SDL_GetModState() & KMOD_SHIFT);
|
||||
uint32_t step = shift ? 4096 : 128;
|
||||
switch (event.key.keysym.sym) {
|
||||
case SDLK_UP:
|
||||
if (!state->btn_vol_up)
|
||||
printf("[input] DOWN VOL_UP @emu_usec=%llu\n", (unsigned long long)state->emu_usec);
|
||||
state->btn_vol_up = true;
|
||||
break;
|
||||
case SDLK_DOWN:
|
||||
if (!state->btn_vol_down)
|
||||
printf("[input] DOWN VOL_DOWN @emu_usec=%llu\n", (unsigned long long)state->emu_usec);
|
||||
state->btn_vol_down = true;
|
||||
break;
|
||||
case SDLK_RETURN:
|
||||
if (!state->btn_power)
|
||||
printf("[input] DOWN POWER @emu_usec=%llu\n", (unsigned long long)state->emu_usec);
|
||||
state->btn_power = true;
|
||||
break;
|
||||
case SDLK_p:
|
||||
state->paused = !state->paused;
|
||||
printf("[diag] Emulation %s\n", state->paused ? "PAUSED" : "RESUMED");
|
||||
break;
|
||||
case SDLK_r: {
|
||||
// R : step rotation 90° clockwise (Auto → 0 → 90 → 180 → 270 → Auto)
|
||||
// Shift+R : step rotation 90° counter-CW (Auto → 270 → 180 → 90 → 0 → Auto)
|
||||
int r = state->rotation_override;
|
||||
if (shift) {
|
||||
// CCW: -1 → 3 → 2 → 1 → 0 → -1
|
||||
r = (r == -1) ? 3 : (r == 0) ? -1 : r - 1;
|
||||
} else {
|
||||
// CW: -1 → 0 → 1 → 2 → 3 → -1
|
||||
r = (r == 3) ? -1 : r + 1;
|
||||
}
|
||||
state->rotation_override = r;
|
||||
const char *label =
|
||||
r == -1 ? "Auto" : r == 0 ? "0\xC2\xB0" :
|
||||
r == 1 ? "90\xC2\xB0 CW" :
|
||||
r == 2 ? "180\xC2\xB0" :
|
||||
"270\xC2\xB0 CW";
|
||||
printf("[diag] Rotation Override: %d (%s)\n", r, label);
|
||||
break;
|
||||
}
|
||||
case SDLK_i:
|
||||
state->manual_offset -= step;
|
||||
printf("[diag] Offset: %d\n", state->manual_offset);
|
||||
break;
|
||||
case SDLK_o:
|
||||
state->manual_offset += step;
|
||||
printf("[diag] Offset: %d\n", state->manual_offset);
|
||||
break;
|
||||
case SDLK_s:
|
||||
g_swizzle_override =
|
||||
(g_swizzle_override == -1) ? 0 : (g_swizzle_override == 0 ? 2 : -1);
|
||||
printf("[diag] Swizzle Override: %d (-1=Auto, 0=Pitch, 2=Block)\n",
|
||||
g_swizzle_override);
|
||||
break;
|
||||
case SDLK_ESCAPE:
|
||||
state->running = false;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (event.type == SDL_KEYUP) {
|
||||
switch (event.key.keysym.sym) {
|
||||
case SDLK_UP:
|
||||
if (state->btn_vol_up)
|
||||
printf("[input] UP VOL_UP @emu_usec=%llu\n", (unsigned long long)state->emu_usec);
|
||||
state->btn_vol_up = false;
|
||||
break;
|
||||
case SDLK_DOWN:
|
||||
if (state->btn_vol_down)
|
||||
printf("[input] UP VOL_DOWN @emu_usec=%llu\n", (unsigned long long)state->emu_usec);
|
||||
state->btn_vol_down = false;
|
||||
break;
|
||||
case SDLK_RETURN:
|
||||
if (state->btn_power)
|
||||
printf("[input] UP POWER @emu_usec=%llu\n", (unsigned long long)state->emu_usec);
|
||||
state->btn_power = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void sdl_display_shutdown() {
|
||||
SDL_Quit();
|
||||
printf("[display] SDL2 shutdown\n");
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
#ifndef SDL_DISPLAY_H
|
||||
#define SDL_DISPLAY_H
|
||||
|
||||
#include <unicorn/unicorn.h>
|
||||
|
||||
struct EmuState;
|
||||
|
||||
bool sdl_display_init();
|
||||
void sdl_display_update(EmuState *state, uc_engine *uc);
|
||||
bool sdl_display_poll_events(EmuState *state, uc_engine *uc);
|
||||
void sdl_display_shutdown();
|
||||
|
||||
#endif // SDL_DISPLAY_H
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
#ifndef EMU_STATE_H
|
||||
#define EMU_STATE_H
|
||||
|
||||
#include <cstdint>
|
||||
#include <atomic>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
|
||||
/*
|
||||
* Emulator State
|
||||
*
|
||||
* Shared state between CPU emulation, MMIO handlers, and display.
|
||||
*/
|
||||
|
||||
#include <unicorn/unicorn.h>
|
||||
|
||||
struct EmuState {
|
||||
uc_engine *uc = nullptr;
|
||||
// Button state (updated by SDL keyboard events).
|
||||
std::atomic<bool> btn_vol_up{false};
|
||||
std::atomic<bool> btn_vol_down{false};
|
||||
std::atomic<bool> btn_power{false};
|
||||
|
||||
// Touchscreen state (FTS4/STMFTS stub on I2C3 @ slave 0x49).
|
||||
// Updated by SDL mouse events; consumed by i2c3_*/STMFTS code on CPU thread.
|
||||
// Coordinates are in panel-raw space (X long axis 0..1264, Y short 0..704)
|
||||
// matching what touch.c expects before its rescaling.
|
||||
std::atomic<uint16_t> tc_x{0};
|
||||
std::atomic<uint16_t> tc_y{0};
|
||||
std::atomic<bool> tc_pressed{false};
|
||||
std::atomic<bool> tc_event_pending{false};
|
||||
std::atomic<uint8_t> tc_event_op{0}; // 0x03=ENTER, 0x04=LEAVE, 0x05=MOTION
|
||||
uint8_t tc_finger_id = 1; // FTS4 finger IDs are 1-indexed
|
||||
// last_rot mirrors the rotation last applied by sdl_display_update.
|
||||
// Read from the SDL event handler to invert the display→window transform.
|
||||
std::atomic<uint32_t> last_rot{0};
|
||||
std::atomic<uint32_t> last_out_w{1280};
|
||||
std::atomic<uint32_t> last_out_h{720};
|
||||
|
||||
// Display state.
|
||||
uint64_t fb_addr = 0, pre_addr = 0;
|
||||
uint32_t fb_width = 720, pre_w = 720;
|
||||
uint32_t fb_height = 1280, pre_h = 1280;
|
||||
uint32_t fb_stride = 2880, pre_stride = 2880;
|
||||
uint32_t fb_swizzle = 0, pre_sw = 0;
|
||||
uint32_t fb_rotation = 0, pre_rot = 0;
|
||||
uint32_t pre_bh = 0; // block height in GOBs from DC surface-kind (0 = unset)
|
||||
uint32_t fb_sw_gobs = 80;
|
||||
uint32_t fb_bh = 0; // 0 = use display code default until DC surface-kind latches
|
||||
|
||||
// DC window selection: tracks DC_CMD_DISPLAY_WINDOW_HEADER.
|
||||
// Bit 4 = Window A, Bit 5 = Window B, Bit 6 = Window C, Bit 7 = Window D.
|
||||
uint32_t dc_window_sel = 0x10; // Default: Window A
|
||||
// Saved Window A parameters (primary display surface).
|
||||
uint64_t winA_addr = 0;
|
||||
uint32_t winA_w = 720, winA_h = 1280, winA_stride = 2880;
|
||||
uint32_t winA_sw = 0, winA_rot = 0, winA_bh = 0;
|
||||
std::atomic<bool> display_dirty{false};
|
||||
std::atomic<bool> display_initialized{false};
|
||||
int32_t manual_offset = 0;
|
||||
int32_t rotation_override = -1; // -1 = Auto, 0=0, 1=90, 2=180, 3=270
|
||||
|
||||
// Emulation control.
|
||||
std::atomic<bool> running{true};
|
||||
std::atomic<bool> paused{false};
|
||||
|
||||
// Backlight brightness (0-255).
|
||||
uint32_t backlight = 100;
|
||||
|
||||
// Deterministic timer.
|
||||
uint64_t emu_usec = 0;
|
||||
uint64_t insn_count = 0;
|
||||
|
||||
// DRAM pointer (host memory backing the emulated DRAM).
|
||||
uint8_t *dram_ptr = nullptr;
|
||||
uint8_t *iram_ptr = nullptr;
|
||||
uint8_t *fb_ptr = nullptr;
|
||||
|
||||
// SDMMC1 State
|
||||
uint32_t sdmmc_arg = 0;
|
||||
uint32_t sdmmc_rsp[4] = {0};
|
||||
uint32_t sdmmc_norintsts = 0;
|
||||
uint32_t sdmmc_errintsts = 0;
|
||||
uint32_t sdmmc_sysad = 0;
|
||||
uint8_t sdmmc_hostctl = 0;
|
||||
uint16_t sdmmc_blksize = 0;
|
||||
uint16_t sdmmc_blkcnt = 0;
|
||||
uint16_t sdmmc_trnmod = 0;
|
||||
uint64_t sdmmc_adma_addr = 0;
|
||||
|
||||
// SDMMC4 State
|
||||
uint32_t sdmmc4_arg = 0;
|
||||
uint32_t sdmmc4_rsp[4] = {0};
|
||||
uint32_t sdmmc4_norintsts = 0;
|
||||
uint32_t sdmmc4_errintsts = 0;
|
||||
uint32_t sdmmc4_sysad = 0;
|
||||
uint8_t sdmmc4_hostctl = 0;
|
||||
uint16_t sdmmc4_blksize = 0;
|
||||
uint16_t sdmmc4_blkcnt = 0;
|
||||
uint16_t sdmmc4_trnmod = 0;
|
||||
uint64_t sdmmc4_adma_addr = 0;
|
||||
|
||||
// File-backed storage
|
||||
int sd_fd = -1;
|
||||
int emmc_boot0_fd = -1;
|
||||
int emmc_boot1_fd = -1;
|
||||
std::vector<int> emmc_gpp_fds;
|
||||
uint32_t emmc_partition = 0; // 0=GPP, 1=BOOT0, 2=BOOT1
|
||||
|
||||
// Command state tracking
|
||||
bool last_cmd_was_55 = false;
|
||||
bool last_cmd4_was_55 = false;
|
||||
|
||||
// Touch injection state (STMFTS FTS5 controller, I2C addr 0x49 on I2C1)
|
||||
// touch_phase: 0=idle, 1=send_down, 2=send_up, 3=done
|
||||
std::atomic<int> touch_phase{0};
|
||||
uint16_t touch_x = 360; // Portrait X coordinate (0-719)
|
||||
uint16_t touch_y = 640; // Portrait Y coordinate (0-1279)
|
||||
};
|
||||
|
||||
#endif // EMU_STATE_H
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 68 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 18 KiB |
@@ -0,0 +1,551 @@
|
||||
/*
|
||||
* RCM Payload Emulator - Main Entry Point
|
||||
*
|
||||
* Loads an RCM binary payload (.bin), initializes ARM32 emulation
|
||||
* via Unicorn Engine, sets up T210 memory map and MMIO hooks,
|
||||
* and runs the payload with SDL2 display output.
|
||||
*
|
||||
* Usage: ./rcm_emu <payload.bin>
|
||||
*/
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <thread>
|
||||
#include <chrono>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/stat.h>
|
||||
|
||||
#include <unicorn/unicorn.h>
|
||||
|
||||
#include "emu_state.h"
|
||||
#include "t210/memory_map.h"
|
||||
#include "t210/mmio.h"
|
||||
#include "display/sdl_display.h"
|
||||
|
||||
// ==================== Payload Loading ====================
|
||||
|
||||
static uint8_t *load_payload(const char *path, size_t *out_size) {
|
||||
FILE *f = fopen(path, "rb");
|
||||
if (!f) {
|
||||
fprintf(stderr, "[error] Cannot open payload: %s\n", path);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
fseek(f, 0, SEEK_END);
|
||||
size_t size = ftell(f);
|
||||
fseek(f, 0, SEEK_SET);
|
||||
|
||||
uint8_t *buf = (uint8_t *)malloc(size);
|
||||
if (!buf) {
|
||||
fclose(f);
|
||||
fprintf(stderr, "[error] Failed to allocate %zu bytes\n", size);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
size_t nread = fread(buf, 1, size, f);
|
||||
if (nread != size) {
|
||||
fprintf(stderr, "[warning] Short read: %zu/%zu bytes\n", nread, size);
|
||||
size = nread;
|
||||
}
|
||||
fclose(f);
|
||||
|
||||
*out_size = size;
|
||||
printf("[loader] Loaded payload: %s (%zu bytes / %.1f KB)\n", path, size, size / 1024.0);
|
||||
|
||||
// Try to identify the payload
|
||||
if (size >= 0x120) {
|
||||
uint32_t magic = *(uint32_t *)(buf + 0x118);
|
||||
if (magic == 0x43544349) { // "ICTC" - hekate
|
||||
uint32_t ver = *(uint32_t *)(buf + 0x11C);
|
||||
int major = (ver & 0xFF) - '0';
|
||||
int minor = ((ver >> 8) & 0xFF) - '0';
|
||||
int hotfix = ((ver >> 16) & 0xFF) - '0';
|
||||
printf("[loader] Detected: Hekate v%d.%d.%d\n", major, minor, hotfix);
|
||||
} else if (magic == 0x4E595849) { // "IXYN" - Nyx
|
||||
printf("[loader] Detected: Nyx GUI\n");
|
||||
} else {
|
||||
printf("[loader] Unknown payload type (magic: 0x%08X)\n", magic);
|
||||
}
|
||||
}
|
||||
|
||||
return buf;
|
||||
}
|
||||
|
||||
// ==================== Emulation Setup ====================
|
||||
|
||||
// Global for instruction tracing
|
||||
static uint32_t pc_trace[2000];
|
||||
static size_t pc_trace_idx = 0;
|
||||
static uint32_t last_valid_block = 0;
|
||||
static uc_hook trace_h, block_h;
|
||||
|
||||
static void trace_callback(uc_engine *uc, uint64_t address, uint32_t size, void *user_data) {
|
||||
static uint32_t last_pc = 0;
|
||||
if (address == last_pc) return;
|
||||
last_pc = (uint32_t)address;
|
||||
|
||||
pc_trace[pc_trace_idx] = (uint32_t)address;
|
||||
pc_trace_idx = (pc_trace_idx + 1) % 2000;
|
||||
|
||||
// NOP-slide detection
|
||||
if (address >= 0x40030000 && address < 0x41000000) {
|
||||
uint16_t insn = 0;
|
||||
if (uc_mem_read(uc, address, &insn, 2) == UC_ERR_OK && insn == 0) {
|
||||
static int nop_count = 0;
|
||||
if (++nop_count > 10) {
|
||||
printf("\n[emu] NOP-slide detected at 0x%08llX! Last valid block: 0x%08X\n",
|
||||
(unsigned long long)address, last_valid_block);
|
||||
uc_emu_stop(uc);
|
||||
}
|
||||
} else {
|
||||
// nop_count = 0; // would need a persistent counter
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void block_callback(uc_engine *uc, uint64_t address, uint32_t size, void *user_data) {
|
||||
if (address >= 0x40000000 && address < 0x40030000) {
|
||||
last_valid_block = (uint32_t)address;
|
||||
}
|
||||
}
|
||||
|
||||
static uc_engine *setup_emulation(EmuState *state, uint8_t *payload, size_t payload_size) {
|
||||
uc_engine *uc;
|
||||
uc_err err;
|
||||
|
||||
// Open Unicorn in ARM32 mode with Thumb support
|
||||
err = uc_open(UC_ARCH_ARM, UC_MODE_ARM, &uc);
|
||||
if (err != UC_ERR_OK) {
|
||||
fprintf(stderr, "[error] uc_open failed: %s\n", uc_strerror(err));
|
||||
return nullptr;
|
||||
}
|
||||
state->uc = uc;
|
||||
|
||||
// Setup hooks
|
||||
uc_hook_add(uc, &trace_h, UC_HOOK_CODE, (void*)trace_callback, nullptr, 1, 0);
|
||||
uc_hook_add(uc, &block_h, UC_HOOK_BLOCK, (void*)block_callback, nullptr, 1, 0);
|
||||
|
||||
// Enable VFP/NEON
|
||||
uint32_t cpacr = 0x00F00000;
|
||||
uc_reg_write(uc, UC_ARM_REG_C1_C0_2, &cpacr);
|
||||
|
||||
// Map IRAM (16MB)
|
||||
state->iram_ptr = (uint8_t *)calloc(1, IRAM_SIZE);
|
||||
err = uc_mem_map_ptr(uc, IRAM_BASE, IRAM_SIZE, UC_PROT_ALL, state->iram_ptr);
|
||||
if (err != UC_ERR_OK) {
|
||||
fprintf(stderr, "[error] Failed to map IRAM: %s\n", uc_strerror(err));
|
||||
uc_close(uc);
|
||||
return nullptr;
|
||||
}
|
||||
printf("[emu] Mapped IRAM: 0x%08llX - 0x%08llX (%u KB)\n",
|
||||
(unsigned long long)IRAM_BASE,
|
||||
(unsigned long long)(IRAM_BASE + IRAM_SIZE),
|
||||
(unsigned)(IRAM_SIZE / 1024));
|
||||
|
||||
uc_mem_write(uc, IPL_LOAD_ADDR, payload, payload_size);
|
||||
|
||||
// Setup instruction tracing
|
||||
uc_hook_add(uc, &trace_h, UC_HOOK_CODE, (void*)trace_callback, nullptr, 1, 0);
|
||||
|
||||
// ---- Map DRAM Low (256MB @ 0x80000000) ----
|
||||
err = uc_mem_map(uc, DRAM_BASE, 256 * 1024 * 1024, UC_PROT_ALL);
|
||||
if (err != UC_ERR_OK) {
|
||||
fprintf(stderr, "[error] Failed to map low DRAM: %s\n", uc_strerror(err));
|
||||
uc_close(uc);
|
||||
return nullptr;
|
||||
}
|
||||
printf("[emu] Mapped DRAM Low: 0x%08llX - 0x%08llX (256 MB)\n",
|
||||
(unsigned long long)DRAM_BASE,
|
||||
(unsigned long long)(DRAM_BASE + 256 * 1024 * 1024));
|
||||
|
||||
// ---- Map DRAM High + FB (1GB @ 0xC0000000) ----
|
||||
// This covers 0xE5000000 and 0xF5A00000
|
||||
size_t high_dram_size = 1024 * 1024 * 1024;
|
||||
state->dram_ptr = (uint8_t *)calloc(1, high_dram_size);
|
||||
if (!state->dram_ptr) {
|
||||
fprintf(stderr, "[error] Failed to allocate high DRAM host buffer\n");
|
||||
return nullptr;
|
||||
}
|
||||
err = uc_mem_map_ptr(uc, 0xC0000000, high_dram_size, UC_PROT_ALL, state->dram_ptr);
|
||||
if (err != UC_ERR_OK) {
|
||||
fprintf(stderr, "[error] Failed to map high DRAM: %s\n", uc_strerror(err));
|
||||
return nullptr;
|
||||
}
|
||||
printf("[emu] Mapped DRAM High: 0xC0000000 - 0x%08llX (1024 MB)\n",
|
||||
(unsigned long long)(0xC0000000 + high_dram_size));
|
||||
|
||||
// ---- Map Framebuffer pointer ----
|
||||
// FB_BASE is 0xF5A00000. Offset in 1GB block starting at 0xC0000000 is 0x35A00000.
|
||||
state->fb_ptr = state->dram_ptr + (FB_BASE - 0xC0000000);
|
||||
// Fill with hekate background color (0x1B1B1B)
|
||||
for (size_t i = 0; i < FB_SIZE; i += 4) {
|
||||
state->fb_ptr[i + 0] = 0x1B; // B
|
||||
state->fb_ptr[i + 1] = 0x1B; // G
|
||||
state->fb_ptr[i + 2] = 0x1B; // R
|
||||
state->fb_ptr[i + 3] = 0xFF; // A
|
||||
}
|
||||
state->fb_addr = FB_BASE;
|
||||
printf("[emu] Defined FB: 0x%08llX - 0x%08llX (%u MB)\n",
|
||||
(unsigned long long)FB_BASE,
|
||||
(unsigned long long)(FB_BASE + FB_SIZE),
|
||||
(unsigned)(FB_SIZE / (1024 * 1024)));
|
||||
|
||||
// ---- Map low memory (16MB @ 0x0) ----
|
||||
// hekate seems to do a memset(0, ...) for clear screen if some ptr is NULL.
|
||||
uint8_t *low_ptr = (uint8_t *)calloc(1, 0x01000000);
|
||||
uc_mem_map_ptr(uc, 0, 0x01000000, UC_PROT_ALL, low_ptr);
|
||||
|
||||
// ---- Nyx Storage (16MB @ 0xED000000) ----
|
||||
// Already mapped as part of 2GB DRAM chunk
|
||||
|
||||
// ---- Map Peripherals (PWM, SDMMC, etc.) ----
|
||||
// Map individual pages to allow MMIO hooks
|
||||
// The mappings previously declared manually were moved here:
|
||||
// Some are mapped earlier in setup_emulation properly using FB_BASE e.g.
|
||||
uc_mem_map(uc, 0x7000A000, 0x1000, UC_PROT_ALL); // PWM
|
||||
uc_mem_map(uc, 0x700B0000, 0x1000, UC_PROT_ALL); // SDMMC1
|
||||
uc_mem_map(uc, 0x7000E000, 0x1000, UC_PROT_ALL); // RTC/PMC
|
||||
uc_mem_map(uc, 0x6000C000, 0x2000, UC_PROT_ALL); // SYSREG/APB_SEMAPH
|
||||
|
||||
// ---- heap region (32MB @ 0x90000000) ----
|
||||
// Already mapped as part of 2GB DRAM chunk
|
||||
|
||||
// ---- Copy payload to IRAM at IPL_LOAD_ADDR ----
|
||||
size_t copy_size = payload_size;
|
||||
if (copy_size > IRAM_SIZE - (IPL_LOAD_ADDR - IRAM_BASE)) {
|
||||
copy_size = IRAM_SIZE - (IPL_LOAD_ADDR - IRAM_BASE);
|
||||
printf("[loader] Warning: payload truncated to %zu bytes\n", copy_size);
|
||||
}
|
||||
memcpy(state->iram_ptr + (IPL_LOAD_ADDR - IRAM_BASE), payload, copy_size);
|
||||
printf("[emu] Payload copied to IRAM @ 0x%08llX\n", (unsigned long long)IPL_LOAD_ADDR);
|
||||
|
||||
// ---- Set initial register state ----
|
||||
uint32_t sp = IPL_STACK_ADDR;
|
||||
uint32_t pc = IPL_LOAD_ADDR;
|
||||
|
||||
uc_reg_write(uc, UC_ARM_REG_SP, &sp);
|
||||
uc_reg_write(uc, UC_ARM_REG_PC, &pc);
|
||||
|
||||
printf("[emu] Initial PC=0x%08X SP=0x%08X\n", pc, sp);
|
||||
|
||||
// ---- Setup MMIO hooks ----
|
||||
mmio_init(uc, state);
|
||||
printf("[emu] MMIO hooks registered\n");
|
||||
|
||||
return uc;
|
||||
}
|
||||
|
||||
// ==================== Main ====================
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
if (argc < 2) {
|
||||
fprintf(stderr, "Usage: %s <payload.bin> [--sd <sd.img>] [--boot0 <boot0.bin>] [--rawnand <rawnand_prefix>] [--prod-keys <prod.keys>]\n", argv[0]);
|
||||
fprintf(stderr, "\nControls:\n");
|
||||
fprintf(stderr, " Arrow Up/Down = VOL+/VOL- buttons\n");
|
||||
fprintf(stderr, " Enter = POWER button\n");
|
||||
fprintf(stderr, " Escape = Quit\n");
|
||||
fprintf(stderr, " F8 = Save raw guest FB to fb_dump_NNNN.raw\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
printf("=== RCM Payload Emulator ===\n");
|
||||
printf("Using Unicorn Engine for ARM32 emulation\n\n");
|
||||
|
||||
// Initialize emulator state
|
||||
EmuState state = {};
|
||||
|
||||
// Load payload binary
|
||||
size_t payload_size = 0;
|
||||
uint8_t *payload = load_payload(argv[1], &payload_size);
|
||||
if (!payload) return 1;
|
||||
|
||||
// Parse additional arguments for storage
|
||||
const char *sd_path = nullptr;
|
||||
const char *boot0_path = nullptr;
|
||||
const char *rawnand_prefix = nullptr;
|
||||
const char *prod_keys_path = nullptr;
|
||||
|
||||
for (int i = 2; i < argc; i++) {
|
||||
if (strcmp(argv[i], "--sd") == 0 && i + 1 < argc) {
|
||||
sd_path = argv[++i];
|
||||
} else if (strcmp(argv[i], "--boot0") == 0 && i + 1 < argc) {
|
||||
boot0_path = argv[++i];
|
||||
} else if (strcmp(argv[i], "--rawnand") == 0 && i + 1 < argc) {
|
||||
rawnand_prefix = argv[++i];
|
||||
} else if (strcmp(argv[i], "--prod-keys") == 0 && i + 1 < argc) {
|
||||
prod_keys_path = argv[++i];
|
||||
}
|
||||
}
|
||||
|
||||
if (prod_keys_path) {
|
||||
extern int se_engine_load_prod_keys(const char *);
|
||||
se_engine_load_prod_keys(prod_keys_path);
|
||||
}
|
||||
|
||||
// Auto-script flag: feed a deterministic button sequence after the menu
|
||||
// has settled. Useful for capturing the PIN recovery flow non-interactively
|
||||
// (e.g. when verifying a fix without manually clicking through the SDL window).
|
||||
bool auto_pin_recovery = false;
|
||||
bool auto_te_script = false;
|
||||
for (int i = 2; i < argc; i++) {
|
||||
if (strcmp(argv[i], "--auto-pin-recovery") == 0) auto_pin_recovery = true;
|
||||
else if (strcmp(argv[i], "--auto-te-script") == 0) auto_te_script = true;
|
||||
}
|
||||
|
||||
if (sd_path) {
|
||||
state.sd_fd = open(sd_path, O_RDWR);
|
||||
if (state.sd_fd < 0) perror("[emu] Failed to open SD image");
|
||||
else printf("[emu] SD image opened: %s\n", sd_path);
|
||||
}
|
||||
if (boot0_path) {
|
||||
state.emmc_boot0_fd = open(boot0_path, O_RDWR);
|
||||
if (state.emmc_boot0_fd < 0) perror("[emu] Failed to open BOOT0 image");
|
||||
else printf("[emu] BOOT0 image opened: %s\n", boot0_path);
|
||||
}
|
||||
if (rawnand_prefix) {
|
||||
for (int i = 0; i < 16; i++) {
|
||||
char path[512];
|
||||
snprintf(path, sizeof(path), "%s.%02d", rawnand_prefix, i);
|
||||
int fd = open(path, O_RDWR);
|
||||
if (fd >= 0) {
|
||||
state.emmc_gpp_fds.push_back(fd);
|
||||
// printf("[emu] rawnand part %02d opened: %s\n", i, path);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!state.emmc_gpp_fds.empty()) {
|
||||
printf("[emu] GPP rawnand opened (%zu parts starting with %s.00)\n",
|
||||
state.emmc_gpp_fds.size(), rawnand_prefix);
|
||||
}
|
||||
}
|
||||
|
||||
// Setup ARM emulation
|
||||
uc_engine *uc = setup_emulation(&state, payload, payload_size);
|
||||
free(payload);
|
||||
if (!uc) return 1;
|
||||
|
||||
// Initialize SDL2 display
|
||||
if (!sdl_display_init()) {
|
||||
fprintf(stderr, "[error] Failed to initialize display\n");
|
||||
uc_close(uc);
|
||||
return 1;
|
||||
}
|
||||
|
||||
printf("\n[emu] Starting emulation...\n");
|
||||
printf("[emu] Press Escape to quit\n\n");
|
||||
|
||||
// ---- Emulation loop ----
|
||||
// We run emulation in batches, interleaving with SDL event handling
|
||||
// and display updates to keep the UI responsive.
|
||||
|
||||
const uint64_t BATCH_INSTRUCTIONS = 100000; // Instructions per batch
|
||||
const int DISPLAY_UPDATE_MS = 16; // ~60 FPS
|
||||
|
||||
auto last_display_update = std::chrono::steady_clock::now();
|
||||
|
||||
while (state.running) {
|
||||
// Process SDL events (keyboard input, window close)
|
||||
if (!sdl_display_poll_events(&state, uc)) break;
|
||||
|
||||
if (!state.paused) {
|
||||
uint32_t pc, cpsr;
|
||||
uc_reg_read(uc, UC_ARM_REG_PC, &pc);
|
||||
uc_reg_read(uc, UC_ARM_REG_CPSR, &cpsr);
|
||||
|
||||
// PC of an IPL btn_wait site in Hekate 6.5.2 — depending on build
|
||||
// this is "press any key", the Nyx fallback prompt, or similar.
|
||||
// We hold POWER for ~100 ticks to advance past it without manual
|
||||
// input. If a different Hekate stalls forever, capture the new PC
|
||||
// and update this constant.
|
||||
static int auto_enter_timer = 0;
|
||||
if (pc == 0x4000D14E || auto_enter_timer > 0) {
|
||||
if (auto_enter_timer < 100) {
|
||||
state.btn_power = true;
|
||||
auto_enter_timer++;
|
||||
if (auto_enter_timer == 100) {
|
||||
state.btn_power = false;
|
||||
printf("[emu] Auto-advanced past IPL btn_wait at PC=0x4000D14E\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- PIN recovery scripted navigation (Lockpick patch menu) ----
|
||||
// With EmuNAND grayed out (no emummc.ini), Lockpick's main menu
|
||||
// layout effectively becomes:
|
||||
// 0: Dump from SysNAND
|
||||
// 1: --- (was EmuNAND, grayed)
|
||||
// 2: --- (caption)
|
||||
// 3: Recover Parental PIN ← target (single VOL_DOWN reaches it)
|
||||
// Stage 1: VOL_DOWN to navigate. Stage 2: POWER press-then-release
|
||||
// (just long enough for the menu to dispatch recover_pin), then
|
||||
// idle so recover_pin's final btn_wait blocks on us — keeps the
|
||||
// result text visible in the framebuffer when the run times out.
|
||||
if (auto_pin_recovery) {
|
||||
static int pin_stage = 0;
|
||||
static uint64_t pin_t = 0;
|
||||
auto press_release = [&](std::atomic<bool> *btn,
|
||||
uint64_t hold_us,
|
||||
uint64_t cooldown_us) {
|
||||
if (state.emu_usec - pin_t < hold_us) {
|
||||
btn->store(true);
|
||||
} else if (state.emu_usec - pin_t < hold_us + cooldown_us) {
|
||||
btn->store(false);
|
||||
} else {
|
||||
pin_t = state.emu_usec;
|
||||
++pin_stage;
|
||||
}
|
||||
};
|
||||
if (pin_t == 0 && state.emu_usec > 6000000) {
|
||||
pin_t = state.emu_usec;
|
||||
pin_stage = 1;
|
||||
printf("[emu] Auto PIN recovery armed at emu_usec=%llu\n",
|
||||
(unsigned long long)state.emu_usec);
|
||||
}
|
||||
static int last_logged_stage = -1;
|
||||
if (pin_stage != last_logged_stage) {
|
||||
printf("[emu] Auto PIN stage %d at emu_usec=%llu\n", pin_stage,
|
||||
(unsigned long long)state.emu_usec);
|
||||
last_logged_stage = pin_stage;
|
||||
}
|
||||
switch (pin_stage) {
|
||||
case 1: press_release(&state.btn_vol_down, 1500000, 1500000); break;
|
||||
case 2:
|
||||
if (state.emu_usec - pin_t < 1500000) {
|
||||
state.btn_power.store(true);
|
||||
} else if (state.emu_usec - pin_t < 3000000) {
|
||||
state.btn_power.store(false);
|
||||
} else {
|
||||
printf("[emu] Auto PIN recovery sequence done\n");
|
||||
pin_t = state.emu_usec;
|
||||
pin_stage = 3;
|
||||
}
|
||||
break;
|
||||
case 3: break; // Idle — let recover_pin run to completion.
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- TegraExplorer scripted nav (recover_pin.te) ----
|
||||
// Sequence captured from a manual interactive run on the same
|
||||
// testcase (sw051/13.2.1 + TegraExplorer.bin) and replayed
|
||||
// verbatim — emu_usec is deterministic, so identical timestamps
|
||||
// hit the UI in the same state.
|
||||
//
|
||||
// Flow: POWER (skip "Grabbing keys... done") → 13×VOL_DOWN
|
||||
// (reach recover_pin.te in main menu) → POWER (enter script)
|
||||
// → 1×VOL_DOWN (select "Recover from sysmmc") → POWER (run).
|
||||
// After the last POWER we idle: returning to TE's main menu
|
||||
// means the script crashed/errored; otherwise the PIN stays
|
||||
// painted in the framebuffer.
|
||||
if (auto_te_script) {
|
||||
struct InputEv { uint64_t at_us; char btn; bool down; };
|
||||
static const InputEv te_events[] = {
|
||||
// Skip "Grabbing keys... done"
|
||||
{3480000, 'P', true}, {3640000, 'P', false},
|
||||
// 13× VOL_DOWN to recover_pin.te
|
||||
{10080000, 'D', true}, {10460000, 'D', false},
|
||||
{10830000, 'D', true}, {11000000, 'D', false},
|
||||
{11340000, 'D', true}, {11540000, 'D', false},
|
||||
{11850000, 'D', true}, {12010000, 'D', false},
|
||||
{12330000, 'D', true}, {12540000, 'D', false},
|
||||
{12830000, 'D', true}, {13040000, 'D', false},
|
||||
{13360000, 'D', true}, {13580000, 'D', false},
|
||||
{13900000, 'D', true}, {14110000, 'D', false},
|
||||
{14420000, 'D', true}, {14650000, 'D', false},
|
||||
{14980000, 'D', true}, {15210000, 'D', false},
|
||||
{15550000, 'D', true}, {15760000, 'D', false},
|
||||
{16200000, 'D', true}, {16340000, 'D', false},
|
||||
// POWER → enter recover_pin.te
|
||||
{18110000, 'P', true}, {18310000, 'P', false},
|
||||
// VOL_DOWN → select "Recover from sysmmc"
|
||||
{21670000, 'D', true}, {21900000, 'D', false},
|
||||
// POWER → run script
|
||||
{22850000, 'P', true}, {23020000, 'P', false},
|
||||
};
|
||||
static const size_t te_n = sizeof(te_events)/sizeof(te_events[0]);
|
||||
static size_t te_idx = 0;
|
||||
while (te_idx < te_n && state.emu_usec >= te_events[te_idx].at_us) {
|
||||
const InputEv &ev = te_events[te_idx];
|
||||
std::atomic<bool> *btn = (ev.btn == 'P') ? &state.btn_power
|
||||
: (ev.btn == 'D') ? &state.btn_vol_down
|
||||
: &state.btn_vol_up;
|
||||
btn->store(ev.down);
|
||||
printf("[auto-te] %s %s @emu_usec=%llu (event %zu/%zu)\n",
|
||||
ev.down ? "DOWN" : "UP ",
|
||||
ev.btn == 'P' ? "POWER " :
|
||||
ev.btn == 'D' ? "VOL_DOWN" : "VOL_UP ",
|
||||
(unsigned long long)state.emu_usec, te_idx + 1, te_n);
|
||||
te_idx++;
|
||||
if (te_idx == te_n)
|
||||
printf("[auto-te] sequence complete; idling for output\n");
|
||||
}
|
||||
}
|
||||
|
||||
// Touch injection for the Nyx GUI popup (eMMC Issues Warning).
|
||||
// Nyx initializes after the IPL stage; we inject a tap once enough
|
||||
// emulated time has passed for Nyx to load and render its dialog.
|
||||
// touch_x/y are portrait coordinates (720x1280 space); Nyx maps them
|
||||
// to landscape (1280x720) internally.
|
||||
// Default: (360, 640) = portrait center. Tune if the OK button
|
||||
// is not hit (e.g. try touch_x=490, touch_y=640 for the actual button).
|
||||
if (state.emu_usec > 3000000 && state.touch_phase == 0) {
|
||||
state.touch_phase = 1;
|
||||
printf("[emu] Touch injection armed: portrait (%d,%d)\n",
|
||||
state.touch_x, state.touch_y);
|
||||
}
|
||||
|
||||
// Run a batch of ARM instructions
|
||||
uint32_t start_addr = pc;
|
||||
if (cpsr & (1 << 5)) start_addr |= 1;
|
||||
|
||||
uc_err err = uc_emu_start(uc, start_addr, 0, 0, BATCH_INSTRUCTIONS);
|
||||
if (err != UC_ERR_OK) {
|
||||
uint32_t error_pc;
|
||||
uc_reg_read(uc, UC_ARM_REG_PC, &error_pc);
|
||||
fprintf(stderr, "\n[emu] FATAL: Emulation error at PC=0x%08X: %s\n", error_pc, uc_strerror(err));
|
||||
state.running = false;
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
||||
}
|
||||
|
||||
// Update display periodically
|
||||
auto now = std::chrono::steady_clock::now();
|
||||
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now - last_display_update);
|
||||
if (elapsed.count() >= DISPLAY_UPDATE_MS) {
|
||||
sdl_display_update(&state, uc);
|
||||
last_display_update = now;
|
||||
}
|
||||
}
|
||||
|
||||
// Cleanup
|
||||
printf("\n[emu] Shutting down...\n");
|
||||
|
||||
uint32_t final_pc;
|
||||
uc_reg_read(uc, UC_ARM_REG_PC, &final_pc);
|
||||
printf("[emu] Final PC: 0x%08X\n", final_pc);
|
||||
|
||||
// Print the instruction that it halted on as well as the previous 8 bytes
|
||||
uint16_t final_insn[8];
|
||||
if (uc_mem_read(uc, (final_pc & ~1) - 8, final_insn, 16) == UC_ERR_OK) {
|
||||
printf("[emu] Final INSNS (-8): %04X %04X %04X %04X %04X %04X %04X %04X\n",
|
||||
final_insn[0], final_insn[1], final_insn[2], final_insn[3],
|
||||
final_insn[4], final_insn[5], final_insn[6], final_insn[7]);
|
||||
}
|
||||
|
||||
sdl_display_shutdown();
|
||||
uc_close(uc);
|
||||
|
||||
free(state.iram_ptr);
|
||||
free(state.dram_ptr);
|
||||
// fb_ptr points inside dram_ptr; do not free separately.
|
||||
|
||||
printf("[emu] Done.\n");
|
||||
return 0;
|
||||
}
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build a FAT32 SD image from a source folder.
|
||||
|
||||
The output is an `sd.img` containing a single bootable FAT32 partition
|
||||
populated with the contents of `--src`. Usable directly with rcm_emu via
|
||||
`--sd sd.img`.
|
||||
|
||||
Requires Docker (uses an alpine container for dosfstools, mtools and
|
||||
util-linux).
|
||||
|
||||
Usage:
|
||||
python3 make_sd.py --src ./sd_root --out sd.img [--size-mb 512]
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
def build_sd_image(src_dir: str, out_img: str, size_mb: int) -> int:
|
||||
if not os.path.isdir(src_dir):
|
||||
print(f"[error] source folder not found: {src_dir}")
|
||||
return 1
|
||||
|
||||
src_dir_abs = os.path.abspath(src_dir)
|
||||
out_img_abs = os.path.abspath(out_img)
|
||||
work_dir = os.path.dirname(out_img_abs) or os.getcwd()
|
||||
img_name = os.path.basename(out_img_abs)
|
||||
fat_name = img_name + ".fat"
|
||||
|
||||
print(f"[*] source : {src_dir_abs}")
|
||||
print(f"[*] output : {out_img_abs}")
|
||||
print(f"[*] size : {size_mb} MB")
|
||||
|
||||
# Create a blank disk image and a slightly smaller blank FAT image.
|
||||
print(f"[*] allocating blank image files")
|
||||
disk_path = os.path.join(work_dir, img_name)
|
||||
fat_path = os.path.join(work_dir, fat_name)
|
||||
with open(disk_path, "wb") as f:
|
||||
f.seek(size_mb * 1024 * 1024 - 1)
|
||||
f.write(b"\0")
|
||||
with open(fat_path, "wb") as f:
|
||||
f.seek((size_mb - 1) * 1024 * 1024 - 1)
|
||||
f.write(b"\0")
|
||||
|
||||
print(f"[*] formatting + populating via Docker (alpine)")
|
||||
fdisk_script = f"o\\nn\\np\\n1\\n2048\\n\\nt\\nc\\nw\\n"
|
||||
docker_cmd = [
|
||||
"docker", "run", "--rm",
|
||||
"-v", f"{work_dir}:/work",
|
||||
"-v", f"{src_dir_abs}:/src:ro",
|
||||
"-w", "/work",
|
||||
"alpine",
|
||||
"sh", "-c",
|
||||
"apk add --no-cache dosfstools mtools util-linux >/dev/null && "
|
||||
f"mkfs.fat -F 32 -s 8 {fat_name} && "
|
||||
f"mcopy -i {fat_name} -s /src/* :: && "
|
||||
f"printf '{fdisk_script}' | fdisk {img_name} && "
|
||||
f"dd if={fat_name} of={img_name} bs=1M seek=1 conv=notrunc status=none"
|
||||
]
|
||||
try:
|
||||
subprocess.run(docker_cmd, check=True)
|
||||
except subprocess.CalledProcessError as e:
|
||||
print(f"[error] docker step failed: {e}")
|
||||
try:
|
||||
os.remove(fat_path)
|
||||
except OSError:
|
||||
pass
|
||||
return 1
|
||||
except FileNotFoundError:
|
||||
print("[error] docker not found. Install Docker Desktop or docker.io and retry.")
|
||||
try:
|
||||
os.remove(fat_path)
|
||||
except OSError:
|
||||
pass
|
||||
return 1
|
||||
|
||||
print("[*] cleanup")
|
||||
try:
|
||||
os.remove(fat_path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
print(f"[+] wrote {out_img_abs} ({size_mb} MB)")
|
||||
return 0
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description="Build a FAT32 SD image for rcm_emu.")
|
||||
ap.add_argument("--src", required=True, help="folder whose contents go into the FAT32 partition")
|
||||
ap.add_argument("--out", default="sd.img", help="output image path (default: sd.img)")
|
||||
ap.add_argument("--size-mb", type=int, default=512, help="image size in MB (default: 512)")
|
||||
args = ap.parse_args()
|
||||
return build_sd_image(args.src, args.out, args.size_mb)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+397
@@ -0,0 +1,397 @@
|
||||
#include "i2c3.h"
|
||||
#include "../emu_state.h"
|
||||
#include "memory_map.h"
|
||||
|
||||
#include <array>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
// ============================================================================
|
||||
// I²C3 + STMFTS (FTS4) touchscreen stub
|
||||
//
|
||||
// Reference:
|
||||
// - hekate/bdk/soc/i2c.c — Tegra I²C controller register protocol
|
||||
// - hekate/bdk/input/touch.{c,h} — STMFTS / FTS4 wire protocol on I²C3@0x49
|
||||
//
|
||||
// Hekate uses two I²C transfer modes:
|
||||
// * Normal mode: writes/reads ≤8 bytes via CMD_DATA1/CMD_DATA2 with a single
|
||||
// CMD_ADDR0+CNFG round-trip. Used for short FTS4 commands.
|
||||
// * Packet mode: variable-length, FIFO-driven. A 3-word header is pushed to
|
||||
// TX_FIFO, then payload words. Combined write+read sequences use a
|
||||
// REP_START header followed by a READ header. Used for FTS4 register
|
||||
// reads (HW_REG_READ, FB_REG_READ) and event polling.
|
||||
//
|
||||
// This stub captures TX bytes from both modes into `tx_buf`, runs an
|
||||
// `execute()` step that interprets the FTS4 command and produces RX bytes
|
||||
// in `rx_buf`, and serves those bytes back through CMD_DATA1/2 (normal) or
|
||||
// RX_FIFO (packet).
|
||||
// ============================================================================
|
||||
|
||||
namespace {
|
||||
|
||||
// ---- FTS4 command opcodes (subset we need) ----
|
||||
constexpr uint8_t FTS4_CMD_READ_INFO = 0x80;
|
||||
constexpr uint8_t FTS4_CMD_READ_STATUS = 0x84;
|
||||
constexpr uint8_t FTS4_CMD_READ_ONE_EVENT = 0x85;
|
||||
constexpr uint8_t FTS4_CMD_READ_ALL_EVENT = 0x86;
|
||||
constexpr uint8_t FTS4_CMD_LATEST_EVENT = 0x87;
|
||||
constexpr uint8_t FTS4_CMD_MS_MT_SENSE_OFF = 0x92;
|
||||
constexpr uint8_t FTS4_CMD_MS_MT_SENSE_ON = 0x93;
|
||||
constexpr uint8_t FTS4_CMD_SYSTEM_RESET = 0xA0;
|
||||
constexpr uint8_t FTS4_CMD_CLEAR_EVENT_STACK = 0xA1;
|
||||
constexpr uint8_t FTS4_CMD_HW_REG_READ = 0xB6; // also HW_REG_WRITE
|
||||
constexpr uint8_t FTS4_CMD_SWITCH_SENSE_MODE = 0xC3;
|
||||
constexpr uint8_t FTS4_CMD_FB_REG_READ = 0xD0; // also FB_REG_WRITE
|
||||
|
||||
// ---- FTS4 HW register addresses (accessed via 0xB6) ----
|
||||
constexpr uint16_t FTS4_HW_REG_CHIP_ID_INFO_ALT = 0x0002; // returns chip_id at bytes [3..4]
|
||||
constexpr uint16_t FTS4_HW_REG_CHIP_ID_INFO = 0x0004; // returns chip_id at bytes [1..2]
|
||||
constexpr uint16_t FTS4_HW_REG_EVENT_COUNT = 0x0023;
|
||||
constexpr uint16_t FTS4_HW_REG_SYS_RESET = 0x0028;
|
||||
|
||||
// ---- FTS4 chip identity ----
|
||||
constexpr uint16_t FTS4_CHIP_ID = 0x3670;
|
||||
|
||||
// ---- FTS4 event opcodes (low nibble of event[0]) ----
|
||||
constexpr uint8_t FTS4_EV_NO_EVENT = 0x00;
|
||||
constexpr uint8_t FTS4_EV_MULTI_TOUCH_ENTER = 0x03;
|
||||
constexpr uint8_t FTS4_EV_MULTI_TOUCH_LEAVE = 0x04;
|
||||
constexpr uint8_t FTS4_EV_MULTI_TOUCH_MOTION = 0x05;
|
||||
constexpr uint8_t FTS4_EV_CONTROLLER_READY = 0x10;
|
||||
|
||||
// ---- Tegra I²C packet header flags (mmio.h-style bit positions) ----
|
||||
constexpr uint32_t I2C_HEADER_CONT_XFER = 1u << 15;
|
||||
constexpr uint32_t I2C_HEADER_REP_START = 1u << 16;
|
||||
constexpr uint32_t I2C_HEADER_READ = 1u << 19;
|
||||
|
||||
// ---- I²C controller register offsets (within I2C3_BASE) ----
|
||||
constexpr uint32_t I2C_CNFG = 0x00;
|
||||
constexpr uint32_t I2C_CMD_ADDR0 = 0x04;
|
||||
constexpr uint32_t I2C_CMD_DATA1 = 0x0C;
|
||||
constexpr uint32_t I2C_CMD_DATA2 = 0x10;
|
||||
constexpr uint32_t I2C_STATUS = 0x1C;
|
||||
constexpr uint32_t I2C_TX_FIFO = 0x50;
|
||||
constexpr uint32_t I2C_RX_FIFO = 0x54;
|
||||
constexpr uint32_t I2C_PACKET_TRANSFER_STATUS = 0x58;
|
||||
constexpr uint32_t I2C_FIFO_CONTROL = 0x5C;
|
||||
constexpr uint32_t I2C_FIFO_STATUS = 0x60;
|
||||
constexpr uint32_t I2C_INT_STATUS = 0x68;
|
||||
constexpr uint32_t I2C_CONFIG_LOAD = 0x8C;
|
||||
|
||||
constexpr uint32_t CNFG_CMD1_READ = 1u << 6; // 0=write, 1=read
|
||||
constexpr uint32_t CNFG_NORMAL_MODE_GO = 1u << 9;
|
||||
constexpr uint32_t CNFG_PACKET_MODE_GO = 1u << 10;
|
||||
constexpr uint32_t INT_STATUS_BUS_CLEAR_DONE = 1u << 11;
|
||||
|
||||
// ---- I²C controller state ----
|
||||
uint8_t slave_addr = 0; // 7-bit target slave
|
||||
bool dir_read = false; // last direction set via CMD_ADDR0 / packet header
|
||||
uint32_t cmd_data[2] = {0}; // staged CMD_DATA1/CMD_DATA2 for normal-mode writes
|
||||
uint32_t last_cnfg = 0; // last value written to CNFG; the driver does a
|
||||
// read-modify-write to set NORMAL_MODE_GO, so we
|
||||
// must echo this back through i2c3_read.
|
||||
|
||||
// Packet-mode header parser
|
||||
enum PktState { PKT_HDR_W1, PKT_HDR_W2, PKT_HDR_W3, PKT_PAYLOAD };
|
||||
PktState pkt_state = PKT_HDR_W1;
|
||||
uint32_t pkt_size = 0; // expected payload bytes (size-1 from header word 2)
|
||||
uint32_t pkt_recv = 0; // payload bytes received so far
|
||||
bool pkt_is_combined = false; // true if write phase of REP_START combined op (defer execute)
|
||||
|
||||
// FTS4 command/response buffers
|
||||
std::vector<uint8_t> tx_buf; // accumulated TX bytes (cmd byte first)
|
||||
std::vector<uint8_t> rx_buf; // staged RX bytes
|
||||
size_t rx_pos = 0; // read pointer into rx_buf
|
||||
|
||||
// FTS4 event stack (head = oldest event). Each entry is one 8-byte event.
|
||||
std::vector<std::array<uint8_t, 8>> ev_stack;
|
||||
|
||||
// ---- Helpers ----
|
||||
|
||||
void push_event(uint8_t op, uint8_t finger, uint16_t x, uint16_t y, uint16_t pressure) {
|
||||
std::array<uint8_t, 8> ev = {0};
|
||||
ev[0] = (uint8_t)((finger << 4) | (op & 0x0F));
|
||||
ev[1] = (uint8_t)((x >> 4) & 0xFF);
|
||||
ev[2] = (uint8_t)((y >> 4) & 0xFF);
|
||||
ev[3] = (uint8_t)(((x & 0xF) << 4) | (y & 0xF));
|
||||
ev[4] = (uint8_t)(pressure & 0xFF);
|
||||
ev[5] = (uint8_t)((pressure >> 8) & 0xFF);
|
||||
ev[6] = 0x40; // pressure modifier sentinel — touch.c uses 0x40 fallback
|
||||
ev[7] = 0x00;
|
||||
if (ev_stack.size() < 32) ev_stack.push_back(ev);
|
||||
}
|
||||
|
||||
void push_controller_ready() {
|
||||
std::array<uint8_t, 8> ev = {FTS4_EV_CONTROLLER_READY, 0, 0, 0, 0, 0, 0, 0};
|
||||
if (ev_stack.size() < 32) ev_stack.push_back(ev);
|
||||
}
|
||||
|
||||
// If SDL has flagged a pending touch event, pack it into the FTS4 stack.
|
||||
void try_emit_pending_touch(EmuState *state) {
|
||||
bool was_pending = state->tc_event_pending.exchange(false);
|
||||
if (!was_pending) return;
|
||||
uint8_t op = state->tc_event_op.load();
|
||||
uint16_t x = state->tc_x.load();
|
||||
uint16_t y = state->tc_y.load();
|
||||
// pressure: a small non-zero value keeps z below the 500-palm-reject threshold
|
||||
// in touch.c (z = (pressure_lo|pressure_hi<<8) << 6 / (mod+0x40)).
|
||||
uint16_t pressure = (op == FTS4_EV_MULTI_TOUCH_LEAVE) ? 0 : 0x10;
|
||||
push_event(op, state->tc_finger_id, x, y, pressure);
|
||||
}
|
||||
|
||||
// Pop oldest event into 8-byte buffer; on empty, return NO_EVENT.
|
||||
void pop_event_to(uint8_t *buf) {
|
||||
if (ev_stack.empty()) {
|
||||
std::memset(buf, 0, 8);
|
||||
buf[0] = FTS4_EV_NO_EVENT;
|
||||
return;
|
||||
}
|
||||
std::memcpy(buf, ev_stack.front().data(), 8);
|
||||
ev_stack.erase(ev_stack.begin());
|
||||
}
|
||||
|
||||
// Run the buffered TX as an FTS4 command; populate rx_buf for the read phase.
|
||||
void execute(EmuState *state, uint32_t expected_rx_size) {
|
||||
rx_buf.clear();
|
||||
rx_pos = 0;
|
||||
if (tx_buf.empty()) return;
|
||||
|
||||
uint8_t cmd = tx_buf[0];
|
||||
|
||||
if (slave_addr != 0x49) {
|
||||
// Not the touchscreen — return zeros (no other slaves modelled on I²C3).
|
||||
if (dir_read) rx_buf.assign(expected_rx_size ? expected_rx_size : 1, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
switch (cmd) {
|
||||
case FTS4_CMD_HW_REG_READ: { // 0xB6 — also HW_REG_WRITE
|
||||
if (tx_buf.size() < 3) break;
|
||||
uint16_t reg = ((uint16_t)tx_buf[1] << 8) | tx_buf[2];
|
||||
if (dir_read) {
|
||||
// HW_REG_READ
|
||||
if (reg == FTS4_HW_REG_CHIP_ID_INFO) {
|
||||
// touch.c expects: chip_id = buf[1]<<8 | buf[2]; fw = buf[3]<<8 | buf[4]
|
||||
rx_buf = {0x00,
|
||||
(uint8_t)(FTS4_CHIP_ID >> 8), (uint8_t)(FTS4_CHIP_ID & 0xFF),
|
||||
0x00, 0x01, // fw_ver = 0x0001
|
||||
0x00, 0x00}; // config_id, config_ver
|
||||
} else if (reg == FTS4_HW_REG_CHIP_ID_INFO_ALT) {
|
||||
// Anti-clone check: chip_id at bytes [3..4]
|
||||
rx_buf = {0x00, 0x00, 0x00,
|
||||
(uint8_t)(FTS4_CHIP_ID >> 8), (uint8_t)(FTS4_CHIP_ID & 0xFF),
|
||||
0x00, 0x00};
|
||||
} else if (reg == FTS4_HW_REG_EVENT_COUNT) {
|
||||
try_emit_pending_touch(state);
|
||||
// touch_get_event_count: returns buf[1] >> 1
|
||||
uint8_t cnt = (uint8_t)ev_stack.size();
|
||||
rx_buf = {0x00, (uint8_t)(cnt << 1)};
|
||||
} else {
|
||||
rx_buf.assign(expected_rx_size ? expected_rx_size : 4, 0);
|
||||
}
|
||||
} else {
|
||||
// HW_REG_WRITE: tx_buf[1..2] = reg, tx_buf[3..] = value
|
||||
if (reg == FTS4_HW_REG_SYS_RESET && tx_buf.size() >= 4 && tx_buf[3] == 0x80) {
|
||||
ev_stack.clear();
|
||||
push_controller_ready();
|
||||
}
|
||||
// Other HW writes: ignored.
|
||||
}
|
||||
break;
|
||||
}
|
||||
case FTS4_CMD_FB_REG_READ: { // 0xD0
|
||||
// FB read of FW info etc — return zeros, Hekate just memcpys the result.
|
||||
rx_buf.assign(expected_rx_size ? expected_rx_size : 4, 0);
|
||||
break;
|
||||
}
|
||||
case FTS4_CMD_LATEST_EVENT:
|
||||
case FTS4_CMD_READ_ONE_EVENT:
|
||||
case FTS4_CMD_READ_ALL_EVENT: {
|
||||
try_emit_pending_touch(state);
|
||||
rx_buf.resize(8);
|
||||
pop_event_to(rx_buf.data());
|
||||
break;
|
||||
}
|
||||
case FTS4_CMD_SYSTEM_RESET:
|
||||
ev_stack.clear();
|
||||
push_controller_ready();
|
||||
break;
|
||||
case FTS4_CMD_CLEAR_EVENT_STACK:
|
||||
ev_stack.clear();
|
||||
break;
|
||||
case FTS4_CMD_MS_MT_SENSE_ON:
|
||||
case FTS4_CMD_MS_MT_SENSE_OFF:
|
||||
case FTS4_CMD_SWITCH_SENSE_MODE:
|
||||
case FTS4_CMD_READ_INFO:
|
||||
case FTS4_CMD_READ_STATUS:
|
||||
default:
|
||||
// Unmodelled writes are ACKed silently; unmodelled reads return zeros.
|
||||
if (dir_read) rx_buf.assign(expected_rx_size ? expected_rx_size : 1, 0);
|
||||
break;
|
||||
}
|
||||
|
||||
printf("[i2c3] EXEC slave=0x%02X dir=%c cmd=0x%02X tx=%zuB rx=%zuB stack=%zu\n",
|
||||
slave_addr, dir_read ? 'R' : 'W', cmd, tx_buf.size(), rx_buf.size(),
|
||||
ev_stack.size());
|
||||
}
|
||||
|
||||
// Pack up to 4 bytes from rx_buf at the current read pointer into a u32.
|
||||
uint32_t pull_rx_word() {
|
||||
uint32_t v = 0;
|
||||
for (size_t i = 0; i < 4 && rx_pos + i < rx_buf.size(); ++i) {
|
||||
v |= ((uint32_t)rx_buf[rx_pos + i]) << (i * 8);
|
||||
}
|
||||
rx_pos += 4;
|
||||
return v;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
uint32_t i2c3_read(EmuState *state, uint64_t addr) {
|
||||
uint32_t offset = (uint32_t)(addr - I2C3_BASE);
|
||||
switch (offset) {
|
||||
case I2C_CNFG:
|
||||
// The driver does CNFG = (CNFG & ~NORMAL_MODE_GO) | NORMAL_MODE_GO to kick
|
||||
// off a transfer; if we returned 0, the size field would be lost. Echo the
|
||||
// last written CNFG value back so the read-modify-write preserves config.
|
||||
return last_cnfg;
|
||||
case I2C_CMD_DATA1:
|
||||
return pull_rx_word();
|
||||
case I2C_CMD_DATA2:
|
||||
return pull_rx_word();
|
||||
case I2C_STATUS:
|
||||
return 0; // not busy, no NACK
|
||||
case I2C_RX_FIFO:
|
||||
return pull_rx_word();
|
||||
case I2C_PACKET_TRANSFER_STATUS: {
|
||||
// Bits 4..15 = bytes transferred. Driver compares == (size - 1).
|
||||
uint32_t bytes = pkt_size;
|
||||
return (bytes ? (bytes - 1) << 4 : 0);
|
||||
}
|
||||
case I2C_FIFO_STATUS: {
|
||||
size_t left = (rx_pos < rx_buf.size()) ? (rx_buf.size() - rx_pos) : 0;
|
||||
uint32_t words = (uint32_t)((left + 3) / 4);
|
||||
if (words > 8) words = 8;
|
||||
return words; // RX_FIFO_FULL_CNT in low 4 bits
|
||||
}
|
||||
case I2C_INT_STATUS:
|
||||
return INT_STATUS_BUS_CLEAR_DONE;
|
||||
case I2C_CONFIG_LOAD:
|
||||
return 0; // load complete
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
(void)state;
|
||||
}
|
||||
|
||||
void i2c3_write(EmuState *state, uint64_t addr, uint32_t val) {
|
||||
uint32_t offset = (uint32_t)(addr - I2C3_BASE);
|
||||
switch (offset) {
|
||||
case I2C_CNFG: {
|
||||
last_cnfg = val;
|
||||
bool packet_go = val & CNFG_PACKET_MODE_GO;
|
||||
bool normal_go = val & CNFG_NORMAL_MODE_GO;
|
||||
bool is_read = val & CNFG_CMD1_READ;
|
||||
uint32_t total = ((val >> 1) & 0x7) + 1; // (size-1)+1 in bits [3:1]
|
||||
|
||||
if (normal_go) {
|
||||
if (!is_read) {
|
||||
// Capture TX bytes from CMD_DATA1/CMD_DATA2.
|
||||
tx_buf.clear();
|
||||
for (uint32_t i = 0; i < total; ++i) {
|
||||
uint32_t word = (i < 4) ? cmd_data[0] : cmd_data[1];
|
||||
uint8_t b = (word >> ((i % 4) * 8)) & 0xFF;
|
||||
tx_buf.push_back(b);
|
||||
}
|
||||
dir_read = false;
|
||||
execute(state, 0);
|
||||
} else {
|
||||
// Read direction — rx_buf was prepared by the preceding write+execute.
|
||||
// Driver will read CMD_DATA1 (and DATA2 if total > 4) next.
|
||||
dir_read = true;
|
||||
// If no rx prepared (e.g. raw read with no preceding write), produce zeros.
|
||||
if (rx_buf.empty()) rx_buf.assign(total, 0);
|
||||
rx_pos = 0;
|
||||
}
|
||||
}
|
||||
if (packet_go) {
|
||||
// Reset packet header parser; subsequent TX_FIFO writes start a fresh packet.
|
||||
pkt_state = PKT_HDR_W1;
|
||||
pkt_size = 0;
|
||||
pkt_recv = 0;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case I2C_CMD_ADDR0:
|
||||
slave_addr = (val >> 1) & 0x7F;
|
||||
dir_read = (val & 1);
|
||||
break;
|
||||
case I2C_CMD_DATA1:
|
||||
cmd_data[0] = val;
|
||||
break;
|
||||
case I2C_CMD_DATA2:
|
||||
cmd_data[1] = val;
|
||||
break;
|
||||
case I2C_TX_FIFO: {
|
||||
switch (pkt_state) {
|
||||
case PKT_HDR_W1:
|
||||
pkt_state = PKT_HDR_W2;
|
||||
break;
|
||||
case PKT_HDR_W2:
|
||||
pkt_size = val + 1;
|
||||
pkt_state = PKT_HDR_W3;
|
||||
break;
|
||||
case PKT_HDR_W3: {
|
||||
bool is_read = val & I2C_HEADER_READ;
|
||||
bool is_rep_start = val & I2C_HEADER_REP_START;
|
||||
// Re-extract slave addr from header (bits 1..7 = addr<<1, bit 0 = R/W flag)
|
||||
uint8_t hdr_slave = (val >> 1) & 0x7F;
|
||||
slave_addr = hdr_slave;
|
||||
dir_read = is_read;
|
||||
|
||||
if (is_read) {
|
||||
// Combined read phase: produce RX from previously buffered TX.
|
||||
execute(state, pkt_size);
|
||||
pkt_state = PKT_HDR_W1;
|
||||
} else {
|
||||
// Write phase. Defer execute if a read header is expected to follow.
|
||||
tx_buf.clear();
|
||||
pkt_recv = 0;
|
||||
pkt_is_combined = is_rep_start;
|
||||
pkt_state = PKT_PAYLOAD;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case PKT_PAYLOAD:
|
||||
for (int b = 0; b < 4 && pkt_recv < pkt_size; ++b) {
|
||||
tx_buf.push_back((val >> (b * 8)) & 0xFF);
|
||||
pkt_recv++;
|
||||
}
|
||||
if (pkt_recv >= pkt_size) {
|
||||
if (!pkt_is_combined) {
|
||||
// Pure write (CONT_XFER) — execute now with no expected RX.
|
||||
execute(state, 0);
|
||||
}
|
||||
// Combined writes defer execution to the upcoming READ header.
|
||||
pkt_state = PKT_HDR_W1;
|
||||
}
|
||||
break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case I2C_FIFO_CONTROL:
|
||||
if (val & 0x1) { // RX_FIFO_FLUSH
|
||||
rx_pos = rx_buf.size();
|
||||
}
|
||||
break;
|
||||
case I2C_INT_STATUS:
|
||||
// Write-1-clear from driver — no internal state to clear.
|
||||
break;
|
||||
case I2C_CONFIG_LOAD:
|
||||
// Auto-clears in real HW; we already report 0 on read.
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
#ifndef T210_I2C3_H
|
||||
#define T210_I2C3_H
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
struct EmuState;
|
||||
|
||||
// I²C3 controller dispatcher (base 0x7000C500).
|
||||
// Models enough of the Tegra I²C controller state machine (normal + packet
|
||||
// modes) to satisfy Hekate's bdk/soc/i2c.c driver, with an STMFTS touchscreen
|
||||
// (FTS4) stub at slave 0x49 sitting behind it.
|
||||
uint32_t i2c3_read(EmuState *state, uint64_t addr);
|
||||
void i2c3_write(EmuState *state, uint64_t addr, uint32_t val);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,168 @@
|
||||
#ifndef T210_MEMORY_MAP_H
|
||||
#define T210_MEMORY_MAP_H
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
/*
|
||||
* Tegra X1 (T210) Memory Map for RCM Payload Emulation
|
||||
*
|
||||
* RCM payloads (hekate, etc.) run ARM32 code on the BPMP.
|
||||
* They primarily use IRAM and access hardware via MMIO registers.
|
||||
*/
|
||||
|
||||
// ==================== RAM Regions ====================
|
||||
|
||||
// IRAM (Internal SRAM) - 256KB
|
||||
constexpr uint64_t IRAM_BASE = 0x40000000;
|
||||
constexpr uint64_t IRAM_SIZE = (16 * 1024 * 1024); // 16 MB mapped (actual 512 KB, but hekate needs relocation space)
|
||||
|
||||
// DRAM - We allocate a modest amount for framebuffer + heap
|
||||
constexpr uint64_t DRAM_BASE = 0x80000000;
|
||||
constexpr uint64_t DRAM_SIZE = 0x80000000; // 2GB (Full T210 DRAM space for FatFs buffers)
|
||||
|
||||
// Payload load address within IRAM
|
||||
constexpr uint64_t IPL_LOAD_ADDR = 0x40010000;
|
||||
|
||||
// Stack addresses used by hekate
|
||||
constexpr uint64_t IPL_STACK_ADDR = 0x4003FF00;
|
||||
|
||||
// Heap (in DRAM)
|
||||
constexpr uint64_t IPL_HEAP_START = 0x90000000;
|
||||
constexpr uint64_t IPL_HEAP_SIZE = 0x02000000; // 32MB
|
||||
|
||||
// ==================== MMIO Regions ====================
|
||||
// All MMIO is in the 0x50000000-0x7FFFFFFF range on T210
|
||||
|
||||
// Clock and Reset Controller
|
||||
constexpr uint64_t CLK_RST_BASE = 0x60006000;
|
||||
constexpr uint64_t CLK_RST_SIZE = 0x1000;
|
||||
|
||||
// Timer (TMR)
|
||||
constexpr uint64_t TMR_BASE = 0x60005000;
|
||||
constexpr uint64_t TMR_SIZE = 0x1000;
|
||||
|
||||
// GPIO
|
||||
constexpr uint64_t GPIO_BASE = 0x6000D000;
|
||||
constexpr uint64_t GPIO_SIZE = 0x1000;
|
||||
|
||||
// PINMUX
|
||||
constexpr uint64_t PINMUX_BASE = 0x70003000;
|
||||
constexpr uint64_t PINMUX_SIZE = 0x1000;
|
||||
|
||||
// UART
|
||||
constexpr uint64_t UART_A_BASE = 0x70006000;
|
||||
constexpr uint64_t UART_SIZE = 0x1000;
|
||||
|
||||
// I2C controllers
|
||||
// Note: Tegra X1 base offsets per Hekate bdk/soc/i2c.c _i2c_base_offsets[]:
|
||||
// I2C1=0x0, I2C2=0x400, I2C3=0x500, I2C4=0x700, I2C5=0x1000, I2C6=0x1100
|
||||
// All measured from APB I2C base 0x7000C000.
|
||||
constexpr uint64_t I2C1_BASE = 0x7000C000;
|
||||
constexpr uint64_t I2C3_BASE = 0x7000C500; // GEN3_I2C, used by STMFTS touchscreen at slave 0x49
|
||||
constexpr uint64_t I2C5_BASE = 0x7000D000;
|
||||
constexpr uint64_t I2C_SIZE = 0x1000;
|
||||
constexpr uint64_t I2C3_SIZE = 0x100;
|
||||
|
||||
// PWM
|
||||
constexpr uint64_t PWM_BASE = 0x7000A000;
|
||||
constexpr uint64_t PWM_SIZE = 0x1000;
|
||||
|
||||
// RTC
|
||||
constexpr uint64_t RTC_BASE = 0x7000E000;
|
||||
constexpr uint64_t RTC_SIZE = 0x1000;
|
||||
|
||||
// PMC (Power Management Controller)
|
||||
constexpr uint64_t PMC_BASE = 0x7000E400;
|
||||
constexpr uint64_t PMC_SIZE = 0x0C00;
|
||||
|
||||
// Fuse Controller
|
||||
constexpr uint64_t FUSE_BASE = 0x7000F800;
|
||||
constexpr uint64_t FUSE_SIZE = 0x0400;
|
||||
|
||||
// EMC (External Memory Controller)
|
||||
constexpr uint64_t EMC_BASE = 0x7001B000;
|
||||
constexpr uint64_t EMC_SIZE = 0x1000;
|
||||
|
||||
// MC (Memory Controller)
|
||||
constexpr uint64_t MC_BASE = 0x70019000;
|
||||
constexpr uint64_t MC_SIZE = 0x1000;
|
||||
|
||||
// Display Controller (DC/DSI)
|
||||
constexpr uint64_t DISPLAY_A_BASE = 0x54200000;
|
||||
constexpr uint64_t DISPLAY_SIZE = 0x40000;
|
||||
|
||||
// DSI Controller
|
||||
constexpr uint64_t DSI_BASE = 0x54300000;
|
||||
constexpr uint64_t DSI_SIZE = 0x1000;
|
||||
|
||||
// MIPI CAL
|
||||
constexpr uint64_t MIPI_CAL_BASE = 0x700E3000;
|
||||
constexpr uint64_t MIPI_CAL_SIZE = 0x1000;
|
||||
|
||||
// SOR (Serial Output Resource) / HDMI
|
||||
constexpr uint64_t SOR_BASE = 0x54540000;
|
||||
constexpr uint64_t SOR_SIZE = 0x1000;
|
||||
|
||||
// SDMMC controllers
|
||||
constexpr uint64_t SDMMC1_BASE = 0x700B0000; // SD Card
|
||||
constexpr uint64_t SDMMC4_BASE = 0x700B0600; // eMMC
|
||||
constexpr uint64_t SDMMC_SIZE = 0x1000;
|
||||
|
||||
// APB Misc
|
||||
constexpr uint64_t APB_MISC_BASE = 0x70000000;
|
||||
constexpr uint64_t APB_MISC_SIZE = 0x1000;
|
||||
|
||||
// VIC (Video Image Compositor)
|
||||
constexpr uint64_t VIC_BASE = 0x54340000;
|
||||
constexpr uint64_t VIC_SIZE = 0x40000;
|
||||
|
||||
// Host1x (display sync)
|
||||
constexpr uint64_t HOST1X_BASE = 0x50000000;
|
||||
constexpr uint64_t HOST1X_SIZE = 0x40000;
|
||||
|
||||
// BPMP Cache
|
||||
constexpr uint64_t BPMP_CACHE_BASE = 0x50040000;
|
||||
constexpr uint64_t BPMP_CACHE_SIZE = 0x1000;
|
||||
|
||||
// System Registers (SYSREG)
|
||||
constexpr uint64_t SYSREG_BASE = 0x6000C000;
|
||||
constexpr uint64_t SYSREG_SIZE = 0x1000;
|
||||
|
||||
// I2S (Audio)
|
||||
constexpr uint64_t I2S_BASE = 0x702D1000;
|
||||
constexpr uint64_t I2S_SIZE = 0x1000;
|
||||
|
||||
// SE (Security Engine)
|
||||
constexpr uint64_t SE_BASE = 0x70012000;
|
||||
constexpr uint64_t SE_SIZE = 0x2000;
|
||||
|
||||
// TSEC (Falcon control regs are in the 0x1000–0x11FF window within TSEC_BASE)
|
||||
constexpr uint64_t TSEC_BASE = 0x54500000;
|
||||
constexpr uint64_t TSEC_SIZE = 0x2000;
|
||||
|
||||
// TZRAM
|
||||
constexpr uint64_t TZRAM_BASE = 0x7C010000;
|
||||
constexpr uint64_t TZRAM_SIZE = 0x10000; // 64KB
|
||||
|
||||
// System Registers (SYSCTR0)
|
||||
constexpr uint64_t SYSCTR0_BASE = 0x700F0000;
|
||||
constexpr uint64_t SYSCTR0_SIZE = 0x1000;
|
||||
|
||||
// ==================== Framebuffer ====================
|
||||
|
||||
// hekate uses a display window within DRAM for framebuffer
|
||||
// The display init code sets up a linear framebuffer at predefined addresses.
|
||||
// IPL_FB_ADDRESS is 0xF5A00000, NYX is 0xF6200000.
|
||||
// We allocate a 16MB block covering 0xF5A00000 - 0xF6A00000
|
||||
constexpr uint64_t FB_BASE = 0xF5A00000;
|
||||
constexpr uint64_t FB_SIZE = 0x01000000; // 16MB
|
||||
|
||||
// Display dimensions (hekate: 720 width, 1280 height in portrait)
|
||||
constexpr int DISPLAY_WIDTH = 720;
|
||||
constexpr int DISPLAY_HEIGHT = 1280;
|
||||
|
||||
// Landscape dimensions for SDL window
|
||||
constexpr int WINDOW_WIDTH = 720;
|
||||
constexpr int WINDOW_HEIGHT = 1280;
|
||||
|
||||
#endif // T210_MEMORY_MAP_H
|
||||
+1608
File diff suppressed because it is too large.
Load diff
+45
@@ -0,0 +1,45 @@
|
||||
#ifndef T210_MMIO_H
|
||||
#define T210_MMIO_H
|
||||
|
||||
#include <cstdint>
|
||||
#include <unicorn/unicorn.h>
|
||||
|
||||
/*
|
||||
* Tegra X1 MMIO Handler
|
||||
*
|
||||
* Routes memory-mapped IO reads/writes to peripheral handlers.
|
||||
* Unknown registers return 0 / ignore writes (permissive stub).
|
||||
*/
|
||||
|
||||
// Forward declarations for peripheral modules.
|
||||
struct EmuState;
|
||||
|
||||
// Initialize all MMIO hooks on the Unicorn engine.
|
||||
void mmio_init(uc_engine *uc, EmuState *state);
|
||||
|
||||
// Individual peripheral handlers.
|
||||
uint32_t timer_read(EmuState *state, uint64_t addr);
|
||||
void timer_write(EmuState *state, uint64_t addr, uint32_t val);
|
||||
|
||||
uint32_t gpio_read(EmuState *state, uint64_t addr);
|
||||
void gpio_write(EmuState *state, uint64_t addr, uint32_t val);
|
||||
|
||||
uint32_t i2c_read(EmuState *state, uint64_t addr);
|
||||
void i2c_write(EmuState *state, uint64_t addr, uint32_t val);
|
||||
|
||||
uint32_t display_read(EmuState *state, uint64_t addr);
|
||||
void display_write(EmuState *state, uint64_t addr, uint32_t val);
|
||||
|
||||
uint32_t pmc_read(EmuState *state, uint64_t addr);
|
||||
void pmc_write(EmuState *state, uint64_t addr, uint32_t val);
|
||||
|
||||
uint32_t clk_rst_read(EmuState *state, uint64_t addr);
|
||||
void clk_rst_write(EmuState *state, uint64_t addr, uint32_t val);
|
||||
|
||||
uint32_t fuse_read(EmuState *state, uint64_t addr);
|
||||
void fuse_write(EmuState *state, uint64_t addr, uint32_t val);
|
||||
|
||||
uint32_t misc_read(EmuState *state, uint64_t addr);
|
||||
void misc_write(uc_engine *uc, EmuState *state, uint64_t addr, int64_t value, int size);
|
||||
|
||||
#endif // T210_MMIO_H
|
||||
+239
@@ -0,0 +1,239 @@
|
||||
#include "sdmmc.h"
|
||||
#include "memory_map.h"
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/stat.h>
|
||||
#include <vector>
|
||||
#include <sys/types.h>
|
||||
|
||||
#define SDHCI_PRESENT_STATE 0x24
|
||||
#define SDHCI_CMD_REG 0x0E
|
||||
#define SDHCI_TRANSFER_MODE 0x0C
|
||||
#define SDHCI_BLOCK_SIZE 0x04
|
||||
#define SDHCI_BLOCK_COUNT 0x06
|
||||
#define SDHCI_ARGUMENT 0x08
|
||||
#define SDHCI_RESPONSE 0x10
|
||||
#define SDHCI_INT_STATUS 0x30
|
||||
#define SDHCI_ADMA_ADDR 0x58
|
||||
#define SDHCI_HOST_CONTROL 0x28
|
||||
|
||||
#define SDHCI_INT_RESPONSE 1
|
||||
#define SDHCI_INT_DATA_AVAIL (1 << 1)
|
||||
#define SDHCI_INT_DMA (1 << 3)
|
||||
#define SDHCI_INT_XFER_DONE (1 << 1) // In norintsts, bit 1 is Transfer Complete
|
||||
|
||||
// SDHCI Status Bits
|
||||
#define SDHCI_CMD_INHIBIT 1
|
||||
#define SDHCI_DATA_INHIBIT 2
|
||||
#define SDHCI_CARD_PRESENT (1 << 16)
|
||||
#define SDHCI_DATA_0_LVL (1 << 20)
|
||||
|
||||
void sdmmc_init_storage(EmuState *state) {
|
||||
if (state->sd_fd == -1) {
|
||||
state->sd_fd = open("sd_card.bin", O_RDWR);
|
||||
if (state->sd_fd == -1) {
|
||||
// Create a small empty file if it doesn't exist
|
||||
state->sd_fd = open("sd_card.bin", O_RDWR | O_CREAT, 0644);
|
||||
if (state->sd_fd != -1) {
|
||||
if (ftruncate(state->sd_fd, 64 * 1024 * 1024) != 0) perror("ftruncate sd_card.bin");
|
||||
}
|
||||
}
|
||||
}
|
||||
if (state->emmc_boot0_fd == -1) {
|
||||
state->emmc_boot0_fd = open("emmc_boot0.bin", O_RDWR | O_CREAT, 0644);
|
||||
if (state->emmc_boot0_fd != -1) {
|
||||
if (ftruncate(state->emmc_boot0_fd, 4 * 1024 * 1024) != 0) perror("ftruncate emmc_boot0.bin");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void handle_adma2(uc_engine *uc, EmuState *state, int id) {
|
||||
uint64_t adma_addr = (id == 1) ? state->sdmmc_adma_addr : state->sdmmc4_adma_addr;
|
||||
int fd = (id == 1) ? state->sd_fd : state->emmc_boot0_fd; // Simple mock: always boot0 for now
|
||||
uint32_t arg = (id == 1) ? state->sdmmc_arg : state->sdmmc4_arg;
|
||||
uint16_t trn = (id == 1) ? state->sdmmc_trnmod : state->sdmmc4_trnmod;
|
||||
|
||||
// trn & 0x10 == 0x10 means READ
|
||||
if (!(trn & 0x10)) return;
|
||||
|
||||
// ADMA2 Descriptor Table
|
||||
struct {
|
||||
uint16_t attr;
|
||||
uint16_t len;
|
||||
uint32_t addr;
|
||||
} desc;
|
||||
|
||||
uint64_t sector = arg;
|
||||
if (id == 4) sector = arg; // Adjust if needed
|
||||
|
||||
while (true) {
|
||||
if (uc_mem_read(uc, adma_addr, &desc, sizeof(desc)) != UC_ERR_OK) break;
|
||||
|
||||
// Attr bits: 0=Valid, 1=End, 2=Int, 4=Act1, 5=Act2
|
||||
if (!(desc.attr & 1)) break; // Not valid
|
||||
|
||||
uint32_t act = (desc.attr >> 4) & 3;
|
||||
if (act == 2) { // Transfer data
|
||||
uint32_t len = desc.len ? desc.len : 65536;
|
||||
std::vector<uint8_t> buffer(len);
|
||||
lseek(fd, (off_t)sector * 512, SEEK_SET);
|
||||
if (read(fd, buffer.data(), len) != (ssize_t)len) {
|
||||
// Handle short read or error if necessary
|
||||
}
|
||||
uc_mem_write(uc, desc.addr, buffer.data(), len);
|
||||
|
||||
sector += (len / 512);
|
||||
}
|
||||
|
||||
if (desc.attr & 2) break; // End bit
|
||||
adma_addr += 8;
|
||||
}
|
||||
|
||||
// Set Transfer Complete interrupt
|
||||
if (id == 1) state->sdmmc_norintsts |= 0x01;
|
||||
else state->sdmmc4_norintsts |= 0x01;
|
||||
}
|
||||
|
||||
static void handle_sd_command(uc_engine *uc, EmuState *state, int id, uint32_t cmd) {
|
||||
uint32_t *arg = (id == 1) ? &state->sdmmc_arg : &state->sdmmc4_arg;
|
||||
uint32_t *rsp = (id == 1) ? state->sdmmc_rsp : state->sdmmc4_rsp;
|
||||
uint32_t *norintsts = (id == 1) ? &state->sdmmc_norintsts : &state->sdmmc4_norintsts;
|
||||
bool *last_55 = (id == 1) ? &state->last_cmd_was_55 : &state->last_cmd4_was_55;
|
||||
|
||||
printf("[sdmmc%d] CMD%d Arg: 0x%08X\n", id, cmd, *arg);
|
||||
|
||||
*norintsts |= 0x01; // Command Complete interrupt
|
||||
|
||||
switch (cmd) {
|
||||
case 0: // GO_IDLE_STATE
|
||||
break;
|
||||
case 8: // SEND_IF_COND
|
||||
rsp[0] = *arg; // Echo check pattern
|
||||
break;
|
||||
case 55: // APP_CMD
|
||||
*last_55 = true;
|
||||
break;
|
||||
case 41: // ACMD41: SD_SEND_OP_COND
|
||||
if (*last_55) {
|
||||
rsp[0] = 0xC0FF8000; // Ready, High Capacity, Voltage range
|
||||
*last_55 = false;
|
||||
}
|
||||
break;
|
||||
case 1: // SEND_OP_COND (eMMC)
|
||||
rsp[0] = 0x80FF8080; // Ready, High Capacity
|
||||
break;
|
||||
case 2: // ALL_SEND_CID
|
||||
rsp[0] = 0x12345678;
|
||||
rsp[1] = 0xABCDEF01;
|
||||
rsp[2] = 0x23456789;
|
||||
rsp[3] = 0x88;
|
||||
break;
|
||||
case 3: // SEND_RELATIVE_ADDR
|
||||
rsp[0] = 0x00010000; // RCA = 1
|
||||
break;
|
||||
case 9: // SEND_CSD
|
||||
rsp[0] = 0x400E0032;
|
||||
rsp[1] = 0x5B590000;
|
||||
rsp[2] = 0x00007F3F;
|
||||
rsp[3] = 0x0A400000;
|
||||
break;
|
||||
case 7: // SELECT_CARD
|
||||
break;
|
||||
case 17: // READ_SINGLE_BLOCK
|
||||
case 18: // READ_MULTIPLE_BLOCK
|
||||
handle_adma2(uc, state, id);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
uint32_t sdmmc1_read(EmuState *state, uint64_t addr) {
|
||||
uint32_t offset = (uint32_t)(addr - SDMMC1_BASE);
|
||||
switch (offset) {
|
||||
case SDHCI_PRESENT_STATE:
|
||||
return SDHCI_CARD_PRESENT | SDHCI_DATA_0_LVL;
|
||||
case SDHCI_INT_STATUS:
|
||||
return state->sdmmc_norintsts | (state->sdmmc_errintsts << 16);
|
||||
case SDHCI_RESPONSE + 0: return state->sdmmc_rsp[0];
|
||||
case SDHCI_RESPONSE + 4: return state->sdmmc_rsp[1];
|
||||
case SDHCI_RESPONSE + 8: return state->sdmmc_rsp[2];
|
||||
case SDHCI_RESPONSE + 12: return state->sdmmc_rsp[3];
|
||||
case 0x1FC: return 0x0303; // Host Controller Version
|
||||
default: return 0;
|
||||
}
|
||||
}
|
||||
|
||||
void sdmmc1_write(uc_engine *uc, EmuState *state, uint64_t addr, uint32_t val) {
|
||||
uint32_t offset = (uint32_t)(addr - SDMMC1_BASE);
|
||||
switch (offset) {
|
||||
case SDHCI_ARGUMENT:
|
||||
state->sdmmc_arg = val;
|
||||
break;
|
||||
case SDHCI_CMD_REG:
|
||||
handle_sd_command(uc, state, 1, (val >> 8) & 0x3F);
|
||||
break;
|
||||
case SDHCI_TRANSFER_MODE:
|
||||
state->sdmmc_trnmod = val;
|
||||
break;
|
||||
case SDHCI_ADMA_ADDR:
|
||||
state->sdmmc_adma_addr = (state->sdmmc_adma_addr & 0xFFFFFFFF00000000ULL) | val;
|
||||
break;
|
||||
case SDHCI_ADMA_ADDR + 4:
|
||||
state->sdmmc_adma_addr = (state->sdmmc_adma_addr & 0xFFFFFFFFULL) | ((uint64_t)val << 32);
|
||||
break;
|
||||
case SDHCI_INT_STATUS:
|
||||
state->sdmmc_norintsts &= ~(val & 0xFFFF);
|
||||
state->sdmmc_errintsts &= ~(val >> 16);
|
||||
break;
|
||||
case 0x2C: // CLKCON - poll for stable
|
||||
// Reads of CLKCON return SDHCI_CLOCK_INT_STABLE; writes are dropped here
|
||||
// since this module's matching read path returns the stable bit unconditionally.
|
||||
(void)addr; (void)val; (void)state;
|
||||
break;
|
||||
case 0x2F: // SWRST
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
uint32_t sdmmc4_read(EmuState *state, uint64_t addr) {
|
||||
uint32_t offset = (uint32_t)(addr - SDMMC4_BASE);
|
||||
switch (offset) {
|
||||
case SDHCI_PRESENT_STATE:
|
||||
return SDHCI_CARD_PRESENT | SDHCI_DATA_0_LVL;
|
||||
case SDHCI_INT_STATUS:
|
||||
return state->sdmmc4_norintsts | (state->sdmmc4_errintsts << 16);
|
||||
case SDHCI_RESPONSE + 0: return state->sdmmc4_rsp[0];
|
||||
case SDHCI_RESPONSE + 4: return state->sdmmc4_rsp[1];
|
||||
case SDHCI_RESPONSE + 8: return state->sdmmc4_rsp[2];
|
||||
case SDHCI_RESPONSE + 12: return state->sdmmc4_rsp[3];
|
||||
default: return 0;
|
||||
}
|
||||
}
|
||||
|
||||
void sdmmc4_write(uc_engine *uc, EmuState *state, uint64_t addr, uint32_t val) {
|
||||
uint32_t offset = (uint32_t)(addr - SDMMC4_BASE);
|
||||
switch (offset) {
|
||||
case SDHCI_ARGUMENT:
|
||||
state->sdmmc4_arg = val;
|
||||
break;
|
||||
case SDHCI_CMD_REG:
|
||||
handle_sd_command(uc, state, 4, (val >> 8) & 0x3F);
|
||||
break;
|
||||
case SDHCI_TRANSFER_MODE:
|
||||
state->sdmmc4_trnmod = val;
|
||||
break;
|
||||
case SDHCI_ADMA_ADDR:
|
||||
state->sdmmc4_adma_addr = (state->sdmmc4_adma_addr & 0xFFFFFFFF00000000ULL) | val;
|
||||
break;
|
||||
case SDHCI_ADMA_ADDR + 4:
|
||||
state->sdmmc4_adma_addr = (state->sdmmc4_adma_addr & 0xFFFFFFFFULL) | ((uint64_t)val << 32);
|
||||
break;
|
||||
case SDHCI_INT_STATUS:
|
||||
state->sdmmc4_norintsts &= ~(val & 0xFFFF);
|
||||
state->sdmmc4_errintsts &= ~(val >> 16);
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
#include <unicorn/unicorn.h>
|
||||
#include "../emu_state.h"
|
||||
|
||||
void sdmmc_init_storage(EmuState *state);
|
||||
uint32_t sdmmc1_read(EmuState *state, uint64_t addr);
|
||||
void sdmmc1_write(uc_engine *uc, EmuState *state, uint64_t addr, uint32_t val);
|
||||
uint32_t sdmmc4_read(EmuState *state, uint64_t addr);
|
||||
void sdmmc4_write(uc_engine *uc, EmuState *state, uint64_t addr, uint32_t val);
|
||||
@@ -0,0 +1,758 @@
|
||||
#include "se_engine.h"
|
||||
#include "../emu_state.h"
|
||||
#include "memory_map.h"
|
||||
|
||||
#include <unicorn/unicorn.h>
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <cstdlib>
|
||||
|
||||
// =============================================================================
|
||||
// Tegra X1 Security Engine (SE) emulation
|
||||
//
|
||||
// Implements a useful subset of the SE so that Hekate's BDK and Lockpick_RCM's
|
||||
// key derivation pipelines run real AES-128 against the emulated keytable.
|
||||
//
|
||||
// References:
|
||||
// * hekate/bdk/sec/se.c (driver flow used by both payloads)
|
||||
// * Lockpick_RCM/bdk/sec/se_t210.h (register offsets / bitfields)
|
||||
// * Lockpick_RCM/source/keys/keys.c (uses cases: ECB, CTR, CMAC, unwrap)
|
||||
//
|
||||
// AES-128 implementation below is a compact reference variant adapted from
|
||||
// the public-domain "tiny-AES-c" project (Brad Conte / kokke). Only AES-128
|
||||
// is needed; 192/256 are unused by the BDK.
|
||||
// =============================================================================
|
||||
|
||||
// ---- SHA-256 (public-domain reference) --------------------------------------
|
||||
|
||||
namespace sha256 {
|
||||
|
||||
static const uint32_t K[64] = {
|
||||
0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,
|
||||
0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,
|
||||
0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,
|
||||
0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,
|
||||
0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,
|
||||
0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,
|
||||
0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,
|
||||
0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2,
|
||||
};
|
||||
|
||||
#define ROR32(x, n) (((x) >> (n)) | ((x) << (32 - (n))))
|
||||
|
||||
static void compute(const uint8_t *msg, uint32_t len, uint8_t out[32]) {
|
||||
uint32_t H[8] = {
|
||||
0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,
|
||||
0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19,
|
||||
};
|
||||
// Total padded length: msg + 0x80 + zeros + 8-byte length, multiple of 64
|
||||
uint64_t bitlen = (uint64_t)len * 8;
|
||||
uint32_t padded_len = ((len + 1 + 8 + 63) / 64) * 64;
|
||||
uint8_t *buf = (uint8_t*)std::calloc(1, padded_len);
|
||||
std::memcpy(buf, msg, len);
|
||||
buf[len] = 0x80;
|
||||
for (int i = 0; i < 8; i++) buf[padded_len - 1 - i] = (uint8_t)(bitlen >> (i * 8));
|
||||
for (uint32_t off = 0; off < padded_len; off += 64) {
|
||||
uint32_t W[64];
|
||||
for (int i = 0; i < 16; i++) {
|
||||
W[i] = ((uint32_t)buf[off + i*4 + 0] << 24) |
|
||||
((uint32_t)buf[off + i*4 + 1] << 16) |
|
||||
((uint32_t)buf[off + i*4 + 2] << 8) |
|
||||
((uint32_t)buf[off + i*4 + 3]);
|
||||
}
|
||||
for (int i = 16; i < 64; i++) {
|
||||
uint32_t s0 = ROR32(W[i-15],7) ^ ROR32(W[i-15],18) ^ (W[i-15] >> 3);
|
||||
uint32_t s1 = ROR32(W[i-2],17) ^ ROR32(W[i-2],19) ^ (W[i-2] >> 10);
|
||||
W[i] = W[i-16] + s0 + W[i-7] + s1;
|
||||
}
|
||||
uint32_t a=H[0],b=H[1],c=H[2],d=H[3],e=H[4],f=H[5],g=H[6],h=H[7];
|
||||
for (int i = 0; i < 64; i++) {
|
||||
uint32_t S1 = ROR32(e,6) ^ ROR32(e,11) ^ ROR32(e,25);
|
||||
uint32_t ch = (e & f) ^ ((~e) & g);
|
||||
uint32_t t1 = h + S1 + ch + K[i] + W[i];
|
||||
uint32_t S0 = ROR32(a,2) ^ ROR32(a,13) ^ ROR32(a,22);
|
||||
uint32_t mj = (a & b) ^ (a & c) ^ (b & c);
|
||||
uint32_t t2 = S0 + mj;
|
||||
h=g; g=f; f=e; e=d+t1; d=c; c=b; b=a; a=t1+t2;
|
||||
}
|
||||
H[0]+=a; H[1]+=b; H[2]+=c; H[3]+=d;
|
||||
H[4]+=e; H[5]+=f; H[6]+=g; H[7]+=h;
|
||||
}
|
||||
std::free(buf);
|
||||
for (int i = 0; i < 8; i++) {
|
||||
out[i*4 + 0] = (uint8_t)(H[i] >> 24);
|
||||
out[i*4 + 1] = (uint8_t)(H[i] >> 16);
|
||||
out[i*4 + 2] = (uint8_t)(H[i] >> 8);
|
||||
out[i*4 + 3] = (uint8_t)(H[i]);
|
||||
}
|
||||
}
|
||||
|
||||
#undef ROR32
|
||||
|
||||
} // namespace sha256
|
||||
|
||||
// ---- AES-128 (public-domain reference) --------------------------------------
|
||||
|
||||
namespace aes {
|
||||
|
||||
static const uint8_t Sbox[256] = {
|
||||
0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76,
|
||||
0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0,
|
||||
0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15,
|
||||
0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a,0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75,
|
||||
0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0,0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84,
|
||||
0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b,0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf,
|
||||
0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85,0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8,
|
||||
0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5,0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2,
|
||||
0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17,0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73,
|
||||
0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88,0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb,
|
||||
0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c,0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79,
|
||||
0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9,0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08,
|
||||
0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6,0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a,
|
||||
0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e,0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e,
|
||||
0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf,
|
||||
0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16
|
||||
};
|
||||
|
||||
static const uint8_t InvSbox[256] = {
|
||||
0x52,0x09,0x6a,0xd5,0x30,0x36,0xa5,0x38,0xbf,0x40,0xa3,0x9e,0x81,0xf3,0xd7,0xfb,
|
||||
0x7c,0xe3,0x39,0x82,0x9b,0x2f,0xff,0x87,0x34,0x8e,0x43,0x44,0xc4,0xde,0xe9,0xcb,
|
||||
0x54,0x7b,0x94,0x32,0xa6,0xc2,0x23,0x3d,0xee,0x4c,0x95,0x0b,0x42,0xfa,0xc3,0x4e,
|
||||
0x08,0x2e,0xa1,0x66,0x28,0xd9,0x24,0xb2,0x76,0x5b,0xa2,0x49,0x6d,0x8b,0xd1,0x25,
|
||||
0x72,0xf8,0xf6,0x64,0x86,0x68,0x98,0x16,0xd4,0xa4,0x5c,0xcc,0x5d,0x65,0xb6,0x92,
|
||||
0x6c,0x70,0x48,0x50,0xfd,0xed,0xb9,0xda,0x5e,0x15,0x46,0x57,0xa7,0x8d,0x9d,0x84,
|
||||
0x90,0xd8,0xab,0x00,0x8c,0xbc,0xd3,0x0a,0xf7,0xe4,0x58,0x05,0xb8,0xb3,0x45,0x06,
|
||||
0xd0,0x2c,0x1e,0x8f,0xca,0x3f,0x0f,0x02,0xc1,0xaf,0xbd,0x03,0x01,0x13,0x8a,0x6b,
|
||||
0x3a,0x91,0x11,0x41,0x4f,0x67,0xdc,0xea,0x97,0xf2,0xcf,0xce,0xf0,0xb4,0xe6,0x73,
|
||||
0x96,0xac,0x74,0x22,0xe7,0xad,0x35,0x85,0xe2,0xf9,0x37,0xe8,0x1c,0x75,0xdf,0x6e,
|
||||
0x47,0xf1,0x1a,0x71,0x1d,0x29,0xc5,0x89,0x6f,0xb7,0x62,0x0e,0xaa,0x18,0xbe,0x1b,
|
||||
0xfc,0x56,0x3e,0x4b,0xc6,0xd2,0x79,0x20,0x9a,0xdb,0xc0,0xfe,0x78,0xcd,0x5a,0xf4,
|
||||
0x1f,0xdd,0xa8,0x33,0x88,0x07,0xc7,0x31,0xb1,0x12,0x10,0x59,0x27,0x80,0xec,0x5f,
|
||||
0x60,0x51,0x7f,0xa9,0x19,0xb5,0x4a,0x0d,0x2d,0xe5,0x7a,0x9f,0x93,0xc9,0x9c,0xef,
|
||||
0xa0,0xe0,0x3b,0x4d,0xae,0x2a,0xf5,0xb0,0xc8,0xeb,0xbb,0x3c,0x83,0x53,0x99,0x61,
|
||||
0x17,0x2b,0x04,0x7e,0xba,0x77,0xd6,0x26,0xe1,0x69,0x14,0x63,0x55,0x21,0x0c,0x7d
|
||||
};
|
||||
|
||||
static const uint8_t Rcon[11] = {0x00,0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80,0x1b,0x36};
|
||||
|
||||
static inline uint8_t xtime(uint8_t x) { return (uint8_t)((x << 1) ^ (((x >> 7) & 1) * 0x1b)); }
|
||||
static inline uint8_t mul(uint8_t x, uint8_t y) {
|
||||
uint8_t r = 0;
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
if (y & 1) r ^= x;
|
||||
x = xtime(x);
|
||||
y >>= 1;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
// 11 round keys × 16 bytes = 176 bytes.
|
||||
static void key_expand(const uint8_t key[16], uint8_t rk[176]) {
|
||||
std::memcpy(rk, key, 16);
|
||||
uint32_t i = 16;
|
||||
uint8_t tmp[4];
|
||||
while (i < 176) {
|
||||
tmp[0] = rk[i - 4]; tmp[1] = rk[i - 3]; tmp[2] = rk[i - 2]; tmp[3] = rk[i - 1];
|
||||
if ((i % 16) == 0) {
|
||||
// RotWord + SubWord + Rcon
|
||||
uint8_t t = tmp[0]; tmp[0] = tmp[1]; tmp[1] = tmp[2]; tmp[2] = tmp[3]; tmp[3] = t;
|
||||
tmp[0] = Sbox[tmp[0]]; tmp[1] = Sbox[tmp[1]];
|
||||
tmp[2] = Sbox[tmp[2]]; tmp[3] = Sbox[tmp[3]];
|
||||
tmp[0] ^= Rcon[i / 16];
|
||||
}
|
||||
rk[i + 0] = rk[i - 16 + 0] ^ tmp[0];
|
||||
rk[i + 1] = rk[i - 16 + 1] ^ tmp[1];
|
||||
rk[i + 2] = rk[i - 16 + 2] ^ tmp[2];
|
||||
rk[i + 3] = rk[i - 16 + 3] ^ tmp[3];
|
||||
i += 4;
|
||||
}
|
||||
}
|
||||
|
||||
static void add_rk(uint8_t s[16], const uint8_t *rk) {
|
||||
for (int i = 0; i < 16; ++i) s[i] ^= rk[i];
|
||||
}
|
||||
static void sub_bytes(uint8_t s[16]) { for (int i = 0; i < 16; ++i) s[i] = Sbox[s[i]]; }
|
||||
static void inv_sub_bytes(uint8_t s[16]){ for (int i = 0; i < 16; ++i) s[i] = InvSbox[s[i]]; }
|
||||
static void shift_rows(uint8_t s[16]) {
|
||||
uint8_t t;
|
||||
t = s[1]; s[1] = s[5]; s[5] = s[9]; s[9] = s[13]; s[13] = t;
|
||||
t = s[2]; s[2] = s[10]; s[10] = t; t = s[6]; s[6] = s[14]; s[14] = t;
|
||||
t = s[15]; s[15] = s[11]; s[11] = s[7]; s[7] = s[3]; s[3] = t;
|
||||
}
|
||||
static void inv_shift_rows(uint8_t s[16]) {
|
||||
uint8_t t;
|
||||
t = s[13]; s[13] = s[9]; s[9] = s[5]; s[5] = s[1]; s[1] = t;
|
||||
t = s[2]; s[2] = s[10]; s[10] = t; t = s[6]; s[6] = s[14]; s[14] = t;
|
||||
t = s[3]; s[3] = s[7]; s[7] = s[11]; s[11] = s[15]; s[15] = t;
|
||||
}
|
||||
static void mix_cols(uint8_t s[16]) {
|
||||
for (int c = 0; c < 4; ++c) {
|
||||
uint8_t a0 = s[4*c+0], a1 = s[4*c+1], a2 = s[4*c+2], a3 = s[4*c+3];
|
||||
uint8_t t = a0 ^ a1 ^ a2 ^ a3;
|
||||
s[4*c+0] ^= t ^ xtime(a0 ^ a1);
|
||||
s[4*c+1] ^= t ^ xtime(a1 ^ a2);
|
||||
s[4*c+2] ^= t ^ xtime(a2 ^ a3);
|
||||
s[4*c+3] ^= t ^ xtime(a3 ^ a0);
|
||||
}
|
||||
}
|
||||
static void inv_mix_cols(uint8_t s[16]) {
|
||||
for (int c = 0; c < 4; ++c) {
|
||||
uint8_t a = s[4*c+0], b = s[4*c+1], cc = s[4*c+2], d = s[4*c+3];
|
||||
s[4*c+0] = mul(a,0x0e) ^ mul(b,0x0b) ^ mul(cc,0x0d) ^ mul(d,0x09);
|
||||
s[4*c+1] = mul(a,0x09) ^ mul(b,0x0e) ^ mul(cc,0x0b) ^ mul(d,0x0d);
|
||||
s[4*c+2] = mul(a,0x0d) ^ mul(b,0x09) ^ mul(cc,0x0e) ^ mul(d,0x0b);
|
||||
s[4*c+3] = mul(a,0x0b) ^ mul(b,0x0d) ^ mul(cc,0x09) ^ mul(d,0x0e);
|
||||
}
|
||||
}
|
||||
|
||||
static void encrypt_block(const uint8_t in[16], uint8_t out[16], const uint8_t rk[176]) {
|
||||
uint8_t s[16]; std::memcpy(s, in, 16);
|
||||
add_rk(s, rk);
|
||||
for (int r = 1; r < 10; ++r) {
|
||||
sub_bytes(s); shift_rows(s); mix_cols(s); add_rk(s, rk + r*16);
|
||||
}
|
||||
sub_bytes(s); shift_rows(s); add_rk(s, rk + 160);
|
||||
std::memcpy(out, s, 16);
|
||||
}
|
||||
|
||||
static void decrypt_block(const uint8_t in[16], uint8_t out[16], const uint8_t rk[176]) {
|
||||
uint8_t s[16]; std::memcpy(s, in, 16);
|
||||
add_rk(s, rk + 160);
|
||||
for (int r = 9; r >= 1; --r) {
|
||||
inv_shift_rows(s); inv_sub_bytes(s); add_rk(s, rk + r*16); inv_mix_cols(s);
|
||||
}
|
||||
inv_shift_rows(s); inv_sub_bytes(s); add_rk(s, rk);
|
||||
std::memcpy(out, s, 16);
|
||||
}
|
||||
|
||||
} // namespace aes
|
||||
|
||||
// ---- SE register state ------------------------------------------------------
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr uint32_t SE_OPERATION_REG = 0x008;
|
||||
constexpr uint32_t SE_INT_ENABLE_REG = 0x00C;
|
||||
constexpr uint32_t SE_INT_STATUS_REG = 0x010;
|
||||
constexpr uint32_t SE_CONFIG_REG = 0x014;
|
||||
constexpr uint32_t SE_IN_LL_ADDR_REG = 0x018;
|
||||
constexpr uint32_t SE_OUT_LL_ADDR_REG = 0x024;
|
||||
constexpr uint32_t SE_CRYPTO_LAST_BLOCK = 0x080;
|
||||
constexpr uint32_t SE_CRYPTO_CONFIG_REG = 0x304;
|
||||
constexpr uint32_t SE_CRYPTO_LINEAR_CTR_REG = 0x308; // 4 dwords
|
||||
constexpr uint32_t SE_CRYPTO_BLOCK_COUNT_REG = 0x318;
|
||||
constexpr uint32_t SE_CRYPTO_KEYTABLE_ADDR = 0x31C;
|
||||
constexpr uint32_t SE_CRYPTO_KEYTABLE_DATA = 0x320;
|
||||
constexpr uint32_t SE_CRYPTO_KEYTABLE_DST = 0x330;
|
||||
constexpr uint32_t SE_RNG_CONFIG_REG = 0x340;
|
||||
constexpr uint32_t SE_HASH_RESULT_REG = 0x030; // 16 dwords
|
||||
constexpr uint32_t SE_STATUS_REG = 0x800;
|
||||
constexpr uint32_t SE_ERR_STATUS_REG = 0x804;
|
||||
|
||||
constexpr uint32_t SE_INT_OP_DONE = 1u << 4;
|
||||
|
||||
constexpr uint32_t ALG_NOP = 0;
|
||||
constexpr uint32_t ALG_AES_DEC = 1;
|
||||
constexpr uint32_t ALG_AES_ENC = 1; // same numeric value; chosen via dec/enc field
|
||||
|
||||
constexpr uint32_t DST_MEMORY = 0;
|
||||
constexpr uint32_t DST_HASHREG = 1;
|
||||
constexpr uint32_t DST_KEYTABLE = 2;
|
||||
|
||||
constexpr uint32_t XOR_BYPASS = 0;
|
||||
constexpr uint32_t XOR_TOP = 2;
|
||||
constexpr uint32_t XOR_BOTTOM = 3;
|
||||
|
||||
constexpr uint32_t INPUT_MEMORY = 0;
|
||||
constexpr uint32_t INPUT_AESOUT = 2;
|
||||
constexpr uint32_t INPUT_LNR_CTR = 3;
|
||||
|
||||
constexpr uint32_t VCTRAM_MEM = 0;
|
||||
constexpr uint32_t VCTRAM_AESOUT = 2;
|
||||
constexpr uint32_t VCTRAM_PREVMEM = 3;
|
||||
|
||||
constexpr uint32_t IV_ORIGINAL = 0;
|
||||
constexpr uint32_t IV_UPDATED = 1;
|
||||
|
||||
constexpr uint32_t CORE_DECRYPT = 0;
|
||||
constexpr uint32_t CORE_ENCRYPT = 1;
|
||||
|
||||
// 16 keyslots, each 32 bytes (256-bit max — 2 quads)
|
||||
struct Keyslot {
|
||||
uint8_t key[32]; // KEYS_0_3 + KEYS_4_7
|
||||
uint8_t iv_orig[16];
|
||||
uint8_t iv_upd[16];
|
||||
};
|
||||
static Keyslot ks_table[16];
|
||||
|
||||
// BIS key override: when --prod-keys is supplied, the bis_key_NN values from
|
||||
// it are stashed here. Anytime Lockpick writes to slots 0-5 (the BIS keytable
|
||||
// slots), we substitute the prod.keys value instead of the derived one. This
|
||||
// sidesteps any rounding errors / mismatched key sources in our SE-based key
|
||||
// derivation chain (we get the wrong tsec→master_kek→master_key→bis_kek path
|
||||
// for some firmware versions, but the user already knows the right BIS keys
|
||||
// because their prod.keys file says so).
|
||||
static bool bis_override_present[6] = {false, false, false, false, false, false};
|
||||
static uint8_t bis_override_keys[6][16] = {0};
|
||||
|
||||
static uint32_t reg_config = 0;
|
||||
static uint32_t reg_crypto_config = 0;
|
||||
static uint32_t reg_in_ll_addr = 0;
|
||||
static uint32_t reg_out_ll_addr = 0;
|
||||
static uint32_t reg_block_count = 0;
|
||||
static uint32_t reg_keytable_addr = 0;
|
||||
static uint32_t reg_keytable_dst = 0;
|
||||
static uint32_t reg_op = 0;
|
||||
static uint32_t reg_int_status = 0;
|
||||
static uint32_t reg_int_enable = 0;
|
||||
static uint32_t linear_ctr[4] = {0};
|
||||
static uint32_t hash_result[16] = {0};
|
||||
static uint32_t reg_err_status = 0;
|
||||
static uint32_t reg_rng_config = 0;
|
||||
static uint32_t spare_regs[256] = {0}; // catch-all for less critical regs
|
||||
|
||||
// LL descriptor: { num, addr, size }. Hekate often uses num=0 (single descriptor).
|
||||
struct LLDesc { uint32_t num, addr, size; };
|
||||
|
||||
static bool read_ll(uc_engine *uc, uint32_t ll_addr, LLDesc *out) {
|
||||
if (!ll_addr) return false;
|
||||
if (uc_mem_read(uc, ll_addr, out, sizeof(LLDesc)) != UC_ERR_OK) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Encrypt/decrypt a buffer in-place using the keyslot's key (assumes 128-bit).
|
||||
static void run_aes_blocks(uint32_t slot, bool encrypt,
|
||||
const uint8_t *in, uint8_t *out, size_t blocks,
|
||||
uint32_t xor_pos, uint32_t input_sel,
|
||||
uint32_t vctram_sel, uint32_t iv_sel,
|
||||
bool ctr_mode, bool hash_mode) {
|
||||
uint8_t rk[176];
|
||||
aes::key_expand(ks_table[slot].key, rk);
|
||||
|
||||
// Pick which IV to use for chaining. Hekate typically uses ORIGINAL_IV for
|
||||
// CBC starts and switches to UPDATED_IV mid-CMAC; we honour that.
|
||||
uint8_t chain[16];
|
||||
if (iv_sel == IV_UPDATED) std::memcpy(chain, ks_table[slot].iv_upd, 16);
|
||||
else std::memcpy(chain, ks_table[slot].iv_orig, 16);
|
||||
|
||||
uint8_t prev_in[16] = {0};
|
||||
uint8_t hash_state[16] = {0}; // accumulator for HASH=1 (CMAC) — XOR top, encrypt
|
||||
if (hash_mode) std::memcpy(hash_state, chain, 16);
|
||||
|
||||
for (size_t i = 0; i < blocks; ++i) {
|
||||
uint8_t in_block[16];
|
||||
uint8_t out_block[16];
|
||||
|
||||
if (input_sel == INPUT_LNR_CTR) {
|
||||
// CTR mode input is the linear counter (big-endian 128-bit), per-block.
|
||||
// Our linear_ctr[] is stored as 4 dwords little-endian; assemble.
|
||||
uint8_t ctr_be[16];
|
||||
for (int j = 0; j < 4; ++j) {
|
||||
uint32_t w = linear_ctr[j];
|
||||
ctr_be[j*4 + 0] = (w >> 0) & 0xFF;
|
||||
ctr_be[j*4 + 1] = (w >> 8) & 0xFF;
|
||||
ctr_be[j*4 + 2] = (w >> 16) & 0xFF;
|
||||
ctr_be[j*4 + 3] = (w >> 24) & 0xFF;
|
||||
}
|
||||
std::memcpy(in_block, ctr_be, 16);
|
||||
} else if (input_sel == INPUT_AESOUT) {
|
||||
// Re-feeding previous AES output (used in some chained constructions).
|
||||
std::memcpy(in_block, prev_in, 16);
|
||||
} else {
|
||||
std::memcpy(in_block, in + i*16, 16);
|
||||
}
|
||||
|
||||
// VCTRAM source: the value XORed at XOR_TOP / XOR_BOTTOM.
|
||||
uint8_t vctram[16];
|
||||
if (vctram_sel == VCTRAM_AESOUT) std::memcpy(vctram, prev_in, 16);
|
||||
else if (vctram_sel == VCTRAM_PREVMEM) std::memcpy(vctram, (i==0)? chain : (in + (i-1)*16), 16);
|
||||
else std::memcpy(vctram, chain, 16);
|
||||
|
||||
if (xor_pos == XOR_TOP) {
|
||||
for (int j = 0; j < 16; ++j) in_block[j] ^= vctram[j];
|
||||
}
|
||||
|
||||
if (encrypt) aes::encrypt_block(in_block, out_block, rk);
|
||||
else aes::decrypt_block(in_block, out_block, rk);
|
||||
|
||||
if (xor_pos == XOR_BOTTOM) {
|
||||
// Output XOR with chain (CTR keystream XOR plaintext, etc.)
|
||||
const uint8_t *xb = (input_sel == INPUT_LNR_CTR)
|
||||
? (in + i*16) // CTR: XOR with plaintext from memory
|
||||
: vctram;
|
||||
for (int j = 0; j < 16; ++j) out_block[j] ^= xb[j];
|
||||
}
|
||||
|
||||
if (out) std::memcpy(out + i*16, out_block, 16);
|
||||
|
||||
// Advance chain for next block.
|
||||
if (xor_pos == XOR_BOTTOM && input_sel != INPUT_LNR_CTR) {
|
||||
// CBC encrypt: chain = ciphertext = out_block
|
||||
std::memcpy(chain, out_block, 16);
|
||||
} else if (xor_pos == XOR_TOP) {
|
||||
// CBC decrypt: chain = ciphertext (the input block we read)
|
||||
std::memcpy(chain, in + i*16, 16);
|
||||
}
|
||||
std::memcpy(prev_in, out_block, 16);
|
||||
|
||||
if (ctr_mode) {
|
||||
// Increment linear counter (big-endian 128-bit).
|
||||
for (int j = 15; j >= 0; --j) {
|
||||
uint8_t *p = (uint8_t*)linear_ctr;
|
||||
p[j]++;
|
||||
if (p[j]) break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (hash_mode) {
|
||||
// For HASH paths the final cipher block is exposed via SE_HASH_RESULT_REG.
|
||||
std::memcpy(hash_result, prev_in, 16);
|
||||
}
|
||||
// Save updated IV (chain) for next call's IV_UPDATED.
|
||||
std::memcpy(ks_table[slot].iv_upd, chain, 16);
|
||||
}
|
||||
|
||||
static void op_start(EmuState *state) {
|
||||
// Decode CONFIG / CRYPTO_CONFIG.
|
||||
uint32_t dst_kind = (reg_config >> 2) & 0x7;
|
||||
uint32_t enc_alg = (reg_config >> 12) & 0xF;
|
||||
uint32_t dec_alg = (reg_config >> 8) & 0xF;
|
||||
uint32_t enc_mode = (reg_config >> 24) & 0xFF;
|
||||
bool dec = (dec_alg == ALG_AES_DEC) && (enc_alg == ALG_NOP);
|
||||
bool enc = (enc_alg == ALG_AES_ENC) && (dec_alg == ALG_NOP);
|
||||
|
||||
// ---- SHA-256 path ----
|
||||
// ALG_SHA=3, MODE_SHA256=5, DST=DST_HASHREG. Driver flow: writes
|
||||
// SE_SHA_MSG_LENGTH/LEFT, sets up IN_LL pointing at src/src_size, then
|
||||
// OP_START. Output 32 bytes go into HASH_RESULT_REG as 8 big-endian dwords
|
||||
// (driver byte_swap_32's each on read). We currently only model the
|
||||
// oneshot case (SHA_INIT_HASH); save_process_header uses oneshot.
|
||||
if (enc_alg == 3 /*ALG_SHA*/ && dst_kind == DST_HASHREG && enc_mode == 5 /*MODE_SHA256*/) {
|
||||
LLDesc in_ll{};
|
||||
bool got_in = read_ll(state->uc, reg_in_ll_addr, &in_ll);
|
||||
if (!got_in || !in_ll.size) {
|
||||
reg_int_status |= SE_INT_OP_DONE;
|
||||
return;
|
||||
}
|
||||
std::vector<uint8_t> buf(in_ll.size, 0);
|
||||
uc_mem_read(state->uc, in_ll.addr, buf.data(), in_ll.size);
|
||||
uint8_t digest[32];
|
||||
sha256::compute(buf.data(), in_ll.size, digest);
|
||||
// Pack into HASH_RESULT_REG as 8 big-endian dwords (driver byteswaps).
|
||||
for (int i = 0; i < 8; i++) {
|
||||
hash_result[i] = ((uint32_t)digest[i*4 + 0] << 24) |
|
||||
((uint32_t)digest[i*4 + 1] << 16) |
|
||||
((uint32_t)digest[i*4 + 2] << 8) |
|
||||
((uint32_t)digest[i*4 + 3]);
|
||||
}
|
||||
std::printf("[se] SHA-256 over %u bytes @0x%X -> %02X%02X%02X%02X...\n",
|
||||
in_ll.size, in_ll.addr, digest[0], digest[1], digest[2], digest[3]);
|
||||
reg_int_status |= SE_INT_OP_DONE;
|
||||
return;
|
||||
}
|
||||
|
||||
if (dst_kind == 4 /* DST_RSAREG */) {
|
||||
// RSA not implemented — leave output zero.
|
||||
reg_int_status |= SE_INT_OP_DONE;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!dec && !enc) {
|
||||
reg_int_status |= SE_INT_OP_DONE;
|
||||
return;
|
||||
}
|
||||
|
||||
uint32_t xor_pos = (reg_crypto_config >> 1) & 0x3;
|
||||
uint32_t input_sel = (reg_crypto_config >> 3) & 0x3;
|
||||
uint32_t vctram_sel = (reg_crypto_config >> 5) & 0x3;
|
||||
uint32_t iv_sel = (reg_crypto_config >> 7) & 0x1;
|
||||
uint32_t core_sel = (reg_crypto_config >> 8) & 0x1;
|
||||
bool hash_en = (reg_crypto_config >> 0) & 0x1;
|
||||
uint32_t ctr_cnt = (reg_crypto_config >> 11) & 0x1;
|
||||
uint32_t key_index = (reg_crypto_config >> 24) & 0xF;
|
||||
|
||||
bool encrypt = (core_sel == CORE_ENCRYPT);
|
||||
|
||||
uint32_t blocks = reg_block_count + 1;
|
||||
uint32_t total_bytes = blocks * 16;
|
||||
|
||||
// Read input via IN_LL.
|
||||
std::vector<uint8_t> in_buf, out_buf;
|
||||
in_buf.resize(total_bytes, 0);
|
||||
out_buf.resize(total_bytes, 0);
|
||||
|
||||
LLDesc in_ll{}, out_ll{};
|
||||
bool got_in = read_ll(state->uc, reg_in_ll_addr, &in_ll);
|
||||
bool got_out = read_ll(state->uc, reg_out_ll_addr, &out_ll);
|
||||
(void)got_out;
|
||||
|
||||
if (got_in && in_ll.size && input_sel == INPUT_MEMORY) {
|
||||
uint32_t copy = (in_ll.size < total_bytes) ? in_ll.size : total_bytes;
|
||||
uc_mem_read(state->uc, in_ll.addr, in_buf.data(), copy);
|
||||
}
|
||||
|
||||
run_aes_blocks(key_index, encrypt, in_buf.data(), out_buf.data(), blocks,
|
||||
xor_pos, input_sel, vctram_sel, iv_sel,
|
||||
(input_sel == INPUT_LNR_CTR) || ctr_cnt, hash_en);
|
||||
|
||||
if (dst_kind == DST_MEMORY) {
|
||||
if (got_out && out_ll.size) {
|
||||
uint32_t copy = (out_ll.size < total_bytes) ? out_ll.size : total_bytes;
|
||||
uc_mem_write(state->uc, out_ll.addr, out_buf.data(), copy);
|
||||
}
|
||||
} else if (dst_kind == DST_KEYTABLE) {
|
||||
// Unwrap-key path: store the (single-block) result in the destination slot.
|
||||
uint32_t dst_slot = (reg_keytable_dst >> 8) & 0xF;
|
||||
uint32_t word_quad = reg_keytable_dst & 0x3;
|
||||
uint8_t *target = (word_quad == 1)
|
||||
? ks_table[dst_slot].key + 16
|
||||
: ks_table[dst_slot].key + 0;
|
||||
std::memcpy(target, out_buf.data(), 16);
|
||||
}
|
||||
// DST_HASHREG: hash_result is already populated by run_aes_blocks.
|
||||
|
||||
reg_int_status |= SE_INT_OP_DONE;
|
||||
|
||||
printf("[se] OP slot=%u %s blocks=%u xor=%u in_sel=%u vctram=%u iv=%u dst=%u "
|
||||
"in_addr=0x%X out_addr=0x%X\n",
|
||||
key_index, encrypt ? "ENC" : "DEC", blocks, xor_pos, input_sel,
|
||||
vctram_sel, iv_sel, dst_kind,
|
||||
got_in ? in_ll.addr : 0, got_out ? out_ll.addr : 0);
|
||||
}
|
||||
|
||||
// Keytable address layout: bits 4..7 = slot, bits 2..3 = quad, bits 0..1 = pkt
|
||||
static void keytable_write(uint32_t addr, uint32_t val) {
|
||||
uint32_t slot = (addr >> 4) & 0xF;
|
||||
uint32_t quad = (addr >> 2) & 0x3;
|
||||
uint32_t pkt = addr & 0x3;
|
||||
uint8_t *target = nullptr;
|
||||
switch (quad) {
|
||||
case 0: target = ks_table[slot].key + 0 + pkt*4; break; // KEYS_0_3
|
||||
case 1: target = ks_table[slot].key + 16 + pkt*4; break; // KEYS_4_7
|
||||
case 2: target = ks_table[slot].iv_orig + pkt*4; break; // ORIGINAL_IV
|
||||
case 3: target = ks_table[slot].iv_upd + pkt*4; break; // UPDATED_IV
|
||||
}
|
||||
if (target) std::memcpy(target, &val, 4);
|
||||
|
||||
// After the last word of a 16-byte key is written, optionally substitute
|
||||
// the prod.keys-derived BIS key into slots 0-5 (KS_BIS_NN_CRYPT/TWEAK).
|
||||
// Lockpick's _derive_bis_keys may produce wrong values when our SE engine
|
||||
// doesn't faithfully model some part of the chain; the override is a
|
||||
// pragmatic shortcut that lets the BIS XTS layer succeed regardless.
|
||||
if (quad == 0 && pkt == 3 && slot < 6) {
|
||||
if (bis_override_present[slot]) {
|
||||
std::memcpy(ks_table[slot].key, bis_override_keys[slot], 16);
|
||||
std::printf("[se] slot %u BIS key overridden from prod.keys:", slot);
|
||||
for (int i = 0; i < 16; ++i) std::printf(" %02X", ks_table[slot].key[i]);
|
||||
std::printf("\n");
|
||||
} else {
|
||||
std::printf("[se] slot %u key loaded (derived):", slot);
|
||||
for (int i = 0; i < 16; ++i) std::printf(" %02X", ks_table[slot].key[i]);
|
||||
std::printf("\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static uint32_t keytable_read(uint32_t addr) {
|
||||
uint32_t slot = (addr >> 4) & 0xF;
|
||||
uint32_t quad = (addr >> 2) & 0x3;
|
||||
uint32_t pkt = addr & 0x3;
|
||||
const uint8_t *src = nullptr;
|
||||
switch (quad) {
|
||||
case 0: src = ks_table[slot].key + 0 + pkt*4; break;
|
||||
case 1: src = ks_table[slot].key + 16 + pkt*4; break;
|
||||
case 2: src = ks_table[slot].iv_orig + pkt*4; break;
|
||||
case 3: src = ks_table[slot].iv_upd + pkt*4; break;
|
||||
}
|
||||
if (!src) return 0;
|
||||
uint32_t v;
|
||||
std::memcpy(&v, src, 4);
|
||||
return v;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
#include <vector>
|
||||
|
||||
uint32_t se_engine_read(EmuState *state, uint64_t addr) {
|
||||
uint32_t off = (uint32_t)(addr - SE_BASE);
|
||||
if (off >= SE_HASH_RESULT_REG && off < SE_HASH_RESULT_REG + 16*4) {
|
||||
return hash_result[(off - SE_HASH_RESULT_REG) / 4];
|
||||
}
|
||||
if (off >= SE_CRYPTO_LINEAR_CTR_REG && off < SE_CRYPTO_LINEAR_CTR_REG + 16) {
|
||||
return linear_ctr[(off - SE_CRYPTO_LINEAR_CTR_REG) / 4];
|
||||
}
|
||||
switch (off) {
|
||||
case SE_OPERATION_REG: return reg_op;
|
||||
case SE_INT_ENABLE_REG: return reg_int_enable;
|
||||
case SE_INT_STATUS_REG: return reg_int_status;
|
||||
case SE_CONFIG_REG: return reg_config;
|
||||
case SE_IN_LL_ADDR_REG: return reg_in_ll_addr;
|
||||
case SE_OUT_LL_ADDR_REG: return reg_out_ll_addr;
|
||||
case SE_CRYPTO_CONFIG_REG: return reg_crypto_config;
|
||||
case SE_CRYPTO_BLOCK_COUNT_REG: return reg_block_count;
|
||||
case SE_CRYPTO_KEYTABLE_ADDR: return reg_keytable_addr;
|
||||
case SE_CRYPTO_KEYTABLE_DATA: return keytable_read(reg_keytable_addr);
|
||||
case SE_CRYPTO_KEYTABLE_DST: return reg_keytable_dst;
|
||||
case SE_RNG_CONFIG_REG: return reg_rng_config;
|
||||
case SE_STATUS_REG: return 0; // IDLE
|
||||
case SE_ERR_STATUS_REG: return reg_err_status;
|
||||
default:
|
||||
if (off < sizeof(spare_regs)/sizeof(spare_regs[0])*4)
|
||||
return spare_regs[off / 4];
|
||||
return 0;
|
||||
}
|
||||
(void)state;
|
||||
}
|
||||
|
||||
void se_engine_write(EmuState *state, uint64_t addr, uint32_t val) {
|
||||
uint32_t off = (uint32_t)(addr - SE_BASE);
|
||||
if (off >= SE_CRYPTO_LINEAR_CTR_REG && off < SE_CRYPTO_LINEAR_CTR_REG + 16) {
|
||||
linear_ctr[(off - SE_CRYPTO_LINEAR_CTR_REG) / 4] = val;
|
||||
return;
|
||||
}
|
||||
switch (off) {
|
||||
case SE_OPERATION_REG:
|
||||
reg_op = val;
|
||||
// SE_OP_START runs the configured AES op; other op codes (RESTART_*,
|
||||
// CTX_SAVE, ABORT) just need OP_DONE so the driver's _se_wait() exits.
|
||||
if ((val & 0x7) == 1 /*SE_OP_START*/) {
|
||||
op_start(state);
|
||||
} else if ((val & 0x7) != 0 /*not ABORT*/) {
|
||||
reg_int_status |= SE_INT_OP_DONE;
|
||||
}
|
||||
return;
|
||||
case SE_INT_ENABLE_REG: reg_int_enable = val; return;
|
||||
case SE_INT_STATUS_REG:
|
||||
// Write-1-clear semantics on real HW.
|
||||
reg_int_status &= ~val;
|
||||
return;
|
||||
case SE_CONFIG_REG: reg_config = val; return;
|
||||
case SE_IN_LL_ADDR_REG: reg_in_ll_addr = val; return;
|
||||
case SE_OUT_LL_ADDR_REG: reg_out_ll_addr = val; return;
|
||||
case SE_CRYPTO_CONFIG_REG: reg_crypto_config = val; return;
|
||||
case SE_CRYPTO_BLOCK_COUNT_REG: reg_block_count = val; return;
|
||||
case SE_CRYPTO_KEYTABLE_ADDR: reg_keytable_addr = val; return;
|
||||
case SE_CRYPTO_KEYTABLE_DATA: keytable_write(reg_keytable_addr, val); return;
|
||||
case SE_CRYPTO_KEYTABLE_DST: reg_keytable_dst = val; return;
|
||||
case SE_RNG_CONFIG_REG: reg_rng_config = val; return;
|
||||
case SE_ERR_STATUS_REG: reg_err_status &= ~val; return;
|
||||
default:
|
||||
if (off < sizeof(spare_regs)/sizeof(spare_regs[0])*4)
|
||||
spare_regs[off / 4] = val;
|
||||
return;
|
||||
}
|
||||
(void)state;
|
||||
}
|
||||
|
||||
void se_engine_set_aes128_key(uint32_t slot, const uint8_t key[16]) {
|
||||
if (slot >= 16) return;
|
||||
std::memcpy(ks_table[slot].key, key, 16);
|
||||
}
|
||||
|
||||
// ---- prod.keys parser -------------------------------------------------------
|
||||
|
||||
static int hex_nibble(char c) {
|
||||
if (c >= '0' && c <= '9') return c - '0';
|
||||
if (c >= 'a' && c <= 'f') return 10 + c - 'a';
|
||||
if (c >= 'A' && c <= 'F') return 10 + c - 'A';
|
||||
return -1;
|
||||
}
|
||||
|
||||
static int parse_hex(const char *s, uint8_t *out, size_t out_size) {
|
||||
for (size_t i = 0; i < out_size; ++i) {
|
||||
int h = hex_nibble(s[i*2]);
|
||||
int l = hex_nibble(s[i*2 + 1]);
|
||||
if (h < 0 || l < 0) return 0;
|
||||
out[i] = (uint8_t)((h << 4) | l);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
static void aes_self_test() {
|
||||
// Lockpick's check_keyslot_access vector:
|
||||
// key = 00..0F
|
||||
// ciphertext= 00 (all zeros)
|
||||
// expected = 7B 1D 29 A1 6C F8 CC AB 84 F0 B8 A5 98 E4 2F A6
|
||||
const uint8_t key[16] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
|
||||
const uint8_t ct[16] = {0};
|
||||
const uint8_t exp[16] = {0x7b,0x1d,0x29,0xa1,0x6c,0xf8,0xcc,0xab,
|
||||
0x84,0xf0,0xb8,0xa5,0x98,0xe4,0x2f,0xa6};
|
||||
uint8_t rk[176];
|
||||
uint8_t out[16];
|
||||
aes::key_expand(key, rk);
|
||||
aes::decrypt_block(ct, out, rk);
|
||||
bool ok = std::memcmp(out, exp, 16) == 0;
|
||||
std::printf("[se] AES-128 self-test: %s\n", ok ? "PASS" : "FAIL");
|
||||
if (!ok) {
|
||||
std::printf(" got: ");
|
||||
for (int i = 0; i < 16; ++i) std::printf("%02X ", out[i]);
|
||||
std::printf("\n");
|
||||
}
|
||||
}
|
||||
|
||||
int se_engine_load_prod_keys(const char *path) {
|
||||
static bool tested = false;
|
||||
if (!tested) { aes_self_test(); tested = true; }
|
||||
FILE *f = std::fopen(path, "r");
|
||||
if (!f) {
|
||||
std::printf("[se] failed to open prod.keys: %s\n", path);
|
||||
return 0;
|
||||
}
|
||||
// Slot mapping (matches the bootrom-derived keyslots Hekate/Lockpick rely on):
|
||||
// 12 = KS_TSEC / KS_MARIKO_KEK
|
||||
// 13 = KS_TSEC_ROOT / KS_MARIKO_BEK
|
||||
// 14 = KS_SECURE_BOOT
|
||||
// Plus convenience pre-loads for BIS so SYSTEM mount can short-circuit
|
||||
// when downstream key derivation is incomplete:
|
||||
// 0 = KS_BIS_00_CRYPT (low half of bis_key_00)
|
||||
// 1 = KS_BIS_00_TWEAK (high half of bis_key_00)
|
||||
int loaded = 0;
|
||||
char line[512];
|
||||
while (std::fgets(line, sizeof(line), f)) {
|
||||
char name[128];
|
||||
char hexv[256];
|
||||
if (std::sscanf(line, " %127[^ =] = %255s", name, hexv) != 2) continue;
|
||||
auto load_into = [&](uint32_t slot, size_t bytes, size_t off) {
|
||||
if (std::strlen(hexv) < (off + bytes) * 2) return;
|
||||
uint8_t buf[16];
|
||||
if (!parse_hex(hexv + off*2, buf, bytes)) return;
|
||||
se_engine_set_aes128_key(slot, buf);
|
||||
++loaded;
|
||||
};
|
||||
if (!std::strcmp(name, "tsec_key")) load_into(12, 16, 0);
|
||||
else if (!std::strcmp(name, "tsec_root_key") || !std::strcmp(name, "tsec_root_key_00"))
|
||||
load_into(13, 16, 0);
|
||||
else if (!std::strcmp(name, "secure_boot_key")) load_into(14, 16, 0);
|
||||
else if (!std::strcmp(name, "bis_key_00")) {
|
||||
load_into(0, 16, 0); // crypt half
|
||||
load_into(1, 16, 16); // tweak half
|
||||
// Also stash for runtime override of Lockpick's derived value.
|
||||
if (std::strlen(hexv) >= 64) {
|
||||
if (parse_hex(hexv, bis_override_keys[0], 16)) bis_override_present[0] = true;
|
||||
if (parse_hex(hexv + 32, bis_override_keys[1], 16)) bis_override_present[1] = true;
|
||||
}
|
||||
}
|
||||
else if (!std::strcmp(name, "bis_key_01")) {
|
||||
load_into(2, 16, 0);
|
||||
load_into(3, 16, 16);
|
||||
if (std::strlen(hexv) >= 64) {
|
||||
if (parse_hex(hexv, bis_override_keys[2], 16)) bis_override_present[2] = true;
|
||||
if (parse_hex(hexv + 32, bis_override_keys[3], 16)) bis_override_present[3] = true;
|
||||
}
|
||||
}
|
||||
else if (!std::strcmp(name, "bis_key_02")) {
|
||||
load_into(4, 16, 0);
|
||||
load_into(5, 16, 16);
|
||||
if (std::strlen(hexv) >= 64) {
|
||||
if (parse_hex(hexv, bis_override_keys[4], 16)) bis_override_present[4] = true;
|
||||
if (parse_hex(hexv + 32, bis_override_keys[5], 16)) bis_override_present[5] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
std::fclose(f);
|
||||
std::printf("[se] loaded %d keys from %s\n", loaded, path);
|
||||
return loaded > 0 ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
#ifndef T210_SE_ENGINE_H
|
||||
#define T210_SE_ENGINE_H
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstddef>
|
||||
|
||||
struct EmuState;
|
||||
|
||||
// Tegra X1 Security Engine (SE) — software emulation that runs real AES-128
|
||||
// operations against an emulated 16-slot keytable.
|
||||
//
|
||||
// Currently implemented:
|
||||
// * AES-128 ECB encrypt/decrypt (single + multi-block, DMA via LL descriptors)
|
||||
// * AES-128 CBC encrypt/decrypt
|
||||
// * AES-128 CTR mode
|
||||
// * AES "unwrap" (decrypt and store result in destination keyslot)
|
||||
// * Keyslot programming (CRYPTO_KEYTABLE_ADDR/DATA)
|
||||
// * Pre-population of keyslots from a Switch prod.keys file
|
||||
//
|
||||
// Not implemented (returns zero / no-op):
|
||||
// * AES-CMAC (HASH+VCTRAM_AESOUT path)
|
||||
// * SHA / RNG / RSA
|
||||
// Each unimplemented op still completes (sets OP_DONE) so the boot doesn't hang.
|
||||
|
||||
uint32_t se_engine_read (EmuState *state, uint64_t addr);
|
||||
void se_engine_write(EmuState *state, uint64_t addr, uint32_t val);
|
||||
|
||||
// Load 16-byte AES key into the given slot's KEYS_0_3 quad. For 256-bit keys
|
||||
// (BIS), call with `slot+0` for the low half and `slot+1`-style write into
|
||||
// the second quad — but for our purposes the bdk drivers always use 128-bit
|
||||
// AES, so this is enough.
|
||||
void se_engine_set_aes128_key(uint32_t slot, const uint8_t key[16]);
|
||||
|
||||
// Parse a switch-style "prod.keys" file (lines of `name = hex_value`) and
|
||||
// pre-populate the well-known bootrom-derived keyslots (KS_TSEC=12,
|
||||
// KS_SECURE_BOOT=14, KS_TSEC_ROOT=13) so Lockpick / Hekate's derivation
|
||||
// chain bootstraps without TSEC firmware emulation. Returns 1 on success, 0
|
||||
// on any parse / file error.
|
||||
int se_engine_load_prod_keys(const char *path);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,26 @@
|
||||
#ifndef T210_TEGRA_BL_H
|
||||
#define T210_TEGRA_BL_H
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
// Tegra X1-style block-linear byte offset for 32 bpp (RGBA8888 / XRGB in RAM).
|
||||
// Matches test_img.py "Block Linear / Tegra X1" mode.
|
||||
inline uint32_t tegra_bl_byte_off_rgba8888(uint32_t sx, uint32_t sy,
|
||||
uint32_t width_gobs,
|
||||
uint32_t block_height_gobs) {
|
||||
uint32_t gob_x = sx / 16u;
|
||||
uint32_t pixel_x = sx % 16u;
|
||||
uint32_t gob_y = sy / 8u;
|
||||
uint32_t line_y = sy % 8u;
|
||||
uint32_t block_y = gob_y / block_height_gobs;
|
||||
uint32_t gob_in_block_y = gob_y % block_height_gobs;
|
||||
|
||||
uint32_t idx =
|
||||
(block_y * width_gobs * block_height_gobs * 128u) +
|
||||
(gob_x * block_height_gobs * 128u) + (gob_in_block_y * 128u) +
|
||||
(pixel_x & 3u) + ((line_y & 1u) << 2) + ((pixel_x & 4u) << 1) +
|
||||
((line_y & 2u) << 3) + ((pixel_x & 8u) << 2) + ((line_y & 4u) << 4);
|
||||
return idx * 4u;
|
||||
}
|
||||
|
||||
#endif
|
||||
Reference in new issue
Block a user