Files
Claude 6753c5f3db Fix defects found in a code sweep and a TRM cross-check
Security Engine: CTR ignored its input and returned the raw keystream;
CBC encrypt skipped the IV on the first block and saved the wrong
chaining value, so every CMAC over more than one block was wrong; OFB
was broken. The datapath now follows INPUT_SEL/XOR_POS/VCTRAM_SEL the
way bdk drives it, and matches OpenSSL for ECB, CBC, OFB, CTR and
CMAC. SHA-256 works in parts (SHA_CONTINUE), SE_OP_CTX_SAVE reads keys
back as se_aes_ctx_get_keys() expects, unwrap honours the word quad,
guest block counts and LL sizes are bounded, and unreachable buffers
end the op with an error.

Soft reboot now resets the whole SoC (GPIO/pinmux cache, UARTs, I2C,
PMC, CAR, flow controller, SE, touch, SDMMC, display, ACTMON, ...)
while keeping what hardware keeps (PMC SCRATCH0, the RTC, and the PMIC
unless the reboot is a power cycle). DRAM gets fresh zero pages
instead of a memset that made all 2 GB resident; stale BPMP
translations are dropped; CPSR returns to SVC; scripts restart.

Execution: a branch to address 0 no longer hangs the emulator
(until=0 made PC 0 an exit); bdk's reset-then-bpmp_halt() reboots
instead of exiting; an untimed halt with CPU0 running parks the BPMP
and lets CPU0 continue; CPU0 starts in the same batch it is released
in; CPU0 drops translations of pages the BPMP rewrote; shared models
no longer see time run backwards.

TRM cross-check: RST_CPUG_CMPLX resets to 0x2000feef and CPU0 runs on
CPURESET0/CORERESET0/L2RESET/NONCPURESET (bit names corrected); RAM
repair clears REQ and sets STS, and is no longer a run condition;
refused releases are re-evaluated; MSELECT ENABLE_PCIE_APERTURE gates
PCIe; RST_DEVICES_W/Y direct writes land; DL_UP is read-only; the
whole config aperture and memory window decode; OSC_CTRL reports
38.4 MHz; PLLE/PLLREFE no longer get bit 27 forced into a divider;
PMC is a R/W register file; RTC SECONDS counts; FLOW halt modes follow
17.2.2 and STOP_UNTIL_IRQ wakes on the armed TMR; UART IIR/IER/
loopback MSR; I2C NOACK code and empty I2C4/I2C6 buses; pinmux reset
values; the COP ACTMON counts halt time.

Peripherals: MAX77620 LDO power-good follows the rail (hwtest's
gamecard probe no longer fails), the Erista GPU MAX77621 answers at
0x1C, regulators ACK per generation, RTC CONTROL is binary/24h, PS3
card detect reads "slot empty", packet-mode I2C parses 4 bytes per
word, rawnand I/O splits at part boundaries, eMMC returns to its user
area on CMD0, ADMA2 descriptors decode per spec, SD CMD6/ACMD13 data
reaches the programmed buffer, ERR_INTERRUPT is reported, R1 follows
block commands.

Frontend and tooling: touch events queue instead of overwriting each
other, map through rotation overrides and bdk's edge offset, and use
finger ID 0; a scripted press is always seen before its release;
zeroed fuses persist in the ini; dropped UTF-8 paths open on Windows;
bad --input-script is an error; test scripts check exit status and
missing arguments; make_sd.py quotes names and picks a FAT32-valid
cluster size; the Dockerfile marks the mount safe for git.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYewwDPujjo5B2xRyC5Grb
2026-09-25 17:45:02 +00:00

112 lines
3.8 KiB
Python

#!/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 shlex
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
if size_mb < 64:
print("[error] --size-mb must be at least 64: FAT32 needs 65525 clusters")
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"
# FatFs (and every FAT driver) decides FAT12/16/32 by cluster count, and
# FAT32 needs at least 65525 clusters: 4 KiB clusters only get there from
# ~260 MB up. Below that, format with 512-byte clusters, or the payload's
# f_mount rejects the volume (FR_NO_FILESYSTEM).
spc = 8 if size_mb >= 512 else 1
# File names go into a shell command line: quote them.
q_fat, q_img = shlex.quote(fat_name), shlex.quote(img_name)
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 {spc} {q_fat} && "
# Every top-level entry, dotfiles included; an empty source is fine.
f"(cd /src && find . -mindepth 1 -maxdepth 1 "
f"-exec mcopy -i /work/{q_fat} -s {{}} :: \\;) && "
f"printf '{fdisk_script}' | fdisk {q_img} && "
f"dd if={q_fat} of={q_img} 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())