Skip to content

Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.

Carry seedds/nxnative#406 (cheats) as two forwarded patches

v0lumehi1d744a5fa7f7
diff --git a/dm/fork_patches.txt b/dm/fork_patches.txt
index 50e1e394..9a1d2aa9 100644
--- a/dm/fork_patches.txt
+++ b/dm/fork_patches.txt
@@ -18,3 +18,5 @@ games-md-gallery
cloud-saves
lm3-depth-mode
nsp-title-id-from-package
+0028-cheats-engine.patch
+0029-cheats-mac-panel.patch
diff --git a/patches/0028-cheats-engine.patch b/patches/0028-cheats-engine.patch
new file mode 100644
index 00000000..cb8c9081
--- /dev/null
+++ b/patches/0028-cheats-engine.patch
@@ -0,0 +1,5544 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Amost <[email protected]>
+Date: Thu, 29 Oct 2026 20:02:49 +0100
+Subject: [PATCH] =?UTF-8?q?Cheats:=20the=20Atmosph=C3=A8re=20cheat=20engin?=
+ =?UTF-8?q?e,=20its=20hooks,=20tools,=20tests=20and=20docs?=
+MIME-Version: 1.0
+Content-Type: text/plain; charset=UTF-8
+Content-Transfer-Encoding: 8bit
+
+The host reads Atmosphère-format cheat files for the running game's build
+(dm/host/hle_cheats.c), keeps the player's toggles beside them, and
+scripts/cheat_anchor.py carries a cheat file across game updates. Includes
+the Cheats section of docs/frontends.md, the file contract for front ends.
+Ported onto the pinned tree from seedds/nxnative#406 (all but the Mac panel).
+
+Upstream-Status: forwarded seedds/nxnative#406
+Reason: the launcher's cheat manager builds on its file contract until upstream merges it
+Issue: LNPANDY/NX2Apple#97
+
+---
+ dm/games/01003FC01670C000/README.md | 10 +
+ dm/gfx/nvn/hle_nvn.c | 1 +
+ dm/gfx/nvn/nvn_mtl.m | 1 +
+ dm/host/dm.h | 44 +
+ dm/host/dm_input.h | 4 +
+ dm/host/hle_cheats.c | 2059 +++++++++++++++++++++++++++
+ dm/host/hle_hid.c | 25 +
+ dm/host/hle_lifecycle.c | 1 +
+ dm/host/hle_svc.c | 26 +
+ dm/host/main.c | 1 +
+ dm/host/tests/Makefile | 9 +-
+ dm/host/tests/t_cheats.c | 609 ++++++++
+ dm/tools/tests/test_cheat_anchor.py | 638 +++++++++
+ docs/development.md | 107 ++
+ docs/env_switches.tsv | 5 +
+ docs/frontends.md | 14 +
+ docs/reference/README.md | 3 +-
+ docs/reference/cheats.md | 251 ++++
+ docs/reference/rewriter.md | 14 +
+ scripts/cheat_anchor.py | 1443 +++++++++++++++++++
+ 20 files changed, 5263 insertions(+), 2 deletions(-)
+ create mode 100644 dm/host/hle_cheats.c
+ create mode 100644 dm/host/tests/t_cheats.c
+ create mode 100644 dm/tools/tests/test_cheat_anchor.py
+ create mode 100644 docs/reference/cheats.md
+ create mode 100644 scripts/cheat_anchor.py
+
+diff --git a/dm/games/01003FC01670C000/README.md b/dm/games/01003FC01670C000/README.md
+index d4f7ba00..68c218f3 100644
+--- a/dm/games/01003FC01670C000/README.md
++++ b/dm/games/01003FC01670C000/README.md
+@@ -38,6 +38,14 @@ No `patches.py`, no `sdk_patches.py` cut for its `sdk` build (`2d369d99…`), no
+ - Every texture is created with `TextureBuilderSetPackagedTextureData`. **Current:** the host copies that data at `TextureInitialize` and uploads it like a packaged texture; the linear ones (the save thumbnails) are excluded and, in a CPU-visible pool, read straight from the pool buffer.
+ - Attachment loads and stores per frame on the Mac went down about 15% once an inline uniform update inside a render pass stopped ending the pass ([development.md, Power](../../../docs/development.md#power)).
+
++## Cheats
++
++- **A community list is for 1.10** (`4B632573CA5C160E`): a Ryujinx list with invincible, one-hit kill, EP never decreases, plus an entry that installs the code the first two use.
++ - Its four `BD405800` (`ldr s0, [x0, #0x58]`) sites are 1.10's. In the base game 1.00 (main `57212E16CB83BB55`) the same functions lie 0x330 lower.
++ - Its code cave is the padding before the read-only data, `main+0x451FC4` = the read-only data − 0x3C in both builds. The cave's first two words are the #01 / #02 flags.
++ - A `BL` at `main+0x8F0EC` (1.10), in place of `0ABB7F75`, enters the cave.
++- **Compiled for 1.00** by `scripts/cheat_anchor.py` ([Cheats carried across game updates](../../../docs/reference/rewriter.md#cheats-carried-across-game-updates)): the EP sites by fingerprint, the hook by body digest (`main+0x8EDBC`), the `BL` re-encoded. Not tried in play.
++
+ ## Found on this game
+
+ General host changes first needed here; each applies to every game:
+@@ -47,8 +55,10 @@ General host changes first needed here; each applies to every game:
+ - **GLSLC outputs in `main`** (`shader_split.py` `glslc_shaders`, the control / code / length check): [GLSLC outputs in `main` and in loose files](../../../docs/reference/shaders.md#glslc-outputs-in-main-and-in-loose-files).
+ - **Single-stage programs paired with a cover** (`vs_pad`), **a shader cache key that covers the pairs** (`shader_key`, `pair_keyed`), **triangle fans and indexed quads** (a shared fan index buffer; CPU expansion at replay in `nvn_mtl.m`), **vertex streams 14 and 15 at slots 14 and 15** (`VB_SLOT`) and **packaged texture data copied at `TextureInitialize`**: [Single-stage programs paired with a cover](../../../docs/reference/shaders.md#single-stage-programs-paired-with-a-cover), [Shader cache key covering the pairs](../../../docs/reference/shaders.md#shader-cache-key-covering-the-pairs), [Triangle fans and indexed quads](../../../docs/reference/rendering.md#triangle-fans-and-indexed-quads), [Vertex streams 14 and 15 at Metal slots 14 and 15](../../../docs/reference/rendering.md#vertex-streams-14-and-15-at-metal-slots-14-and-15), [Packaged texture data copied at `TextureInitialize`](../../../docs/reference/nvn-objects.md#packaged-texture-data-copied-at-textureinitialize).
+ - **Finding service calls before the first boot** (`main`'s `nn::` imports filtered against `HLE_FORCE` names): [Listing a game's unhooked imports before they are met](../../../docs/reference/services.md#listing-a-games-unhooked-imports-before-they-are-met).
++- **Cheats carried across game updates** (`scripts/cheat_anchor.py`): [rewriter reference](../../../docs/reference/rewriter.md#cheats-carried-across-game-updates).
+
+ ## Open
+
++- Cheats: the community list's install entry writes 0 to both the #01 / #02 flags on every pass, after those two in file order, so with it on the flags read 0 at the end of each pass. Check in play whether it must be turned off once its code is in.
+ - `game.tsv` still describes the game as "In bring-up" (the Mac reaching the first battle), while AGENTS.md lists it as playable on the iPhone.
+ - `game.tsv`: only the merged 1.10 copy is extracted; the base game's own build IDs are added when needed.
+diff --git a/dm/gfx/nvn/hle_nvn.c b/dm/gfx/nvn/hle_nvn.c
+index 2f78c010..8c728bbb 100644
+--- a/dm/gfx/nvn/hle_nvn.c
++++ b/dm/gfx/nvn/hle_nvn.c
+@@ -1374,6 +1374,7 @@ static void dump_frame(void) {
+ static long cap = -1; if (cap < 0) { const char *e = getenv("DM_MEM_CAP_GB"); cap = e ? atol(e) : DM_MEM_CAP_DEFAULT_GB; }
+ if (cap > 0 && mb > (unsigned long long)cap * 1024) { LOG("[RED] memory watchdog: resident %llu MB over the limit of %ld GB (frame %llu), exiting", mb, cap, (unsigned long long)g_frame); _exit(86); } } }
+ dm_guest_frame_tick(); // Deterministic guest clock (DM_DETCLOCK, host hle_os.c): each present advances a fixed step; a no-op when not enabled
++ dm_cheats_present(); // Atmosphère cheat files (hle_cheats.c): enabled cheats apply once per presented frame; the ~60 Hz idle thread only covers gaps
+ }
+ // ---------- Timing instrumentation (per-frame rows written to DM_NVN_TSV: frame / @metric / value; every 300 frames a summary of p50 / p95 / max) ----------
+ #define TWIN 300
+diff --git a/dm/gfx/nvn/nvn_mtl.m b/dm/gfx/nvn/nvn_mtl.m
+index 65a16379..503407b3 100644
+--- a/dm/gfx/nvn/nvn_mtl.m
++++ b/dm/gfx/nvn/nvn_mtl.m
+@@ -2779,6 +2779,7 @@ static inline int passdump(void) {
+ #define PD(...) do { if (passdump()) { fprintf(stderr, "[pass] F%llu ", (unsigned long long)atomic_load(&g_cur_frame)); fprintf(stderr, __VA_ARGS__); fputc('\n', stderr); } } while (0)
+ static void blit_note(void) { if (g_enc) PD("E %llu copy / buffer update ends the render pass", g_stat_pass); }
+ __attribute__((weak)) void dm_guest_frame_tick(void) {} // hle_os.c provides the strong definition (DM_DETCLOCK deterministic guest clock); a no-op when graphics unit tests do not link the host // diag.c provides the strong definition (DM_TICK_HOLD=E:SHOT unfreeze); a no-op when graphics unit tests do not link the host
++__attribute__((weak)) void dm_cheats_present(void) {} // hle_cheats.c provides the strong definition (the Atmosphère cheat pass per presented frame); a no-op when graphics unit tests do not link the host
+ __attribute__((weak)) int dm_detclock_enabled(void) { return 0; } // Same as above: the host's hle_os.c provides the strong definition; when graphics unit tests do not link the host, the deterministic clock is treated as off
+ __attribute__((weak)) uint64_t guest_ns(void) { return 0; } // Same as above: read only when the deterministic clock is on; never reached in graphics unit tests
+ static uint64_t att_bytes(id<MTLTexture> t, NSUInteger level) {
+diff --git a/dm/host/dm.h b/dm/host/dm.h
+index 54f15f61..a163fb1a 100644
+--- a/dm/host/dm.h
++++ b/dm/host/dm.h
+@@ -134,6 +134,50 @@ void dm_guest_write_prep_register(void (*fn)(void *addr, size_t len));
+ void dm_res_report_register(void (*fn)(uint32_t tick, const char *why)); // Resource count callback (registered by the graphics layer): called every 250 ticks, when the loading screen has been dismissed, and on exit when the record is full
+ void (*dm_res_report_cb(void))(uint32_t tick, const char *why); // Get the registered resource count callback (null if not registered)
+ void dm_guest_write_prepare(void *addr, size_t len);
++void dm_guest_heap_range(uint64_t *base, size_t *open_len); // hle_svc.c: the guest heap's base and opened length (guest addresses), 0 / 0 when none
++int dm_guest_heap_read(uint64_t addr, void *out, size_t len); // hle_svc.c: hole-free guest heap read for the cheat VM (under the memory lock); 0 = ok, 1 = a byte outside the opened span
++int dm_guest_heap_write(uint64_t addr, const void *src, size_t len); // hle_svc.c: hole-free guest heap write (the dirty tracking sees it first)
++// Cheats (hle_cheats.c): Atmosphère-format cheat code files applied to the running game (docs/development.md "Cheats")
++void dm_cheats_init(void); // Called once in host_preload after loading the modules (main.c): reads DM_CHEATS and friends, loads the build's file
++void dm_cheats_present(void); // Per presented frame (hle_nvn.c presents): applies the enabled cheats once
++// The Cheats submenu's rows (front_mac.m, Mac window only). Readers of the list of cheats; the front end copies the strings out immediately
++int dm_cheats_found(void); // A cheat file is loaded (this build's, or another build's on DM_CHEATS_ANY_BUILD)
++int dm_cheats_ncheats(void); // The loaded file's cheats, in file order
++const char *dm_cheats_build(void); // This game's build ID, first 16 hex digits ("" when the main NSO has none)
++const char *dm_cheats_dir_path(void); // The cheats folder ("", when neither DM_CHEATS nor DM_ROOT is set: the menu's folder action is off)
++int dm_cheats_nothers(void); // The .txt files of other builds in the folder (the menu's disabled "another version" rows)
++const char *dm_cheats_other(int i);
++const char *dm_cheat_name_at(int i);
++const char *dm_cheat_why_at(int i); // The disabled state's reason (" (unsupported opcode N)", " (off: ...)"); "" when plain
++int dm_cheat_kind_at(int i); // 0 a plain row (click toggles), 1 master (always on, no toggle), 2 disabled (broken or killed at run time), 3 a label (credits, a section marker)
++int dm_cheat_on_at(int i);
++void dm_cheat_toggle(int i); // The click on a plain row: flips the cheat (an on / off pair as one switch) and rewrites <build ID>.enabled
++void dm_cheats_reload(void); // "Reload cheats": re-reads the file (the same path), so edits during play need no re-launch
++// What the panel shows beyond the menu (hle_cheats.c header: labels and sections, the meta file of scripts/cheat_anchor.py)
++enum { DM_CHEAT_LABEL = 1, DM_CHEAT_SECTION_START = 2, DM_CHEAT_SECTION_END = 4, DM_CHEAT_PAIR_ON = 8, DM_CHEAT_PAIR_OFF = 16,
++ DM_CHEAT_ONCE = 32, DM_CHEAT_ASK = 64, DM_CHEAT_HOST = 128, DM_CHEAT_WEAK = 256 }; // ONCE: a "set" cheat; HOST: a never-decrease run by this host only
++int dm_cheat_flags_at(int i); // DM_CHEAT_* of entry i
++const char *dm_cheat_section_at(int i); // the section entry i lies in ("" none)
++const char *dm_cheat_note_at(int i); // the meta file's note: how the cheat was compiled, and its own note
++const char *dm_cheat_type_at(int i); // the meta type (u16, s32, f32, …), "" unknown
++int dm_cheat_pair_at(int i); // the other half of an on / off pair, -1 none
++int dm_cheat_preview(int i, char *out, size_t cap); // a dry run: one line per write it would make now ("main+0x… (2 bytes): 37 -> 999"), nothing written; returns the writes
++int dm_cheat_value_get(int i, char *out, size_t cap); // an "ask" cheat's value as text: 1, or 0 when it takes none
++int dm_cheat_value_set(int i, const char *text); // set it (its type, its bounds) and keep it in <build ID>.values: 0 done, -1 refused
++const char *dm_cheat_value_bounds(int i); // "min..max" (a side empty when open), "" when it takes none
++int dm_cheats_master(void); // the master switch (off: no cheat runs; kept in the folder's .cheats-off)
++void dm_cheats_master_set(int on);
++int dm_cheats_safe(void); // safe mode: the last run ended without a clean exit while cheats were on, so all start off
++void dm_cheats_safe_restore(void); // leave safe mode: the masters and the saved toggles come back
++const char *dm_cheats_report(void); // the load report: counts, duplicate names, ignored lines, carried-over toggles, Atmosphère's limits
++const char *dm_cheats_version(void); // this build's display version ("" unknown)
++const char *dm_cheats_other_version(int i); // the display version of another build's file (its meta file), "" unknown
++int dm_cheats_nskipped(void); // cheats the compiler left out of this build's file (its meta file), with their reasons
++const char *dm_cheats_skipped_name(int i);
++const char *dm_cheats_skipped_why(int i);
++int dm_cheats_nsources(void); // anchored sources (*.cheats.toml) in the cheats folder
++const char *dm_cheats_source(int i);
++void dm_cheats_exit(void); // a clean exit (hle_lifecycle.c, atexit): removes the safe-mode flag
+ // Graphics lifecycle (hle_nvn.c): on=1 suspends (afterwards submit / present block, and in-flight GPU work is drained before returning), on=0 resumes; called by the iOS front end when entering and leaving the background
+ void dm_gfx_suspend(int on);
+ void dm_gfx_enter(void); void dm_gfx_leave(void); // hle_nvn.c: the gate dm_gfx_suspend closes, for graphics layers other than NVN (dm/gfx/vk)
+diff --git a/dm/host/dm_input.h b/dm/host/dm_input.h
+index 9cda0d02..f784e7c6 100644
+--- a/dm/host/dm_input.h
++++ b/dm/host/dm_input.h
+@@ -13,6 +13,10 @@ enum {
+ #define DM_STICK_MAX 32767
+ void dm_input_set(uint64_t buttons, int32_t lx, int32_t ly, int32_t rx, int32_t ry);
+ uint64_t dm_input_samples(void); // Cumulative number of times the game has sampled the controller
++// The cheat VM's key mask (hle_cheats.c): every input source's button bits (0..15 in the enum above) ORed and the
++// merged axes' eight stick-direction bits (16..23), one flat bitset; no latches are consumed (the game's own reads
++// keep them). The NpadButton SL / SR bits (24 / 25) never fire: no input source of this host reports them
++uint64_t dm_cheats_keys(void);
+ // Physical controller path (Mac / iOS GameController): stored separately from keyboard / touch and scripted input (DM_KEYS / DM_CTL); when the game reads player 1,
+ // buttons are ORed bitwise and each stick axis takes whichever source is deflected more. All 0 when no controller is connected.
+ // dm_pad_set is player 1's controller (DM_BTN_SHAKE counts there only); dm_pad_set_player sets player n + 1's, which the game reads on its own npad (hle_hid.c) while
+diff --git a/dm/host/hle_cheats.c b/dm/host/hle_cheats.c
+new file mode 100644
+index 00000000..2932ca6e
+--- /dev/null
++++ b/dm/host/hle_cheats.c
+@@ -0,0 +1,2059 @@
++// Atmosphère-format cheat codes (the dmnt cheat VM) applied to the running game: the `.txt` files that cheat sites share as
++// atmosphere/contents/<title ID>/cheats/<build ID>.txt, loaded by the first 16 hex digits (8 bytes) of the main NSO's
++// build ID (dm_main_build(), from the rewriter's fixups header). The Mac front end shows them in the window's Cheats menu
++// and panel (front_mac.m); toggles are remembered per build in <build>.enabled in the cheats folder and restored at the next launch.
++// The host applies the enabled cheats once per presented frame (hle_nvn.c dump_frame -> dm_cheats_present) and at a fixed
++// ~60 Hz from its own thread when the game is not presenting (window minimized, graphics suspended, start-up).
++// The cheat VM follows the reference implementation (Atmosphère stratosphere/dmnt/source/cheat/impl/dmnt_cheat_vm.cpp and
++// docs/features/cheats.md; the semantics are written down in docs/reference/cheats.md) in word order, conditions, loops
++// (jump-back counters) and register semantics. A pass resets the registers once, then runs the masters and the enabled
++// cheats in file order sharing them, as the reference's ResetState over its one concatenated program does; one
++// deliberate difference: each cheat runs as its own program (the reference concatenates them into one), so an unclosed
++// conditional in one cheat cannot swallow the next cheat's words, and the loop tops, word indexes into the program
++// that set them, are reset per cheat: a loop end without its start jumps to the first word of its own cheat, not of the
++// whole program and never into another cheat's words. Implemented opcodes: 0 store static, 1 begin
++// conditional, 2 end / else, 3 loop, 4 load register static, 5 load register from memory, 6 store static to a register
++// address, 7 legacy arithmetic, 8 key-press conditional, 9 register arithmetic (integer and float), A store register to
++// memory, C0 register conditional, C1 / C2 save and restore of registers (the saved values reset once per pass like the
++// registers), C3 static registers (read 0x00..0x7F into a register, write a register to 0x80..0xFF; kept across passes,
++// cleared when the file is loaded; on a Switch an overlay tool fills the readable ones and reads the written ones, and
++// nothing here does yet, so a cheat reads 0), C4 extended key-press conditional (a 64-bit mask; without auto-repeat it is
++// met only on the pass where the keys became held, against one previous-keys value shared by every C4 of the pass, as
++// the reference's static is). The keys are read once per pass, before the first cheat, as the reference's Execute does.
++// A cheat that uses anything else (pause / resume, the debug log, or an unknown form) is turned off before it ever runs,
++// shown in the menu with "(unsupported opcode N)".
++// The reference's memory-type nybble selects 0 main NSO, 1 heap, 2 alias, 3 aslr, 4 absolute
++// and 5..F main, from the host's own layout. What an access reaches follows the kernel's debug rule as the reference has
++// it: a read any page the guest address block or a module maps, a write main (through its writable alias), the opened heap,
++// another module's data and any other mapped guest page, never another module's code nor the host's key page. A failed
++// access (an unmapped page: a pointer the game has not set yet, a loading screen) is ignored as on a Switch: a load leaves
++// the register as it was, a conditional compares against 0, a store writes nothing, and the cheat stays on and retries
++// next pass; the first failure of a cheat logs one [RED] line, the rest are counted into a note on its row.
++// Beyond the reference, all optional (a plain community file behaves as on a Switch):
++// - an entry without code words is a label, never a cheat: a credits line, or EdiZon's [--SectionStart:Name--] /
++// [--SectionEnd:Name--] markers, which give the entries between them a section; a header glued to the previous line's
++// last code word ("00000008[Next]", a sloppy site file) still starts a new entry
++// - <build>.meta.tsv beside the file (scripts/cheat_anchor.py compiles one with it): per entry its section, note, type,
++// on / off pair, a value the panel may set ("ask", kept in <build>.values), "set" cheats that run one pass and turn
++// themselves off, and never-decrease, a host action on a typed address that keeps the highest value seen (Atmosphère's
++// VM keeps no state of a cheat between passes, so its .txt entry is empty and other engines show an inert label)
++// - "X - on" / "X - off" entries (or a meta pair) form one switch: turning it off runs the off entry (the restore) for one
++// pass; whatever <build>.enabled says is kept as it is
++// - a dry run (dm_cheat_preview) describes what a cheat would write right now and writes nothing
++// - a master switch (the folder's .cheats-off-<title> file) and a safe mode (not on iOS): a run that ended without a
++// clean exit while cheats were on leaves the folder's .cheats-running-<title> file behind, and the next launch starts
++// with every cheat off (masters too) until the player restores the saved toggles or turns a cheat on (which restores them)
++// - <build>.enabled names a duplicate name's later entries "Name #2", "Name #3", ...; a compiled file (one with a meta
++// file) of a build without <build>.enabled takes its toggles from the newest other build's compiled from the same source
++// - a load report (dm_cheats_report): counts, duplicate names, skipped lines, Atmosphère's size limits
++// Switches of this file:
++// DM_CHEATS=<folder> cheats folder (default <DM_ROOT>/cheats; the flat layout with the Atmosphère tree under it)
++// DM_CHEATS_ANY_BUILD=1 with no file of this build, load the folder's single .txt of another build, with a warning
++// DM_CHEATS_ON=<n>,… cheats turned on by name at launch (the menu's own toggle states stay what they were)
++// DM_CHEATS_DEBUG=1 log every applied write (cheat name, where, value)
++#include "dm.h"
++#include "dm_input.h" // dm_cheats_keys, the key mask the type-8 conditional reads
++#include <libkern/OSCacheControl.h>
++#include <sys/mman.h>
++#include <sys/stat.h>
++#include <mach/mach.h> // vm_read_overwrite / vm_write: guest pages the game maps and unmaps while a pass runs (guest_page_read / _write)
++#if !TARGET_OS_IPHONE
++#include <mach/mach_vm.h> // the alias mapping of main's pages (mach_vm_remap), below; the iPhone SDK has no mach_vm.h
++#include <mach/vm_prot.h>
++#endif
++#include <dispatch/dispatch.h> // the state files are written off the presenting thread (files_queue)
++#include <errno.h>
++#include <dirent.h>
++#include <unistd.h>
++#include <strings.h>
++#include <stdarg.h>
++#include <stdatomic.h>
++#include <ctype.h>
++
++// Limits of Atmosphère's own order (0x2000 dwords of program, 256 cheats per file): no shared cheat-site file and no
++// hand-made one can exhaust the arrays
++#define CHEAT_MAX 256 // cheats in one file
++#define INS_MAX 0x2000 // dwords of one cheat's program
++#define NAME_MAX 128 // characters of a [Name] / {Name} header
++#define OTHER_MAX 24 // another build's .txt files listed in the menu
++#define CAND_MAX 64 // .txt files scanned in the cheats folder and its Atmosphère tree
++#define VM_STEP_CAP 4000000 // instructions of one cheat in one pass (the reference has none; a runaway loop must never stall a frame)
++#define VW_MAX 8 // program words holding a settable value (a min / max writes it twice, an 8-byte value is two words)
++#define SKIP_MAX 64 // cheats the compiler left out (the meta file's "unresolved" rows), listed for the panel
++#define SRC_MAX 8 // anchored sources (*.cheats.toml) found in the folder
++#define FILE_MAX (4u << 20) // a cheat file larger than this is not a cheat file
++#define ATM_CHEATS 0x80 // Atmosphère's dmnt: cheats per file,
++#define ATM_WORDS 0x100 // ... words per cheat,
++#define ATM_PROGRAM 0x400 // ... and words of all enabled cheats together (the load report warns past them)
++
++typedef struct {
++ char name[NAME_MAX]; // the [Name] / {Name} header line, trimmed
++ uint32_t ins[INS_MAX]; // the cheat's code words, one program run per pass
++ int nins;
++ uint8_t master; // {Name} header: always on, applied first, not toggleable from the menu
++ uint8_t on; // switched on (masters always; everyone else by the menu's saved <build>.enabled state)
++ uint8_t broken; // unsupported opcode / region / width / condition, or malformed: shown disabled, never runs
++ uint8_t dead; // its program failed at run time (a runaway loop, an else at depth 0, a write into the host's key page):
++ // off until the next reload of the file. A failed memory access never sets it (fails below)
++ uint32_t fails; // accesses that failed since the file was loaded (an unmapped page): ignored like the reference does,
++ // counted into the row's note; the first one logs a [RED] line
++ uint8_t pass_fail; // an access failed in the pass running now (the note stays while the latest pass had one)
++ uint8_t noted; // why holds the failed-access note (cleared, with why, by the first pass without a failure)
++ uint64_t note_ns; // when the note was last rewritten (cheat_fail rewrites it sparingly: the panel reads why unlocked)
++ uint8_t label; // no code words (and no meta action): a credits line or a section marker, never a cheat
++ uint8_t sec_mark; // 1 = [--SectionStart:…--], 2 = [--SectionEnd:…--]
++ uint8_t once; // meta "set": runs one pass, then turns itself off
++ uint8_t restore_once; // the off half of a pair just switched off: runs one pass (the restore), then turns itself off
++ uint8_t heap_wait; // it waited for the game's heap once (logged once)
++ int junk_line; // the first line under it that was not code words (an entry left without code is broken, not a label)
++ uint8_t nd; // meta never-decrease: the host keeps the highest value of (nd_region, nd_off), no program
++ uint8_t ask; // meta "ask": the panel may set the value held in the program words vw[]
++ uint8_t weak; // meta: scripts/cheat_anchor.py resolved one of its anchors weakly
++ uint8_t pair_off; // the off (restore) half of an on / off pair
++ int pair; // the other half of an on / off pair, -1 none
++ int dup; // how many earlier entries carry the same name (its <build>.enabled key is "Name #dup+1")
++ char why[80]; // the reason text the menu appends to the name: the disabled state (broken, dead) filled at load or
++ // at run time, or, on a running cheat, the failed-access note (" (no effect: N accesses …)")
++ char section[NAME_MAX]; // the section it lies in ("" outside any)
++ char note[200]; // the meta file's "resolved" and "note", for the panel's tooltip
++ char type[8]; // the meta type (u8 … u64, s8 … s64, f32, f64), "" unknown
++ char pairname[NAME_MAX]; // the meta pair's name, linked to an index after the meta file is read
++ int vw[VW_MAX], nvw; // the program words holding the value (an 8-byte value: its high word, then its low word)
++ double vmin, vmax; uint8_t has_min, has_max; // the meta ask bounds
++ uint8_t nd_region; uint64_t nd_off; // never-decrease: region 0 main / 1 heap, offset in it
++ uint8_t nd_have; uint64_t nd_max; // never-decrease: the highest value seen since it was turned on
++} cheat_t;
++
++static cheat_t g_cheat[CHEAT_MAX]; static int g_ncheat;
++static char g_dir[1024]; // cheats folder (DM_CHEATS or <DM_ROOT>/cheats), "" when neither is set
++static char g_path[2048]; // the loaded file (logged; "Reload cheats" re-reads exactly this path)
++static char g_build[17]; // the loaded file's build ID: main's build ID cut to 16 hex digits, upper case as the
++ // cheat files name it (dmnt matches the file name case-insensitively on disk)
++static char g_tid[17]; // this game's title ID (the profile's DM_GAME_PROGRAM_ID), for the Atmosphère tree
++static char g_others[OTHER_MAX][17]; static int g_nothers; // builds on disk that are not this game's build
++static char g_other_ver[OTHER_MAX][24]; // their display versions, from their meta files ("" unknown)
++static char g_version[24]; // this build's display version (the profile's build rows, else the meta file), "" unknown
++static char g_on[16][NAME_MAX]; static int g_non; // the names of DM_CHEATS_ON, turned on at load time
++static char g_skip_name[SKIP_MAX][NAME_MAX], g_skip_why[SKIP_MAX][160]; static int g_nskip; // the compiler's left-outs
++static char g_src[SRC_MAX][256]; static int g_nsrc; // *.cheats.toml sources in the folder
++static char g_report[4096]; // the load report (dm_cheats_report)
++static int g_have_meta; // the loaded file came with a meta file
++static int g_junk, g_junk_line, g_glued; // prose lines ignored and the first one; headers split off a code line
++static char g_carried[64]; // the other build whose <build>.enabled gave the toggles ("" none)
++static char g_meta_src[256]; // the source the meta file names ("compiled from <source>"), "" without a meta file
++static _Atomic int g_exiting; // dm_cheats_exit ran: no pass may write the safe-mode flag again
++static _Atomic int g_active; // a file is loaded (the per-present hook exits before taking any lock)
++static _Atomic int g_master = 1; // the master switch: 0 = no cheat runs (the folder's .cheats-off-<title> file)
++static int g_safe; // safe mode: the last run ended without a clean exit while cheats were on
++static _Atomic uint64_t g_present_ns; // the last present: the ~60 Hz thread stands down while it is recent
++static _Atomic int g_dbg; // DM_CHEATS_DEBUG
++static int g_any; // DM_CHEATS_ANY_BUILD
++static _Atomic int g_inited; // dm_cheats_init done (the thread keeps running under the consoleless iOS app too)
++
++// Region 0: the guest main NSO as the loader mapped it (dm/host/loader.c map_image: text pages and the patch area
++// read+execute, data and bss read+write, the host's key page read-only at the image's end); region 1: the heap,
++// whose opened extent grows and shrinks as the game's heap does (hle_svc.c); regions 2 (alias) and 3 (aslr) from the
++// same file's layout (region_base)
++static module_t *g_main_mod; // the "main" module of the profile (not an NRO), found at init; its loaded fields come from loader.c
++int dm_guest_as_contains(uintptr_t a); // hle_svc.c: the address lies in the reserved guest address block
++void svc_guest_range(uint8_t **base, size_t *size); // hle_svc.c: that block (the aslr region of GetInfo), NULL before mem_init
++
++// A second mapping of main's memory (same physical pages, mach_vm_remap with copy = false), protected read+write for the
++// whole process: a cheat's write to a code page goes through it while the game's own mapping stays executable. Toggling
++// the original page mprotect RW -> copy -> RX on every write races with the game's running cores: between the first
++// mprotect and the restore their fetches of any instruction on that page fault (a 16 KB macOS page holds ~4 KB of
++// instructions, found when main+0x305DD98 faulted while the poke page 0x305F3FC was toggled, run xa). With the alias the
++// protections never change, so only the honest mid-word race the reference on Switch itself has is left. NULL when the
++// remap failed: writes fall back to the per-page mprotect toggle (kept below), logged [RED] once
++static uint8_t *g_alias; // the alias mapping of main's image (same layout, page rounded up); every offset a
++ // cheat reaches is bounds-checked against main's own span first, so the page-rounded
++ // size needs no variable of its own
++static int g_alias_fallback; // the fallback [RED] was already logged once
++
++// Map main's image a second time, writable. Called once a cheat file is actually picked (at init that is before the
++// guest starts, so nothing protects or tracks these pages yet); the mapping stays for the process's lifetime, the
++// loader's per-page protections never change after load. iPhone only: its SDK forbids mach_vm.h, and there the
++// guarded main_write_pages falls back to the per-page mprotect toggle (unsampled, plain C must stay compiling)
++#if TARGET_OS_IPHONE
++static void alias_setup(void) { g_alias = NULL; }
++#else
++static void alias_setup(void) {
++ module_t *m = g_main_mod;
++ long pg = sysconf(_SC_PAGESIZE); if (pg <= 0) pg = 0x4000; // 16 KB on Apple Silicon, a safe floor elsewhere
++ uint64_t size = ((uint64_t)m->size + (uint64_t)pg - 1) & ~((uint64_t)pg - 1); // mach_vm_remap wants whole pages
++ mach_vm_address_t dst = 0;
++ vm_prot_t cur = 0, mx = 0;
++ kern_return_t kr = mach_vm_remap(mach_task_self(), &dst, size, 0, VM_FLAGS_ANYWHERE,
++ mach_task_self(), (mach_vm_address_t)(uintptr_t)m->base, FALSE,
++ &cur, &mx, VM_INHERIT_SHARE);
++ if (kr) { g_alias = NULL; return; }
++ // The alias's protections are independent of the original mapping's: make everything writable once. The key page
++ // stays refused by the write path; the alias is only ever used by a check-passing write
++ kr = mach_vm_protect(mach_task_self(), dst, size, 0, VM_PROT_READ | VM_PROT_WRITE);
++ if (kr) { mach_vm_deallocate(mach_task_self(), dst, size); g_alias = NULL; return; }
++ g_alias = (uint8_t *)(uintptr_t)dst;
++}
++#endif
++
++// The cheats list, the toggles and one VM pass at a time
++static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;
++
++// ---------- the dry run (dm_cheat_preview): what a cheat would write, nothing written ----------
++
++static int g_dry; // a dry run is in progress (under g_lock): writes are described, nothing is turned off
++static char *g_dry_out; static size_t g_dry_cap, g_dry_len; static int g_dry_writes;
++
++// One line of the dry run's description (truncated silently at the caller's buffer size)
++static void dry_line(const char *fmt, ...) {
++ if (!g_dry_out || g_dry_len + 1 >= g_dry_cap) return;
++ va_list ap; va_start(ap, fmt);
++ int n = vsnprintf(g_dry_out + g_dry_len, g_dry_cap - g_dry_len, fmt, ap);
++ va_end(ap);
++ if (n < 0) return;
++ g_dry_len += (size_t)n < g_dry_cap - g_dry_len ? (size_t)n : g_dry_cap - g_dry_len - 1;
++ if (g_dry_len + 1 < g_dry_cap) { g_dry_out[g_dry_len++] = '\n'; g_dry_out[g_dry_len] = 0; }
++}
++
++// A cheat turned itself off for good (until the file is reloaded): its program cannot run here (a runaway loop, an else
++// at depth 0, a write into the host's key page), and the menu shows it disabled with the reason. Never for a failed
++// memory access (cheat_fail). In a dry run the reason is only described: a preview must never change the cheat
++static void cheat_kill(cheat_t *c, const char *fmt, ...) {
++ va_list ap; va_start(ap, fmt);
++ char msg[160]; vsnprintf(msg, sizeof msg, fmt, ap);
++ va_end(ap);
++ if (g_dry) { dry_line("stops: %s", msg); return; }
++ if (c->dead) return;
++ c->dead = 1;
++ c->noted = 0; // why now holds the kill reason, which note_settle must never erase as a stale failed-access note
++ snprintf(c->why, sizeof c->why, " (off: %s)", msg);
++ LOG("[RED] cheat \"%s\": %s, turning it off", c->name, msg);
++}
++
++// A memory access of a cheat failed (what: "read" / "write", at the guest address the VM computed; why: the page's state).
++// The reference discards the failure and goes on (docs/reference/cheats.md, "Behaviour on failure": "The cheat stays
++// enabled and the pass goes on. It is retried on the next pass"), and so does this: the caller leaves its destination
++// as it was. The cheat is never turned off, since the usual cause is a pointer the game has not set yet (start-up, a
++// loading screen) and the cheat must start working once it is. The first failure of a cheat logs one [RED] line, every
++// one is counted, and the row's reason text carries the count as a note while the cheat's latest pass had a failure
++// (cheats_pass clears it on the first pass without one, so a cheat that works now shows no stale note). A dry run only
++// describes it
++static void cheat_fail(cheat_t *c, const char *what, uint64_t addr, const char *why) {
++ if (g_dry) { dry_line("%s at guest address 0x%llx fails (%s): ignored, retried next pass", what, (unsigned long long)addr, why); return; }
++ c->pass_fail = 1;
++ if (c->fails < UINT32_MAX) c->fails++;
++ if (c->fails == 1) LOG("[RED] cheat \"%s\": %s at guest address 0x%llx fails (%s): ignored like a Switch does, retried every pass (counted on its row from now on)", c->name, what, (unsigned long long)addr, why);
++ if (c->dead || c->broken) return; // a dead cheat keeps its own reason (its never-decrease state may still read)
++ // The panel reads why without the lock (a stale row is accepted, a torn one is not worth 60 rewrites a second): the
++ // note is rewritten only when its count is a power of two or a second has passed since the last rewrite, so a cheat
++ // failing every pass changes its text a few times a minute, with the count exact at each rewrite
++ uint64_t now = now_ns();
++ if ((c->fails & (c->fails - 1)) == 0 || now - c->note_ns >= 1000000000ull) {
++ snprintf(c->why, sizeof c->why, " (no effect: %u access%s out of mapped memory)", c->fails, c->fails == 1 ? "" : "es");
++ c->note_ns = now;
++ }
++ c->noted = 1;
++}
++
++// ---------- decode: one decoder for both the load verdict and the run ----------
++
++// The Atmosphère opcode of the instruction starting at *p: a nibble, extended by the second and third nibble for the
++// 0xC / 0xF forms (register conditionals; pause / resume / debug log), the way the reference DecodeNextOpcode does it
++static unsigned op_kind(uint32_t w) {
++ unsigned op = w >> 28;
++ if (op >= 0xC) op = (op << 4) | ((w >> 24) & 0xF);
++ if (op >= 0xF0) op = (op << 4) | ((w >> 20) & 0xF);
++ return op;
++}
++
++// Conditional begins (1 / 8 / C0 / C4): when a failed conditional is skipped, its whole nested block must be walked to its
++// own end / else, so each of these increases the depth counter
++static int op_cond_begin(unsigned op) { return op == 1 || op == 8 || op == 0xC0 || op == 0xC4; }
++
++// The reason of the last decode failure (UNSUP / ins_unsupported), for the run's own message. A dry run never marks the
++// cheat (a preview must leave it as it was: the decoder runs under the dry flag only from vm_run / vm_skip, and a
++// failure there is described, not recorded), so the reason lives here rather than only in c->why
++static char g_dec_why[48];
++
++// Unsupported opcode, with the reference's own opcode name in the menu label ("unsupported opcode FFF", "… FF0")
++static int ins_unsupported(cheat_t *c, const uint32_t *p) {
++ snprintf(g_dec_why, sizeof g_dec_why, "unsupported opcode %X", op_kind(p[0]));
++ if (!g_dry) { snprintf(c->why, sizeof c->why, " (%s)", g_dec_why); c->broken = 1; }
++ return 0;
++}
++
++// One unsupported verdict, of the reasons the reference can still decode but the host does not run
++#define UNSUP(c, what) { snprintf(g_dec_why, sizeof g_dec_why, "%s", what); if (!g_dry) { snprintf((c)->why, sizeof (c)->why, " (%s)", what); (c)->broken = 1; } return 0; }
++
++// The instruction the way the run and the load verdict must both see it: fields from the reference's decode, one place.
++// rel = the 40-bit (36-bit for A / C0) relative address, val = the static value / a loop's iterations / the key mask;
++// s = the source register (A) or the compared register (C0), o = the offset type (A) or the operand type (C0)
++typedef struct {
++ unsigned op, len, t, m, r, x, c, flags, s, o;
++ uint64_t rel, val;
++} ins_t;
++
++// The width nibble every sized form shares: 1, 2, 4 or 8 bytes
++static int width_ok(unsigned t) { return t == 1 || t == 2 || t == 4 || t == 8; }
++
++// The width's mask for conditions, arithmetic results and immediates (the reference truncates to the width)
++static uint64_t width_mask(unsigned t) { return t == 8 ? UINT64_MAX : (1ull << (8 * t)) - 1; }
++
++// Decode the instruction at p (n words left) or 0 when it cannot run here (c->why: why). Mirrors the reference
++// DecodeNextOpcode field by field, so the run never miscounts a word; outside what the host implements
++// (opcodes 0..A, C0..C4 with the reference's value widths and its six comparisons) the verdict is unsupported. The
++// memory-type nybble is never a verdict: every value selects a base (region_base), as the reference's
++// GetCheatProcessAddress has a base for each (5..F share main's)
++static int ins_dec(cheat_t *c, const uint32_t *p, int n, ins_t *o) {
++ unsigned t;
++ if (n <= 0) UNSUP(c, "truncated");
++ memset(o, 0, sizeof *o);
++ uint32_t w = p[0];
++ o->op = op_kind(w); o->len = 1;
++ switch (o->op) {
++ case 0: { // 0TMR00AA AAAAAAAA VVVVVVVV (VVVVVVVV): store the value at memory base + rel + reg[r]
++ // (the reference adds the offset register unconditionally: all registers start at 0)
++ if ((t = (w >> 24) & 0xF, !width_ok(t))) UNSUP(c, "width");
++ o->m = (w >> 20) & 0xF;
++ o->t = t; o->r = (w >> 16) & 0xF;
++ if (n < 2) UNSUP(c, "truncated");
++ o->rel = ((uint64_t)(w & 0xFF) << 32) | p[1];
++ o->len = 3;
++ if (o->t == 8) { // a width-8 value comes in the reference's word order: first dword high, second low
++ if (n < 4) UNSUP(c, "truncated");
++ o->val = ((uint64_t)p[2] << 32) | p[3]; o->len = 4;
++ } else o->val = p[2];
++ } break;
++ case 1: { // 1TMCXrAA AAAAAAAA VVVVVVVV (VVVVVVVV): compare memory at base + rel (+ reg[x] for X=1) with the value
++ if ((t = (w >> 24) & 0xF, !width_ok(t))) UNSUP(c, "width");
++ o->m = (w >> 20) & 0xF;
++ o->t = t; o->c = (w >> 16) & 0xF;
++ if (o->c < 1 || o->c > 6) UNSUP(c, "condition"); // only the six comparisons run
++ o->flags = ((w >> 12) & 0xF) != 0; // X, taken as a boolean like the reference does
++ o->x = (w >> 8) & 0xF;
++ if (n < 2) UNSUP(c, "truncated");
++ o->rel = ((uint64_t)(w & 0xFF) << 32) | p[1];
++ o->len = 3;
++ if (o->t == 8) {
++ if (n < 4) UNSUP(c, "truncated");
++ o->val = ((uint64_t)p[2] << 32) | p[3]; o->len = 4;
++ } else o->val = p[2];
++ } break;
++ case 2: // 2X000000: end of a conditional, else for X = 1 (the reference reads it as an else flag)
++ o->flags = ((w >> 24) & 0xF) == 1;
++ break;
++ case 3: { // 300R0000 VVVVVVVV starts (the reference's Loop, reg r counted), 310R0000 ends (the same r again;
++ // any X but 0 at nibble 1 is the end form, the way DecodeNextOpcode reads start_loop == 0)
++ o->flags = ((w >> 24) & 0xF) != 0;
++ o->r = (w >> 16) & 0xF;
++ if (!o->flags) {
++ if (n < 2) UNSUP(c, "truncated");
++ o->val = p[1]; o->len = 2;
++ }
++ } break;
++ case 4: { // 400R0000 VVVVVVVV VVVVVVVV: reg[r] = the 64-bit value
++ if (n < 3) UNSUP(c, "truncated");
++ o->r = (w >> 16) & 0xF;
++ o->val = ((uint64_t)p[1] << 32) | p[2]; o->len = 3;
++ } break;
++ case 5: { // 5TMR00AA / 5T0R10AA / 5T0R2SAA / 5TMR3SAA AAAAAAAA: reg[r] = the width bytes of one address
++ if ((t = (w >> 24) & 0xF, !width_ok(t))) UNSUP(c, "width");
++ o->t = t; o->m = (w >> 20) & 0xF; o->r = (w >> 16) & 0xF;
++ o->flags = (w >> 12) & 0xF; o->x = (w >> 8) & 0xF; // flags: 0 fixed, 1 reg[r] + rel, 2 reg[x] + rel, 3 region + reg[x] + rel
++ if (o->flags > 3) UNSUP(c, "operand");
++ if (n < 2) UNSUP(c, "truncated");
++ o->rel = ((uint64_t)(w & 0xFF) << 32) | p[1]; o->len = 2;
++ } break;
++ case 6: { // 6T0RIor0 VVVVVVVV VVVVVVVV: the value at reg[r] (+ reg[x] for o=1), reg[r] + width for I=1
++ if ((t = (w >> 24) & 0xF, !width_ok(t))) UNSUP(c, "width");
++ if (n < 3) UNSUP(c, "truncated");
++ o->t = t; o->r = (w >> 16) & 0xF;
++ o->flags = (((w >> 12) & 0xF) != 0) | (((w >> 8) & 0xF) != 0) << 1; // 1 = increment reg[r], 2 = add reg[x]
++ o->x = (w >> 4) & 0xF;
++ o->val = ((uint64_t)p[1] << 32) | p[2]; o->len = 3;
++ } break;
++ case 7: { // 7T0RC000 VVVVVVVV: reg[r] performs the width arithmetic with the value
++ if ((t = (w >> 24) & 0xF, !width_ok(t))) UNSUP(c, "width");
++ if ((o->c = (w >> 12) & 0xF) > 4) UNSUP(c, "arithmetic"); // the five legacy operations
++ o->t = t; o->r = (w >> 16) & 0xF;
++ if (n < 2) UNSUP(c, "truncated");
++ o->val = p[1]; o->len = 2;
++ } break;
++ case 8: // 8kkkkkkk: a 28-bit mask, every key of it held on any controller (the reference ORs the held keys of
++ // the handheld and players 1..8; dm_cheats_keys ORs every input source the same way). The DM_BTN_*
++ // bit order (nn::hid::NpadButton), the sticks' directions on 16..23 (dm_input.h); the Joy-Cons' SL / SR
++ // on 24..27 can never be held here, no input source of this host reports them, so such a mask is never met
++ o->val = w & 0x0FFFFFFFu;
++ break;
++ case 9: { // 9TCRSIs0 (VVVVVVVV (VVVVVVVV)): reg[r] = reg[s] op operand, the operand reg[x] or, for I != 0, an
++ // immediate of T bytes (the low T bytes of one word; two words, high first, for T = 8); C the math
++ // type (0..9 integer, 10..13 float); the result is truncated to T bytes at run time
++ if ((t = (w >> 24) & 0xF, !width_ok(t))) UNSUP(c, "width");
++ o->t = t; o->c = (w >> 20) & 0xF; o->r = (w >> 16) & 0xF; o->s = (w >> 12) & 0xF;
++ o->flags = ((w >> 8) & 0xF) != 0; o->x = (w >> 4) & 0xF;
++ if (o->flags) {
++ if (n < (t == 8 ? 3 : 2)) UNSUP(c, "truncated");
++ o->val = t == 8 ? ((uint64_t)p[1] << 32) | p[2] : p[1] & width_mask(t); o->len = t == 8 ? 3 : 2;
++ }
++ } break;
++ case 0xA: { // ATSRIOxa (aaaaaaaa): store reg[s] (width T) at an address from reg[r] and the offset type O:
++ // 0 reg[r], 1 reg[r] + reg[x], 2 reg[r] + a, 3 region x + reg[r], 4 region x + a, 5 region x + reg[r] + a;
++ // I (flags) adds the width to reg[r] afterwards
++ if ((t = (w >> 24) & 0xF, !width_ok(t))) UNSUP(c, "width");
++ o->t = t; o->s = (w >> 20) & 0xF; o->r = (w >> 16) & 0xF;
++ o->flags = ((w >> 12) & 0xF) != 0; o->o = (w >> 8) & 0xF; o->x = (w >> 4) & 0xF;
++ if (o->o > 5) UNSUP(c, "operand");
++ if (o->o >= 3) o->m = o->x;
++ if (o->o == 2 || o->o == 4 || o->o == 5) {
++ if (n < 2) UNSUP(c, "truncated");
++ o->rel = ((uint64_t)(w & 0xF) << 32) | p[1]; o->len = 2;
++ }
++ } break;
++ case 0xC0: { // C0TcSX..: compare reg[s] (width T) with operand X under condition c, a conditional block like 1:
++ // 0 memory region M + a, 1 region M + reg[r], 2 reg[R] + a, 3 reg[R] + reg[r], 4 a static value,
++ // 5 another register
++ if ((t = (w >> 20) & 0xF, !width_ok(t))) UNSUP(c, "width");
++ o->t = t; o->c = (w >> 16) & 0xF;
++ if (o->c < 1 || o->c > 6) UNSUP(c, "condition");
++ o->s = (w >> 12) & 0xF; o->o = (w >> 8) & 0xF;
++ switch (o->o) {
++ case 0: case 1:
++ o->m = (w >> 4) & 0xF;
++ if (o->o == 1) { o->x = w & 0xF; break; }
++ if (n < 2) UNSUP(c, "truncated");
++ o->rel = ((uint64_t)(w & 0xF) << 32) | p[1]; o->len = 2;
++ break;
++ case 2:
++ o->r = (w >> 4) & 0xF;
++ if (n < 2) UNSUP(c, "truncated");
++ o->rel = ((uint64_t)(w & 0xF) << 32) | p[1]; o->len = 2;
++ break;
++ case 3: o->r = (w >> 4) & 0xF; o->x = w & 0xF; break;
++ case 4:
++ if (n < (t == 8 ? 3 : 2)) UNSUP(c, "truncated");
++ o->val = t == 8 ? ((uint64_t)p[1] << 32) | p[2] : p[1]; o->len = t == 8 ? 3 : 2;
++ break;
++ case 5: o->x = (w >> 4) & 0xF; break;
++ default: UNSUP(c, "operand");
++ }
++ } break;
++ case 0xC1: // C10D0Sx0: the operation x (c) between reg[d] (r) and saved[s]: 0 reg[d] = saved[s], 1 saved[d] = reg[s],
++ // 2 saved[d] = 0, 3 reg[d] = 0 (any other x restores, the reference's default)
++ o->r = (w >> 16) & 0xF; o->s = (w >> 8) & 0xF; o->c = (w >> 4) & 0xF;
++ break;
++ case 0xC2: // C2x0XXXX: the C1 operation x (c) on every register i whose bit of the 16-bit mask (val) is set, reg[i] <-> saved[i]
++ o->c = (w >> 20) & 0xF; o->val = w & 0xFFFF;
++ break;
++ case 0xC4: { // C4r00000 kkkkkkkk kkkkkkkk: a 64-bit key mask (high word first). r != 0 (flags): auto-repeat, met
++ // while every key is held like 8; r = 0: met only on the pass where the mask became fully held
++ if (n < 3) UNSUP(c, "truncated");
++ o->flags = ((w >> 20) & 0xF) != 0;
++ o->val = ((uint64_t)p[1] << 32) | p[2]; o->len = 3;
++ } break;
++ case 0xC3: // C3000XXx: static register XX: 0x00..0x7F read into reg[x], 0x80..0xFF written from reg[x]
++ o->x = (w >> 4) & 0xFF; o->r = w & 0xF;
++ break;
++ default: // B, C5..CF, F... (pause / resume, the debug log) and any unknown form
++ return ins_unsupported(c, p);
++ }
++ if (o->len > (unsigned)n) UNSUP(c, "truncated"); // the cheat's words end in the middle of an instruction
++ return (int)o->len;
++}
++
++// ---------- guest memory: what a cheat may reach, and the accesses into it ----------
++
++// Where the guest range [addr, addr+len) lies, the kinds in the order they are tried:
++// WH_MAIN main's mapped image: read directly (the loader's protections never change after load), written through
++// the alias (main_write_pages)
++// WH_HEAP the currently opened heap: read and written under hle_svc.c's g_map_lock (dm_guest_heap_read / _write),
++// so a concurrent SetHeapSize cannot mprotect the span away under the copy
++// WH_MODULE another module (an NSO of the profile, an NRO): mapped for the process's lifetime like main, read
++// directly; only its data and bss are written (never its code or read-only data, never its key page)
++// WH_GUEST any other page of the reserved guest address block: thread stacks, the alias region's virtual address
++// memory (MapPhysicalMemory), MapMemory'd pages. The game maps and unmaps these while a pass runs and no
++// lock of this file covers them, so the copies go through the kernel (vm_read_overwrite / vm_write), which
++// fail instead of faulting on a page gone PROT_NONE in between: the failure is then the reference's ignored
++// access. The block is otherwise only known as a whole (dm_guest_as_contains); whether the page is mapped
++// right now is what the copy itself answers
++// -1 none of these (the host's own memory, a null pointer): refused without touching it. The reference reads
++// any mapped page of the process, but the host process maps far more than the game's, none of it a cheat's
++// This is the reference's "What a read or write can reach is the kernel's rule, not the region" (docs/reference/cheats.md,
++// Memory regions), restricted to the game's own memory. base is the kind's base for the player-facing name (addr_name)
++enum { WH_MAIN = 0, WH_HEAP = 1, WH_MODULE = 2, WH_GUEST = 3 };
++typedef struct { int kind; module_t *mod; uint64_t base; } where_t;
++static int where_get(uint64_t addr, uint64_t len, where_t *w) {
++ w->kind = -1; w->mod = NULL; w->base = 0;
++ if (!len || addr + len < addr) return -1;
++ if (g_main_mod) {
++ uint64_t b = (uint64_t)(uintptr_t)g_main_mod->base, off = addr - b;
++ if (addr >= b && off < g_main_mod->size && len <= g_main_mod->size - off) { w->kind = WH_MAIN; w->mod = g_main_mod; w->base = b; return 0; }
++ }
++ for (int i = 0; i < g_nmod; i++) { // the other modules of the loader's table (NSOs and NROs, all mapped at start)
++ module_t *m = &g_mod[i];
++ if (m == g_main_mod || !m->base || !m->size) continue;
++ uint64_t b = (uint64_t)(uintptr_t)m->base, off = addr - b;
++ if (addr >= b && off < m->size && len <= m->size - off) { w->kind = WH_MODULE; w->mod = m; w->base = b; return 0; }
++ }
++ uint64_t hb; size_t hopen; dm_guest_heap_range(&hb, &hopen);
++ if (hb && hopen && addr >= hb && addr - hb < hopen && len <= hopen - (addr - hb)) { w->kind = WH_HEAP; w->base = hb; return 0; }
++ if (dm_guest_as_contains((uintptr_t)addr) && dm_guest_as_contains((uintptr_t)(addr + len - 1))) {
++ uint8_t *as = NULL; size_t n = 0; svc_guest_range(&as, &n);
++ w->kind = WH_GUEST; w->base = (uint64_t)(uintptr_t)as; return 0;
++ }
++ return -1;
++}
++
++// Copy len bytes of a WH_GUEST page out (0) or fail (-1) without faulting: the kernel's copy refuses an unmapped or
++// PROT_NONE page (KERN_INVALID_ADDRESS / KERN_PROTECTION_FAILURE) where a memcpy would take the signal
++static int guest_page_read(uint64_t addr, void *out, uint64_t len) {
++ vm_size_t got = 0;
++ return vm_read_overwrite(mach_task_self(), (vm_address_t)addr, (vm_size_t)len, (vm_address_t)(uintptr_t)out, &got) == KERN_SUCCESS && got == len ? 0 : -1;
++}
++
++// The counterpart for a write: the write-protect dirty tracking of the graphics layer is told first (a page it holds
++// read-only is unprotected and marked dirty, as every guest write path does), then the kernel copies, failing on a page
++// that is not mapped writable right now
++static int guest_page_write(uint64_t addr, const void *src, uint64_t len) {
++ dm_guest_write_prepare((void *)(uintptr_t)addr, (size_t)len);
++ return vm_write(mach_task_self(), (vm_address_t)addr, (vm_offset_t)(uintptr_t)src, (mach_msg_type_number_t)len) == KERN_SUCCESS ? 0 : -1;
++}
++
++// Read len bytes at a guest address into a zero-extended little-endian value: 0, or -1 when the range is not readable
++// right now (where_get refused it, or the page went away). No consequence for any cheat: cheat_read adds the accounting
++static int mem_read(uint64_t addr, uint64_t len, uint64_t *out) {
++ where_t w; uint64_t v = 0;
++ if (where_get(addr, len, &w)) return -1;
++ if (w.kind == WH_HEAP) { if (dm_guest_heap_read(addr, &v, len)) return -1; }
++ else if (w.kind == WH_GUEST) { if (guest_page_read(addr, &v, len)) return -1; }
++ else memcpy(&v, (void *)(uintptr_t)addr, len);
++ *out = v;
++ return 0;
++}
++
++// Cheats writing into main's pages (dmnt's WriteCheatProcessMemoryUnsafe on this host): if the writable alias of main
++// was mapped at init (alias_setup), everything is copied through it — the same physical memory, the game's own mapping
++// stays untouched and executable, no mprotect at write time. Without the alias (a remap failure) the code pages (text
++// to its text_end, the patch area) are toggled writable, copied and put back per page, and the instruction cache is
++// invalidated, so the game's fetches see exactly what the cheat says (the rewriter may have rewritten the same
++// instruction; the cheat still overwrites it when enabled) — but that path races with the game's running cores (see
++// alias_setup), so it logs a [RED] once and is truly a last resort. The key page (this host's TLS slot numbers, inside
++// the mapped image) is refused either way: changing it would break every guest thread
++static int main_write_pages(cheat_t *c, uint64_t addr, uint64_t len, const void *src) {
++ static long pg; if (!pg) pg = getpagesize();
++ module_t *m = g_main_mod; uint64_t mb = (uint64_t)(uintptr_t)m->base;
++ uint64_t rx_end = (m->text_end + pg - 1) & ~(uint64_t)(pg - 1); // the text as mprotect'd at load
++ // The patch area when it follows the image (patch_off >= 0), page-rounded. When it lies before the base
++ // (patch_off < 0, the loader's large-image layout) m->size excludes it and no cheat write can reach it: po = size
++ // leaves the second code range below empty. UINT64_MAX there would wrap mb + po to mb - 1, make every page count
++ // as code in the fallback (a [mb - 1, ...) test) and seal data / bss pages R|X, which faults the game's next write
++ uint64_t po = m->patch_off >= 0 ? ((uint64_t)m->patch_off & ~(uint64_t)(pg - 1)) : (uint64_t)m->size;
++ uint64_t kp0 = mb + m->key_page_off, kp1 = kp0 + m->key_page_size;
++ if (addr < kp1 && addr + len > kp0) { // the write would cover the key page: refuse it like an out-of-range access
++ cheat_kill(c, "write into the host key page is refused");
++ return -1;
++ }
++ dm_guest_write_prepare((void *)(uintptr_t)addr, len); // the write-protect dirty tracking must see this write coming
++ const uint8_t *v = src;
++ uint64_t start = addr; // kept for the icache invalidate: the fallback loop walks addr past it
++ if (g_alias) {
++ memcpy(g_alias + (size_t)(addr - mb), v, len); // through the writable alias, the same image offset
++ } else {
++ if (!g_alias_fallback) { g_alias_fallback = 1; LOG("[RED] cheats: no writable alias of main, code pages go through an mprotect toggle that races with the game's own execution"); }
++ for (uint64_t end = addr + len; addr < end;) {
++ uint64_t p0 = addr & ~(uint64_t)(pg - 1), hi = p0 + pg < end ? p0 + pg : end; // the slice of this page
++ void *page = (void *)(uintptr_t)p0;
++ int code = p0 < mb + rx_end || (p0 >= mb + po && p0 < mb + m->size);
++ if (code) {
++ if (mprotect(page, pg, PROT_READ | PROT_WRITE)) { cheat_kill(c, "mprotect of a code page failed (errno %d)", errno); return -1; }
++ memcpy((void *)(uintptr_t)addr, v + (addr - start), hi - addr);
++ if (mprotect(page, pg, PROT_READ | PROT_EXEC)) { cheat_kill(c, "mprotect restore failed (errno %d)", errno); return -1; }
++ } else memcpy((void *)(uintptr_t)addr, v + (addr - start), hi - addr);
++ addr = hi;
++ }
++ }
++ sys_icache_invalidate((void *)(uintptr_t)start, len); // the game's own fetches must see the new instructions
++ return 0;
++}
++
++// Read len bytes at a guest address without any consequence for a cheat: 0 and the value, or -1 when unmapped (the dry run
++// and the preview's current values use it)
++static int peek(uint64_t addr, uint64_t len, uint64_t *out) { return mem_read(addr, len, out); }
++
++static uint64_t region_base(int m);
++
++// A guest address the way a player reads it: main+0x…, heap+0x…, alias+0x… (the reference's regions), <module>+0x… for
++// another module, or the bare address (a stack, an unmapped page)
++static void addr_name(uint64_t addr, char *out, size_t n) {
++ where_t w;
++ uint64_t ab = region_base(2);
++ if (where_get(addr, 1, &w) || w.kind == WH_GUEST) {
++ if (ab && addr >= ab && addr - ab < (uint64_t)DM_GAME_MEM_ALIAS) snprintf(out, n, "alias+0x%llX", (unsigned long long)(addr - ab));
++ else snprintf(out, n, "0x%llX", (unsigned long long)addr);
++ } else snprintf(out, n, "%s+0x%llX", w.kind == WH_MAIN ? "main" : w.kind == WH_HEAP ? "heap" : w.mod->name, (unsigned long long)(addr - w.base));
++}
++
++// The width in bytes of a meta type ("u16" -> 2), 0 when unknown
++static unsigned type_width(const char *t) { int b = atoi(t + (t[0] ? 1 : 0)); return b == 8 || b == 16 || b == 32 || b == 64 ? (unsigned)b / 8 : 0; }
++
++// A value as the meta type of its cheat reads it (unsigned, signed, float), or unsigned decimal and hex when the type is
++// unknown or does not match the width (a code word reads best in hex)
++static void value_text(const cheat_t *c, unsigned width, uint64_t v, char *out, size_t n) {
++ char k = c->type[0]; int tw = (int)type_width(c->type);
++ if (k == 'f' && tw == (int)width && width == 4) { uint32_t u = (uint32_t)v; float f; memcpy(&f, &u, 4); snprintf(out, n, "%g", f); return; }
++ if (k == 'f' && tw == (int)width && width == 8) { double d; memcpy(&d, &v, 8); snprintf(out, n, "%g", d); return; }
++ if (k == 's' && tw == (int)width) { int sh = 64 - 8 * (int)width; snprintf(out, n, "%lld", (long long)((int64_t)(v << sh) >> sh)); return; }
++ if (k == 'u' && tw == (int)width) { snprintf(out, n, "%llu", (unsigned long long)v); return; }
++ snprintf(out, n, "%llu (0x%llX)", (unsigned long long)v, (unsigned long long)v);
++}
++
++// dmnt's WriteCheatProcessMemoryUnsafe for this host: val's low len bytes, little-endian (guest aarch64 = host arm64),
++// into the page where_get finds. A range that is not writable (unmapped, another module's code, the host's own memory)
++// is a failed access: nothing is written and the cheat goes on (cheat_fail; the reference discards a failed write the
++// same way), except a write into the host's key page, which main_write_pages refuses for good. The guest address is
++// logged as the cheat VM computes it (region base + rel + offset register), which is what the player reads in the cheat
++// file's own terms. In a dry run the write is described (where, the value there now, the new value) instead
++static void cheat_write(cheat_t *c, uint64_t addr, uint64_t len, uint64_t val) {
++ where_t w;
++ if (where_get(addr, len, &w)) { cheat_fail(c, "write", addr, "not mapped"); return; }
++ if (w.kind == WH_MODULE) { // another module: only what the loader mapped writable (loader.c map_image). Refused: the
++ // code and read-only data before data_off (read + execute), the key page (read-only), and the
++ // patch area, which with patch_off >= 0 lies after the key page up to the image's end, page
++ // rounded down as the loader sealed it read + execute: a memcpy into any of these is a SIGBUS
++ static long pg; if (!pg) pg = getpagesize();
++ uint64_t off = addr - w.base, m_data = w.mod->data_off, kp0 = w.mod->key_page_off, kp1 = kp0 + w.mod->key_page_size;
++ uint64_t po = w.mod->patch_off >= 0 ? (uint64_t)w.mod->patch_off & ~(uint64_t)(pg - 1) : (uint64_t)w.mod->size;
++ if (off < m_data || (off < kp1 && off + len > kp0) || off + len > po) {
++ char why[80]; snprintf(why, sizeof why, "code, read-only data, key page or patch area of module %s", w.mod->name);
++ cheat_fail(c, "write", addr, why);
++ return;
++ }
++ }
++ if (g_dry) {
++ char where[48], now[48], new_[48]; uint64_t cur = 0;
++ addr_name(addr, where, sizeof where);
++ if (peek(addr, len, &cur)) snprintf(now, sizeof now, "?"); else value_text(c, (unsigned)len, cur, now, sizeof now);
++ value_text(c, (unsigned)len, val, new_, sizeof new_);
++ dry_line("%s (%llu bytes): %s -> %s%s", where, (unsigned long long)len, now, new_, cur == val ? " (already)" : "");
++ g_dry_writes++;
++ return;
++ }
++ if (atomic_load(&g_dbg)) LOG("cheat \"%s\": write %llu bytes of 0x%llx at guest address 0x%llx (%s)", c->name, (unsigned long long)len, (unsigned long long)val, (unsigned long long)addr,
++ w.kind == WH_MAIN ? "main NSO" : w.kind == WH_HEAP ? "heap" : w.kind == WH_MODULE ? w.mod->name : "guest page");
++ int bad = 0;
++ switch (w.kind) {
++ case WH_MAIN: main_write_pages(c, addr, len, &val); break;
++ // The heap write happens under the memory lock (dm_guest_heap_write), so a concurrent SetHeapSize cannot shrink it
++ // out from under the copy; it only refuses if the span shrank since the check a moment ago: a failed access as ever
++ case WH_HEAP: bad = dm_guest_heap_write(addr, &val, len) != 0; break;
++ case WH_MODULE: dm_guest_write_prepare((void *)(uintptr_t)addr, (size_t)len); memcpy((void *)(uintptr_t)addr, &val, len); break;
++ default: bad = guest_page_write(addr, &val, len) != 0; break;
++ }
++ if (bad) cheat_fail(c, "write", addr, "page not mapped writable");
++}
++
++// dmnt's ReadCheatProcessMemoryUnsafe for this host: the value is assembled zero-extended little-endian from any page
++// where_get accepts; 0, or -1 with the failure counted (cheat_fail) and *out untouched, so the caller leaves its
++// destination as it was (opcode 5 keeps the register, 1 / C0 compare against the 0 they started from)
++static int cheat_read(cheat_t *c, uint64_t addr, uint64_t len, uint64_t *out) {
++ if (mem_read(addr, len, out) == 0) return 0;
++ cheat_fail(c, "read", addr, "not mapped");
++ return -1;
++}
++
++// ---------- the cheat VM: one pass ----------
++
++static uint64_t g_reg[16]; // the reference's registers: reset once per pass, shared by its cheats
++static uint64_t g_saved[16]; // the reference's saved values (C1 / C2): reset once per pass with the registers, shared the same way
++static uint64_t g_held; // the keys held, read once at the start of the pass (the reference's one GetKeysHeld per
++ // Execute): every key conditional (8, C4) of the pass sees the same keys. Written under g_lock only
++static uint64_t g_keyold; // the keys held at the end of the last pass that ran a cheat (the reference's s_keyold, one
++ // static for every C4): a C4 without auto-repeat is met only when its mask is held now and
++ // was not fully held then. Never updated by a dry run. Under g_lock only
++static uint64_t g_looptop[16]; // the reference's loop tops, word indexes into the program that set them; each cheat is its own
++ // program here, so they are reset at the start of every cheat (vm_run): a loop end without
++ // its start jumps to word 0 of its own cheat, never to an index inside another cheat's words
++static uint64_t g_static[256]; // the reference's static registers (C3): kept across passes, cleared on load
++
++// Region base for the memory-type nybble m, the reference's GetCheatProcessAddress table (docs/reference/cheats.md,
++// Memory regions): 0 main NSO, 1 heap, 2 alias, 3 aslr, 4 non-relative (the offset is an absolute address), 5..F main
++// (the reference's default case). The bases come from the host's own layout: main from the loader, the heap and the
++// block from hle_svc.c (dm_guest_heap_range, svc_guest_range), and the alias region from that file's fixed partition
++// (mem_init_once: alias, then the profile's stack region, then the heap, so alias = heap - stack - alias sizes); the
++// aslr base check in region_ready keeps a changed partition from silently misplacing region 2. The caller checks
++// region_ready(m) first: with no span open the base is 0, and a cheat resolved against 0 could by luck fall inside
++// main's mapped span, which a failed-access line then does not explain
++static uint64_t region_base(int m) {
++ uint64_t hb; size_t hopen;
++ switch (m) {
++ case 1: dm_guest_heap_range(&hb, &hopen); return hb && hopen ? hb : 0;
++ case 2: dm_guest_heap_range(&hb, &hopen); return hb ? hb - (uint64_t)DM_GAME_MEM_STACK - (uint64_t)DM_GAME_MEM_ALIAS : 0;
++ case 3: { uint8_t *as = NULL; size_t n = 0; svc_guest_range(&as, &n); return (uint64_t)(uintptr_t)as; }
++ case 4: return 0;
++ default: return g_main_mod ? (uint64_t)(uintptr_t)g_main_mod->base : 0;
++ }
++}
++
++// The named region must have its base right now: a cheat that names the heap (region 1) before the game's first
++// SetHeapSize would compute its addresses from base 0, so its pass stops here and it waits (logged once): a cheat turned
++// on from <build>.enabled at launch runs as soon as the game opens its heap instead of failing its accesses before that.
++// The alias region (2) is ready as soon as the block is reserved, which is before any cheat runs; its base must agree
++// with the block's partition (alias = block + 256 MB in hle_svc.c mem_init_once), else region 2 stays refused, logged once
++static int region_ready(cheat_t *c, int m) {
++ if (m == 1) {
++ uint64_t hb; size_t hopen; dm_guest_heap_range(&hb, &hopen);
++ if (hb && hopen) return 1;
++ if (g_dry) dry_line("waits: region 1 (heap) has no span opened yet");
++ else if (!c->heap_wait) { c->heap_wait = 1; LOG("cheats: \"%s\" waits for the game's heap (region 1 has no span opened yet)", c->name); }
++ return 0;
++ }
++ if (m == 2) {
++ static int warned;
++ uint64_t ab = region_base(2), as = region_base(3);
++ if (!ab || !as) { // the block is not reserved yet (the idle thread passes from start-up, before mem_init): wait, silently
++ if (g_dry) dry_line("waits: region 2 (alias) is not reserved yet");
++ return 0;
++ }
++ if (ab == as + 0x10000000ull) return 1;
++ if (g_dry) dry_line("stops: region 2 (alias) is not where the host's layout puts it");
++ else if (!warned++) LOG("[RED] cheat \"%s\": region 2 (alias) refused: its base 0x%llx is not the guest block 0x%llx + 256 MB (hle_svc.c mem_init_once changed its partition)", c->name, (unsigned long long)ab, (unsigned long long)as);
++ return 0;
++ }
++ if (m == 3) return region_base(3) != 0;
++ if (m == 4) return 1;
++ return g_main_mod != NULL; // main is always mapped by the time a cheat file was picked
++}
++
++// Skipping a failed / finished conditional the reference's way: walk nested begins and ends (each counted once at its
++// decode), and a not-taken if also meets its else at the same depth as the skip's end (the else block is skipped too)
++static int vm_skip(cheat_t *c, const uint32_t *ins, int nins, int *pidx, int *pdepth, int is_if) {
++ int desired = *pdepth - 1;
++ while (*pdepth > desired && *pidx < nins) {
++ ins_t in;
++ int len = ins_dec(c, ins + *pidx, nins - *pidx, &in);
++ if (len <= 0) return -1; // validated before the first pass; keep the walk safe anyway
++ if (op_cond_begin(in.op)) (*pdepth)++;
++ else if (in.op == 2) {
++ if (!in.flags) (*pdepth)--;
++ else if (is_if && *pdepth - 1 == desired) { *pidx += len; return 0; } // an else of a not-taken if: stop there
++ }
++ *pidx += len;
++ }
++ return 0;
++}
++
++// The float operations of opcode 9 (c = 10 add, 11 sub, 12 mul, 13 div) on the bit patterns of the two operands, the
++// way the reference's bit_casts have them: T = 4 single precision on the low 32 bits of each operand, T = 8 double, any
++// other width 0. Plain IEEE arithmetic (the build has no fast-math): a NaN, an infinity (a division by 0 traps nowhere)
++// (the pass runs on the game's presenting thread, so a game that sets FPCR flush-to-zero or another rounding mode sees its own settings in these results, where dmnt in its own process would not: rare, and no game is known to)
++// or a denormal comes out bit for bit as the Switch's own FPU gives it
++static uint64_t float_math(unsigned c, unsigned t, uint64_t a, uint64_t b) {
++ if (t == 4) {
++ uint32_t ua = (uint32_t)a, ub = (uint32_t)b, ur; float x, y, r;
++ memcpy(&x, &ua, 4); memcpy(&y, &ub, 4);
++ r = c == 10 ? x + y : c == 11 ? x - y : c == 12 ? x * y : x / y;
++ memcpy(&ur, &r, 4);
++ return ur;
++ }
++ if (t == 8) {
++ uint64_t ur; double x, y, r;
++ memcpy(&x, &a, 8); memcpy(&y, &b, 8);
++ r = c == 10 ? x + y : c == 11 ? x - y : c == 12 ? x * y : x / y;
++ memcpy(&ur, &r, 8);
++ return ur;
++ }
++ return 0;
++}
++
++// The six comparisons in the reference's number order (opcodes 1 and C0, both unsigned): 1 >, 2 >=, 3 <, 4 <=, 5 ==, 6 !=
++static int cond_met(unsigned cond, uint64_t got, uint64_t want) {
++ return cond == 1 ? got > want : cond == 2 ? got >= want : cond == 3 ? got < want :
++ cond == 4 ? got <= want : cond == 5 ? got == want : got != want;
++}
++
++// One pass of cheat c; the VM state is whatever the caller reset. Returns -1 when the cheat killed itself (its
++// word-boundary verdicts already marked it broken at load; a skip over a shuffled word could still fail here)
++static int vm_run(cheat_t *c) {
++ const uint32_t *ins = c->ins; int nins = c->nins;
++ int idx = 0, depth = 0; // like the reference Execute: one instruction pointer, one conditional depth
++ long steps = 0;
++ memset(g_looptop, 0, sizeof g_looptop); // loop tops index this cheat's own words (see their declaration); the registers stay
++ while (idx < nins) {
++ if (++steps > VM_STEP_CAP) { cheat_kill(c, "over %d instructions in one pass: runaway loop", VM_STEP_CAP); return -1; }
++ ins_t in;
++ int len = ins_dec(c, ins + idx, nins - idx, &in);
++ if (len <= 0) { cheat_kill(c, "malformed instruction at word %d (%s)", idx, g_dec_why); return -1; }
++ switch (in.op) {
++ case 0: { // static store: base + rel + reg[r] (the bounds check is the span check inside cheat_write)
++ if (!region_ready(c, in.m)) return -1;
++ cheat_write(c, region_base(in.m) + in.rel + g_reg[in.r], in.t, in.val & width_mask(in.t));
++ } break;
++ case 8: case 0xC4: case 1: { // key-press conditionals (8, C4) / memory conditional (1): depth counted like the reference, before the verdict
++ depth++;
++ int met = 1;
++ if (in.op == 8) {
++ met = (g_held & in.val) == in.val; // every key of the mask held (the keys of this pass)
++ } else if (in.op == 0xC4) {
++ // Every key of the 64-bit mask held now; without auto-repeat, only if the mask was not fully held at
++ // the end of the last pass (the reference's one s_keyold, which no C4 of the pass changes: two C4s
++ // of the same mask both fire on that pass). An empty mask without auto-repeat is never met: the old
++ // keys always hold all of nothing, as they do in the reference
++ int now = (g_held & in.val) == in.val;
++ met = in.flags ? now : now && (g_keyold & in.val) != in.val;
++ } else {
++ if (!region_ready(c, in.m)) return -1; // the conditional reads the region it names
++ // The reference reads into a zeroed value and compares whatever is there afterwards: a failed read
++ // (counted by cheat_read) compares against 0, as docs/reference/cheats.md has it ("opcodes 1 and C0
++ // compare against 0")
++ uint64_t src = 0;
++ cheat_read(c, region_base(in.m) + in.rel + (in.flags ? g_reg[in.x] : 0), in.t, &src);
++ met = cond_met(in.c, src & width_mask(in.t), in.val & width_mask(in.t));
++ }
++ if (!met) { idx += len; if (vm_skip(c, ins, nins, &idx, &depth, 1)) return -1; continue; } // block (else too) skipped
++ } break;
++ case 0xC0: { // register conditional: reg[s] against memory, a static value or another register, a block like 1's;
++ // a memory operand that cannot be read stays 0 (the reference's zeroed value), the failure counted
++ depth++;
++ uint64_t want = 0, got = g_reg[in.s] & width_mask(in.t);
++ switch (in.o) {
++ case 0: if (!region_ready(c, in.m)) return -1; cheat_read(c, region_base(in.m) + in.rel, in.t, &want); break;
++ case 1: if (!region_ready(c, in.m)) return -1; cheat_read(c, region_base(in.m) + g_reg[in.x], in.t, &want); break;
++ case 2: cheat_read(c, g_reg[in.r] + in.rel, in.t, &want); break;
++ case 3: cheat_read(c, g_reg[in.r] + g_reg[in.x], in.t, &want); break;
++ case 4: want = in.val; break;
++ default: want = g_reg[in.x]; break;
++ }
++ if (!cond_met(in.c, got, want & width_mask(in.t))) { idx += len; if (vm_skip(c, ins, nins, &idx, &depth, 1)) return -1; continue; }
++ } break;
++ case 2: // end / else of a conditional: an else skips its block, a plain end closes the block
++ if (in.flags) { // an else: skip its block like the reference. An else at depth 0 is mismatched: the
++ // reference aborts the whole of dmnt there (SkipConditionalBlock's R_ABORT_UNLESS on
++ // the depth), which no host can copy; turning that one cheat off for the session is
++ // the lenient choice, and the one file error the host keeps as a kill
++ if (depth == 0) { cheat_kill(c, "mismatched else at conditional depth 0"); return -1; }
++ idx += len; if (vm_skip(c, ins, nins, &idx, &depth, 0)) return -1; continue;
++ }
++ if (depth > 0) depth--; // a plain end (a no-op at depth 0, the reference's own gracious assumption)
++ break;
++ case 3: // loop: start (counter set, jump-back point kept), end (decrement, jump back until it reaches 0)
++ if (!in.flags) { g_reg[in.r] = in.val; g_looptop[in.r] = idx + 2; idx += (int)in.len; continue; }
++ g_reg[in.r]--;
++ if (g_reg[in.r]) { idx = (int)g_looptop[in.r]; continue; }
++ break;
++ case 4: // register = static 64-bit value
++ g_reg[in.r] = in.val;
++ break;
++ case 5: { // register = the width bytes of one address (fixed, by register, or region + register, the reference's four forms)
++ uint64_t addr, v0 = 0;
++ switch (in.flags) {
++ case 0: if (!region_ready(c, in.m)) return -1; addr = region_base(in.m) + in.rel; break;
++ case 1: addr = g_reg[in.r] + in.rel; break;
++ case 2: addr = g_reg[in.x] + in.rel; break;
++ default: if (!region_ready(c, in.m)) return -1; addr = region_base(in.m) + g_reg[in.x] + in.rel; break;
++ }
++ // The reference reads the T bytes straight into the register's storage (little-endian): a load narrower
++ // than 8 bytes replaces the low T bytes and keeps the upper ones, it does not zero-extend
++ // (docs/reference/cheats.md, opcode 5). A failed read leaves the register as it was (counted by cheat_read)
++ if (cheat_read(c, addr, in.t, &v0) == 0) g_reg[in.r] = (g_reg[in.r] & ~width_mask(in.t)) | (v0 & width_mask(in.t));
++ } break;
++ case 6: { // store the value at reg[r] (+ reg[x] for o=1); reg[r] gains the width for I=1, like the reference
++ cheat_write(c, g_reg[in.r] + (in.flags & 2 ? g_reg[in.x] : 0), in.t, in.val & width_mask(in.t));
++ if (in.flags & 1) g_reg[in.r] += in.t;
++ } break;
++ case 7: { // register arithmetic the reference's order: the full dword (its u64 zero-extension) goes into
++ // the operation and only the result is truncated to the width, as its ((u8)(reg - 0x100)) does
++ // (masking the operand to the width first happens to give the same add / sub / mul, but there
++ // is no reason to rely on that). The shift counts are masked to 63 bits, aarch64's LSLV / LSRV
++ uint64_t v = in.val, r = g_reg[in.r];
++ switch (in.c) {
++ case 0: r += v; break; // 0 add
++ case 1: r -= v; break; // 1 sub
++ case 2: r *= v; break; // 2 mul
++ case 3: r <<= (v & 63); break; // 3 lsl
++ case 4: r >>= (v & 63); break; // 4 lsr
++ }
++ g_reg[in.r] = r & width_mask(in.t);
++ } break;
++ case 9: { // register arithmetic: reg[r] = reg[s] op (reg[x] or the immediate), the full 64-bit operands into the
++ // operation (the immediate already cut to T bytes, zero-extended, as the reference's GetVmInt gives
++ // it) and only the result truncated to the width; an unknown math type stores 0 (the reference's
++ // res_val stays 0). The shift counts are masked to 63 bits: the reference's C++ shift of a 64-bit
++ // value is undefined past 63, and the Switch's own core, where it compiles to LSLV / LSRV, takes
++ // the count modulo 64, as opcode 7 does here
++ uint64_t a = g_reg[in.s], b = in.flags ? in.val : g_reg[in.x], r;
++ switch (in.c) {
++ case 0: r = a + b; break; // 0 add
++ case 1: r = a - b; break; // 1 sub
++ case 2: r = a * b; break; // 2 mul
++ case 3: r = a << (b & 63); break; // 3 lsl
++ case 4: r = a >> (b & 63); break; // 4 lsr
++ case 5: r = a & b; break; // 5 and
++ case 6: r = a | b; break; // 6 or
++ case 7: r = ~a; break; // 7 not (the operand is ignored)
++ case 8: r = a ^ b; break; // 8 xor
++ case 9: r = a; break; // 9 move
++ case 10: case 11: case 12: case 13: r = float_math(in.c, in.t, a, b); break; // float add / sub / mul / div
++ default: r = 0; break; // 14, 15: no operation defined, the reference stores 0
++ }
++ g_reg[in.r] = r & width_mask(in.t);
++ } break;
++ case 0xC1: // save / restore one register: 0 restore reg[r] from saved[s], 1 save reg[s] into saved[r], 2 clear saved[r], 3 clear reg[r]
++ switch (in.c) {
++ case 1: g_saved[in.r] = g_reg[in.s]; break;
++ case 2: g_saved[in.r] = 0; break;
++ case 3: g_reg[in.r] = 0; break;
++ default: g_reg[in.r] = g_saved[in.s]; break; // 0, and the reference's default for any other x
++ }
++ break;
++ case 0xC2: // the same operation on every register of the 16-bit mask, each with its own saved slot
++ for (unsigned i = 0; i < 16; i++) {
++ if (!(in.val & (1u << i))) continue;
++ if (in.c == 1) g_saved[i] = g_reg[i]; else if (in.c == 2) g_saved[i] = 0; else if (in.c == 3) g_reg[i] = 0; else g_reg[i] = g_saved[i];
++ }
++ break;
++ case 0xA: { // store register: reg[s] (width) at the address of the offset type, reg[r] += width for I=1
++ uint64_t addr;
++ switch (in.o) {
++ case 0: addr = g_reg[in.r]; break;
++ case 1: addr = g_reg[in.r] + g_reg[in.x]; break;
++ case 2: addr = g_reg[in.r] + in.rel; break;
++ case 3: if (!region_ready(c, in.m)) return -1; addr = region_base(in.m) + g_reg[in.r]; break;
++ case 4: if (!region_ready(c, in.m)) return -1; addr = region_base(in.m) + in.rel; break;
++ default: if (!region_ready(c, in.m)) return -1; addr = region_base(in.m) + g_reg[in.r] + in.rel; break;
++ }
++ cheat_write(c, addr, in.t, g_reg[in.s] & width_mask(in.t));
++ if (in.flags) g_reg[in.r] += in.t;
++ } break;
++ case 0xC3: // static registers: 0x00..0x7F are read into a register, 0x80..0xFF written from one
++ if (in.x < 0x80) g_reg[in.r] = g_static[in.x]; else g_static[in.x] = g_reg[in.r];
++ break;
++ default:
++ cheat_kill(c, "instruction the VM does not run reached it"); // cannot happen: validation turned the cheat off
++ return -1;
++ }
++ idx += len;
++ }
++ return 0;
++}
++
++// ---------- host actions: never-decrease ----------
++
++// a < b in the cheat's meta type: unsigned, signed (sign-extended from its width) or float (a NaN compares false, so it is
++// never written back over)
++static int value_less(const cheat_t *c, unsigned width, uint64_t a, uint64_t b) {
++ if (c->type[0] == 'f' && width == 4) { uint32_t ua = (uint32_t)a, ub = (uint32_t)b; float x, y; memcpy(&x, &ua, 4); memcpy(&y, &ub, 4); return x < y; }
++ if (c->type[0] == 'f' && width == 8) { double x, y; memcpy(&x, &a, 8); memcpy(&y, &b, 8); return x < y; }
++ if (c->type[0] == 's') { int sh = 64 - 8 * (int)width; return (int64_t)(a << sh) >> sh < (int64_t)(b << sh) >> sh; }
++ return a < b;
++}
++
++// One never-decrease pass: the first pass after the cheat was turned on notes the value; afterwards a lower value is put
++// back to the highest one seen and a higher one becomes the new highest (Atmosphère's VM keeps no state of a cheat
++// between passes, so this is the host's own action)
++static void nd_step(cheat_t *c) {
++ unsigned w = type_width(c->type);
++ if (!w || !region_ready(c, c->nd_region)) return;
++ uint64_t addr = region_base(c->nd_region) + c->nd_off, cur = 0;
++ if (cheat_read(c, addr, w, &cur)) return;
++ if (!c->nd_have) { c->nd_max = cur; c->nd_have = 1; return; }
++ if (value_less(c, w, cur, c->nd_max)) cheat_write(c, addr, w, c->nd_max);
++ else c->nd_max = cur;
++}
++
++// ---------- the pass, the present hook and the idle thread ----------
++
++static void states_save(void);
++
++// Does cheat c take part in a pass's half (0 = the masters, 1 = the enabled plain cheats in file order)? Not a broken,
++// dead or label entry, not a master in safe mode (they wait for the player too), not a plain cheat that is off. One
++// place for the pass and for the dry run, which replays the same order
++static int pass_runs(const cheat_t *c, int half) {
++ if (c->broken || c->dead || c->label) return 0;
++ if ((half == 0) != (c->master != 0)) return 0;
++ if (half == 0 && g_safe) return 0;
++ if (half && !c->on) return 0;
++ return 1;
++}
++
++// The failed-access note of one cheat after its run (cheat_fail): the latest pass had no failure, so a note from earlier
++// passes no longer describes it and goes (the count itself stays for the next failure's note)
++static void note_settle(cheat_t *c) {
++ if (c->noted && !c->pass_fail) { c->noted = 0; c->why[0] = 0; }
++}
++
++// One pass: the masters first, then the enabled cheats in file order, as the reference's LoadProgram orders them. The
++// keys are read once, then the registers and the saved values are reset, before the first cheat, and shared by every
++// cheat of the pass: the reference's Execute (one GetKeysHeld, then ResetState) over its one concatenated program
++// (docs/reference/cheats.md, "One program per pass"), which cheat_anchor.py's pointer chains rely on when they zero
++// register 15 behind themselves. Each cheat is still its own program (vm_run): the conditional depth starts at 0 and the
++// loop tops are reset for each (they index the cheat's own words), so an unclosed block cannot swallow the next cheat
++// and a stray loop end stays inside its own cheat. The static registers stay, and so does the previous-keys value of C4,
++// which the end of a pass that ran a VM cheat sets to this pass's keys (the reference's s_keyold, written at the end of
++// Execute, which only runs when the program has words). The lock is never waited for: a pass that arrives while a menu
++// operation or another pass runs is simply skipped (the next frame / tick applies again). The master switch stops
++// everything; safe mode holds the masters back too; a "set" cheat turns itself off after its pass
++static void cheats_pass(void) {
++ if (!atomic_load(&g_active) || !atomic_load(&g_master)) return;
++ if (pthread_mutex_trylock(&g_lock)) return;
++ if (!atomic_load(&g_master)) { pthread_mutex_unlock(&g_lock); return; } // switched off while this pass waited for the lock
++ int fired = 0, ran = 0;
++ g_held = dm_cheats_keys();
++ memset(g_reg, 0, sizeof g_reg); memset(g_saved, 0, sizeof g_saved); // the reference's once-per-pass ResetState (the loop tops: per cheat, in vm_run)
++ for (int half = 0; half < 2; half++) for (int i = 0; i < g_ncheat; i++) {
++ cheat_t *c = &g_cheat[i];
++ if (!pass_runs(c, half)) continue;
++ c->pass_fail = 0;
++ if (c->nd) nd_step(c); else { vm_run(c); ran = 1; }
++ note_settle(c);
++ if ((c->once || c->restore_once) && half) { c->on = 0; c->restore_once = 0; fired = 1; }
++ }
++ if (ran) g_keyold = g_held;
++ if (fired) states_save(); // the file writes themselves leave on the files queue: the presenting thread never waits for the disk
++ pthread_mutex_unlock(&g_lock);
++}
++
++// Per presented frame (hle_nvn.c dump_frame): apply the cheats and note the present, so the idle thread stands down
++// (brief: once per presented frame; the idle thread only when it is not presenting)
++void dm_cheats_present(void) {
++ atomic_store(&g_present_ns, now_ns());
++ cheats_pass();
++}
++
++// The fixed ~60 Hz passes when the game is not presenting (window minimized, graphics suspended or before the first
++// present): a stopped game still changes under its cheats, as on hardware where the cheat process keeps running
++static void *cheat_tick_thread(void *arg) {
++ (void)arg;
++ while (atomic_load(&g_inited)) {
++ usleep(16667); // ~60 Hz
++ if (now_ns() - atomic_load(&g_present_ns) < 250000000ull) continue; // presenting again: the hook applies
++ cheats_pass();
++ }
++ return NULL;
++}
++
++// ---------- the cheat states: <build>.enabled, DM_CHEATS_ON, the folder's flag files ----------
++
++// The key of a cheat in <build>.enabled and <build>.values: its name, "Name #2" for the second entry of that name, …
++static void cheat_key(const cheat_t *c, char *out, size_t n) {
++ if (c->dup) snprintf(out, n, "%s #%d", c->name, c->dup + 1); else snprintf(out, n, "%s", c->name);
++}
++
++
++// The folder's flag files carry this game's title ID: one cheats folder may serve several games (an SD card's tree)
++static void flag_file(char *out, size_t n, const char *what) { snprintf(out, n, "%s/.cheats-%s-%s", g_dir, what, g_tid); }
++
++// The state files (<build>.enabled, the safe-mode flag) are written from one serial dispatch queue, never on the thread
++// that asked: a "set" cheat fires inside a pass on the presenting thread (hle_nvn.c dump_frame), where an fopen on the
++// cheats folder (a slow or external volume) would hold the frame. What to write is captured under g_lock by the caller
++// and handed to the queue, which writes in the order it was asked, so the files end as a synchronous write would have
++// left them. files_drain waits for everything queued: before the engine reads <build>.enabled back (states_load) and at
++// a clean exit, so nothing is lost or read stale. The queue's blocks take no lock of this file: a drain under g_lock
++// cannot deadlock
++static dispatch_queue_t files_queue(void) {
++ static dispatch_queue_t q; static dispatch_once_t once;
++ dispatch_once(&once, ^{ q = dispatch_queue_create("nxnative.cheats.files", DISPATCH_QUEUE_SERIAL); });
++ return q;
++}
++static void files_drain(void) { dispatch_sync(files_queue(), ^{}); }
++
++// The safe-mode flag: <dir>/.cheats-running-<title> exists while some cheat runs (a plain cheat on, or the masters while
++// not in safe mode, with the master switch on); a clean exit removes it (dm_cheats_exit), a crash leaves it for the next
++// launch. Not on iOS: an iOS app usually ends killed (swiped away, or while suspended), and the app has no cheats panel
++// to leave safe mode with. The verdict is taken here, under g_lock; the file itself is written by the files queue, where
++// it checks g_exiting again: a flag queued just before a clean exit must not come back after the exit removed it
++static void running_update(void) {
++#if TARGET_OS_IPHONE
++ return;
++#endif
++ if (!g_dir[0] || atomic_load(&g_exiting)) return;
++ int any = 0;
++ for (int i = 0; i < g_ncheat && !any; i++) {
++ const cheat_t *c = &g_cheat[i];
++ if (c->label || c->broken) continue;
++ any = c->master ? !g_safe : c->on;
++ }
++ char p[1100]; flag_file(p, sizeof p, "running");
++ int want = any && atomic_load(&g_master);
++ char *path = strdup(p), *build = strdup(g_build);
++ if (!path || !build) { free(path); free(build); return; }
++ dispatch_async(files_queue(), ^{
++ if (!atomic_load(&g_exiting)) {
++ if (want) { FILE *f = fopen(path, "w"); if (f) { fprintf(f, "%s\n", build); fclose(f); } }
++ else unlink(path);
++ }
++ free(path); free(build);
++ });
++}
++
++// Save the enabled states: one key per line, <build>.enabled in the cheats folder (masters are always on, labels never
++// run, and a "set" cheat or a pending restore runs one pass only, so none of them is saved). Rewritten on every menu
++// toggle and when a one-pass cheat fired, read at each load; the safe-mode flag follows the states. The content is
++// built here under g_lock and written by the files queue
++static void states_save(void) {
++ if (!g_dir[0] || !g_build[0]) return;
++ char p[1400]; snprintf(p, sizeof p, "%s/%s.enabled", g_dir, g_build);
++ size_t cap = (size_t)g_ncheat * (NAME_MAX + 16) + 1, o = 0; // every key with its newline fits
++ char *text = malloc(cap), *path = strdup(p);
++ if (!text || !path) { free(text); free(path); return; }
++ text[0] = 0;
++ for (int i = 0; i < g_ncheat; i++) {
++ const cheat_t *c = &g_cheat[i];
++ if (!c->on || c->master || c->label || c->once || c->restore_once) continue; // one-pass cheats are never saved as on
++ char k[NAME_MAX + 16]; cheat_key(c, k, sizeof k);
++ o += (size_t)snprintf(text + o, cap - o, "%s\n", k);
++ }
++ dispatch_async(files_queue(), ^{
++ // Written to a temporary beside it and renamed over the old file: fopen("w") truncates first, so an exit (or a
++ // crash) in the middle would leave the saved toggles empty; the rename is atomic, the old file stays until then
++ char tmp[1500]; snprintf(tmp, sizeof tmp, "%s.tmp", path);
++ FILE *f = fopen(tmp, "w");
++ if (!f) LOG("cheats: cannot write %s (errno %d)", tmp, errno);
++ else if (fputs(text, f) < 0 || fclose(f)) { LOG("cheats: cannot write %s (errno %d)", tmp, errno); unlink(tmp); }
++ else if (rename(tmp, path)) { LOG("cheats: cannot rename %s over %s (errno %d)", tmp, path, errno); unlink(tmp); }
++ free(text); free(path);
++ });
++ running_update();
++}
++
++// Turn on the cheats a states file names, key for key; a line that is no key ("X" written by an older version for every
++// entry of that name) turns on the next entry of that name that is still off, so such a file keeps all its duplicates on.
++// Returns how many it turned on, -1 when the file cannot be read
++static int states_read(const char *path) {
++ FILE *f = fopen(path, "r");
++ if (!f) return -1;
++ char line[1024]; int n = 0;
++ while (fgets(line, sizeof line, f)) {
++ char *save = NULL, *s = strtok_r(line, "\r\n", &save);
++ if (!s) continue;
++ int hit = -1;
++ for (int i = 0; i < g_ncheat && hit < 0; i++) {
++ cheat_t *c = &g_cheat[i];
++ char k[NAME_MAX + 16]; cheat_key(c, k, sizeof k);
++ if (!c->master && !c->label && !c->on && !strcmp(k, s)) hit = i;
++ }
++ for (int i = 0; i < g_ncheat && hit < 0; i++)
++ if (!g_cheat[i].master && !g_cheat[i].label && !g_cheat[i].on && !strcmp(g_cheat[i].name, s)) hit = i;
++ if (hit >= 0) { if (!g_cheat[hit].on) n++; g_cheat[hit].on = 1; }
++ }
++ fclose(f);
++ return n;
++}
++
++// The source a meta file says it was compiled from ("" when none)
++static void meta_source(const char *meta_path, char *out, size_t n) {
++ out[0] = 0;
++ FILE *f = fopen(meta_path, "r");
++ if (!f) return;
++ char line[512];
++ if (fgets(line, sizeof line, f) && !strncmp(line, "# cheat_anchor.py: compiled from ", 33)) {
++ char *e = strstr(line, " for build ");
++ if (e) snprintf(out, n, "%.*s", (int)(e - line - 33), line + 33);
++ }
++ fclose(f);
++}
++
++// The newest <BID>.enabled of the folder other than this build's whose build was compiled from the same source (its
++// <BID>.meta.tsv says so): a compiled file of a new build takes its toggles, the same cheats by name, and never those of
++// another game or another source sharing the folder; "" when there is none
++static void newest_other_enabled(char *out, size_t n) {
++ out[0] = 0;
++ DIR *d = opendir(g_dir);
++ if (!d) return;
++ struct dirent *e; time_t best = 0;
++ while ((e = readdir(d))) {
++ size_t L = strlen(e->d_name);
++ if (L != 16 + 8 || strcasecmp(e->d_name + 16, ".enabled") || !strncasecmp(e->d_name, g_build, 16)) continue;
++ char p[1400], src[256]; snprintf(p, sizeof p, "%s/%.16s.meta.tsv", g_dir, e->d_name);
++ meta_source(p, src, sizeof src);
++ if (!g_meta_src[0] || strcmp(src, g_meta_src)) continue;
++ snprintf(p, sizeof p, "%s/%s", g_dir, e->d_name);
++ struct stat st;
++ if (!stat(p, &st) && st.st_mtime >= best) { best = st.st_mtime; snprintf(out, n, "%s", e->d_name); }
++ }
++ closedir(d);
++}
++
++// Restore the states: the saved <build>.enabled (or, for a compiled file of a build without one, the newest other
++// build's), then DM_CHEATS_ON's names (name for name, case-insensitive, as the brief lets sites write the names); neither
++// writes a master or a label. In safe mode the saved states wait for dm_cheats_safe_restore
++static void states_load(void) {
++ g_carried[0] = 0;
++ files_drain(); // a save still on the files queue (a toggle, a "set" cheat that just fired) lands before it is read back
++ if (g_dir[0] && !g_safe) {
++ char path[1400]; snprintf(path, sizeof path, "%s/%s.enabled", g_dir, g_build);
++ if (states_read(path) < 0 && g_have_meta) {
++ char other[64]; newest_other_enabled(other, sizeof other);
++ if (other[0]) {
++ snprintf(path, sizeof path, "%s/%s", g_dir, other);
++ if (states_read(path) >= 0) snprintf(g_carried, sizeof g_carried, "%s", other);
++ }
++ }
++ }
++ for (int k = 0; k < g_non; k++)
++ for (int i = 0; i < g_ncheat; i++)
++ if (!g_cheat[i].master && !g_cheat[i].label && !strcasecmp(g_cheat[i].name, g_on[k])) g_cheat[i].on = 1;
++}
++
++// ---------- typed values the panel may set ("ask") ----------
++
++// The number base of a typed value: 16 for a "0x" prefix (after an optional sign), else 10 ("010" is ten, as
++// scripts/cheat_anchor.py reads it, never C's octal)
++static int value_base(const char *t) {
++ while (isspace((unsigned char)*t)) t++;
++ if (*t == '-' || *t == '+') t++;
++ return t[0] == '0' && (t[1] == 'x' || t[1] == 'X') ? 16 : 10;
++}
++
++// Set a cheat's value from text in its meta type, within its bounds: the program words that hold it are rewritten (an
++// 8-byte value: its high word, then its low word). 0 = done, -1 = refused (no ask, unparsable, out of bounds, no fit)
++static int value_set_locked(cheat_t *c, const char *text) {
++ unsigned w = type_width(c->type);
++ if (!c->ask || !w || !c->nvw || !text || !*text) return -1;
++ char *end = NULL; uint64_t raw; double d;
++ errno = 0;
++ if (c->type[0] == 'f') {
++ d = strtod(text, &end);
++ if (w == 4) { float f = (float)d; uint32_t u; memcpy(&u, &f, 4); raw = u; } else memcpy(&raw, &d, 8);
++ } else if (c->type[0] == 's') {
++ long long v = strtoll(text, &end, value_base(text)); d = (double)v;
++ if (w < 8 && (v < -(1ll << (8 * w - 1)) || v >= (1ll << (8 * w - 1)))) return -1;
++ raw = (uint64_t)v & width_mask(w);
++ } else {
++ if (strchr(text, '-')) return -1;
++ unsigned long long v = strtoull(text, &end, value_base(text)); d = (double)v;
++ if (w < 8 && v > width_mask(w)) return -1;
++ raw = v;
++ }
++ if (errno || end == text || (end && *end && !isspace((unsigned char)*end))) return -1;
++ if ((c->has_min && d < c->vmin) || (c->has_max && d > c->vmax)) return -1;
++ int per = w == 8 ? 2 : 1;
++ for (int k = 0; k + per <= c->nvw; k += per) {
++ if (per == 2) { c->ins[c->vw[k]] = (uint32_t)(raw >> 32); c->ins[c->vw[k + 1]] = (uint32_t)raw; }
++ else c->ins[c->vw[k]] = (uint32_t)raw;
++ }
++ return 0;
++}
++
++// The current value of an ask cheat as text in its type ("" when it takes none)
++static void value_get(const cheat_t *c, char *out, size_t n) {
++ out[0] = 0;
++ unsigned w = type_width(c->type);
++ if (!c->ask || !w || !c->nvw) return;
++ uint64_t raw = w == 8 && c->nvw >= 2 ? ((uint64_t)c->ins[c->vw[0]] << 32) | c->ins[c->vw[1]] : c->ins[c->vw[0]] & width_mask(w);
++ char k = c->type[0];
++ if (k == 'f' && w == 4) { uint32_t u = (uint32_t)raw; float f; memcpy(&f, &u, 4); snprintf(out, n, "%g", f); }
++ else if (k == 'f') { double v; memcpy(&v, &raw, 8); snprintf(out, n, "%g", v); }
++ else if (k == 's') { int sh = 64 - 8 * (int)w; snprintf(out, n, "%lld", (long long)((int64_t)(raw << sh) >> sh)); }
++ else snprintf(out, n, "%llu", (unsigned long long)raw);
++}
++
++// Save the panel's values: <build>.values, one "key<TAB>value" line per ask cheat
++static void values_save(void) {
++ if (!g_dir[0] || !g_build[0]) return;
++ char path[1400]; snprintf(path, sizeof path, "%s/%s.values", g_dir, g_build);
++ FILE *f = fopen(path, "w");
++ if (!f) { LOG("cheats: cannot write %s (errno %d)", path, errno); return; }
++ for (int i = 0; i < g_ncheat; i++) {
++ if (!g_cheat[i].ask) continue;
++ char k[NAME_MAX + 16], v[64]; cheat_key(&g_cheat[i], k, sizeof k); value_get(&g_cheat[i], v, sizeof v);
++ fprintf(f, "%s\t%s\n", k, v);
++ }
++ fclose(f);
++}
++
++// Apply <build>.values (a value that no longer fits its bounds keeps the file's own)
++static void values_load(void) {
++ if (!g_dir[0]) return;
++ char path[1400]; snprintf(path, sizeof path, "%s/%s.values", g_dir, g_build);
++ FILE *f = fopen(path, "r");
++ if (!f) return;
++ char line[1024];
++ while (fgets(line, sizeof line, f)) {
++ char *tab = strchr(line, '\t');
++ if (!tab) continue;
++ char *save = NULL;
++ *tab = 0; char *v = strtok_r(tab + 1, "\r\n", &save);
++ for (int i = 0; i < g_ncheat && v; i++) {
++ char k[NAME_MAX + 16]; cheat_key(&g_cheat[i], k, sizeof k);
++ if (!strcmp(k, line)) { value_set_locked(&g_cheat[i], v); break; }
++ }
++ }
++ fclose(f);
++}
++
++// ---------- loading: the folder, the build's file, the parse, the meta file ----------
++
++// The folders scanned, in the brief's order: the flat folder, the Atmosphère tree under it
++// (atmosphere/contents/<tid>/cheats) and the tree with the folder itself as the "atmosphere" half (contents/<tid>/cheats)
++static int scan_dirs(char out[3][1024]) {
++ if (!g_dir[0] || !g_tid[0]) return 0;
++ snprintf(out[0], 1024, "%s", g_dir);
++ snprintf(out[1], 1024, "%s/atmosphere/contents/%s/cheats", g_dir, g_tid);
++ snprintf(out[2], 1024, "%s/contents/%s/cheats", g_dir, g_tid);
++ return 3;
++}
++
++// Does the file name hold exactly this build ID (any case), as the atmosphere loader names its cheat files?
++static int name_is_build(const char *name, const char *build) {
++ for (int k = 0; k < 16; k++) {
++ char a = name[k], b = build[k];
++ if (!a) return 0;
++ a = (char)tolower((unsigned char)a); b = (char)tolower((unsigned char)b);
++ if (a != b) return 0;
++ }
++ return (int)strlen(name) >= 16 && (name[16] == '.' || !name[16]);
++}
++
++// The first 16 characters as a hex build ID (for the other-build list)? "another version of the game" needs a real
++// build ID name, so hunks like "readme.txt" do not show up as builds
++static int name_hex16(const char *name) {
++ if (strlen(name) < 16) return 0;
++ for (int k = 0; k < 16; k++) {
++ char a = (char)tolower((unsigned char)name[k]);
++ if (!((a >= '0' && a <= '9') || (a >= 'a' && a <= 'f'))) return 0;
++ }
++ return 1;
++}
++
++static char g_cand[CAND_MAX][2048]; static int g_ncand;
++
++// Collect the .txt files of one folder (case-insensitive suffix, .enabled ignored), deduped by path
++static void collect_dir(const char *dir_) {
++ DIR *d = opendir(dir_);
++ if (!d) return;
++ struct dirent *e;
++ while ((e = readdir(d))) {
++ size_t n = strlen(e->d_name);
++ if (n < 5 || strcasecmp(e->d_name + n - 4, ".txt")) continue;
++ if (g_ncand >= CAND_MAX) break;
++ char *p = g_cand[g_ncand];
++ snprintf(p, 2048, "%s/%s", dir_, e->d_name);
++ int dup = 0;
++ for (int i = 0; i < g_ncand; i++) if (!strcmp(g_cand[i], p)) { dup = 1; break; }
++ if (!dup) g_ncand++;
++ }
++ closedir(d);
++}
++
++// The whole file, with a header glued to a code word ("00000008[Next]": a whole 8-hex-digit word at the start of the line
++// or after a space) moved to a piece of its own (a '\v' break, which parse_file splits on without counting a line); NULL
++// when it cannot be read or is larger than FILE_MAX (no cheat file is). The caller frees it
++static char *read_text(const char *path) {
++ FILE *f = fopen(path, "rb");
++ if (!f) return NULL;
++ char *raw = malloc(FILE_MAX + 2);
++ size_t n = raw ? fread(raw, 1, FILE_MAX + 1, f) : 0;
++ fclose(f);
++ if (!raw) return NULL;
++ if (n > FILE_MAX) { LOG("[RED] cheats: %s is larger than %u bytes: not a cheat file", path, FILE_MAX); free(raw); errno = EFBIG; return NULL; }
++ raw[n] = 0;
++ char *out = malloc(2 * n + 1);
++ if (!out) { free(raw); return NULL; }
++ size_t o = 0;
++ for (size_t i = 0; i < n; i++) {
++ if ((raw[i] == '[' || raw[i] == '{') && i >= 8) { // a header right after a whole code word
++ int word = 1;
++ for (size_t k = i - 8; k < i && word; k++) word = isxdigit((unsigned char)raw[k]) != 0;
++ if (word && (i == 8 || raw[i - 9] == ' ' || raw[i - 9] == '\t' || raw[i - 9] == '\n' || raw[i - 9] == '\r')) { out[o++] = '\v'; g_glued++; }
++ }
++ out[o++] = raw[i];
++ }
++ out[o] = 0;
++ free(raw);
++ return out;
++}
++
++// EdiZon's section markers: [--SectionStart:Name--] (1) / [--SectionEnd:Name--] (2), the name copied out; 0 otherwise
++static int section_marker(const char *name, char *sec, size_t n) {
++ size_t L = strlen(name);
++ if (L < 4 || strcmp(name + L - 2, "--")) return 0;
++ int kind = !strncmp(name, "--SectionStart:", 15) ? 1 : !strncmp(name, "--SectionEnd:", 13) ? 2 : 0;
++ if (!kind) return 0;
++ size_t s = kind == 1 ? 15 : 13;
++ snprintf(sec, n, "%.*s", (int)(L - 2 - s), name + s);
++ return kind;
++}
++
++// Parse the file into the cheats array; lines other than [Name] / {Name} headers and 8-hex-digit code words
++// separated by spaces are ignored (the brief), with one [RED] line for a line whose words are code-like but not valid.
++// An entry without code words is a label (its name only: credits, or a section marker that sets the section of the
++// entries after it); every entry notes how many earlier entries carry its name (dup, the key of a duplicate)
++static void parse_file(const char *path) {
++ char *text = read_text(path);
++ if (!text) { LOG("[RED] cheats: cannot read %s (errno %d)", path, errno); return; }
++ cheat_t *cur = NULL;
++ int lineno = 1, warned = 0; // the file line of the next piece
++ char section[NAME_MAX] = "";
++ static uint32_t got[INS_MAX]; // one line's words (static: 32 KB, parse_file runs under g_lock only)
++ for (char *line = text, *next; line; line = next) {
++ // one piece: a file line, or part of one when a glued header was split off with '\v'
++ char *e = line + strcspn(line, "\n\v");
++ char sep = *e;
++ next = sep ? e + 1 : NULL;
++ *e = 0;
++ int ln = lineno; // the file line this piece is on, for the [RED] lines
++ if (sep == '\n') lineno++;
++ char *p = line;
++ while (*p == ' ' || *p == '\t') p++;
++ char end = 0;
++ if (*p == '[') end = ']';
++ else if (*p == '{') end = '}';
++ if (end) { // a header starts a new cheat; the name is what lies inside
++ char *q = strchr(p, end);
++ size_t nl = q && q > p ? (size_t)(q - p - 1) : 0;
++ if (nl == 0 || g_ncheat >= CHEAT_MAX) {
++ if (g_ncheat >= CHEAT_MAX && !warned++) LOG("[RED] cheats: more than %d cheats in %s, the rest is skipped", CHEAT_MAX, path);
++ cur = NULL;
++ continue;
++ }
++ cur = &g_cheat[g_ncheat++];
++ memset(cur, 0, sizeof *cur);
++ cur->pair = -1;
++ // the name keeps NAME_MAX - 1 characters: a shorter cut once let two long-named cheats share a line in <build>.enabled
++ // a cut name ends on a UTF-8 character boundary: the first byte left out must not be a continuation byte
++ int keep = (int)(nl > 127 ? 127 : nl);
++ if (nl > 127) while (keep > 0 && ((unsigned char)p[1 + keep] & 0xC0) == 0x80) keep--;
++ snprintf(cur->name, NAME_MAX, "%.*s", keep, p + 1);
++ cur->master = end == '}';
++ cur->on = cur->master;
++ char sec[NAME_MAX];
++ int mark = section_marker(cur->name, sec, sizeof sec);
++ if (mark == 1) snprintf(section, sizeof section, "%s", sec);
++ if (mark) cur->sec_mark = (uint8_t)mark;
++ snprintf(cur->section, NAME_MAX, "%s", mark == 1 ? sec : section);
++ if (mark == 2) section[0] = 0;
++ for (int i = 0; i < g_ncheat - 1; i++) if (!strcmp(g_cheat[i].name, cur->name)) cur->dup++;
++ p = q + 1; // dmnt reads on after the header: code words may follow on the same line
++ while (*p == ' ' || *p == '\t' || *p == '\r') p++;
++ if (!*p) continue;
++ }
++ if (!cur) continue; // words before any [Name] / {Name} header belong to nothing: the line is ignored (site files carry prose)
++ // The words of the line. dmnt accumulates hex digits and cuts a word every 8, whitespace only separating
++ // (docs/reference/cheats.md, "The file"), so a token of hex digits whose length is a multiple of 8 is that many
++ // words, glued ("0400000000123456"). A token of hex digits of any other length is not code on a Switch either
++ // (the file fails there) and here makes the line malformed: a 7-digit word is a typo, never prose. A token with
++ // a non-hex character is prose: alone it makes the line one to ignore, beside words it makes the line malformed.
++ // Every token is classified before the verdict, so a word after a prose token still counts as a word
++ int ngot = 0, prose = 0, oddhex = 0;
++ const char *badt = ""; // the token that is not a word, named on the [RED] line
++ for (char *s2 = NULL, *t = strtok_r(p, " \t\r", &s2); t; t = strtok_r(NULL, " \t\r", &s2)) {
++ size_t L = strlen(t), h = 0;
++ while (h < L && isxdigit((unsigned char)t[h])) h++;
++ if (h < L) { prose = 1; if (!badt[0]) badt = t; continue; }
++ if (L % 8) { oddhex = 1; badt = t; continue; }
++ for (size_t k = 0; k < L; k += 8) {
++ uint32_t w = 0;
++ for (size_t j = k; j < k + 8; j++) {
++ char a = (char)tolower((unsigned char)t[j]);
++ w = w << 4 | (a >= '0' && a <= '9' ? (unsigned)(a - '0') : (unsigned)(a - 'a' + 10));
++ }
++ if (ngot < INS_MAX) got[ngot++] = w;
++ else { LOG("[RED] cheat \"%s\": line %d has more than %d code words, the rest of the line is ignored", cur->name, ln, INS_MAX); break; }
++ }
++ }
++ if (!ngot && !prose && !oddhex) continue; // only whitespace
++ if (prose && !ngot && !oddhex) { // the file format ignores the line (the brief's "other lines"): prose, once warned
++ if (!g_junk++) g_junk_line = ln;
++ if (!cur->junk_line) cur->junk_line = ln;
++ if (!warned++) LOG("[RED] cheats: %s line %d is not code words and is ignored", path, ln);
++ continue;
++ }
++ if (prose || oddhex) {
++ // words would be dropped from a line that held them (or a hex token is not whole words): the dropped token
++ // may carry an instruction of its own (a vanished begin or end leaves the body running every frame
++ // unconditionally), so the cheat stays off entirely instead of silently running a fragment of itself; once
++ // per cheat, with the token named
++ if (!cur->broken) {
++ cur->broken = 1; snprintf(cur->why, sizeof cur->why, " (malformed line %d)", ln);
++ LOG("[RED] cheats: %s: \"%s\" line %d %s \"%s\", the cheat stays off", path, cur->name, ln, oddhex ? "holds hex digits that are not whole words:" : "mixes code words with", badt);
++ }
++ continue;
++ }
++ if (cur->nins + ngot > INS_MAX) { LOG("[RED] cheat \"%s\": over %d code words, skipped", cur->name, INS_MAX); continue; }
++ memcpy(cur->ins + cur->nins, got, sizeof(uint32_t) * (size_t)ngot);
++ cur->nins += ngot;
++ }
++ free(text);
++ // The verdict per cheat: no code words at all is a label (the meta file may still make it a host action), unless lines
++// under it were dropped as prose (then it is broken, with the first such line named); anything
++ // else is decoded word by word, and one instruction the VM does not run (unsupported opcode, region, width,
++ // condition) or the words ending inside a field turns the whole cheat off, shown in the menu with the reason, never run
++ for (int i = 0; i < g_ncheat; i++) {
++ cheat_t *c = &g_cheat[i];
++ if (c->broken) continue; // already off with its own reason (a malformed line): the decode would overwrite why
++ if (c->nins == 0 && c->junk_line) { // its lines were all prose: a broken cheat (a typo), not a label
++ c->broken = 1; snprintf(c->why, sizeof c->why, " (no code words: line %d is not code)", c->junk_line); continue;
++ }
++ if (c->nins == 0) { c->label = 1; c->on = 0; continue; }
++ for (int a = 0; a < c->nins;) {
++ ins_t in;
++ int len = ins_dec(c, c->ins + a, c->nins - a, &in);
++ if (len <= 0) break; // the reason is already in c->why and c->broken is set
++ a += len;
++ }
++ }
++}
++
++// Split a TSV line into at most max fields in place (empty fields kept); returns the count
++static int tsv_split(char *line, char **f, int max) {
++ int n = 0;
++ char *s = line;
++ while (n < max) {
++ f[n++] = s;
++ char *t = strchr(s, '\t');
++ if (!t) break;
++ *t = 0; s = t + 1;
++ }
++ char *e = f[n - 1] + strcspn(f[n - 1], "\r\n"); *e = 0;
++ return n;
++}
++
++// The display version a meta file's header names for a build ("# build <BID> <version>"), "" when none
++static void meta_version(const char *meta_path, const char *bid, char *out, size_t n) {
++ out[0] = 0;
++ FILE *f = fopen(meta_path, "r");
++ if (!f) return;
++ char line[512];
++ while (fgets(line, sizeof line, f) && line[0] == '#') {
++ if (strncmp(line, "# build ", 8) || strncasecmp(line + 8, bid, 16) || line[24] != ' ') continue;
++ snprintf(out, n, "%s", line + 25); out[strcspn(out, "\r\n")] = 0;
++ }
++ fclose(f);
++}
++
++// Is program word k of a cheat a value field of its instruction (the value of 0 / 1 / 4 / 6 / 7, 9's immediate, C0's static value)?
++// Decodes with a scratch cheat, so the cheat itself is never touched
++static int value_word(const cheat_t *c, int k) {
++ static cheat_t probe; // the decoder's scratch (it writes why / broken on a failure); callers hold g_lock
++ for (int a = 0; a < c->nins;) {
++ ins_t in;
++ int len = ins_dec(&probe, c->ins + a, c->nins - a, &in);
++ if (len <= 0) return 0;
++ int first = in.op == 0 || in.op == 1 ? a + 2 : in.op == 4 || in.op == 6 || in.op == 7 ? a + 1 : (in.op == 0xC0 && in.o == 4) || (in.op == 9 && in.flags) ? a + 1 : -1;
++ if (first >= 0 && k >= first && k < a + len) return 1;
++ a += len;
++ }
++ return 0;
++}
++
++// <txt>.meta.tsv: the companion scripts/cheat_anchor.py writes beside a compiled <build>.txt. Its rows go to the
++// entries of the same name in file order (a duplicate name's rows to its entries in turn); "unresolved" rows (cheats the
++// compiler left out) are listed for the panel. Columns are read by their header names
++static void meta_load(const char *txt_path) {
++ char path[2100];
++ size_t L = strlen(txt_path);
++ if (L < 4 || strcasecmp(txt_path + L - 4, ".txt")) return;
++ snprintf(path, sizeof path, "%.*s.meta.tsv", (int)(L - 4), txt_path);
++ FILE *f = fopen(path, "r");
++ if (!f) return;
++ g_have_meta = 1;
++ meta_source(path, g_meta_src, sizeof g_meta_src);
++ enum { NAME, KIND, SECTION, TYPE, ACTION, ASK, VWORDS, ONCE, PAIR, RESOLVED, NOTE, ADDRESS, NCOL };
++ static const char *cols[NCOL] = {"name", "kind", "section", "type", "action", "ask", "value_words", "once", "pair", "resolved", "note", "address"};
++ int at[NCOL]; for (int k = 0; k < NCOL; k++) at[k] = -1;
++ char line[4096]; int cursor = 0, head = 0;
++ while (fgets(line, sizeof line, f)) {
++ if (line[0] == '#') {
++ if (!g_version[0] && !strncmp(line, "# build ", 8) && !strncasecmp(line + 8, g_build, 16) && line[24] == ' ') {
++ snprintf(g_version, sizeof g_version, "%s", line + 25); g_version[strcspn(g_version, "\r\n")] = 0;
++ }
++ continue;
++ }
++ char *fld[24]; int nf = tsv_split(line, fld, 24);
++ if (!head) { // the header row: column names to indexes
++ head = 1;
++ for (int i = 0; i < nf; i++) for (int k = 0; k < NCOL; k++) if (!strcmp(fld[i], cols[k])) at[k] = i;
++ if (at[NAME] < 0) break;
++ continue;
++ }
++ #define COL(k) (at[k] >= 0 && at[k] < nf ? fld[at[k]] : "")
++ const char *name = COL(NAME), *kind = COL(KIND);
++ if (!strcmp(kind, "unresolved")) {
++ if (g_nskip < SKIP_MAX) { snprintf(g_skip_name[g_nskip], NAME_MAX, "%s", name); snprintf(g_skip_why[g_nskip], 160, "%s", COL(NOTE)); g_nskip++; }
++ continue;
++ }
++ int j = cursor;
++ while (j < g_ncheat && strcmp(g_cheat[j].name, name)) j++;
++ if (j >= g_ncheat) continue; // no entry of that name after the previous one: the row is ignored
++ cursor = j + 1;
++ cheat_t *c = &g_cheat[j];
++ if (COL(SECTION)[0] && !c->section[0]) snprintf(c->section, NAME_MAX, "%s", COL(SECTION));
++ snprintf(c->type, sizeof c->type, "%s", COL(TYPE));
++ if (!strcmp(COL(ONCE), "1")) c->once = 1;
++ if (!strcmp(kind, "patch-off")) c->pair_off = 1;
++ snprintf(c->pairname, NAME_MAX, "%s", COL(PAIR));
++ if (strstr(COL(RESOLVED), "weak")) c->weak = 1;
++ snprintf(c->note, sizeof c->note, "%s%s%s", COL(RESOLVED), COL(RESOLVED)[0] && COL(NOTE)[0] ? "; " : "", COL(NOTE));
++ if (COL(ASK)[0]) { // "min..max", either side may be empty
++ const char *a = COL(ASK), *dots = strstr(a, "..");
++ c->ask = 1;
++ if (dots && dots > a) { c->vmin = strtod(a, NULL); c->has_min = 1; }
++ if (dots && dots[2]) { c->vmax = strtod(dots + 2, NULL); c->has_max = 1; }
++ for (char *s = (char *)COL(VWORDS), *e; *s && c->nvw < VW_MAX; s = *e ? e + 1 : e) {
++ long v = strtol(s, &e, 10);
++ if (e == s) break;
++ if (v >= 0 && v < c->nins) c->vw[c->nvw++] = (int)v;
++ }
++ // the indexes must be value words of the program's own instructions, in whole values (an 8-byte value is two
++ // words): a value set may never rewrite an opcode word behind the load-time verdict
++ unsigned w = type_width(c->type);
++ if (!w || !c->nvw || c->nvw % (w == 8 ? 2 : 1) || c->broken) c->ask = 0;
++ for (int k = 0; k < c->nvw && c->ask; k++) if (!value_word(c, c->vw[k])) c->ask = 0;
++ }
++ if (!strcmp(COL(ACTION), "never-decrease") && c->nins == 0) { // "region:0xOFFSET" of a typed address
++ const char *a = COL(ADDRESS), *colon = strchr(a, ':');
++ if (colon && type_width(c->type)) {
++ c->nd_region = (uint8_t)atoi(a); c->nd_off = strtoull(colon + 1, NULL, 0);
++ if (c->nd_region <= 1) { c->nd = 1; c->label = 0; }
++ }
++ }
++ #undef COL
++ }
++ fclose(f);
++}
++
++// "X - on" / "X - off" (also "X on", "X: off", "X (off)", …): the base name and which half, 1 when the name has the form
++static int onoff_split(const char *name, char *base, size_t n, int *is_off) {
++ size_t e = strlen(name);
++ while (e && isspace((unsigned char)name[e - 1])) e--;
++ if (e && (name[e - 1] == ')' || name[e - 1] == ']')) e--;
++ int off;
++ if (e >= 3 && !strncasecmp(name + e - 3, "off", 3)) { off = 1; e -= 3; }
++ else if (e >= 2 && !strncasecmp(name + e - 2, "on", 2)) { off = 0; e -= 2; }
++ else return 0;
++ size_t s = e; int sep = 0;
++ while (s && strchr(" -:_([", name[s - 1])) { s--; sep = 1; }
++ if (!sep || !s) return 0;
++ snprintf(base, n, "%.*s", (int)s, name);
++ *is_off = off;
++ return 1;
++}
++
++// Link on / off pairs: the meta file's pair names first, then the naming convention for files without one; both halves
++// must be plain runnable cheats (a master runs whatever its toggle says, so it can never be half of a switch)
++static void pairs_link(void) {
++ for (int i = 0; i < g_ncheat; i++) {
++ cheat_t *c = &g_cheat[i];
++ if (!c->pairname[0] || c->pair >= 0 || c->master || c->label || c->nd || c->broken) continue;
++ for (int j = 0; j < g_ncheat; j++) {
++ cheat_t *o = &g_cheat[j];
++ if (j == i || o->pair >= 0 || o->master || o->label || o->nd || o->broken || strcmp(o->name, c->pairname)) continue;
++ c->pair = j; o->pair = i; break;
++ }
++ }
++ for (int i = 0; i < g_ncheat; i++) {
++ cheat_t *a = &g_cheat[i]; char ba[NAME_MAX]; int offa;
++ if (a->pair >= 0 || a->master || a->label || a->nd || !onoff_split(a->name, ba, sizeof ba, &offa)) continue;
++ for (int j = i + 1; j < g_ncheat; j++) {
++ cheat_t *b = &g_cheat[j]; char bb[NAME_MAX]; int offb;
++ if (b->pair >= 0 || b->master || b->label || b->nd || !onoff_split(b->name, bb, sizeof bb, &offb)) continue;
++ if (offa == offb || strcasecmp(ba, bb)) continue;
++ a->pair = j; b->pair = i; a->pair_off = (uint8_t)offa; b->pair_off = (uint8_t)offb;
++ break;
++ }
++ }
++}
++
++// The load report (dm_cheats_report, and the log): counts, duplicate names, ignored lines, where the states came from,
++// the compiler's left-outs, and Atmosphère's limits (a Switch refuses past them; this host takes more)
++static void report_build(void) {
++ char *r = g_report; size_t n = sizeof g_report, o = 0;
++ #define ADD(...) do { if (o < n) o += (size_t)snprintf(r + o, n - o, __VA_ARGS__); } while (0)
++ int cheats = 0, on = 0, bad = 0, labels = 0, sections = 0, masters = 0, enabled_words = 0, big = 0;
++ for (int i = 0; i < g_ncheat; i++) {
++ const cheat_t *c = &g_cheat[i];
++ if (c->label) { labels++; sections += c->sec_mark == 1; continue; }
++ cheats++; masters += c->master; bad += c->broken;
++ if ((c->on || c->master) && !c->broken) { on += !c->master; enabled_words += c->nins; }
++ if (c->nins > ATM_WORDS) big++;
++ }
++ r[0] = 0;
++ ADD("Build %s%s%s%s: %d cheats (%d on, %d master, %d broken)", g_build, g_version[0] ? " (" : "", g_version, g_version[0] ? ")" : "", cheats, on, masters, bad);
++ if (labels) ADD(", %d labels (%d sections)", labels, sections);
++ ADD("\n");
++ int dups = 0;
++ for (int i = 0; i < g_ncheat; i++) if (g_cheat[i].dup == 1 && !g_cheat[i].label) { if (!dups++) ADD("Duplicate names (saved as \"Name #2\", …):"); ADD(" \"%s\"", g_cheat[i].name); }
++ if (dups) ADD("\n");
++ if (g_junk) ADD("%d lines that are not code words were ignored (the first: line %d)\n", g_junk, g_junk_line);
++ if (g_glued) ADD("%d headers glued to a code line were split off\n", g_glued);
++ if (g_carried[0]) ADD("Toggles carried over from %s (no %s.enabled yet)\n", g_carried, g_build);
++ if (g_safe) ADD("Safe mode: the last run ended without a clean exit while cheats were on; every cheat starts off\n");
++ if (!atomic_load(&g_master)) ADD("The master switch is off: no cheat runs\n");
++ if (g_nskip) ADD("%d cheats were left out when this file was compiled\n", g_nskip);
++ if (cheats > ATM_CHEATS || big || enabled_words > ATM_PROGRAM)
++ ADD("Over Atmosphère's limits (a Switch refuses them): %d cheats (0x80), %d cheats over 0x100 words, %d words enabled (0x400)\n", cheats, big, enabled_words);
++ #undef ADD
++}
++
++// This build's display version from the profile's build rows (by the whole main build ID), as GetDisplayVersion answers it
++static void profile_version(void) {
++#ifdef DM_GAME_DISPLAY_VERSIONS
++ static const struct { const char *build, *ver; } k[] = {DM_GAME_DISPLAY_VERSIONS};
++ const char *bid = dm_main_build();
++ for (unsigned j = 0; j < sizeof k / sizeof *k; j++) if (!strcasecmp(bid, k[j].build)) snprintf(g_version, sizeof g_version, "%s", k[j].ver);
++#endif
++}
++
++// The anchored sources (*.cheats.toml) in the folder, for the panel's "compile them for this build" hint
++static void sources_scan(void) {
++ g_nsrc = 0;
++ DIR *d = g_dir[0] ? opendir(g_dir) : NULL;
++ if (!d) return;
++ struct dirent *e;
++ while ((e = readdir(d)) && g_nsrc < SRC_MAX) {
++ size_t L = strlen(e->d_name);
++ if (L > 12 && !strcasecmp(e->d_name + L - 12, ".cheats.toml")) snprintf(g_src[g_nsrc++], sizeof g_src[0], "%s", e->d_name);
++ }
++ closedir(d);
++}
++
++// (Re)load: choose the file, note the other builds, parse, read the meta file and the values, link pairs, restore the
++// states, build the report. Called at init and from "Reload cheats" (safe mode and the master switch stay as they are)
++static void load_all(void) {
++ g_ncheat = 0; g_ncand = 0; g_nothers = 0; g_path[0] = 0; g_nskip = 0; g_have_meta = 0;
++ g_junk = g_junk_line = g_glued = 0; g_carried[0] = 0; g_version[0] = 0; g_meta_src[0] = 0;
++ memset(g_static, 0, sizeof g_static); // the reference clears its static registers when it loads cheats
++ atomic_store(&g_active, 0);
++ profile_version();
++ sources_scan();
++ char dirs[3][1024]; int nd = scan_dirs(dirs);
++ for (int i = 0; i < nd; i++) collect_dir(dirs[i]);
++ if (!g_build[0]) { LOG("[RED] cheats: the main NSO has no build ID, so no file can be picked from %s", g_dir); return; }
++ int pick = -1, other = 0; // pick = the matching candidate; other = when a non-matching one is used by DM_CHEATS_ANY_BUILD
++ int nbuild = 0, lone = -1; // the candidates named after a build ID, and the last of them: DM_CHEATS_ANY_BUILD takes the
++ // single such file, never a readme.txt that collect_dir listed beside it
++ for (int i = 0; i < g_ncand; i++) { // the whole list is walked: the build's file may lie after an "another version" one
++ const char *nm = strrchr(g_cand[i], '/') + 1;
++ int hex = name_hex16(nm);
++ if (!hex) continue;
++ nbuild++; lone = i;
++ if (name_is_build(nm, g_build)) {
++ if (pick < 0) pick = i; // the first matching candidate wins (the flat folder, then the Atmosphere tree)
++ continue; // keep walking: the other builds get collected below either way
++ }
++ // the other versions of the game (max OTHER_MAX, the menu shows them disabled), with their versions when a meta file names them
++ int dup = 0;
++ for (int k = 0; k < g_nothers; k++) if (!strncasecmp(g_others[k], nm, 16)) { dup = 1; break; }
++ if (!dup && g_nothers < OTHER_MAX) {
++ snprintf(g_others[g_nothers], 17, "%s", nm);
++ char mp[2100]; snprintf(mp, sizeof mp, "%.*s.meta.tsv", (int)(strlen(g_cand[i]) - 4), g_cand[i]);
++ meta_version(mp, g_others[g_nothers], g_other_ver[g_nothers], sizeof g_other_ver[0]);
++ g_nothers++;
++ }
++ }
++ if (pick < 0 && !(g_any && nbuild == 1)) {
++ LOG("cheats: %s: no file for build %s", g_dir, g_build);
++ if (g_nothers && atomic_load(&g_dbg)) { // the menu's "another version" rows, this file's context
++ char list[OTHER_MAX * 18]; list[0] = 0;
++ for (int i = 0; i < g_nothers; i++) { strlcat(list, " ", sizeof list); strlcat(list, g_others[i], sizeof list); }
++ LOG("cheats: %s: %d .txt of other builds in the folder:%s", g_dir, g_nothers, list);
++ }
++ report_build();
++ running_update(); // no cheat runs now: a reload that lost its file must not leave the safe-mode flag behind
++ return;
++ }
++ if (pick < 0) { pick = lone; other = 1; } // DM_CHEATS_ANY_BUILD and a single file of another build: load it
++ g_nothers = 0; // a file is loaded (this build's own, or DM_CHEATS_ANY_BUILD's): no "another version" rows
++ snprintf(g_path, sizeof g_path, "%s", g_cand[pick]);
++ // The writable alias of main is mapped once a cheat file is actually picked, not at init merely because DM_ROOT is
++ // set: a run without cheats would otherwise always map a second image of main and log a line for it. At init the
++ // pick happens before the guest starts; a later "Reload cheats" retries only when no alias mapped the first time
++ if (g_main_mod && !g_alias) {
++ alias_setup();
++ LOG("cheats: writable alias of main %s", g_alias ? "mapped" : "not mapped (mprotect toggle fallback)");
++ }
++ parse_file(g_path);
++ meta_load(g_path);
++ pairs_link();
++ values_load();
++ states_load();
++ // the summary: masters are always on, a broken / empty cheat never runs, the rest keep the menu's saved state
++ int on = 0, bad = 0, masters = 0, labels = 0;
++ for (int i = 0; i < g_ncheat; i++) {
++ if (g_cheat[i].label) { labels++; continue; }
++ if (g_cheat[i].master) masters++;
++ if (g_cheat[i].broken) bad++;
++ else if (!g_cheat[i].master && g_cheat[i].on) on++;
++ }
++ if (other) LOG("[RED] cheats: no file for build %s, loading %s of another build on DM_CHEATS_ANY_BUILD: its addresses may be wrong", g_build, g_cand[pick]);
++ LOG("cheats: %s: build %s: %d cheats (%d master, %d on, %d broken, %d runnable)%s", g_path, g_build, g_ncheat - labels, masters, on, bad, g_ncheat - labels - bad,
++ g_have_meta ? ", with its meta file" : "");
++ report_build();
++ atomic_store(&g_active, g_ncheat > labels);
++ running_update();
++}
++
++// The folder's flag files of this game, read once at init: .cheats-off-<title> (the master switch) and
++// .cheats-running-<title> (left behind by a run that did not end cleanly while cheats were on: safe mode for this launch)
++static void folder_flags(void) {
++ if (!g_dir[0]) return;
++ char p[1100];
++ flag_file(p, sizeof p, "off");
++ atomic_store(&g_master, access(p, F_OK) != 0);
++#if !TARGET_OS_IPHONE // iOS keeps no safe mode (running_update)
++ flag_file(p, sizeof p, "running");
++ g_safe = access(p, F_OK) == 0;
++#endif
++ if (g_safe) LOG("[RED] cheats: the last run ended without a clean exit while cheats were on: every cheat starts off (the Cheats panel restores them)");
++}
++
++// Read the switches, find the game's file, load it, and start the idle apply thread. Called after load_modules
++// (main.c host_preload): the build ID to pick the file by comes from the modules them
++void dm_cheats_init(void) {
++ atomic_store(&g_dbg, !!getenv("DM_CHEATS_DEBUG"));
++ const char *e = getenv("DM_CHEATS_ANY_BUILD"); g_any = e && *e && atoi(e) != 0;
++ e = getenv("DM_CHEATS");
++ if (e && *e) snprintf(g_dir, sizeof g_dir, "%s", e);
++ else { e = getenv("DM_ROOT"); if (e && *e) snprintf(g_dir, sizeof g_dir, "%s/cheats", e); }
++ snprintf(g_tid, sizeof g_tid, "%016llX", (unsigned long long)DM_GAME_PROGRAM_ID);
++ // g_build: the main NSO's first 16 hex digits, upper case like the menu and the brief state them; the candidate
++ // match itself is case-insensitive (name_is_build lower-cases both sides)
++ const char *bid = dm_main_build();
++ if (strlen(bid) >= 16) {
++ for (int k = 0; k < 16; k++) g_build[k] = (char)toupper((unsigned char)bid[k]);
++ g_build[16] = 0;
++ }
++ e = getenv("DM_CHEATS_ON");
++ if (e && *e) { // one-off names turned on at launch, split on ','; the saves' own <build>.enabled states stay too
++ char *dup = strdup(e), *s = dup;
++ while (s && g_non < 16) {
++ char *t = strchr(s, ',');
++ if (t) *t = 0;
++ if (*s) snprintf(g_on[g_non++], NAME_MAX, "%s", s);
++ s = t ? t + 1 : NULL;
++ }
++ free(dup);
++ }
++ if (!g_dir[0]) { LOG("cheats: off (neither DM_CHEATS nor DM_ROOT is set)"); }
++ else { // for the main module the pass needs its base: the loader's g_mod tables them by name
++ for (int i = 0; i < g_nmod; i++) if (!strcmp(g_mod[i].name, "main") && !g_mod[i].nro) { g_main_mod = &g_mod[i]; break; }
++ folder_flags();
++ if (g_main_mod) { pthread_mutex_lock(&g_lock); load_all(); pthread_mutex_unlock(&g_lock); } // load_all maps the writable alias once a file is picked
++ atexit(dm_cheats_exit); // exit() paths (⌘Q, closing the window); dm_host_exit's _exit calls it itself
++ }
++ atomic_store(&g_inited, 1);
++ pthread_t th; pthread_attr_t a; pthread_attr_init(&a); pthread_attr_setdetachstate(&a, PTHREAD_CREATE_DETACHED);
++ // The idle thread always runs (it stands down while the presents are recent, and a later "Reload cheats" that
++ // brings cheats in must also get its idle passes)
++ if (pthread_create(&th, &a, cheat_tick_thread, NULL)) LOG("[RED] cheats: cannot start the ~60 Hz apply thread (errno %d), only presents apply", errno);
++ pthread_attr_destroy(&a);
++}
++
++// A clean exit: no cheat runs any more, so the safe-mode flag goes (atexit, and dm_host_exit before its _exit)
++void dm_cheats_exit(void) {
++ atomic_store(&g_exiting, 1); // a pass still running on another thread must not write the flag back
++ if (!g_dir[0]) return;
++ files_drain(); // a queued <build>.enabled lands before the process ends; a queued flag sees g_exiting
++ char p[1100]; flag_file(p, sizeof p, "running");
++ unlink(p);
++}
++
++// ---------- the Mac cheats menu and panel (callers: front_mac.m; nothing else uses these) ----------
++// Cheap accessors read straight from the shared state: the list itself is rebuilt only from the main thread (this
++// menu's own actions, and init on the Mac's main thread), and a VM pass mutates only its own cheat's dead / why / fails /
++// noted fields, the on / restore_once flags of a one-pass cheat, the never-decrease state, and (through the files queue)
++// <build>.enabled and the safe-mode flag when a one-pass cheat fired; the worst-case tear shows as one stale row in a
++// row rebuilt in that instant. Each accessor's meaning is in dm.h
++
++int dm_cheats_found(void) { return atomic_load(&g_active) || g_ncheat > 0; } // a file, of this build or another
++
++int dm_cheats_ncheats(void) { return g_ncheat; }
++
++const char *dm_cheats_build(void) { return g_build; } // static after init
++
++const char *dm_cheats_dir_path(void) { return g_dir; } // "" when neither DM_CHEATS nor DM_ROOT is set
++
++int dm_cheats_nothers(void) { return g_nothers; }
++
++const char *dm_cheats_other(int i) { return i >= 0 && i < g_nothers ? g_others[i] : ""; }
++
++const char *dm_cheats_other_version(int i) { return i >= 0 && i < g_nothers ? g_other_ver[i] : ""; }
++
++const char *dm_cheats_version(void) { return g_version; }
++
++const char *dm_cheat_name_at(int i) { return i >= 0 && i < g_ncheat ? g_cheat[i].name : ""; }
++
++const char *dm_cheat_why_at(int i) { return i >= 0 && i < g_ncheat ? g_cheat[i].why : ""; }
++
++const char *dm_cheat_section_at(int i) { return i >= 0 && i < g_ncheat ? g_cheat[i].section : ""; }
++
++const char *dm_cheat_note_at(int i) { return i >= 0 && i < g_ncheat ? g_cheat[i].note : ""; }
++
++const char *dm_cheat_type_at(int i) { return i >= 0 && i < g_ncheat ? g_cheat[i].type : ""; }
++
++int dm_cheat_pair_at(int i) { return i >= 0 && i < g_ncheat ? g_cheat[i].pair : -1; }
++
++// The row's kind, for the menu's builder: 0 = a plain cheat (click toggles), 1 = master (always on, no click),
++// 2 = broken / off (disabled), 3 = a label (credits, a section marker: no checkbox). The checkmark itself: dm_cheat_on_at
++int dm_cheat_kind_at(int i) {
++ if (i < 0 || i >= g_ncheat) return 2;
++ const cheat_t *c = &g_cheat[i];
++ return c->label ? 3 : c->broken || c->dead ? 2 : c->master ? 1 : 0;
++}
++
++// The row's DM_CHEAT_* flags (dm.h)
++int dm_cheat_flags_at(int i) {
++ if (i < 0 || i >= g_ncheat) return 0;
++ const cheat_t *c = &g_cheat[i];
++ return (c->label ? DM_CHEAT_LABEL : 0) | (c->sec_mark == 1 ? DM_CHEAT_SECTION_START : 0) | (c->sec_mark == 2 ? DM_CHEAT_SECTION_END : 0)
++ | (c->pair >= 0 ? (c->pair_off ? DM_CHEAT_PAIR_OFF : DM_CHEAT_PAIR_ON) : 0) | (c->once ? DM_CHEAT_ONCE : 0)
++ | (c->ask ? DM_CHEAT_ASK : 0) | (c->nd ? DM_CHEAT_HOST : 0) | (c->weak ? DM_CHEAT_WEAK : 0);
++}
++
++int dm_cheat_on_at(int i) { return i >= 0 && i < g_ncheat ? g_cheat[i].on != 0 : 0; }
++
++// The menu's toggle: flip the cheat, save the states. A pair is one switch: turning its on half off runs the off half (the
++// restore) for one pass, turning the on half on turns the off half off, and turning the off half on turns the on half off.
++// Turning a cheat on ends safe mode (the player chose: the saved toggles come back too) and starts a never-decrease from
++// the value there now
++void dm_cheat_toggle(int i) {
++ if (i < 0 || i >= g_ncheat) return;
++ pthread_mutex_lock(&g_lock);
++ cheat_t *c = &g_cheat[i];
++ if (!c->master && !c->broken && !c->dead && !c->label) {
++ int now = !c->on;
++ if (now && g_safe) { g_safe = 0; states_load(); } // the player turns a cheat on in safe mode: the saved toggles come back first
++ c->on = (uint8_t)now;
++ c->restore_once = 0; // the player's own choice: a pending one-pass restore no longer applies
++ if (now) c->nd_have = 0;
++ if (c->noted) { c->noted = 0; c->why[0] = 0; } // the failed-access note describes passes before this choice; its next pass renews it if it must
++ if (c->pair >= 0) {
++ cheat_t *p = &g_cheat[c->pair];
++ if (!c->pair_off) { if (!p->broken && !p->dead) { p->on = (uint8_t)!now; p->restore_once = (uint8_t)!now; } }
++ else if (now) p->on = 0;
++ }
++ states_save();
++ }
++ pthread_mutex_unlock(&g_lock);
++}
++
++// "Reload cheats": re-read the file (the same path), so edits during play do not need a re-launch
++void dm_cheats_reload(void) {
++ pthread_mutex_lock(&g_lock);
++ load_all();
++ pthread_mutex_unlock(&g_lock);
++}
++
++// The dry run: what cheat i would write right now, one line per write ("main+0x… (2 bytes): 37 -> 999"), nothing written
++// and nothing turned off (static registers, never-decrease state, the failure counts and C4's previous-keys value are
++// left as they were). The cheats a pass runs before it (the masters, the enabled plain cheats earlier in the file) are
++// replayed first with their description switched off, so the registers and the saved values hold what a real pass
++// leaves in them when its turn comes (cheats_pass shares them); the keys are read once, like a pass. Returns the number
++// of writes
++int dm_cheat_preview(int i, char *out, size_t cap) {
++ if (!out || !cap) return 0;
++ out[0] = 0;
++ if (i < 0 || i >= g_ncheat) return 0;
++ pthread_mutex_lock(&g_lock);
++ cheat_t *c = &g_cheat[i];
++ g_dry_out = out; g_dry_cap = cap; g_dry_len = 0; g_dry_writes = 0;
++ if (c->label) dry_line("a label, not a cheat");
++ else if (c->broken || c->dead) dry_line("does not run:%s", c->why);
++ else if (c->nd) {
++ unsigned w = type_width(c->type); uint64_t cur = 0; char where[48], now[48], mx[48];
++ uint64_t base = c->nd_region == 0 ? (g_main_mod ? (uint64_t)(uintptr_t)g_main_mod->base : 0) : region_base(1);
++ addr_name(base + c->nd_off, where, sizeof where);
++ if (!base || peek(base + c->nd_off, w, &cur)) dry_line("%s: not mapped right now", where);
++ else {
++ value_text(c, w, cur, now, sizeof now);
++ if (c->on && c->nd_have) { value_text(c, w, c->nd_max, mx, sizeof mx); dry_line("%s: %s now, kept at least %s (the highest seen)", where, now, mx); }
++ else dry_line("%s: %s now; turned on, it never goes below the highest value it reaches", where, now);
++ }
++ } else {
++ static uint64_t keep[256];
++ memcpy(keep, g_static, sizeof keep);
++ g_held = dm_cheats_keys();
++ memset(g_reg, 0, sizeof g_reg); memset(g_saved, 0, sizeof g_saved); // the loop tops are reset per cheat by vm_run
++ g_dry = 1;
++ g_dry_out = NULL; // the predecessors' run describes nothing (dry_line returns at once) and writes nothing
++ for (int half = 0, stop = 0; half < 2 && !stop; half++) for (int j = 0; j < g_ncheat && !stop; j++) {
++ cheat_t *o = &g_cheat[j];
++ if (o == c && (half == 0) == (c->master != 0)) { stop = 1; break; } // its own turn: the replay ends here
++ if (pass_runs(o, half) && !o->nd) vm_run(o); // never-decrease keeps its own state: not replayed
++ }
++ g_dry_out = out; g_dry_len = 0; g_dry_writes = 0;
++ vm_run(c);
++ g_dry = 0;
++ memcpy(g_static, keep, sizeof keep);
++ if (!g_dry_writes && !g_dry_len) dry_line("writes nothing right now (a condition is not met, or a patch's code is not the original any more)");
++ }
++ int n = g_dry_writes;
++ g_dry_out = NULL;
++ pthread_mutex_unlock(&g_lock);
++ return n;
++}
++
++// The value of an "ask" cheat as text (1), or 0 when it takes none
++int dm_cheat_value_get(int i, char *out, size_t cap) {
++ if (!out || !cap) return 0;
++ out[0] = 0;
++ if (i < 0 || i >= g_ncheat || !g_cheat[i].ask) return 0;
++ pthread_mutex_lock(&g_lock);
++ value_get(&g_cheat[i], out, cap);
++ pthread_mutex_unlock(&g_lock);
++ return 1;
++}
++
++// Set an "ask" cheat's value (text in its type, within its bounds) and remember it in <build>.values: 0 done, -1 refused
++int dm_cheat_value_set(int i, const char *text) {
++ if (i < 0 || i >= g_ncheat) return -1;
++ pthread_mutex_lock(&g_lock);
++ int r = value_set_locked(&g_cheat[i], text);
++ if (!r) values_save();
++ pthread_mutex_unlock(&g_lock);
++ return r;
++}
++
++// The bounds of an "ask" cheat's value as "min..max" (either side empty when open), "" when it takes none
++const char *dm_cheat_value_bounds(int i) {
++ static char b[64];
++ b[0] = 0;
++ if (i < 0 || i >= g_ncheat || !g_cheat[i].ask) return b;
++ const cheat_t *c = &g_cheat[i];
++ char lo[24] = "", hi[24] = "";
++ if (c->has_min) snprintf(lo, sizeof lo, "%g", c->vmin);
++ if (c->has_max) snprintf(hi, sizeof hi, "%g", c->vmax);
++ snprintf(b, sizeof b, "%s..%s", lo, hi);
++ return b;
++}
++
++// The master switch: off stops every cheat (masters too) without touching the toggles; kept in the folder's .cheats-off-<title>
++int dm_cheats_master(void) { return atomic_load(&g_master); }
++
++void dm_cheats_master_set(int on) {
++ pthread_mutex_lock(&g_lock);
++ atomic_store(&g_master, !!on);
++ if (g_dir[0]) {
++ char p[1100]; flag_file(p, sizeof p, "off");
++ if (on) unlink(p);
++ else { FILE *f = fopen(p, "w"); if (f) fclose(f); }
++ }
++ report_build();
++ running_update();
++ pthread_mutex_unlock(&g_lock);
++}
++
++// Safe mode (the last run ended without a clean exit while cheats were on): 1 while every cheat waits for the player
++int dm_cheats_safe(void) { return g_safe; }
++
++// Leave safe mode: the masters run again and the saved toggles come back
++void dm_cheats_safe_restore(void) {
++ pthread_mutex_lock(&g_lock);
++ if (g_safe) {
++ g_safe = 0;
++ states_load();
++ report_build();
++ running_update();
++ }
++ pthread_mutex_unlock(&g_lock);
++}
++
++const char *dm_cheats_report(void) { return g_report; }
++
++int dm_cheats_nskipped(void) { return g_nskip; }
++
++const char *dm_cheats_skipped_name(int i) { return i >= 0 && i < g_nskip ? g_skip_name[i] : ""; }
++
++const char *dm_cheats_skipped_why(int i) { return i >= 0 && i < g_nskip ? g_skip_why[i] : ""; }
++
++int dm_cheats_nsources(void) { return g_nsrc; }
++
++const char *dm_cheats_source(int i) { return i >= 0 && i < g_nsrc ? g_src[i] : ""; }
+diff --git a/dm/host/hle_hid.c b/dm/host/hle_hid.c
+index 148fdb3c..095ad8af 100644
+--- a/dm/host/hle_hid.c
++++ b/dm/host/hle_hid.c
+@@ -258,6 +258,31 @@ static void fill(NpadState *s, uint32_t id, uint32_t style) {
+ s->buttons = b;
+ s->attributes = ATTR_CONNECTED | (id == NPAD_HANDHELD ? ATTR_WIRED | ATTR_LEFT_CONN | ATTR_LEFT_WIRED | ATTR_RIGHT_CONN | ATTR_RIGHT_WIRED : ATTR_LEFT_CONN | ATTR_RIGHT_CONN);
+ }
++// The cheat VM's key mask (hle_cheats.c "all keys of the mask held"): the OR of every player's controller buttons
++// (the keyboard / touch source's bits included) plus the eight stick-direction pseudo buttons of the merged axes —
++// one flat bitset, not exactly any one npad read (fill() publishes per-npad states with attributes, merges and
++// latches), and nothing here consumes a latch or bumps the sampling: the game's own reads keep them both. Mask bits:
++// the buttons 0..15 in NpadButton order and the sticks' directions 16..23; SL / SR (bits 24 / 25) can never fire, no
++// input source of this host reports them
++uint64_t dm_cheats_keys(void) {
++ uint64_t b = 0; int32_t a[4] = {0};
++ b |= atomic_load(&g_btn);
++ for (int p = 0; p < DM_PLAYERS; p++) {
++ b |= atomic_load(&g_pad_btn[p]);
++ uint64_t v = atomic_load(&g_pad_axes[p]); for (int i = 0; i < 4; i++) a[i] = pick(a[i], ax(v, i));
++ }
++ uint64_t k = atomic_load(&g_axes); for (int i = 0; i < 4; i++) a[i] = pick(a[i], ax(k, i));
++ b &= 0xffffull;
++ if (a[0] < -STICK_THRESH) b |= 1u << 16;
++ if (a[1] > STICK_THRESH) b |= 1u << 17;
++ if (a[0] > STICK_THRESH) b |= 1u << 18;
++ if (a[1] < -STICK_THRESH) b |= 1u << 19;
++ if (a[2] < -STICK_THRESH) b |= 1u << 20;
++ if (a[3] > STICK_THRESH) b |= 1u << 21;
++ if (a[2] > STICK_THRESH) b |= 1u << 22;
++ if (a[3] < -STICK_THRESH) b |= 1u << 23;
++ return b;
++}
+ // GetNpadStates(out, n, id): newest first, n entries: the current state repeated with consecutive sampling numbers. The host keeps no history, but on hardware the
+ // 16-entry history is always full, and games read all of it whatever count comes back: Super Mario Odyssey (main+0x93fc20) polls every controller slot each frame, which advances
+ // the shared sampling number by about 16 per frame, and with only entry 0 written neither stick did anything in play (the camera did not turn at its first hint) while buttons
+diff --git a/dm/host/hle_lifecycle.c b/dm/host/hle_lifecycle.c
+index e70fd9bd..c961452f 100644
+--- a/dm/host/hle_lifecycle.c
++++ b/dm/host/hle_lifecycle.c
+@@ -13,6 +13,7 @@ void dm_host_shutdown(const char *why) {
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1500 * NSEC_PER_MSEC), dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0), ^{
+ LOG("[RED] graceful exit not done in 1.5 seconds, exiting at once"); _exit(0); });
+ hlecount_flush(); // DM_HLECOUNT: _exit does not run atexit, write a copy here
++ dm_cheats_exit(); // a clean exit: no safe mode for the cheats at the next launch (atexit does not run either)
+ dm_audio_suspend(1);
+ dm_gfx_suspend(1);
+ LOG("graceful exit done (%.3f s)", (now_ns() - t0) / 1e9);
+diff --git a/dm/host/hle_svc.c b/dm/host/hle_svc.c
+index 0673018b..e25655f5 100644
+--- a/dm/host/hle_svc.c
++++ b/dm/host/hle_svc.c
+@@ -22,6 +22,14 @@ static size_t g_reserve; // its size: RESERVE, or more with a DM_ALIAS
+ static uint8_t *g_heap; static _Atomic size_t g_heap_cur; static size_t g_heap_cap;
+ // The address range lies entirely within the currently opened (readable and writable) part of the guest heap: such reads need no kernel trap to check, memcpy directly (used where guest memory is read every tick, such as diag.c tk_rd)
+ int dm_guest_heap_readable(uint64_t a, size_t n) { uint64_t b = (uint64_t)(uintptr_t)g_heap; size_t cur = g_heap_cur; return g_heap && a >= b && n <= cur && a - b <= cur - n; }
++// The opened heap span for callers that address guest memory by region (hle_cheats.c region 1, like dmnt's heap extents): the
++// reservation's base (guest address) and the length the game has actually opened with SetHeapSize right now, which grows and
++// shrinks with it; both 0 until the game's first SetHeapSize. There is no lock: the caller uses the pair only to bounds-check and
++// restarts the check on each access, so a concurrent resize can at worst give it an answer about the span a moment ago
++void dm_guest_heap_range(uint64_t *base, size_t *open_len) {
++ if (base) *base = (uint64_t)(uintptr_t)g_heap;
++ if (open_len) *open_len = g_heap ? atomic_load(&g_heap_cur) : 0;
++}
+ static uint8_t *g_alias; static size_t g_alias_cap;
+ static _Atomic uint64_t *g_alias_bits; // alias region page bitmap (alias_pages)
+ static uint64_t *g_alias_exposed; // one bit per host page ever opened; protected by g_map_lock
+@@ -98,6 +106,24 @@ static uint8_t g_seen[256];
+ static struct { uint64_t base, size, src; uint32_t state; } g_map[MAX_MAP];
+ static int g_nmap;
+ static pthread_mutex_t g_map_lock = PTHREAD_MUTEX_INITIALIZER;
++// A hole-free read / write of guest heap bytes for the cheat VM (hle_cheats.c): under g_map_lock no concurrent SetHeapSize
++// can mprotect the span away between the bounds check and the copy (both hold this same lock), so a live heap address cannot
++// turn into a fault while the cheat VM touches it. Both return 0 when every byte was inside the currently opened (readable
++// and writable) span, 1 otherwise. The address is the guest heap address the cheat VM computed (heap base + rel + offset register)
++int dm_guest_heap_write(uint64_t addr, const void *src, size_t len) {
++ pthread_mutex_lock(&g_map_lock);
++ int out = !dm_guest_heap_readable(addr, len);
++ if (!out) { dm_guest_write_prepare((void *)(uintptr_t)addr, len); memcpy((void *)(uintptr_t)addr, src, len); }
++ pthread_mutex_unlock(&g_map_lock);
++ return out;
++}
++int dm_guest_heap_read(uint64_t addr, void *out, size_t len) {
++ pthread_mutex_lock(&g_map_lock);
++ int bad = !dm_guest_heap_readable(addr, len);
++ if (!bad) memcpy(out, (void *)(uintptr_t)addr, len);
++ pthread_mutex_unlock(&g_map_lock);
++ return bad;
++}
+ static int map_find(uint64_t a, uint64_t n) { // returns a 1-based index, 0 = no overlap; caller holds g_map_lock
+ for (int i = 0; i < g_nmap; i++) if (a < g_map[i].base + g_map[i].size && g_map[i].base < a + n) return i + 1;
+ return 0;
+diff --git a/dm/host/main.c b/dm/host/main.c
+index ce87f4a4..8feecc47 100644
+--- a/dm/host/main.c
++++ b/dm/host/main.c
+@@ -101,6 +101,7 @@ static void host_preload(int argc, char **argv) {
+ }
+ if (!n) { static const char *def[] = DM_GAME_MODULES; for (int k = 0; k < DM_GAME_NMOD; k++) names[n++] = def[k]; } // default module list from the game profile's modules (Mario: main sdk)
+ load_modules(argv[1], names, n);
++ dm_cheats_init(); // the Atmosphère cheat files for this build (hle_cheats.c): picked by first 16 hex digits of main's build ID, which the loader knows now
+ dm_sdk_major(); // logs the SDK version, which SDK-dependent behaviour follows (loader.c)
+ uint64_t ta = now_ns();
+ probe_install(); // DM_PROBE probes (for diagnostics)
+diff --git a/dm/host/tests/Makefile b/dm/host/tests/Makefile
+index 89904bc7..f1acffe8 100644
+--- a/dm/host/tests/Makefile
++++ b/dm/host/tests/Makefile
+@@ -12,7 +12,7 @@ QUIET = $(if $(strip $(SAN)),,2>/dev/null)
+ GINC = $(if $(strip $(GAME)),-I../gen/$(GAME) -I../../games/$(GAME),$(error GAME is not set: make GAME=<base game title ID>: $(shell python3 ../../games/game.py list | awk -F'\t' '{printf "%s (%s) ", $$1, $$3}')))
+ $(B)/t_fs $(B)/t_fs_case $(B)/t_fs_commit_list $(B)/t_fs_commit_list_tsan: ../romfs_image.h
+ GAME_H = ../gen/$(GAME)/game_profile.h
+-run: $(B)/t_language $(B)/t_motion $(B)/t_heap_size $(B)/t_touch $(B)/t_gesture $(B)/t_oe $(B)/t_fs $(B)/t_fs_commit_list $(B)/t_thread_leak $(B)/t_fs_case $(B)/t_audio $(B)/t_audio_spsc $(B)/t_swkbd $(B)/t_altstack $(B)/t_condvar $(B)/t_condvar_old $(B)/t_pctl $(B)/t_time $(B)/t_shared_font $(B)/t_vorbis $(B)/t_vorbis_divides $(B)/t_hid $(B)/t_input_map $(B)/t_launcher_contract $(B)/t_haptics $(B)/t_haptics_apple
++run: $(B)/t_language $(B)/t_motion $(B)/t_heap_size $(B)/t_touch $(B)/t_gesture $(B)/t_oe $(B)/t_fs $(B)/t_fs_commit_list $(B)/t_thread_leak $(B)/t_fs_case $(B)/t_audio $(B)/t_audio_spsc $(B)/t_swkbd $(B)/t_altstack $(B)/t_condvar $(B)/t_condvar_old $(B)/t_pctl $(B)/t_time $(B)/t_shared_font $(B)/t_vorbis $(B)/t_vorbis_divides $(B)/t_hid $(B)/t_input_map $(B)/t_launcher_contract $(B)/t_haptics $(B)/t_haptics_apple $(B)/t_cheats
+ $(B)/t_language
+ $(B)/t_heap_size
+ $(B)/t_touch
+@@ -50,6 +50,7 @@ run: $(B)/t_language $(B)/t_motion $(B)/t_heap_size $(B)/t_touch $(B)/t_gesture
+ $(B)/t_launcher_contract
+ $(B)/t_haptics
+ $(B)/t_haptics_apple
++ TMPDIR="$(abspath $(B))" $(B)/t_cheats 2>/dev/null
+ $(B)/t_nro
+ $(B)/t_symbols
+ run: $(B)/t_nro
+@@ -82,6 +83,12 @@ $(B)/t_nro: t_nro.c ../loader.c ../hle_ro.c ../hle.h ../dm.h $(GAME_H) | $(B)
+ .PHONY: nro
+ nro: $(B)/t_nro
+ $(B)/t_nro
++# the cheat engine (hle_cheats.c, compiled into the test with stubs for the loader, the heap and the keys)
++$(B)/t_cheats: t_cheats.c ../hle_cheats.c ../dm.h ../dm_input.h $(GAME_H) | $(B)
++ $(CLANG) -O1 -g -Wall -Werror -Wno-unused-function -I.. $(GINC) -o $@ t_cheats.c
++.PHONY: cheats
++cheats: $(B)/t_cheats
++ TMPDIR="$(abspath $(B))" $(B)/t_cheats
+ # Regenerated on every make (FORCE), by the host Makefile: a header from an older game.py lacks newer defines; game.py writes it only when it changes, so an unchanged header rebuilds no test
+ $(GAME_H): FORCE
+ $(MAKE) -C .. game_profile GAME=$(GAME)
+diff --git a/dm/host/tests/t_cheats.c b/dm/host/tests/t_cheats.c
+new file mode 100644
+index 00000000..f6b71a57
+--- /dev/null
++++ b/dm/host/tests/t_cheats.c
+@@ -0,0 +1,609 @@
++// Cheat engine unit test (hle_cheats.c): the Atmosphère opcodes against hand-computed results held to
++// docs/reference/cheats.md (the memory and key conditionals, else, loops, the four load forms and the narrow load that
++// keeps a register's upper bytes, the register-address store, legacy arithmetic, nested skipping, the 8-byte word order,
++// a truncated instruction, 9 register arithmetic in every math type and width with the shifts and the float forms, A
++// store register, C0 register conditional, C1 / C2 save and restore across cheats and their reset between passes, C3
++// static registers, C4 extended key-press across passes with its one previous-keys value), the pass (registers shared
++// between the cheats of one pass, masters first, reset between passes), what an access may reach (main, the heap, another
++// module's data but not its code, a mapped page of the guest block but not an unmapped one) and that a failed access is
++// ignored and counted, never turning the cheat off; and the host's own layer over the format: labels and EdiZon
++// sections, a header glued to a code line, duplicate names in <build>.enabled, on / off pairs as one switch, the meta
++// file of scripts/cheat_anchor.py (typed "ask" values kept in <build>.values, "set" cheats that run once, never-decrease,
++// the compiler's left-outs, the display version), the dry run, the master switch, safe mode after an unclean exit, toggles
++// carried over to a new build, DM_CHEATS_ANY_BUILD's count of build-named files, and the load report. A synthetic main
++// image (text, data, key page), a second module, a heap and a guest block (one mapped page, one PROT_NONE page) live in
++// host memory; writes go through the engine's real paths (the writable alias of main, vm_write for a guest page).
++// Expectations are written by hand, not generated by the code under test.
++#include "../hle_cheats.c"
++#include <sys/stat.h>
++
++static module_t test_modules[3]; module_t *g_mod = test_modules; int g_nmod; // the loader's module table (loader.c): "main" and a second module "sdk" here
++uint64_t now_ns(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return (uint64_t)t.tv_sec * 1000000000ull + (uint64_t)t.tv_nsec; }
++void dm_guest_write_prepare(void *addr, size_t len) { (void)addr; (void)len; } // no dirty-page tracking in the test
++static uint8_t *heap; static size_t heap_open; // the guest heap (hle_svc.c): a plain buffer, opened in full
++void dm_guest_heap_range(uint64_t *base, size_t *open_len) { *base = (uint64_t)(uintptr_t)heap; *open_len = heap_open; }
++int dm_guest_heap_read(uint64_t a, void *out, size_t n) { memcpy(out, (void *)(uintptr_t)a, n); return 0; }
++int dm_guest_heap_write(uint64_t a, const void *src, size_t n) { memcpy((void *)(uintptr_t)a, src, n); return 0; }
++// The reserved guest address block (hle_svc.c g_as): GAS bytes, of which only the first page is mapped (a thread stack,
++// say); the second page stays PROT_NONE, an address the game has unmapped, which the engine must fail on without faulting
++#define GAS 0x20000
++static uint8_t *gas;
++int dm_guest_as_contains(uintptr_t a) { uintptr_t b = (uintptr_t)gas; return gas && a >= b && a - b < GAS; }
++static int as_ready = 1; // 0: the block is not reserved yet (a pass before hle_svc.c's mem_init): svc_guest_range answers NULL
++void svc_guest_range(uint8_t **base, size_t *size) { *base = as_ready ? gas : NULL; *size = as_ready ? GAS : 0; }
++static uint64_t held; // the keys "held" for the key-press conditional (hle_hid.c)
++uint64_t dm_cheats_keys(void) { return held; }
++
++static int checks, fails;
++#define CHECK(c, s) do { checks++; int ok_ = !!(c); fails += !ok_; printf("%s %s\n", ok_ ? "✓" : "✗", s); } while (0)
++
++#define IMG 0x10000 // main: text 0x0000-0x3FFF, data 0x4000-0xBFFF, the host's key page 0xC000-0xFFFF
++static uint8_t *img; // main's image (page-aligned, so the engine can remap it)
++#define SDK 0x8000 // the second module: text 0x0000-0x0FFF, read-only data 0x1000-0x1FFF, data 0x2000-0x3FFF, key page 0x4000-0x7FFF
++static uint8_t *sdk;
++static char root[1024]; // the test's own folder (TMPDIR); every case gets a fresh subfolder as its cheats folder
++
++// A u32 / u16 of main's image, and setting one (the "game" changing its memory)
++static uint32_t rd32(uint64_t off) { uint32_t v; memcpy(&v, img + off, 4); return v; }
++static void wr32(uint64_t off, uint32_t v) { memcpy(img + off, &v, 4); }
++static void wr16(uint64_t off, uint16_t v) { memcpy(img + off, &v, 2); }
++static uint16_t rd16(uint64_t off) { uint16_t v; memcpy(&v, img + off, 2); return v; }
++
++// Write a file of the cheats folder
++static void put(const char *name, const char *text) {
++ char p[1400]; snprintf(p, sizeof p, "%s/%s", g_dir, name);
++ FILE *f = fopen(p, "w"); fputs(text, f); fclose(f);
++}
++
++// Read a file of the cheats folder into buf ("" when missing), after the engine's queued writes landed (files_drain: the
++// state files are written off the calling thread)
++static const char *get(const char *name) {
++ static char buf[8192]; buf[0] = 0;
++ files_drain();
++ char p[1400]; snprintf(p, sizeof p, "%s/%s", g_dir, name);
++ FILE *f = fopen(p, "r"); if (!f) return buf;
++ size_t n = fread(buf, 1, sizeof buf - 1, f); buf[n] = 0; fclose(f);
++ return buf;
++}
++
++static int exists(const char *name) { files_drain(); char p[1400]; snprintf(p, sizeof p, "%s/%s", g_dir, name); return access(p, F_OK) == 0; }
++
++// Remove a file of the cheats folder (the player deleting the cheat file during play)
++static void rm(const char *name) { files_drain(); char p[1400]; snprintf(p, sizeof p, "%s/%s", g_dir, name); unlink(p); }
++
++// A guest address as two code words of a 4xx load (high word first, the reference's order)
++#define HI(a) ((unsigned)((uint64_t)(uintptr_t)(a) >> 32))
++#define LO(a) ((unsigned)(uint64_t)(uintptr_t)(a))
++
++// A fresh case: a new cheats folder, main's data zeroed, every engine switch back to its default; then the file is loaded
++static void fresh(const char *name, const char *txt) {
++ snprintf(g_dir, sizeof g_dir, "%s/%s", root, name);
++ mkdir(g_dir, 0755);
++ memset(img + 0x4000, 0, 0x8000);
++ g_safe = 0; atomic_store(&g_master, 1); atomic_store(&g_exiting, 0); g_non = 0; held = 0; // g_exiting: a case that exited cleanly must not mute the next one's flag writes
++ if (txt) put("1111111111111111.txt", txt);
++}
++
++// The index of the entry of this name (its n-th occurrence, from 0), -1 when there is none
++static int at(const char *name, int nth) {
++ for (int i = 0; i < g_ncheat; i++) if (!strcmp(g_cheat[i].name, name) && nth-- == 0) return i;
++ return -1;
++}
++
++// Turn an entry on (toggling it when it is off) and run one pass
++static void on_and_pass(int i) { if (!dm_cheat_on_at(i)) dm_cheat_toggle(i); cheats_pass(); }
++
++int main(void) {
++ const char *tmp = getenv("TMPDIR");
++ snprintf(root, sizeof root, "%s/t_cheats.XXXXXX", tmp && *tmp ? tmp : "/tmp");
++ if (!mkdtemp(root)) { perror("mkdtemp"); return 1; }
++ img = mmap(NULL, IMG, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
++ heap = calloc(1, 0x10000); heap_open = 0x10000;
++ gas = mmap(NULL, GAS, PROT_NONE, MAP_PRIVATE | MAP_ANON, -1, 0);
++ if (gas == MAP_FAILED || mprotect(gas, 0x10000, PROT_READ | PROT_WRITE)) { perror("guest block"); return 1; }
++ sdk = mmap(NULL, SDK, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
++ module_t *m = &g_mod[0]; g_nmod = 3;
++ snprintf(m->name, sizeof m->name, "main"); m->base = img; m->size = IMG; m->text_end = 0x4000;
++ m->key_page_off = 0xC000; m->key_page_size = 0x4000; m->patch_off = -1;
++ snprintf(m->build_id, sizeof m->build_id, "1111111111111111aaaaaaaaaaaaaaaa");
++ module_t *s = &g_mod[1]; // the second module's layout is the fixups header's: the engine writes only from data_off on, never the key page
++ snprintf(s->name, sizeof s->name, "sdk"); s->base = sdk; s->size = SDK; s->text_end = 0x1000; s->ro_off = 0x1000; s->data_off = 0x2000;
++ s->key_page_off = 0x4000; s->key_page_size = 0x4000; s->patch_off = -1;
++ // A third module with its patch area after the key page (loader.c map_image, patch_off >= 0): read + execute up to
++ // the image's end, so a cheat's write there must be refused, not attempted (a memcpy would be a SIGBUS)
++ uint8_t *sdk2 = mmap(NULL, 0x10000, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
++ if (sdk2 == MAP_FAILED || mprotect(sdk2 + 0x8000, 0x8000, PROT_READ | PROT_EXEC)) { perror("sdk2"); return 1; }
++ module_t *s2 = &g_mod[2];
++ snprintf(s2->name, sizeof s2->name, "sdk2"); s2->base = sdk2; s2->size = 0x10000; s2->text_end = 0x1000; s2->ro_off = 0x1000; s2->data_off = 0x2000;
++ s2->key_page_off = 0x4000; s2->key_page_size = 0x4000; s2->patch_off = 0x8000;
++ g_main_mod = m; snprintf(g_build, sizeof g_build, "1111111111111111"); snprintf(g_tid, sizeof g_tid, "0100000000000000");
++
++ // ---- A: store register, its six offset types and the increment ----
++ char t[2048];
++ uint64_t abs20 = (uint64_t)(uintptr_t)img + 0x4020;
++ snprintf(t, sizeof t, "[A]\n"
++ "40000000 00000000 00000063\n" // r0 = 0x63
++ "A4000400 00004010\n" // O=4: [main + 0x4010] = r0
++ "40010000 %08X %08X\n" // r1 = &main+0x4020 (absolute)
++ "A4011000\n" "A4011000\n" // O=0, I=1: [r1] = r0 twice, r1 += 4 each
++ "40020000 00000000 00000004\n" // r2 = 4
++ "A4010120\n" // O=1: [r1 + r2] = r0 (r1 is now +0x28: writes +0x2C)
++ "A4010200 00000010\n" // O=2: [r1 + 0x10] = r0 (+0x38)
++ "40030000 00000000 00004040\n" // r3 = 0x4040
++ "A4030300\n" // O=3: [main + r3] = r0 (+0x40)
++ "A4030500 00000004\n", // O=5: [main + r3 + 4] = r0 (+0x44)
++ (unsigned)(abs20 >> 32), (unsigned)abs20);
++ fresh("a", t); load_all(); on_and_pass(at("A", 0));
++ CHECK(rd32(0x4010) == 0x63 && rd32(0x4020) == 0x63 && rd32(0x4024) == 0x63, "A: region + address, and register with increment");
++ CHECK(rd32(0x402C) == 0x63 && rd32(0x4038) == 0x63, "A: register + register, register + address");
++ CHECK(rd32(0x4040) == 0x63 && rd32(0x4044) == 0x63, "A: region + register, region + register + address");
++
++ // ---- C0: register conditionals (static value, memory, another register), then C3 static registers ----
++ fresh("c0", "[C0]\n"
++ // r5 holds the compared value: r0 stays 0, because opcode 0 adds its offset register (R = 0 here) to every address
++ "40050000 00000000 00000005\n" // r5 = 5
++ "C0455400 00000005\n" "04000000 00004050 00000001\n" "20000000\n" // r5 == 5: write 1
++ "C0455400 00000006\n" "04000000 00004054 00000001\n" "20000000\n" // r5 == 6: skipped
++ "C0435000 00004058\n" "04000000 0000405C 00000001\n" "20000000\n" // r5 < [main+0x4058] (7): write
++ "40060000 00000000 00000005\n" // r6 = 5
++ "C0455560\n" "04000000 00004060 00000001\n" "20000000\n" // r5 == r6: write
++ "C3000805\n"); // static[0x80] = r5
++ wr32(0x4058, 7);
++ load_all(); on_and_pass(at("C0", 0));
++ CHECK(rd32(0x4050) == 1 && rd32(0x4054) == 0, "C0: register against a static value, met and not met");
++ CHECK(rd32(0x405C) == 1 && rd32(0x4060) == 1, "C0: register against memory and against another register");
++ CHECK(g_static[0x80] == 5, "C3: a register written to static register 0x80");
++ g_static[0x05] = 42; // a value a tool put into a readable static register
++ put("1111111111111111.txt", "[C3]\nC3000051\nA4100400 00004064\n"); // r1 = static[5]; [main+0x4064] = r1 (A: S = 1, O = 4)
++ snprintf(g_path, sizeof g_path, "%s/1111111111111111.txt", g_dir);
++ g_ncheat = 0; parse_file(g_path); g_active = 1; on_and_pass(at("C3", 0)); // parsed without load_all, which clears the static registers
++ CHECK(rd32(0x4064) == 42, "C3: a readable static register into a register");
++ load_all();
++ CHECK(g_static[0x05] == 0 && g_static[0x80] == 0, "C3: loading a file clears the static registers");
++
++ // ---- labels, EdiZon sections, a glued header, an out-of-range write ----
++ fresh("labels", "[www.example.com]\n"
++ "[--SectionStart:Stats--]\n"
++ "[a]\n04000000 00004070 00000001[b]\n04000000 00004074 00000002\n"
++ "[--SectionEnd:Stats--]\n"
++ "[far]\n040000FF FFFFFF00 00000001\n");
++ load_all();
++ int a = at("a", 0), b = at("b", 0), credits = at("www.example.com", 0);
++ CHECK(g_ncheat == 6 && b >= 0, "a header glued to the previous code line still starts an entry");
++ CHECK(dm_cheat_kind_at(credits) == 3 && dm_cheat_kind_at(at("--SectionStart:Stats--", 0)) == 3 && !g_cheat[credits].broken, "entries without code are labels, not broken cheats");
++ CHECK(!strcmp(dm_cheat_section_at(a), "Stats") && !strcmp(dm_cheat_section_at(b), "Stats") && !dm_cheat_section_at(at("far", 0))[0], "entries between the markers carry the section");
++ CHECK((dm_cheat_flags_at(at("--SectionStart:Stats--", 0)) & DM_CHEAT_SECTION_START) && (dm_cheat_flags_at(at("--SectionEnd:Stats--", 0)) & DM_CHEAT_SECTION_END), "the markers are flagged");
++ CHECK(strstr(dm_cheats_report(), "1 headers glued") != NULL, "the report counts the glued header");
++ fresh("labels2", "[inline] 04000000 00004078 00000003\n[typo]\n0400000 0000407C 00000001\n[typo2]\nhello world\n[Max 999[A]]\n04000000 00004080 00000004\n");
++ load_all();
++ CHECK(g_cheat[at("inline", 0)].nins == 3 && dm_cheat_kind_at(at("inline", 0)) == 0, "code on the header's own line belongs to the entry (dmnt reads on after the header)");
++ CHECK(dm_cheat_kind_at(at("typo", 0)) == 2 && strstr(dm_cheat_why_at(at("typo", 0)), "malformed line 3"), "a 7-digit word is a typo: the line is malformed, the cheat off");
++ CHECK(dm_cheat_kind_at(at("typo2", 0)) == 2 && strstr(dm_cheat_why_at(at("typo2", 0)), "no code words"), "an entry whose lines were all prose is broken, not a label");
++ CHECK(at("Max 999[A", 0) >= 0, "a bracket inside a name is not a glued header (the name ends at the first ], as in dmnt)");
++ fresh("labels", "[www.example.com]\n"
++ "[--SectionStart:Stats--]\n"
++ "[a]\n04000000 00004070 00000001[b]\n04000000 00004074 00000002\n"
++ "[--SectionEnd:Stats--]\n"
++ "[far]\n040000FF FFFFFF00 00000001\n");
++ load_all();
++ on_and_pass(at("far", 0));
++ CHECK(dm_cheat_kind_at(at("far", 0)) == 0 && dm_cheat_on_at(at("far", 0)) && !strcmp(dm_cheat_why_at(at("far", 0)), " (no effect: 1 access out of mapped memory)"),
++ "an out-of-range write is ignored: the cheat stays on, its row carries the count");
++ cheats_pass();
++ CHECK(g_cheat[at("far", 0)].fails == 2 && strstr(dm_cheat_why_at(at("far", 0)), "2 accesses"), "the failures are counted pass after pass");
++ cheats_pass();
++ CHECK(g_cheat[at("far", 0)].fails == 3 && strstr(dm_cheat_why_at(at("far", 0)), "2 accesses"), "the note is rewritten sparingly (powers of two, or once a second): 3 still reads 2");
++ cheats_pass();
++ CHECK(g_cheat[at("far", 0)].fails == 4 && strstr(dm_cheat_why_at(at("far", 0)), "4 accesses"), "and reads 4 at the fourth");
++ g_cheat[at("far", 0)].fails = 1; // back to the count the dry-run check below expects
++ char dry[512]; dm_cheat_preview(at("far", 0), dry, sizeof dry);
++ CHECK(strstr(dry, "write at guest address") && strstr(dry, "fails") && g_cheat[at("far", 0)].fails == 1, "the dry run describes the failure and counts nothing");
++ dm_cheat_toggle(at("far", 0));
++ CHECK(!dm_cheat_why_at(at("far", 0))[0], "toggling the cheat clears the note");
++
++ // ---- duplicate names: "Name #2" in <build>.enabled ----
++ fresh("dup", "[X]\n04000000 00004080 00000001\n[X]\n04000000 00004084 00000002\n");
++ load_all();
++ dm_cheat_toggle(at("X", 1));
++ CHECK(!strcmp(get("1111111111111111.enabled"), "X #2\n"), "the second entry of a name is saved as \"X #2\"");
++ load_all();
++ CHECK(!dm_cheat_on_at(at("X", 0)) && dm_cheat_on_at(at("X", 1)), "and only that entry comes back on");
++ CHECK(strstr(dm_cheats_report(), "Duplicate names") != NULL, "the report names duplicate names");
++ put("1111111111111111.enabled", "X\n"); load_all();
++ CHECK(dm_cheat_on_at(at("X", 0)) && !dm_cheat_on_at(at("X", 1)), "a plain name (an older file) turns on the first entry");
++ put("1111111111111111.enabled", "X\nX\n"); load_all();
++ CHECK(dm_cheat_on_at(at("X", 0)) && dm_cheat_on_at(at("X", 1)), "an older file that names X twice keeps both on");
++
++ // ---- an on / off pair (the naming convention) is one switch ----
++ fresh("pair", "[Y - off]\n04000000 00000100 D503201F\n[Y - on]\n04000000 00000100 52800020\n");
++ load_all();
++ int yon = at("Y - on", 0), yoff = at("Y - off", 0);
++ CHECK(dm_cheat_pair_at(yon) == yoff && (dm_cheat_flags_at(yon) & DM_CHEAT_PAIR_ON) && (dm_cheat_flags_at(yoff) & DM_CHEAT_PAIR_OFF), "\"Y - on\" / \"Y - off\" are paired");
++ dm_cheat_toggle(yon); cheats_pass();
++ CHECK(g_alias != NULL, "the code page write path has its writable alias of main");
++ CHECK(dm_cheat_on_at(yon) && !dm_cheat_on_at(yoff) && rd32(0x100) == 0x52800020, "turning the pair on runs the on half only (code page, through the alias)");
++ dm_cheat_toggle(yon);
++ CHECK(!dm_cheat_on_at(yon) && dm_cheat_on_at(yoff), "turning it off turns the restore on");
++ cheats_pass();
++ CHECK(!dm_cheat_on_at(yoff) && rd32(0x100) == 0xD503201F && !strcmp(get("1111111111111111.enabled"), ""), "the restore runs one pass, then turns itself off");
++ put("1111111111111111.enabled", "Y - off\n"); load_all();
++ CHECK(dm_cheat_on_at(yoff) && !dm_cheat_on_at(yon), "a saved state is kept as it is (a hand-made file's off entry the player left on)");
++
++ // ---- the meta file: values, "set", never-decrease, left-outs, the version, the dry run ----
++ fresh("meta", "[Gold]\n04000000 00004090 000001F4\n[HP keeps]\n[Patch]\n14050000 00000200 00000000\n04000000 00000200 52800040\n20000000\n");
++ wr32(0x200, 0);
++ put("1111111111111111.meta.tsv",
++ "# cheat_anchor.py: compiled from s.cheats.toml for build 1111111111111111 on 2026-10-26\n"
++ "# txt sha256 0000000000000000000000000000000000000000000000000000000000000000\n"
++ "# build 1111111111111111 9.9.9\n"
++ "name\tkind\tsection\ttype\taction\tvalue\task\tvalue_words\tonce\tpair\tresolved\tnote\taddress\n"
++ "Gold\tdata\tItems\tu32\tset\t500\t0..9999\t2\t1\t\texact\t\t0:0x4090\n"
++ "HP keeps\tdata\t\ts16\tnever-decrease\t\t\t\t\t\t2/2 refs (2 exact); nxnative only\t\t0:0x40A0\n"
++ "Lost\tunresolved\t\t\t\t\t\t\t\t\t\tanchor s_10: its function is not in this build\t\n");
++ load_all();
++ int gold = at("Gold", 0), hp = at("HP keeps", 0);
++ CHECK(!strcmp(dm_cheats_version(), "9.9.9") && dm_cheats_nskipped() == 1 && !strcmp(dm_cheats_skipped_name(0), "Lost"), "the version and the compiler's left-outs");
++ CHECK((dm_cheat_flags_at(gold) & (DM_CHEAT_ASK | DM_CHEAT_ONCE)) == (DM_CHEAT_ASK | DM_CHEAT_ONCE) && !strcmp(dm_cheat_section_at(gold), "Items"), "Gold: ask, set once, its section");
++ char v[64]; dm_cheat_value_get(gold, v, sizeof v);
++ CHECK(!strcmp(v, "500") && !strcmp(dm_cheat_value_bounds(gold), "0..9999"), "its value and bounds");
++ CHECK(dm_cheat_value_set(gold, "10000") == -1 && dm_cheat_value_set(gold, "-1") == -1 && dm_cheat_value_set(gold, "x") == -1, "out-of-bounds and unparsable values are refused");
++ CHECK(dm_cheat_value_set(gold, "010") == 0 && g_cheat[gold].ins[2] == 10 && dm_cheat_value_set(gold, "0x10") == 0 && g_cheat[gold].ins[2] == 16, "values are decimal, hex only with 0x");
++ CHECK(dm_cheat_value_set(gold, "1234") == 0 && g_cheat[gold].ins[2] == 1234 && !strcmp(get("1111111111111111.values"), "Gold\t1234\n"), "a value goes into the program and <build>.values");
++ char pv[512]; int nw = dm_cheat_preview(gold, pv, sizeof pv);
++ CHECK(nw == 1 && strstr(pv, "main+0x4090 (4 bytes): 0 -> 1234") && rd32(0x4090) == 0, "the dry run describes the write and writes nothing");
++ on_and_pass(gold);
++ CHECK(rd32(0x4090) == 1234 && !dm_cheat_on_at(gold), "a set cheat writes once and turns itself off");
++ dm_cheats_master_set(0); dm_cheat_toggle(gold);
++ CHECK(!strstr(get("1111111111111111.enabled"), "Gold"), "a set cheat waiting for its pass is never saved as on");
++ dm_cheat_toggle(gold); dm_cheats_master_set(1);
++ load_all(); dm_cheat_value_get(gold, v, sizeof v);
++ CHECK(!strcmp(v, "1234"), "the value comes back from <build>.values");
++ CHECK(dm_cheat_kind_at(hp) == 0 && (dm_cheat_flags_at(hp) & DM_CHEAT_HOST), "never-decrease: a cheat run by the host");
++ wr16(0x40A0, 100); on_and_pass(hp); // the first pass notes the value
++ wr16(0x40A0, 50); cheats_pass();
++ CHECK(rd16(0x40A0) == 100, "never-decrease: a lower value is put back");
++ wr16(0x40A0, 200); cheats_pass(); wr16(0x40A0, 150); cheats_pass();
++ CHECK(rd16(0x40A0) == 200, "never-decrease: it follows an increase");
++ wr16(0x40A0, (uint16_t)-5); cheats_pass();
++ CHECK(rd16(0x40A0) == 200, "never-decrease: a negative s16 is lower (signed compare)");
++ dm_cheat_toggle(hp); dm_cheat_toggle(hp); wr16(0x40A0, 10); cheats_pass(); wr16(0x40A0, 5); cheats_pass();
++ CHECK(rd16(0x40A0) == 10, "never-decrease: turning it on again starts from the value there then");
++ wr32(0x200, 0x14000000); // the "original" word changed (as a rewritten site would): the guard leaves it
++ nw = dm_cheat_preview(at("Patch", 0), pv, sizeof pv);
++ CHECK(nw == 0 && strstr(pv, "writes nothing right now"), "the dry run of a guard that is not met says so");
++
++ // ---- the master switch ----
++ fresh("master", "[M]\n04000000 000040B0 00000007\n");
++ load_all(); dm_cheat_toggle(at("M", 0));
++ dm_cheats_master_set(0); cheats_pass();
++ CHECK(rd32(0x40B0) == 0 && exists(".cheats-off-0100000000000000") && strstr(dm_cheats_report(), "master switch is off"), "master switch off: nothing runs, kept in .cheats-off");
++ dm_cheats_master_set(1); cheats_pass();
++ CHECK(rd32(0x40B0) == 7 && !exists(".cheats-off-0100000000000000"), "master switch on again");
++
++ // ---- safe mode after an unclean exit ----
++ fresh("safe", "{Master}\n04000000 000040C0 00000001\n[S]\n04000000 000040C4 00000002\n");
++ load_all(); dm_cheat_toggle(at("S", 0));
++ CHECK(exists(".cheats-running-0100000000000000"), "cheats on: the safe-mode flag exists");
++ folder_flags(); memset(img + 0x4000, 0, 0x100); load_all(); cheats_pass(); // the next launch, after a crash
++ CHECK(dm_cheats_safe() && !dm_cheat_on_at(at("S", 0)) && rd32(0x40C0) == 0 && rd32(0x40C4) == 0, "after a crash every cheat starts off, masters too");
++ CHECK(!strcmp(get("1111111111111111.enabled"), "S\n"), "and the saved toggles are kept");
++ put("1111111111111111.txt", "{Master}\n04000000 000040C0 00000001\n[S]\n04000000 000040C4 00000002\n[T]\n04000000 000040C8 00000003\n");
++ put("1111111111111111.enabled", "S\n"); g_safe = 1; load_all();
++ dm_cheat_toggle(at("T", 0));
++ CHECK(!dm_cheats_safe() && dm_cheat_on_at(at("S", 0)) && dm_cheat_on_at(at("T", 0)) && !strcmp(get("1111111111111111.enabled"), "S\nT\n"), "turning a cheat on in safe mode brings the saved toggles back too");
++ put("1111111111111111.enabled", "S\n"); g_safe = 1; load_all();
++ dm_cheats_safe_restore(); cheats_pass();
++ CHECK(!dm_cheats_safe() && dm_cheat_on_at(at("S", 0)) && rd32(0x40C0) == 1 && rd32(0x40C4) == 2, "restoring brings them back");
++ dm_cheats_exit();
++ CHECK(!exists(".cheats-running-0100000000000000"), "a clean exit removes the flag");
++
++ // ---- a compiled file of a new build takes the toggles of the previous build ----
++ fresh("carry", "[Gold]\n04000000 000040D0 00000001\n[Silver]\n04000000 000040D4 00000001\n");
++ put("1111111111111111.meta.tsv", "# cheat_anchor.py: compiled from s.cheats.toml for build 1111111111111111 on 2026-10-26\n"
++ "name\tkind\nGold\tdata\nSilver\tdata\n");
++ put("2222222222222222.enabled", "Silver\n");
++ load_all();
++ CHECK(!dm_cheat_on_at(at("Silver", 0)), "no toggles from a build whose file was not compiled from the same source");
++ put("2222222222222222.meta.tsv", "# cheat_anchor.py: compiled from s.cheats.toml for build 2222222222222222 on 2026-10-25\nname\tkind\n");
++ load_all();
++ CHECK(!dm_cheat_on_at(at("Gold", 0)) && dm_cheat_on_at(at("Silver", 0)) && strstr(dm_cheats_report(), "carried over from 2222222222222222.enabled"), "toggles carried over by name");
++ put("1111111111111111.enabled", ""); load_all();
++ CHECK(!dm_cheat_on_at(at("Silver", 0)), "once the build has its own <build>.enabled, that one counts");
++
++ // ---- a heap cheat before the game opens its heap waits instead of being turned off ----
++ fresh("heap", "[H]\n04100000 00000010 0000002A\n");
++ put("1111111111111111.enabled", "H\n");
++ heap_open = 0; load_all(); cheats_pass();
++ CHECK(dm_cheat_kind_at(at("H", 0)) == 0 && dm_cheat_on_at(at("H", 0)), "with no heap yet the cheat waits, still on");
++ heap_open = 0x10000; cheats_pass();
++ CHECK(heap[0x10] == 0x2A, "and writes once the heap is open");
++
++ // ---- the VM held to docs/reference/cheats.md: opcodes 1 (both forms), 2 (else), nesting, 8 ----
++ fresh("vm", "[Cond]\n"
++ "14050000 00004200 00000007\n" "04000000 00004204 00000001\n" "20000000\n" // [main+0x4200] == 7: met
++ "40010000 00000000 00000004\n" // r1 = 4
++ "14051100 00004200 00000007\n" "04000000 00004208 00000001\n" "20000000\n" // X=1, r=1: [main+0x4200 + r1] is 1: not met
++ "14051100 000041FC 00000007\n" "04000000 0000420C 00000001\n" "20000000\n" // [main+0x41FC + r1] is 7: met
++ "14010000 00004200 00000007\n" "04000000 00004210 00000001\n" "21000000\n" "04000000 00004214 00000001\n" "20000000\n" // 7 > 7: the else runs
++ "14020000 00004200 00000007\n" "04000000 00004218 00000001\n" "21000000\n" "04000000 0000421C 00000001\n" "20000000\n" // 7 >= 7: the then runs, the else is skipped
++ "[Nest]\n"
++ "14050000 00004200 00000000\n" // [main+0x4200] == 0: not met, the whole block skipped
++ "14050000 00004200 00000007\n" "04000000 00004220 00000001\n" "20000000\n" // an inner block that would be met
++ "04000000 00004224 00000001\n"
++ "20000000\n"
++ "04000000 00004228 00000001\n" // after the outer end: runs
++ "[Keys]\n" "80000003\n" "04000000 00004230 00000001\n" "20000000\n" // A and B held, on any controller
++ "[SL]\n" "81000001\n" "04000000 00004234 00000001\n" "20000000\n" // bit 24 (a Joy-Con's SL): no input source of this host reports it
++ "[Any]\n" "80000000\n" "04000000 00004238 00000001\n" "20000000\n" // an empty mask is always met
++ "[End0]\n" "20000000\n" "04000000 0000423C 00000001\n" // an end at depth 0 is a no-op
++ "[Else0]\n" "21000000\n" "04000000 00004240 00000001\n"); // an else at depth 0: dmnt aborts; this host turns the cheat off
++ wr32(0x4200, 7);
++ load_all();
++ for (int i = 0; i < g_ncheat; i++) if (!dm_cheat_on_at(i) && dm_cheat_kind_at(i) == 0) dm_cheat_toggle(i);
++ held = DM_BTN_A; cheats_pass();
++ CHECK(rd32(0x4204) == 1 && rd32(0x4208) == 0 && rd32(0x420C) == 1, "1: the fixed form, and the register form reads at base + offset + reg");
++ CHECK(rd32(0x4210) == 0 && rd32(0x4214) == 1 && rd32(0x4218) == 1 && rd32(0x421C) == 0, "2: an else runs when the if is not met, is skipped when it is");
++ CHECK(rd32(0x4220) == 0 && rd32(0x4224) == 0 && rd32(0x4228) == 1, "a not-met block is skipped with its nested block, to its own end");
++ CHECK(rd32(0x4230) == 0 && rd32(0x4234) == 0 && rd32(0x4238) == 1, "8: A alone does not meet A+B; an SL mask is never met; an empty mask always is");
++ held = DM_BTN_A | DM_BTN_B | DM_BTN_X; cheats_pass();
++ CHECK(rd32(0x4230) == 1, "8: every key of the mask held, other keys too, meets it");
++ CHECK(rd32(0x423C) == 1 && rd32(0x4240) == 0 && dm_cheat_kind_at(at("Else0", 0)) == 2 && strstr(dm_cheat_why_at(at("Else0", 0)), "mismatched else"),
++ "an end at depth 0 is a no-op; an else at depth 0 turns the cheat off (the lenient form of dmnt's abort)");
++ held = 0;
++
++ // ---- opcodes 3, 5 (the four forms, the narrow load), 6, 7, 0 with its register, the 8-byte word order, truncation ----
++ uint64_t p4300 = (uint64_t)(uintptr_t)img + 0x4300;
++ snprintf(t, sizeof t, "[P]\n40010000 00000000 00000003\n" // r1 = 3, for Q's loop end below
++ "[Q]\n78020000 00000001\n31010000\nA8200400 00004248\n" // r2 += 1; loop end without a start: r1--, jump to Q's word 0 while r1 != 0; store r2
++ "[Loop]\n30030000 00000003\n78040000 00000001\n31030000\nA8400400 00004250\n" // r3 = 3: r4 += 1 three times; store r4
++ "[Loop0]\n30050000 00000000\n31050000\n" // N = 0: the counter wraps, the loop practically never ends
++ "[Load]\n"
++ "54010000 00004300\n" "A8100400 00004320\n" // I=0: r1 = 4 bytes of main+0x4300 (into a zero register); stored as 8
++ "40020000 FFFFFFFF FFFFFFFF\n" "54020000 00004300\n" "A8200400 00004328\n" // a 4-byte load into a full register keeps its upper bytes
++ "58030000 00004310\n" "54031000 00000004\n" "A4300400 00004330\n" // I=1: r3 = the pointer at main+0x4310; r3 = [r3 + 4]
++ "58040000 00004310\n" "54052400 00000000\n" "A4500400 00004334\n" // I=2: r5 = [r4 + 0]
++ "40060000 00000000 00004300\n" "54073600 00000004\n" "A4700400 00004338\n" // I=3: r7 = [main + r6 + 4]
++ "[Store6]\n"
++ "58080000 00004310\n" "78080000 00000040\n" // r8 = the pointer + 0x40 (main+0x4340)
++ "64081000 00000000 000000FE\n" // [r8] = 0xFE, r8 += 4
++ "64080000 00000000 000000FD\n" // [r8] = 0xFD (main+0x4344)
++ "40090000 00000000 00000008\n" "64080190 00000000 000000FC\n" // [r8 + r9] = 0xFC (main+0x434C)
++ "[Arith]\n"
++ "40010000 00000000 00000001\n" "78013000 00000041\n" "A8100400 00004350\n" // 1 << 65: the count is masked to 63 bits (aarch64's LSLV)
++ "40020000 00000000 000000FF\n" "71020000 00000001\n" "A8200400 00004358\n" // 0xFF + 1 at width 1: truncated to 0
++ "40030000 00000000 00000005\n" "74031000 00000007\n" "A8300400 00004360\n" // 5 - 7 at width 4: 0xFFFFFFFE, truncated to 4 bytes
++ "40040000 00000000 00000006\n" "78042000 00000007\n" "78044000 00000001\n" "A8400400 00004368\n" // 6 * 7 >> 1 = 21
++ "[Words]\n" "08000000 00004370 11111111 22222222\n" // an 8-byte value: first word high, second low
++ "40010000 00000000 00000008\n" "04010000 00004378 00000005\n" // 0 adds its register: [main+0x4378 + r1]
++ "[Trunc]\n04000000 00004000\n" // the value word is missing
++ "[Trunc2]\n04000000 00004390 00000001\n40010000 00000000\n"); // a good store, then a 4 cut short: the cheat never runs here
++ fresh("vm2", t);
++ wr32(0x4300, 0xAABBCCDD); wr32(0x4304, 0x11223344); memcpy(img + 0x4310, &p4300, 8);
++ load_all();
++ for (int i = 0; i < g_ncheat; i++) if (!dm_cheat_on_at(i) && dm_cheat_kind_at(i) == 0) dm_cheat_toggle(i);
++ cheats_pass();
++ CHECK(rd32(0x4248) == 3 && rd32(0x424C) == 0, "3: a loop end without its start jumps to the first word of its own cheat (r1 from the cheat before, shared in the pass)");
++ CHECK(rd32(0x4250) == 3, "3: the body of a loop of 3 runs three times");
++ CHECK(dm_cheat_kind_at(at("Loop0", 0)) == 2 && strstr(dm_cheat_why_at(at("Loop0", 0)), "runaway"), "3: a loop of 0 never ends on a Switch; here the step cap turns it off");
++ CHECK(rd32(0x4320) == 0xAABBCCDD && rd32(0x4324) == 0, "5: the fixed form, 4 bytes into a zero register");
++ CHECK(rd32(0x4328) == 0xAABBCCDD && rd32(0x432C) == 0xFFFFFFFF, "5: a load narrower than 8 bytes keeps the register's upper bytes");
++ CHECK(rd32(0x4330) == 0x11223344 && rd32(0x4334) == 0xAABBCCDD && rd32(0x4338) == 0x11223344, "5: reg + offset, other reg + offset, base + reg + offset");
++ CHECK(rd32(0x4340) == 0xFE && rd32(0x4344) == 0xFD && rd32(0x434C) == 0xFC, "6: the register address, the increment, the offset register");
++ CHECK(rd32(0x4350) == 2 && rd32(0x4354) == 0, "7: a shift count of 65 shifts by 1 (the host masks it; the reference leaves it undefined)");
++ CHECK(rd32(0x4358) == 0 && rd32(0x435C) == 0 && rd32(0x4360) == 0xFFFFFFFE && rd32(0x4364) == 0 && rd32(0x4368) == 21, "7: the result is truncated to the width; mul and shr");
++ CHECK(rd32(0x4370) == 0x22222222 && rd32(0x4374) == 0x11111111, "0: an 8-byte value is two words, high then low, stored little-endian");
++ CHECK(rd32(0x4380) == 5 && rd32(0x4378) == 0, "0: the offset register is always added");
++ CHECK(dm_cheat_kind_at(at("Trunc", 0)) == 2 && strstr(dm_cheat_why_at(at("Trunc", 0)), "truncated"), "an instruction whose last word is missing marks the cheat at load");
++ CHECK(dm_cheat_kind_at(at("Trunc2", 0)) == 2 && rd32(0x4390) == 0, "a cheat cut short never runs here (the reference runs its whole words, then ends the pass)");
++ { // a preview of every cheat leaves the cheats and the game's memory as they were
++ static uint8_t before[0x8000]; static cheat_t keepc[CHEAT_MAX];
++ memcpy(before, img + 0x4000, 0x8000); memcpy(keepc, g_cheat, sizeof(cheat_t) * (size_t)g_ncheat);
++ char pvx[512]; for (int i = 0; i < g_ncheat; i++) dm_cheat_preview(i, pvx, sizeof pvx);
++ int same = !memcmp(before, img + 0x4000, 0x8000);
++ for (int i = 0; i < g_ncheat && same; i++)
++ same = keepc[i].broken == g_cheat[i].broken && keepc[i].dead == g_cheat[i].dead && keepc[i].on == g_cheat[i].on
++ && keepc[i].fails == g_cheat[i].fails && !strcmp(keepc[i].why, g_cheat[i].why);
++ CHECK(same, "a preview of every cheat changes no flag, no reason and no memory");
++ cheat_t probe; memset(&probe, 0, sizeof probe); uint32_t badw = 0x04000000; ins_t inx; // a store cut short
++ g_dry = 1; int r = ins_dec(&probe, &badw, 1, &inx); g_dry = 0;
++ CHECK(r == 0 && !probe.broken && !probe.why[0] && !strcmp(g_dec_why, "truncated"), "a decode failure under the dry flag describes itself and marks nothing");
++ }
++ // loop tops are per cheat: L1's loop on r1 leaves no top for L2's stray loop end, which jumps to L2's own word 0
++ fresh("tops", "[L1]\n30010000 00000002\n04000000 00004400 00000001\n31010000\n40010000 00000000 00000003\n" // loop of 2 on r1 (top at word 2); then r1 = 3
++ "[L2]\n78020000 00000001\n31010000\nA8200400 00004410\n"); // r2 += 1; stray end on r1; store r2
++ load_all(); dm_cheat_toggle(at("L1", 0)); dm_cheat_toggle(at("L2", 0)); cheats_pass();
++ CHECK(rd32(0x4400) == 1 && rd32(0x4410) == 3 && dm_cheat_kind_at(at("L2", 0)) == 0, "a stray loop end jumps to word 0 of its own cheat, never to a top another cheat set");
++ // a note from a failing pass, then a kill in a pass without a failure: the kill reason stays
++ snprintf(t, sizeof t, "[K]\n58010000 000044B0\n58011000 00000000\n64010000 00000000 00000001\n"); // r1 = the pointer at main+0x44B0; r1 = [r1]; [r1] = 1
++ fresh("kill", t); load_all(); dm_cheat_toggle(at("K", 0)); cheats_pass();
++ CHECK(strstr(dm_cheat_why_at(at("K", 0)), "no effect"), "the chase fails while the pointer is 0: noted");
++ { uint64_t p = (uint64_t)(uintptr_t)img + 0x4500, k = (uint64_t)(uintptr_t)img + 0xC000; memcpy(img + 0x44B0, &p, 8); memcpy(img + 0x4500, &k, 8); }
++ cheats_pass(); // the pointer now leads to the host's key page: the write is refused for good
++ CHECK(g_cheat[at("K", 0)].dead && dm_cheat_kind_at(at("K", 0)) == 2 && strstr(dm_cheat_why_at(at("K", 0)), "key page"), "a kill after a noted pass keeps its reason");
++ // a module whose patch area follows its key page (read + execute to the image's end): a write there is refused, one into its data lands
++ { uint64_t pp = (uint64_t)(uintptr_t)g_mod[2].base + 0x8000, pd = (uint64_t)(uintptr_t)g_mod[2].base + 0x2000;
++ snprintf(t, sizeof t, "[Patch]\n40010000 %08X %08X\n64010000 00000000 00000001\n40020000 %08X %08X\n64020000 00000000 00000005\n", HI(pp), LO(pp), HI(pd), LO(pd)); }
++ fresh("patcharea", t); load_all(); dm_cheat_toggle(at("Patch", 0)); cheats_pass();
++ { uint32_t gd; memcpy(&gd, g_mod[2].base + 0x2000, 4);
++ CHECK(g_cheat[at("Patch", 0)].fails == 1 && gd == 5, "a write into another module's patch area is refused (counted), one into its data lands"); }
++ // region 2 (alias) before the guest block is reserved: the cheat waits silently; afterwards a base that is not the block's partition is refused once
++ fresh("alias", "[Al]\n04200000 00000010 00000001\n"); // M = 2
++ load_all(); dm_cheat_toggle(at("Al", 0));
++ as_ready = 0; cheats_pass(); as_ready = 1;
++ CHECK(g_cheat[at("Al", 0)].fails == 0 && dm_cheat_kind_at(at("Al", 0)) == 0, "region 2 before mem_init: not ready, nothing counted, nothing logged");
++ cheats_pass(); // the test's heap is not the block's partition: a real mismatch, logged once, the cheat stays on
++ CHECK(g_cheat[at("Al", 0)].fails == 0 && dm_cheat_kind_at(at("Al", 0)) == 0, "region 2 with a base off the partition: refused, the cheat stays on");
++ // glued hex words are split as dmnt does; a hex token that is not whole words makes the line malformed
++ fresh("glued", "[G]\n0400000000004420 00000003\n04000000 0000442400000004\n[Odd]\n0400000 00004428 00000001\n[Odd2]\n04000000 00004428\n0400000000004428 0000000\n[Prose]\nby dead beef\n04000000 0000442C 00000005\n");
++ load_all();
++ for (int i = 0; i < g_ncheat; i++) if (!dm_cheat_on_at(i) && dm_cheat_kind_at(i) == 0) dm_cheat_toggle(i);
++ cheats_pass();
++ CHECK(g_cheat[at("G", 0)].nins == 6 && rd32(0x4420) == 3 && rd32(0x4424) == 4, "a run of hex digits is cut into 8-digit words, glued or not");
++ CHECK(dm_cheat_kind_at(at("Odd", 0)) == 2 && strstr(dm_cheat_why_at(at("Odd", 0)), "malformed line 5"), "a 7-digit hex token makes its line malformed, not prose");
++ CHECK(dm_cheat_kind_at(at("Odd2", 0)) == 2 && strstr(dm_cheat_why_at(at("Odd2", 0)), "malformed line 8"), "a glued run of 23 digits too");
++ CHECK(dm_cheat_kind_at(at("Prose", 0)) == 2 && strstr(dm_cheat_why_at(at("Prose", 0)), "malformed line 10") && rd32(0x442C) == 0, "a line of short hex-looking words (\"dead beef\") is malformed, so the cheat stays off");
++
++ // ---- failed accesses: ignored and counted; what a read or write can reach ----
++ uint64_t pmapped = (uint64_t)(uintptr_t)gas + 0x100, pnone = (uint64_t)(uintptr_t)gas + 0x10000, psdk = (uint64_t)(uintptr_t)sdk + 0x100, psdkd = (uint64_t)(uintptr_t)sdk + 0x2000;
++ snprintf(t, sizeof t, "[Fail]\n40010000 00000000 00000010\n58011000 00000000\nA8100400 000043A0\n" // r1 = 0x10; r1 = [r1]: unmapped; store r1
++ "[Ptr]\n58010000 000043B0\n54011000 00000000\nA4100400 000043B8\n" // r1 = the pointer at main+0x43B0 (0 at first); r1 = [r1]; store
++ "[FarW]\n040000FF FFFFFF00 00000001\n04000000 000043C0 00000001\n" // a write nothing maps, then a good one
++ "[Stack]\n40010000 %08X %08X\n54011000 00000000\nA4100400 000043C8\n" // a read of a mapped page of the guest block
++ "40020000 %08X %08X\n54021000 00000000\nA8200400 000043D0\n" // a read of its PROT_NONE page: the register keeps the address
++ "40030000 %08X %08X\n64030000 00000000 00000077\n" // a write into the mapped page
++ "40040000 %08X %08X\n64040000 00000000 00000077\n" // a write into the PROT_NONE page: nothing, no fault
++ "[Module]\n40010000 %08X %08X\n54011000 00000000\nA4100400 000043D8\n" // a read of another module's code
++ "40020000 %08X %08X\n64020000 00000000 00000001\n" // a write into its code: refused
++ "40030000 %08X %08X\n64030000 00000000 00000002\n", // a write into its data: done
++ HI(pmapped), LO(pmapped), HI(pnone), LO(pnone), HI(pmapped + 0x100), LO(pmapped + 0x100), HI(pnone), LO(pnone),
++ HI(psdk), LO(psdk), HI(psdk), LO(psdk), HI(psdkd), LO(psdkd));
++ fresh("fail", t);
++ wr32(0x4300, 0xAABBCCDD);
++ memset(gas, 0, 0x10000); wr32(0x43B0, 0); wr32(0x43B4, 0);
++ uint32_t v5a = 0x5A5A; memcpy(gas + 0x100, &v5a, 4);
++ uint32_t v33 = 0x33; memcpy(sdk + 0x100, &v33, 4); memset(sdk + 0x2000, 0, 4);
++ load_all();
++ for (int i = 0; i < g_ncheat; i++) if (!dm_cheat_on_at(i) && dm_cheat_kind_at(i) == 0) dm_cheat_toggle(i);
++ cheats_pass();
++ int fl = at("Fail", 0), ptr = at("Ptr", 0), farw = at("FarW", 0), stk = at("Stack", 0), mod = at("Module", 0);
++ CHECK(rd32(0x43A0) == 0x10 && rd32(0x43A4) == 0 && dm_cheat_kind_at(fl) == 0 && dm_cheat_on_at(fl) && g_cheat[fl].fails == 1, "a failed load leaves the register as it was; the cheat stays on, the failure counted");
++ CHECK(rd32(0x43B8) == 0 && g_cheat[ptr].fails == 1 && strstr(dm_cheat_why_at(ptr), "no effect"), "a pointer the game has not set yet: the chase fails, the cheat waits with a note");
++ CHECK(rd32(0x43C0) == 1 && g_cheat[farw].fails == 1 && dm_cheat_on_at(farw), "a failed write is a no-op; the next store of the cheat runs");
++ CHECK(rd32(0x43C8) == 0x5A5A, "a read of a mapped page of the guest block (a stack, virtual address memory)");
++ CHECK(rd32(0x43D0) == (uint32_t)pnone && rd32(0x43D4) == (uint32_t)(pnone >> 32), "a read of an unmapped guest page fails without a fault and keeps the register");
++ uint32_t got77; memcpy(&got77, gas + 0x200, 4);
++ CHECK(got77 == 0x77 && g_cheat[stk].fails == 2, "a write into a mapped guest page lands; one into an unmapped page fails without a fault (2 failures)");
++ uint32_t gotd; memcpy(&gotd, sdk + 0x2000, 4); uint32_t gotc; memcpy(&gotc, sdk + 0x100, 4);
++ CHECK(rd32(0x43D8) == 0x33 && gotc == 0x33 && gotd == 2 && g_cheat[mod].fails == 1, "another module: its code is readable, never written; its data is written");
++ memcpy(img + 0x43B0, &p4300, 8); // the game sets the pointer
++ cheats_pass();
++ CHECK(rd32(0x43B8) == 0xAABBCCDD && !dm_cheat_why_at(ptr)[0] && g_cheat[ptr].fails == 1, "once the pointer is set the chase works and the note goes");
++ char pv2[512]; dm_cheat_preview(fl, pv2, sizeof pv2);
++ CHECK(strstr(pv2, "read at guest address 0x10 fails") && g_cheat[fl].fails == 2, "the dry run describes a failed read and counts nothing");
++
++ // ---- registers: shared by the cheats of one pass (masters first), reset between passes; the dry run replays the pass ----
++ fresh("regs", "[P2]\n40010000 00000000 00000005\n" // r1 = 5
++ "[Q2]\nA4100400 000043E0\n" // store r1
++ "[Q3]\nA4200400 000043E8\n" // store r2, set by the master below it in the file
++ "{M2}\n40020000 00000000 00000009\n"); // r2 = 9: the master runs first whatever its place
++ load_all();
++ dm_cheat_toggle(at("P2", 0)); dm_cheat_toggle(at("Q2", 0)); dm_cheat_toggle(at("Q3", 0));
++ cheats_pass();
++ CHECK(rd32(0x43E0) == 5 && rd32(0x43E8) == 9, "a register set by an earlier cheat, or by the master, is seen by a later one in the same pass");
++ char pv3[512]; dm_cheat_preview(at("Q2", 0), pv3, sizeof pv3);
++ CHECK(strstr(pv3, "main+0x43E0 (4 bytes): 5 (0x5) -> 5 (0x5)") != NULL, "the dry run replays the cheats before it, so its registers are a real pass's");
++ dm_cheat_toggle(at("P2", 0)); wr32(0x43E0, 7); cheats_pass();
++ CHECK(rd32(0x43E0) == 0, "the registers are reset at the start of every pass");
++
++ // ---- opcode 9: every math type at every width, the immediate forms, the shifts, the float forms; the load verdict ----
++ fresh("math", "[Math]\n"
++ "40010000 00000000 FFFFFFFF\n" "94021100 00000002\n" "A8200400 00004600\n" // r2 = (0xFFFFFFFF + 2) at width 4: 1
++ "40010000 00000000 00000005\n" "91131100 00000107\n" "A8300400 00004608\n" // r3 = (5 - 7) at width 1: 0xFE; the width-1 immediate is the word's low byte
++ "92021100 00012345\n" "A8200400 00004698\n" // r2 = 5 + 0x2345 at width 2 (the immediate's low 16 bits): 0x234A
++ "40040000 00000000 00001234\n" "40050000 00000000 00000010\n" "92264050\n" "A8600400 00004610\n" // r6 = r4 * r5 at width 2: 0x12340 cut to 0x2340
++ "98371100 00000000 00000041\n" "A8700400 00004618\n" // r7 = 5 << 65: the count is masked to 63 bits (aarch64's LSLV), 10
++ "98381100 00000000 00000004\n" "A8800400 00004620\n" // r8 = 5 << 4 = 0x50
++ "94498100 00000004\n" "A8900400 00004628\n" // r9 = r8 >> 4 = 5
++ "400A0000 00000000 000000F0\n" "400B0000 00000000 0000003C\n"
++ "915CA0B0\n" "A8C00400 00004630\n" // rC = rA & rB = 0x30
++ "916DA0B0\n" "A8D00400 00004638\n" // rD = rA | rB = 0xFC
++ "927EA000\n" "A8E00400 00004640\n" // rE = ~rA at width 2 = 0xFF0F
++ "948FA0B0\n" "A8F00400 00004648\n" // rF = rA ^ rB = 0xCC
++ "9891A000\n" "A8100400 00004650\n" // r1 = rA (move) = 0xF0
++ "94E1A000\n" "A8100400 00004658\n" // an unknown math type (14) stores 0
++ "40010000 80000000 00000000\n" "98411100 00000000 0000003F\n" "A8100400 00004690\n" // the top bit >> 63 at width 8: 1
++ "[Float]\n"
++ "40010000 FFFFFFFF 3F800000\n" "94A21100 40000000\n" "A8200400 00004660\n" // 1.0f (the register's upper half ignored) + 2.0f = 3.0f
++ "40030000 3FF00000 00000000\n" "98B43100 40080000 00000000\n" "A8400400 00004668\n" // 1.0 - 3.0 = -2.0 (double)
++ "40050000 00000000 40400000\n" "94C65050\n" "A8600400 00004670\n" // 3.0f * 3.0f (register operand) = 9.0f
++ "40070000 40100000 00000000\n" "98D83070\n" "A8800400 00004678\n" // 1.0 / 4.0 (register operand) = 0.25
++ "40090000 00000000 00000001\n" "92A91100 00003C00\n" "A8900400 00004680\n" // a float add at width 2 gives 0
++ "94DA5100 00000000\n" "A8A00400 00004688\n" // 3.0f / 0.0f = +inf, no trap
++ "[T9]\n98011100 00000001\n" // an 8-byte immediate cut to one word
++ "[Log]\nFFF40400\n"); // the debug log stays unsupported
++ load_all();
++ for (int i = 0; i < g_ncheat; i++) if (!dm_cheat_on_at(i) && dm_cheat_kind_at(i) == 0) dm_cheat_toggle(i);
++ cheats_pass();
++ CHECK(rd32(0x4600) == 1 && rd32(0x4604) == 0 && rd32(0x4608) == 0xFE && rd32(0x4698) == 0x234A, "9: add at width 4 and sub at width 1 truncate the result; a narrow immediate is the word's low bytes");
++ CHECK(rd32(0x4610) == 0x2340 && rd32(0x4614) == 0, "9: mul of two registers at width 2");
++ CHECK(rd32(0x4618) == 10 && rd32(0x461C) == 0 && rd32(0x4620) == 0x50 && rd32(0x4628) == 5, "9: shl by 65 shifts by 1 (the count masked as the Switch's core does), shl by 4, shr by 4");
++ CHECK(rd32(0x4690) == 1 && rd32(0x4694) == 0, "9: shr by 63 of a full 64-bit register");
++ CHECK(rd32(0x4630) == 0x30 && rd32(0x4638) == 0xFC && rd32(0x4640) == 0xFF0F && rd32(0x4648) == 0xCC, "9: and, or, not (at width 2), xor");
++ CHECK(rd32(0x4650) == 0xF0 && rd32(0x4658) == 0, "9: move; an unknown math type stores 0");
++ CHECK(rd32(0x4660) == 0x40400000 && rd32(0x4664) == 0, "9: float add at width 4 on the register's low 32 bits");
++ CHECK(rd32(0x4668) == 0 && rd32(0x466C) == 0xC0000000, "9: float sub at width 8 (-2.0)");
++ CHECK(rd32(0x4670) == 0x41100000 && rd32(0x4678) == 0 && rd32(0x467C) == 0x3FD00000, "9: float mul (9.0f) and div (0.25) with register operands");
++ CHECK(rd32(0x4680) == 0 && rd32(0x4684) == 0 && rd32(0x4688) == 0x7F800000, "9: a float operation at width 2 gives 0; a division by zero gives an infinity");
++ CHECK(dm_cheat_kind_at(at("T9", 0)) == 2 && strstr(dm_cheat_why_at(at("T9", 0)), "truncated"), "9: an immediate cut short marks the cheat at load");
++ CHECK(dm_cheat_kind_at(at("Log", 0)) == 2 && strstr(dm_cheat_why_at(at("Log", 0)), "unsupported opcode FFF"), "the debug log is still an unsupported opcode");
++ CHECK(value_word(&g_cheat[at("Math", 0)], 4) && !value_word(&g_cheat[at("Math", 0)], 3), "9: its immediate word is a value word the panel may set, its opcode word is not");
++
++ // ---- C1 / C2: save and restore across the cheats of a pass, every operation; the saved values reset between passes ----
++ fresh("save", "[Save]\n"
++ "40010000 00000000 00000005\n" "40020000 00000000 00000006\n" // r1 = 5, r2 = 6
++ "C1030110\n" // saved[3] = r1
++ "C2100004\n" // mask save: saved[2] = r2
++ "[Restore]\n"
++ "C1040300\n" "A8400400 00004700\n" // r4 = saved[3]: 5, from the cheat before
++ "C1020030\n" "A8200400 00004708\n" // clear r2: 0
++ "C2000004\n" "A8200400 00004710\n" // mask restore: r2 = saved[2]: 6
++ "40050000 00000000 00000007\n" "C1030020\n" "C1050300\n" "A8500400 00004718\n" // clear saved[3]; r5 = saved[3]: 0
++ "40060000 00000000 00000009\n" "C2200004\n" "C1060200\n" "A8600400 00004720\n" // mask clear saved[2]; r6 = saved[2]: 0
++ "C2300010\n" "A8400400 00004728\n" // mask clear r4: 0
++ "C1030110\n" "C1070390\n" "A8700400 00004730\n"); // saved[3] = r1 again; an unknown x (9) restores: r7 = 5
++ load_all(); dm_cheat_toggle(at("Save", 0)); dm_cheat_toggle(at("Restore", 0)); cheats_pass();
++ CHECK(rd32(0x4700) == 5 && rd32(0x4704) == 0 && rd32(0x4710) == 6, "C1 / C2: a value saved by one cheat is restored by a later one of the same pass");
++ CHECK(rd32(0x4708) == 0 && rd32(0x4718) == 0 && rd32(0x4720) == 0 && rd32(0x4728) == 0, "C1 / C2: clear register, clear saved value, by index and by mask");
++ CHECK(rd32(0x4730) == 5, "C1: an unknown operation restores");
++ dm_cheat_toggle(at("Save", 0)); cheats_pass();
++ CHECK(rd32(0x4700) == 0 && rd32(0x4710) == 0, "the saved values are reset at the start of every pass, like the registers");
++
++ // ---- C4 across passes: the edge form fires on the pass where the keys became held, against one previous-keys value shared by every C4 ----
++ fresh("c4", "[Edge]\n" "C4000000 00000000 00000001\n" "54010000 00004740\n" "78010000 00000001\n" "A4100400 00004740\n" "20000000\n" // r = 0, A: the counter at 0x4740 + 1
++ "[Edge2]\n" "C4000000 00000000 00000001\n" "54010000 00004760\n" "78010000 00000001\n" "A4100400 00004760\n" "20000000\n" // the same mask again
++ "[Repeat]\n" "C4100000 00000000 00000001\n" "54010000 00004748\n" "78010000 00000001\n" "A4100400 00004748\n" "20000000\n" // r = 1: while held
++ "[High]\n" "C4100000 00000001 00000000\n" "04000000 00004750 00000001\n" "20000000\n" // bit 32 of the 64-bit mask: no input source reports it
++ "[Empty0]\n" "C4000000 00000000 00000000\n" "04000000 00004758 00000001\n" "20000000\n"); // an empty mask without auto-repeat: never an edge
++ load_all();
++ for (int i = 0; i < g_ncheat; i++) if (!dm_cheat_on_at(i) && dm_cheat_kind_at(i) == 0) dm_cheat_toggle(i);
++ held = DM_BTN_A; cheats_pass();
++ CHECK(rd32(0x4740) == 1 && rd32(0x4760) == 1 && rd32(0x4748) == 1, "C4: A pressed: the edge form and the auto-repeat form both fire; two edge C4s of one mask both see the edge");
++ cheats_pass();
++ CHECK(rd32(0x4740) == 1 && rd32(0x4760) == 1 && rd32(0x4748) == 2, "C4: A still held: only the auto-repeat form fires again");
++ held = 0; cheats_pass();
++ CHECK(rd32(0x4740) == 1 && rd32(0x4748) == 2, "C4: released: nothing fires");
++ held = DM_BTN_A | DM_BTN_B; cheats_pass();
++ CHECK(rd32(0x4740) == 2 && rd32(0x4760) == 2 && rd32(0x4748) == 3, "C4: pressed again, with another key too: a new edge");
++ CHECK(rd32(0x4750) == 0 && rd32(0x4758) == 0, "C4: a mask above bit 23 is never held; an empty mask is never an edge");
++ held = 0; cheats_pass(); held = DM_BTN_A;
++ char pv4[512]; int nw4 = dm_cheat_preview(at("Edge", 0), pv4, sizeof pv4);
++ CHECK(nw4 == 1 && strstr(pv4, "main+0x4740 (4 bytes): 2 (0x2) -> 3 (0x3)"), "C4: the dry run sees the edge");
++ cheats_pass();
++ CHECK(rd32(0x4740) == 3, "C4: the dry run did not consume it: the next pass fires");
++ held = 0;
++
++ // ---- DM_CHEATS_ANY_BUILD counts only files named after a build ID; the running flag follows a reload that finds no file ----
++ fresh("any", NULL); put("readme.txt", "hello\n");
++ g_any = 1; load_all();
++ CHECK(!dm_cheats_found() && g_ncheat == 0, "ANY_BUILD: a lone readme.txt is not a cheat file of another build");
++ put("2222222222222222.txt", "[Z]\n04000000 000043F0 00000001\n"); load_all();
++ CHECK(dm_cheats_found() && at("Z", 0) >= 0 && strstr(g_path, "2222222222222222.txt"), "ANY_BUILD: the single build-named file loads, the readme beside it ignored");
++ g_any = 0;
++ fresh("nofile", "[R]\n04000000 000043F8 00000001\n");
++ load_all(); dm_cheat_toggle(at("R", 0));
++ CHECK(exists(".cheats-running-0100000000000000"), "a cheat on: the safe-mode flag is there");
++ rm("1111111111111111.txt"); load_all();
++ CHECK(!dm_cheats_found() && !exists(".cheats-running-0100000000000000"), "a reload that finds no file removes the flag: nothing runs now");
++
++ // ---- Atmosphère's limits in the report ----
++ size_t cap = 0x200 * 9 + 64; char *big = malloc(cap); size_t o = (size_t)snprintf(big, cap, "[Big]\n");
++ for (int k = 0; k < 0x200; k++) o += (size_t)snprintf(big + o, cap - o, "20000000\n");
++ fresh("limits", big); free(big);
++ load_all();
++ CHECK(strstr(dm_cheats_report(), "1 cheats over 0x100 words") != NULL, "the report names a cheat over Atmosphère's 0x100 words");
++
++ char rmcmd[1100]; snprintf(rmcmd, sizeof rmcmd, "rm -rf '%s'", root); // the test's cheats folders
++ if (system(rmcmd)) fprintf(stderr, "cannot remove %s\n", root);
++ printf("%d / %d checks passed\n", checks - fails, checks);
++ return fails != 0;
++}
+diff --git a/dm/tools/tests/test_cheat_anchor.py b/dm/tools/tests/test_cheat_anchor.py
+new file mode 100644
+index 00000000..236cf75f
+--- /dev/null
++++ b/dm/tools/tests/test_cheat_anchor.py
+@@ -0,0 +1,638 @@
++"""scripts/cheat_anchor.py: Atmosphère cheats anchored on one build and compiled for another, on synthetic NSO files built
++from real AArch64 encodings (no game files). Relocated code and data, a changed callee, a resized function, pointer
++slots (RELA and RELR) and code caves are carried over; changed or relocated words, ambiguous or disagreeing evidence and
++outputs this tool did not write are refused, and the emitted words are checked against the VM's encodings. The rules on
++what may be written over a relocated or PC-relative word hold for patches and gated code templates alike; data anchors
++stay in their target's segment; malformed files and undecodable cheats are never shortened or dropped silently.
++"""
++import importlib.util
++from pathlib import Path
++import struct
++import sys
++import tempfile
++import tomllib
++import unittest
++import warnings
++
++REPO = Path(__file__).resolve().parents[3]
++sys.path.insert(0, str(REPO / 'dm/tools'))
++from nso_asm import ADRP, ADDI, B, NOP
++
++spec = importlib.util.spec_from_file_location('cheat_anchor', REPO / 'scripts/cheat_anchor.py')
++assert spec and spec.loader # a path that exists: narrows the Optional for the type checker
++ca = importlib.util.module_from_spec(spec); spec.loader.exec_module(ca)
++
++RET = 0xd65f03c0
++TEXT_END, RO, DATA, SIZE, BSS = 0x1c00, 0x2000, 0x4000, 0x6000, 0x1000 # the layout every synthetic build uses
++
++
++def LDRH(rt, rn, off):
++ """ldrh wt, [xn, #off]: a u16 field load, the kind of instruction the stat cheats read."""
++ return 0x79400000 | (off // 2) << 10 | rn << 5 | rt
++
++
++def LDRW(rt, rn, off):
++ """ldr wt, [xn, #off]: a u32 load, here used as an adrp's user."""
++ return 0xb9400000 | (off // 4) << 10 | rn << 5 | rt
++
++
++def LDRX(rt, rn, off):
++ """ldr xt, [xn, #off]: a pointer load from a .data slot."""
++ return 0xf9400000 | (off // 8) << 10 | rn << 5 | rt
++
++
++def MOVZ(rd, imm):
++ """mov wd, #imm: distinct filler instructions around a code site."""
++ return 0x52800000 | imm << 5 | rd
++
++
++def BL(frm, to):
++ """bl from frm to to (nso_asm.B with the link bit)."""
++ return B(frm, to) | 0x80000000
++
++
++def BCOND(cond, frm, to):
++ """b.<cond> from frm to to (cond 0 eq, 1 ne): the branch a "flip b.ne to b.eq" cheat writes."""
++ return 0x54000000 | (((to - frm) // 4) & 0x7ffff) << 5 | cond
++
++
++def reader(start, data, field=0x1e, extra=()):
++ """A function that loads a u16 field of the object at data: adrp x8; add x8, x8, lo; [extra]; ldrh w0, [x8, #field]; ret."""
++ return [ADRP(8, start, data), ADDI(8, 8, data & 0xfff), *extra, LDRH(0, 8, field), RET]
++
++
++def slot_reader(start, slot):
++ """A function that loads the pointer in a .data slot, then a field of what it points to."""
++ return [ADRP(9, start, slot), LDRX(9, 9, slot & 0xfff), LDRH(0, 9, 0x38), RET]
++
++
++def image(functions, relocs=(), relr=()):
++ """The memory image: functions {start: words} with an .eh_frame_hdr describing them, MOD0, and a dynamic section
++ with the relative relocations, as DT_RELA entries [(slot, pointer)] and as DT_RELR slots [(slot, pointer)] (the
++ pointer then lies in the slot itself, RELR's implicit addend)."""
++ img = bytearray(SIZE)
++ struct.pack_into('<I', img, 4, 0x20)
++ img[0x20:0x24] = b'MOD0'
++ struct.pack_into('<i', img, 0x24, 0x2100 - 0x20) # dynamic section
++ struct.pack_into('<ii', img, 0x30, 0x3000 - 0x20, 0x300c + len(functions) * 8 - 0x20)
++ tags = [(7, 0x2200), (8, 24 * len(relocs)), (9, 24)] + ([(36, 0x2400), (35, 8 * len(relr))] if relr else []) + [(0, 0)]
++ for i, (tag, value) in enumerate(tags): struct.pack_into('<qQ', img, 0x2100 + i * 16, tag, value)
++ for i, (slot, ptr) in enumerate(relocs): struct.pack_into('<QQq', img, 0x2200 + i * 24, slot, ca.R_AARCH64_RELATIVE, ptr)
++ for i, (slot, ptr) in enumerate(relr):
++ struct.pack_into('<Q', img, 0x2400 + i * 8, slot); struct.pack_into('<Q', img, slot, ptr)
++ img[0x3000:0x3004] = bytes((1, 0x1b, 3, 0x3b)) # eh_frame_hdr (test_nso_match's)
++ struct.pack_into('<iI', img, 0x3004, 0x3200 - 0x3004, len(functions))
++ struct.pack_into('<II', img, 0x3200, 16, 0)
++ img[0x3208:0x3211] = b'\x01zR\0\x04\x78\x1e\x01\x1b'
++ for i, (start, words) in enumerate(sorted(functions.items())):
++ struct.pack_into('<' + 'I' * len(words), img, start, *words)
++ fde = 0x3240 + i * 24
++ struct.pack_into('<ii', img, 0x300c + i * 8, start - 0x3000, fde - 0x3000)
++ struct.pack_into('<IIiI', img, fde, 16, fde + 4 - 0x3200, start - (fde + 8), len(words) * 4)
++ return img
++
++
++def nso(path, functions, relocs=(), relr=(), build=b'\x11' * 8, text_end=TEXT_END, data=DATA):
++ """Write an uncompressed NSO of image() with the usual three segments plus bss, and load it as a Build. data moves
++ the start of .data (a build whose .rodata grew); the image's own tables stay below it."""
++ img = image(functions, relocs, relr)
++ hdr = bytearray(0x100); hdr[:4] = b'NSO0'
++ segs = ((0, text_end), (RO, data - RO), (data, SIZE - data))
++ fo = 0x100
++ for i, (mo, sz) in enumerate(segs):
++ struct.pack_into('<III', hdr, 0x10 + i * 0x10, fo, mo, sz); fo += sz
++ struct.pack_into('<I', hdr, 0x3c, BSS)
++ hdr[0x40:0x48] = build
++ struct.pack_into('<III', hdr, 0x60, *(sz for _, sz in segs))
++ Path(path).parent.mkdir(parents=True, exist_ok=True)
++ Path(path).write_bytes(bytes(hdr) + b''.join(bytes(img[mo:mo + sz]) for mo, sz in segs))
++ return ca.Build(path)
++
++
++A, B2 = b'\x11' * 8, b'\x22' * 8 # the two build IDs most tests use: 1111111111111111 and 2222222222222222
++
++
++class Anchors(unittest.TestCase):
++ """Import on one synthetic build, compile on another, and check the words the VM will run."""
++ def setUp(self):
++ """A temporary folder per test; nso_syms.load reads the NSO through an unclosed open(), its warning is noise."""
++ warnings.simplefilter('ignore', ResourceWarning)
++ self.tmp = tempfile.TemporaryDirectory(); self.dir = Path(self.tmp.name)
++
++ def tearDown(self):
++ """Remove the temporary folder."""
++ self.tmp.cleanup()
++
++ def build(self, name, functions, **kw):
++ """A synthetic build in the temporary folder."""
++ return nso(self.dir / name, functions, **kw)
++
++ def txt(self, text, name='cheats.txt'):
++ """An Atmosphère file in the temporary folder."""
++ p = self.dir / name; p.write_text(text); return p
++
++ def roundtrip(self, old, new, text, name='cheats.txt', **kw):
++ """Import text on old, compile on new: (entries by name, report lines, skipped count)."""
++ src, _, _ = ca.import_file(self.txt(text, name), old, **kw)
++ ca.write_toml(src, self.dir / 'g.cheats.toml', name)
++ _, entries, report, skipped = ca.compile_source(self.dir / 'g.cheats.toml', new)
++ return {e[0]: e for e in entries}, report, skipped
++
++ def source(self, text, name='s.cheats.toml'):
++ """A hand-written source in the temporary folder."""
++ p = self.dir / name; p.write_text(text); return p
++
++ # ---- data anchors ----
++
++ def test_data_field_follows_the_object_the_code_references(self):
++ """A stat field keeps its offset from the object the code references, wherever the object moves."""
++ old = self.build('a', {0x100: reader(0x100, 0x4100), 0x200: reader(0x200, 0x4100, 0x20)})
++ new = self.build('b', {0x300: reader(0x300, 0x4180), 0x500: reader(0x500, 0x4180, 0x20)}, build=B2)
++ got, report, skipped = self.roundtrip(old, new, '[999 strength]\n02000000 0000411E 000003E7\n')
++ self.assertEqual(skipped, 0, report)
++ self.assertEqual(got['999 strength'][2], [0x02000000, 0x419e, 0x3e7]) # 0x4180 + the same field offset 0x1e
++ self.assertIn('2/2 refs (2 exact)', got['999 strength'][3]['how'])
++
++ def test_the_nearest_referenced_address_wins_over_a_busier_one(self):
++ """The review's silent-misplacement case: a busier neighbour must not become the base of an unrelated field."""
++ # A at 0x4100 is read by two functions, the target B at 0x4200 by one; only B moves in the new build
++ old = self.build('a', {0x100: reader(0x100, 0x4100), 0x200: reader(0x200, 0x4100, 0x20), 0x300: reader(0x300, 0x4200)})
++ new = self.build('b', {0x100: reader(0x100, 0x4100), 0x200: reader(0x200, 0x4100, 0x20), 0x300: reader(0x300, 0x4300)}, build=B2)
++ got, report, skipped = self.roundtrip(old, new, '[B]\n02000000 00004200 00000001\n')
++ self.assertEqual(skipped, 0, report)
++ self.assertEqual(got['B'][2][1], 0x4300); self.assertIn('weak: one reference', got['B'][3]['how'])
++ self.assertTrue(any('weakly' in r for r in report))
++
++ def test_disagreeing_or_missing_references_are_refused(self):
++ """References that disagree, or too few of them, refuse the cheat instead of guessing."""
++ old = self.build('a', {0x100: reader(0x100, 0x4100), 0x200: reader(0x200, 0x4100, 0x20)})
++ split = self.build('b', {0x300: reader(0x300, 0x4180), 0x500: reader(0x500, 0x4240, 0x20)}, build=B2)
++ got, report, skipped = self.roundtrip(old, split, '[x]\n02000000 0000411E 000003E7\n')
++ self.assertEqual(skipped, 1); self.assertIn('disagree', report[0])
++ one = self.build('c', {0x300: reader(0x300, 0x4180)}, build=b'\x33' * 8)
++ _, report, skipped = self.roundtrip(old, one, '[x]\n02000000 0000411E 000003E7\n')
++ self.assertEqual(skipped, 1); self.assertIn('only 1 of its 2', report[0])
++
++ def test_pointer_slot_is_followed_through_its_relocation(self):
++ """An object reached only through a relocated .data slot (FFCC's Mog) is found through the slot's relocation."""
++ # the only code reference is to a .data slot that holds a relocated pointer to the object
++ old = self.build('a', {0x100: slot_reader(0x100, 0x4008), 0x200: slot_reader(0x200, 0x4008)}, relocs=[(0x4008, 0x5000)])
++ new = self.build('b', {0x400: slot_reader(0x400, 0x4010), 0x600: slot_reader(0x600, 0x4010)}, relocs=[(0x4010, 0x5400)], build=B2)
++ got, report, skipped = self.roundtrip(old, new, '[Mog never tired]\n04000000 00005038 00000000\n')
++ self.assertEqual(skipped, 0, report)
++ self.assertEqual(got['Mog never tired'][2][:2], [0x04000000, 0x5438])
++ self.assertIn('through the slot 0x4010', got['Mog never tired'][3]['how'])
++
++ def test_two_slots_of_one_object_agree_on_the_pointer_and_relr_is_read(self):
++ """Two slots of one object agree on its pointer, not on the slots, and DT_RELR relocations are read too."""
++ old = self.build('a', {0x100: slot_reader(0x100, 0x4008), 0x200: slot_reader(0x200, 0x4010)}, relocs=[(0x4008, 0x5000), (0x4010, 0x5000)])
++ got, report, skipped = self.roundtrip(old, old, '[Mog]\n04000000 00005038 00000000\n')
++ self.assertEqual(skipped, 0, report); self.assertEqual(got['Mog'][2][1], 0x5038)
++ self.assertIn('through the slots 0x4008, 0x4010', got['Mog'][3]['how'])
++ new = self.build('b', {0x400: slot_reader(0x400, 0x4020), 0x600: slot_reader(0x600, 0x4028)}, relr=[(0x4020, 0x5200), (0x4028, 0x5200)], build=B2)
++ _, entries, report, skipped = ca.compile_source(self.dir / 'g.cheats.toml', new)
++ self.assertEqual(skipped, 0, report); self.assertEqual(entries[0][2][1], 0x5238)
++
++ # ---- code anchors ----
++
++ def test_code_patch_relocates_its_branch_to_the_cave_and_keeps_both_names(self):
++ """An ASM cheat: guarded words, the BL to its cave re-encoded at the moved site, both on / off names kept."""
++ site_words = lambda s: [0xaa1703e0, NOP, LDRH(0, 0, 0x34), RET]
++ old = self.build('a', {0x100: site_words(0x100)})
++ new = self.build('b', {0x900: site_words(0x900)}, build=B2, text_end=0x1800)
++ cave = RO - 0x100 # the cheat's code in the padding, 0x100 before the read-only data in both builds
++ on = f'[Hack - on]\n04000000 {cave:08X} D2800201\n04000000 {cave + 4:08X} D65F03C0\n04000000 00000108 {BL(0x108, cave):08X}\n'
++ off = f'[Hack - off]\n04000000 00000108 {LDRH(0, 0, 0x34):08X}\n'
++ got, report, skipped = self.roundtrip(old, new, on + off)
++ self.assertEqual(skipped, 0, report)
++ prog = got['Hack - on'][2]
++ guard = [0x14050000, 0x908, LDRH(0, 0, 0x34)] # "if it still holds the original", at the new site
++ self.assertEqual(prog[-7:], guard + [0x04000000, 0x908, BL(0x908, cave), 0x20000000])
++ self.assertEqual(prog[:7], [0x14050000, cave, 0, 0x04000000, cave, 0xd2800201, 0x20000000]) # cave words: "if still 0"
++ self.assertEqual(got['Hack - off'][2], [0x14050000, 0x908, BL(0x908, cave), 0x04000000, 0x908, LDRH(0, 0, 0x34), 0x20000000])
++ self.assertEqual(got['Hack - on'][3]['pair'], 'Hack - off')
++ _, entries, _, _ = ca.compile_source(self.dir / 'g.cheats.toml', new, plain=True)
++ self.assertEqual(entries[0][2][-3:], [0x04000000, 0x908, BL(0x908, cave)]) # --plain: no guards
++
++ def test_pairs_keep_their_order_and_a_pair_that_restores_elsewhere_is_not_merged(self):
++ """Merged pairs keep the file's entry order (it decides which runs last); an off entry that restores another word stays separate."""
++ f = [0xaa1703e0, NOP, LDRH(0, 0, 0x34), 0x1e2e1000, RET]
++ old = self.build('a', {0x100: f})
++ text = '[Y - off]\n04000000 0000010C 1E2E1000\n[Y - on]\n04000000 0000010C 1E2F1000\n'
++ text += '[X - on]\n04000000 0000010C 1E2F1000\n[X - off]\n04000000 00000104 D503201F\n' # restores another word
++ src, _, _ = ca.import_file(self.txt(text), old)
++ self.assertEqual([c['name'] for c in src['cheats']], ['Y', 'X - on', 'X - off'])
++ ca.write_toml(src, self.dir / 'g.cheats.toml', 'cheats.txt')
++ _, entries, _, _ = ca.compile_source(self.dir / 'g.cheats.toml', old)
++ self.assertEqual([e[0] for e in entries[:2]], ['Y - off', 'Y - on']) # off came first in the file: it still does
++
++ def test_changed_callee_falls_back_to_the_body_and_resized_function_to_the_window(self):
++ """The two fallbacks: a changed callee is found by the body digest, a resized function by the window."""
++ # the site (0x1e2e1000, an fmul) sits in the middle of the function, four distinct instructions on each side
++ around = [MOVZ(k, k) for k in range(1, 5)], [MOVZ(k, k) for k in range(5, 9)]
++ def f(start, callee, head=()):
++ """A function with an optional head, a call to callee and the site between the two runs of distinct words."""
++ return [*head, 0xaa1703e0, BL(start + 4 * (1 + len(head)), callee), LDRH(0, 0, 0x34), *around[0], 0x1e2e1000, *around[1], RET]
++ site = 4 * 7 # the site's offset in f without a head
++ old = self.build('a', {0x100: f(0x100, 0x400), 0x400: [MOVZ(0, 1), RET]})
++ changed = self.build('b', {0x200: f(0x200, 0x600), 0x600: [MOVZ(0, 2), RET]}, build=B2)
++ text = f'[Speed]\n04000000 {0x100 + site:08X} 1E2F1000\n'
++ got, report, skipped = self.roundtrip(old, changed, text)
++ self.assertEqual(skipped, 0, report); self.assertEqual(got['Speed'][3]['how'], 'body')
++ self.assertEqual(got['Speed'][2], [0x14050000, 0x200 + site, 0x1e2e1000, 0x04000000, 0x200 + site, 0x1e2f1000, 0x20000000])
++ longer = self.build('c', {0x300: f(0x300, 0x700, (NOP,)), 0x700: [MOVZ(0, 1), RET]}, build=b'\x33' * 8)
++ got, report, skipped = self.roundtrip(old, longer, text)
++ self.assertEqual(skipped, 0, report); self.assertEqual(got['Speed'][3]['how'], 'window'); self.assertEqual(got['Speed'][2][1], 0x304 + site)
++
++ def test_changed_original_word_and_ambiguous_window_are_refused(self):
++ """A changed site word, or a window found twice, refuses the cheat."""
++ f = lambda w: [0xaa1703e0, NOP, LDRH(0, 0, 0x34), w, RET]
++ old = self.build('a', {0x100: f(0x1e2e1000)})
++ other = self.build('b', {0x200: f(0x1e2e9000)}, build=B2)
++ _, report, skipped = self.roundtrip(old, other, '[Speed]\n04000000 0000010C 1E2F1000\n')
++ self.assertEqual(skipped, 1); self.assertIn('not in this build and 0 places match', report[0])
++ # two identical copies where the old build had one: neither the fingerprint (2 copies, 1 expected) nor the window decides
++ twice = self.build('c', {0x400: f(0x1e2e1000), 0x800: f(0x1e2e1000)}, build=b'\x33' * 8)
++ _, report, skipped = self.roundtrip(old, twice, '[Speed]\n04000000 0000010C 1E2F1000\n')
++ self.assertEqual(skipped, 1); self.assertIn('2 places match', report[0])
++
++ def test_identical_copies_are_weak_by_order_and_checked_by_their_window(self):
++ """Identical copies: by order is weak, a unique window confirms it, and a window that points elsewhere refuses it."""
++ f = [0xaa1703e0, NOP, LDRH(0, 0, 0x34), 0x1e2e1000, RET]
++ old = self.build('a', {0x100: f, 0x300: f}) # the same zero padding around both copies: the window cannot tell them apart
++ new = self.build('b', {0x500: f, 0x900: f}, build=B2)
++ got, report, skipped = self.roundtrip(old, new, '[Second]\n04000000 0000030C 1E2F1000\n')
++ self.assertEqual(skipped, 0, report); self.assertEqual(got['Second'][2][1], 0x90c)
++ self.assertIn('copy 2 of 2 by order: weak', got['Second'][3]['how'])
++ # each copy followed by a function of its own: the window identifies the copy, and contradicts a changed order
++ tail = lambda k: [MOVZ(k, k), MOVZ(k, k + 1), RET]
++ old = self.build('c', {0x100: f, 0x114: tail(1), 0x300: f, 0x314: tail(2)})
++ same_order = self.build('d', {0x500: f, 0x514: tail(1), 0x900: f, 0x914: tail(2)}, build=B2)
++ got, report, skipped = self.roundtrip(old, same_order, '[Second]\n04000000 0000030C 1E2F1000\n')
++ self.assertEqual(skipped, 0, report); self.assertIn('confirmed by its window', got['Second'][3]['how'])
++ swapped = self.build('e', {0x500: f, 0x514: tail(2), 0x900: f, 0x914: tail(1)}, build=b'\x33' * 8)
++ _, report, skipped = self.roundtrip(old, swapped, '[Second]\n04000000 0000030C 1E2F1000\n')
++ self.assertEqual(skipped, 1); self.assertIn('its window says 0x50C', report[0])
++
++ def test_a_relocated_word_is_restored_as_this_builds_own_and_never_patched_with_old_bits(self):
++ """A relocated original (an adrp's user) is restored with the new build's own word and never patched with the old build's bits."""
++ g = lambda s, data: [ADRP(8, s, data), LDRW(0, 8, data & 0xfff), RET] # ldr w0, [x8, #lo]: an adrp's user
++ old = self.build('a', {0x100: g(0x100, 0x4100)})
++ new = self.build('b', {0x100: g(0x100, 0x4180)}, build=B2)
++ src, report, bound = ca.import_file(self.txt(f'[Next field]\n04000000 00000104 {LDRW(0, 8, 0x104):08X}\n'), old)
++ self.assertEqual(bound, 1); self.assertIn('takes the page of the adrp at 0x100', ' '.join(report))
++ got, report, skipped = self.roundtrip(old, new, f'[Restore]\n04000000 00000104 {LDRW(0, 8, 0x100):08X}\n')
++ self.assertEqual(skipped, 0, report); self.assertEqual(got['Restore'][2], [0x04000000, 0x104, LDRW(0, 8, 0x180)])
++
++ def test_a_word_the_rewriter_changed_is_reported(self):
++ """A site the rewriter changed is reported, found through the NSP script's folder layout."""
++ f = [0xaa1703e0, NOP, LDRH(0, 0, 0x34), 0x1e2e1000, RET]
++ old = self.build('a', {0x100: f})
++ new = self.build('b/extract/v1/ExeFS/main', {0x200: f}, build=B2) # the NSP script's layout
++ rewritten = bytearray(new.img); struct.pack_into('<I', rewritten, 0x20c, 0x14000000)
++ (self.dir / 'b/patched_v1').mkdir(); (self.dir / 'b/patched_v1/main.patched.bin').write_bytes(rewritten)
++ new = ca.Build(self.dir / 'b/extract/v1/ExeFS/main')
++ _, report, skipped = self.roundtrip(old, new, '[Speed]\n04000000 0000010C 1E2F1000\n')
++ self.assertEqual(skipped, 0); self.assertTrue(any('the rewriter changed the word at 0x20C' in r for r in report), report)
++
++ def test_width_8_cave_store_and_branch_tokens(self):
++ """An 8-byte store into the cave lands low word first, and a BL token is re-encoded; out-of-range branches are refused."""
++ f = [0xaa1703e0, NOP, LDRH(0, 0, 0x34), RET]
++ old = self.build('a', {0x100: f})
++ cave = RO - 0x40
++ got, report, skipped = self.roundtrip(old, old, f'[Cave]\n08000000 {cave:08X} 11112222 33334444\n04000000 00000104 {BL(0x104, cave):08X}\n')
++ self.assertEqual(skipped, 0, report)
++ prog = got['Cave'][2] # memory order: the low word at the address, the high word after it
++ self.assertEqual(prog[:14], [0x14050000, cave, 0, 0x04000000, cave, 0x33334444, 0x20000000,
++ 0x14050000, cave + 4, 0, 0x04000000, cave + 4, 0x11112222, 0x20000000])
++ self.assertEqual(prog[-4:-1], [0x04000000, 0x104, BL(0x104, cave)])
++ with self.assertRaisesRegex(ca.AnchorError, 'out of range'): ca.encode_branch(True, 0, 1 << 28)
++
++ def test_keypress_code_keeps_its_program_with_anchored_addresses(self):
++ """A keypress-gated program keeps its words with only its address re-anchored; a glued header still starts a cheat."""
++ old = self.build('a', {0x100: reader(0x100, 0x4100), 0x200: reader(0x200, 0x4100, 0x20)})
++ new = self.build('b', {0x300: reader(0x300, 0x4180), 0x500: reader(0x500, 0x4180, 0x20)}, build=B2)
++ got, report, skipped = self.roundtrip(old, new, '[Hold A]\n80000001\n02000000 00004104 00000001\n20000000[Next]\n01000000 00004120 00000001\n')
++ self.assertEqual(skipped, 0, report)
++ self.assertEqual(got['Hold A'][2], [0x80000001, 0x02000000, 0x4184, 1, 0x20000000])
++ self.assertIn('Next', got) # a header glued to the previous line still starts a cheat
++
++ def test_build_bound_cheats_and_the_file_name_check(self):
++ """Unanchorable cheats stay bound to their own build, and a file named after another build needs --assume-build."""
++ old = self.build('a', {0x100: reader(0x100, 0x4100), 0x200: reader(0x200, 0x4100, 0x20)})
++ new = self.build('b', {0x100: reader(0x100, 0x4100), 0x200: reader(0x200, 0x4100, 0x20)}, build=B2)
++ got, report, skipped = self.roundtrip(old, new, '[Heap]\n02100000 00001234 00000001\n') # region 1: the heap
++ self.assertEqual(skipped, 1); self.assertIn('written for build 1111111111111111 only', report[0])
++ with self.assertRaisesRegex(ca.AnchorError, 'names build 2222222222222222'):
++ ca.import_file(self.txt('[x]\n02000000 0000411E 00000001\n', '2222222222222222.txt'), old)
++ src, report, bound = ca.import_file(self.txt('[x]\n02000000 0000411E 00000001\n[h]\n02100000 00001234 00000001\n', '2222222222222222.txt'), old, assume_build=True)
++ self.assertTrue(report[0].startswith('[RED] ')); self.assertEqual(bound, 1)
++ self.assertEqual(src['cheats'][1]['builds'], ['2222222222222222']) # its fixed addresses are the file's build's
++
++ # ---- what may be written over a moved instruction ----
++
++ def test_a_gated_store_follows_the_same_relocation_rule_as_a_patch(self):
++ """A keypress-gated store over a moved bl is refused like the plain patch; a gated restore writes this build's word."""
++ fa = lambda s, callee: [MOVZ(1, 1), BL(s + 4, callee), MOVZ(2, 2), MOVZ(3, 3), RET]
++ callee = [MOVZ(0, 7), MOVZ(5, 9), RET]
++ old = self.build('a', {0x100: fa(0x100, 0x300), 0x300: callee})
++ new = self.build('b', {0x140: fa(0x140, 0x400), 0x400: callee}, build=B2)
++ bad = f'{LDRX(0, 1, 8):08X}' # a load with an immediate: carries_address_bits, so not over a moved word
++ text = f'[Gated]\n80000040\n04000000 00000104 {bad}\n20000000\n[Plain]\n04000000 00000104 {bad}\n'
++ text += f'[Gated restore]\n80000040\n04000000 00000104 {BL(0x104, 0x300):08X}\n20000000\n'
++ got, report, skipped = self.roundtrip(old, new, text)
++ self.assertEqual(skipped, 2, report)
++ reasons = [r.split('skipped: ')[1] for r in report if 'skipped' in r]
++ self.assertEqual(reasons[0], reasons[1]); self.assertIn('relocated in this build', reasons[0])
++ self.assertEqual(got['Gated restore'][2], [0x80000040, 0x04000000, 0x144, BL(0x144, 0x400), 0x20000000])
++
++ def test_a_word_without_address_bits_may_replace_a_moved_one(self):
++ """A NOP over a moved bl and a mov over a moved adrp user carry no address bits: written, guarded by this build's word."""
++ fa = lambda s, callee, data: [MOVZ(1, 1), BL(s + 4, callee), ADRP(8, s + 8, data), LDRW(0, 8, data & 0xfff), MOVZ(3, 3), RET]
++ callee = [MOVZ(0, 7), MOVZ(5, 9), RET]
++ old = self.build('a', {0x100: fa(0x100, 0x300, 0x4100), 0x300: callee})
++ new = self.build('b', {0x140: fa(0x140, 0x400, 0x4208), 0x400: callee}, build=B2)
++ got, report, skipped = self.roundtrip(old, new, f'[Nop bl]\n04000000 00000104 {NOP:08X}\n[Mov]\n04000000 0000010C {MOVZ(0, 1):08X}\n')
++ self.assertEqual(skipped, 0, report)
++ self.assertEqual(got['Nop bl'][2], [0x14050000, 0x144, BL(0x144, 0x400), 0x04000000, 0x144, NOP, 0x20000000])
++ self.assertEqual(got['Mov'][2], [0x14050000, 0x14c, LDRW(0, 8, 0x208), 0x04000000, 0x14c, MOVZ(0, 1), 0x20000000])
++
++ def test_carries_address_bits_is_false_only_for_address_free_encodings(self):
++ """The classifier: NOP, MOVZ, register-only data processing, RET and FMOV carry no address; everything else, unknown included, does."""
++ free = {'nop': NOP, 'movz': MOVZ(0, 1), 'movk x': 0xf2a00020, 'mov x0, x1': 0xaa0103e0, 'neg': 0xcb0103e0,
++ 'add reg': 0x8b020020, 'csel': 0x9a821020, 'mul': 0x9b027c20, 'udiv': 0x9ac20820, 'ret': RET,
++ 'fmov s0, s1': 0x1e204020, 'fmov s0, #1.0': 0x1e2e1000}
++ bound = {'bl': BL(0, 0x100), 'b.ne': BCOND(1, 0, 8), 'cbz': 0x34000040, 'tbz': 0x36000040, 'adr': 0x10000040,
++ 'adrp': ADRP(8, 0, 0x4000), 'ldr literal': 0x58000040, 'ldr imm': LDRX(0, 8, 8), 'add imm': ADDI(8, 8, 0x10),
++ 'str imm': 0xf9000100, 'udf': 0, 'move wide opc 01': 0x32800000}
++ for name, w in free.items():
++ with self.subTest(name): self.assertFalse(ca.carries_address_bits(w))
++ for name, w in bound.items():
++ with self.subTest(name): self.assertTrue(ca.carries_address_bits(w))
++
++ def test_a_flipped_conditional_branch_follows_its_function(self):
++ """b.ne flipped to b.eq inside a function that moved: kept as written and checked to be found by fingerprint, refused by window."""
++ def f(s, head=()):
++ """Four distinct words, a b.ne to the function's ret, four more distinct words, ret."""
++ n = len(head)
++ return [*head, *(MOVZ(k, k) for k in range(1, 5)), BCOND(1, s + 4 * (n + 4), s + 4 * (n + 9)), *(MOVZ(k, k) for k in range(5, 9)), RET]
++ old = self.build('a', {0x100: f(0x100)})
++ moved = self.build('b', {0x300: f(0x300)}, build=B2)
++ flip = BCOND(0, 0x110, 0x124)
++ got, report, skipped = self.roundtrip(old, moved, f'[Flip]\n04000000 00000110 {flip:08X}\n')
++ self.assertEqual(skipped, 0, report)
++ self.assertEqual(got['Flip'][2], [0x14050000, 0x310, BCOND(1, 0x310, 0x324), 0x04000000, 0x310, flip, 0x20000000])
++ longer = self.build('c', {0x300: f(0x300, (NOP,))}, build=b'\x33' * 8) # resized: found by its window only
++ _, report, skipped = self.roundtrip(old, longer, f'[Flip]\n04000000 00000110 {flip:08X}\n')
++ self.assertEqual(skipped, 1); self.assertIn('found here by window', report[0])
++
++ # ---- segments, malformed files, the rest ----
++
++ def test_a_data_anchor_stays_in_its_target_segment(self):
++ """A target at the start of .data is never anchored to a nearer .rodata base, and an old source that crosses is refused."""
++ ro = {0x100: reader(0x100, 0x3ff8), 0x200: reader(0x200, 0x3ff8, 0x20)} # an object at the end of .rodata
++ old = self.build('a', ro)
++ src, report, bound = ca.import_file(self.txt('[x]\n02000000 00004010 00000001\n'), old)
++ self.assertEqual(bound, 1); self.assertEqual(src['cheats'][0]['builds'], ['1111111111111111'])
++ self.assertIn('no describable code reference', ' '.join(report))
++ # with an object at the start of .data: anchored to it, and found again when .rodata grows and .data moves up
++ old = self.build('c', {**ro, 0x300: reader(0x300, 0x4000, 0x22), 0x400: reader(0x400, 0x4000, 0x24)})
++ grown = self.build('d', {**ro, 0x300: reader(0x300, 0x4100, 0x22), 0x400: reader(0x400, 0x4100, 0x24)}, build=B2, data=0x4100)
++ got, report, skipped = self.roundtrip(old, grown, '[x]\n02000000 00004010 00000001\n')
++ self.assertEqual(skipped, 0, report); self.assertEqual(got['x'][2][1], 0x4110)
++ # a source that anchors the .data target on the .rodata object (what import used to write) is refused
++ refs = ', '.join(f'{{ old = "{old.word(s):08X}", size = 0x10, at = 0x0, use = 0x4, fp = "{old.digest(s, "fp")}" }}' for s in (0x100, 0x200))
++ self.source(f'format = 1\n[[cheats]]\nname = "x"\ntarget = "d_3FF8+0x18"\ntype = "u16"\nvalue = 1\n[anchors.d_3FF8]\ndata = [{refs}]\n')
++ _, _, report, skipped = ca.compile_source(self.dir / 's.cheats.toml', old)
++ self.assertEqual(skipped, 1); self.assertIn('crosses from ro into data', report[0])
++
++ def test_glued_words_are_split_and_stray_tokens_make_a_cheat_malformed(self):
++ """Glued words split like Atmosphère reads them; prose lines are ignored like the host does; junk on a code
++ line, or a cut word, keeps the cheat whole, bound and refused, with its line; such a token survives the TOML."""
++ entries, warns = ca.parse_atmosphere('[A]\n0400000000004100 00000001\n')
++ self.assertEqual(entries, [('A', False, [0x04000000, 0x4100, 1], [])])
++ old = self.build('a', {0x100: reader(0x100, 0x4100), 0x200: reader(0x200, 0x4100, 0x20)})
++ text = ('[B]\n80000001\n04000000 00004100 00000001\n2000000\n[C]\nby someone\n04000000 00004104 00000002\n'
++ '[Credits]\nMade by X\n[D]\n04000000 00004108 00000003 x""""y\n')
++ src, report, bound = ca.import_file(self.txt(text), old)
++ self.assertEqual(bound, 2)
++ b, cr, d = (next(c for c in src['cheats'] if c['name'] == n) for n in ('B', 'Credits', 'D'))
++ self.assertIn('2000000', b['code']); self.assertIn('x""""y', d['code']); self.assertTrue(cr.get('label')) # never shortened
++ self.assertTrue(any('"B"' in r and 'line 4: "2000000"' in r for r in report), report)
++ self.assertTrue(any('"by" in "C"' in r and 'ignored' in r for r in report), report)
++ ca.write_toml(src, self.dir / 'g.cheats.toml', 'cheats.txt')
++ self.assertIn('x""""y', tomllib.loads((self.dir / 'g.cheats.toml').read_text())['cheats'][3]['code'])
++ _, entries, report, skipped = ca.compile_source(self.dir / 'g.cheats.toml', old) # refused even on its own build
++ self.assertEqual(skipped, 2); self.assertEqual([e[0] for e in entries if e[2] is not None], ['C', 'Credits'])
++
++ def test_an_undecodable_cheat_is_kept_verbatim_on_its_own_build(self):
++ """A cheat the decoder cannot read is emitted word for word on its own build, and skipped on any other."""
++ old = self.build('a', {0x100: reader(0x100, 0x4100)})
++ new = self.build('b', {0x100: reader(0x100, 0x4100)}, build=B2)
++ got, report, skipped = self.roundtrip(old, old, '[Weird]\nB0000000 00000001\n')
++ self.assertEqual(skipped, 0, report); self.assertEqual(got['Weird'][2], [0xB0000000, 1])
++ self.assertIn('[Weird]\nB0000000 00000001\n', ca.render(list(got.values())))
++ _, entries, report, skipped = ca.compile_source(self.dir / 'g.cheats.toml', new)
++ self.assertEqual(skipped, 1)
++
++ def test_a_file_named_after_the_title_id_names_no_build(self):
++ """A file named after the title ID is taken as written for the NSO's build, not refused as another build's."""
++ (self.dir / 't').mkdir()
++ npdm = bytearray(0xa0); struct.pack_into('<I', npdm, 0x70, 0x80); npdm[0x80:0x84] = b'ACI0'
++ struct.pack_into('<Q', npdm, 0x90, 0x0100abcd00000000); (self.dir / 't/main.npdm').write_bytes(npdm)
++ old = self.build('t/main', {0x100: reader(0x100, 0x4100), 0x200: reader(0x200, 0x4100, 0x20)})
++ self.assertEqual(old.title, '0100ABCD00000000')
++ src, report, bound = ca.import_file(self.txt('[h]\n02100000 00001234 00000001\n', '0100ABCD00000000.txt'), old)
++ self.assertEqual(bound, 1); self.assertEqual(src['cheats'][0]['builds'], ['1111111111111111'])
++
++ def test_a_merged_pair_keeps_its_master_flag(self):
++ """A master on or off entry stays a master after its on / off pair is merged."""
++ old = self.build('a', {0x100: [0xaa1703e0, NOP, LDRH(0, 0, 0x34), 0x1e2e1000, RET]})
++ for off_head, off_master in (('[Fast - off]', False), ('{Fast - off}', True)):
++ with self.subTest(off_head):
++ src, _, _ = ca.import_file(self.txt(f'{{Fast - on}}\n04000000 0000010C 1E2F1000\n{off_head}\n04000000 0000010C 1E2E1000\n'), old)
++ self.assertEqual([c.get('on_name') for c in src['cheats']], ['Fast - on']) # merged into one cheat
++ ca.write_toml(src, self.dir / 'g.cheats.toml', 'cheats.txt')
++ _, entries, report, skipped = ca.compile_source(self.dir / 'g.cheats.toml', old)
++ self.assertEqual([(e[0], e[1]) for e in entries], [('Fast - on', True), ('Fast - off', off_master)])
++
++ def test_only_opcode_0_literals_are_carried_into_the_code(self):
++ """A register store (opcode A) into the code is bound to its build: its value never meets the relocation rule."""
++ fa = lambda s, callee: [MOVZ(1, 1), BL(s + 4, callee), MOVZ(2, 2), MOVZ(3, 3), RET]
++ old = self.build('a', {0x100: fa(0x100, 0x300), 0x300: [MOVZ(0, 7), RET]})
++ src, report, bound = ca.import_file(self.txt(f'[RegStore]\n400F0000 00000000 {BL(0x104, 0x308):08X}\nA4F00400 00000104\n'), old)
++ self.assertEqual(bound, 1); self.assertIn('a store of a register into the code at 0x104', ' '.join(report))
++
++ def test_a_new_adrp_user_over_an_unmoved_word_is_bound(self):
++ """A new word that takes a preceding adrp's page keeps this build's low page bits: bound at import, refused at compile elsewhere."""
++ f = lambda s, data: [ADRP(8, s, data), LDRW(1, 8, data & 0xfff), MOVZ(0, 2), MOVZ(3, 3), RET]
++ old = self.build('a', {0x100: f(0x100, 0x4100)})
++ new = self.build('b', {0x100: f(0x100, 0x4180)}, build=B2) # the data moved inside its page, the code did not
++ text = f'[Neighbour]\n04000000 00000108 {LDRW(0, 8, 0x104):08X}\n'
++ src, report, bound = ca.import_file(self.txt(text), old)
++ self.assertEqual(bound, 1); self.assertIn('takes the page of the adrp at 0x100', ' '.join(report))
++ self.source(f'format = 1\nauthored = "1111111111111111"\n[[cheats]]\nname = "N"\npatch = [{{ at = "s_108", new = "{LDRW(0, 8, 0x104):08X}" }}]\n'
++ f'[anchors.s_108]\ncode = {{ old = "{MOVZ(0, 2):08X}", size = 0x14, at = 0x8, fp = "{old.digest(0x100, "fp")}" }}\n')
++ _, entries, report, skipped = ca.compile_source(self.dir / 's.cheats.toml', old)
++ self.assertEqual(skipped, 0, report) # its own build: the word is right there
++ _, entries, report, skipped = ca.compile_source(self.dir / 's.cheats.toml', new)
++ self.assertEqual(skipped, 1); self.assertIn('takes the page of the adrp', report[0])
++
++ def test_a_narrow_write_is_checked_by_the_word_it_makes(self):
++ """A 2-byte write that retargets a bl is bound at import, and refused at compile when the site was found by its window."""
++ F = lambda s, g: [MOVZ(1, 1), BL(s + 4, g), MOVZ(2, 2), MOVZ(3, 3), RET]
++ old = self.build('a', {0x100: F(0x100, 0x400), 0x400: [MOVZ(0, 7), RET], 0x500: [MOVZ(0, 8), MOVZ(6, 9), RET]})
++ src, report, bound = ca.import_file(self.txt(f'[ToH]\n02000000 00000104 0000{BL(0x104, 0x500) & 0xffff:04X}\n'), old)
++ self.assertEqual(bound, 1); self.assertIn('makes 940000FF, PC-relative to 0x500', ' '.join(report))
++ self.source(f'format = 1\n[[cheats]]\nname = "N"\npatch = [{{ at = "s_104", width = 2, new = "{BL(0x104, 0x500) & 0xffff:04X}" }}]\n'
++ f'[anchors.s_104]\ncode = {{ old = "{BL(0x104, 0x400):08X}", size = 0x14, at = 0x4, fp = "{old.digest(0x100, "fp")}" }}\n')
++ _, entries, report, skipped = ca.compile_source(self.dir / 's.cheats.toml', old)
++ self.assertEqual(skipped, 1); self.assertIn('PC-relative to 0x500', report[0])
++
++ def test_a_compare_with_a_moved_original_compares_with_this_builds_word(self):
++ """An "if [X] == original" gate over a moved bl compares with this build's word, so it still opens."""
++ fa = lambda s, callee: [MOVZ(1, 1), BL(s + 4, callee), MOVZ(2, 2), MOVZ(3, 3), RET]
++ old = self.build('a', {0x100: fa(0x100, 0x300), 0x300: [MOVZ(0, 7), RET]})
++ new = self.build('b', {0x140: fa(0x140, 0x400), 0x400: [MOVZ(0, 7), RET]}, build=B2)
++ text = f'[Gate]\n14050000 00000104 {BL(0x104, 0x300):08X}\n04000000 00000104 {NOP:08X}\n20000000\n'
++ got, report, skipped = self.roundtrip(old, new, text)
++ self.assertEqual(skipped, 0, report)
++ self.assertEqual(got['Gate'][2], [0x14050000, 0x144, BL(0x144, 0x400), 0x04000000, 0x144, NOP, 0x20000000])
++
++ def test_a_store_offset_by_r0_the_cheat_sets_is_indexed(self):
++ """The VM adds the offset register, r0 included: a store into code offset by an r0 the cheat loads is not static."""
++ old = self.build('a', {0x100: [0xaa1703e0, NOP, LDRH(0, 0, 0x34), 0x1e2e1000, RET]})
++ src, report, bound = ca.import_file(self.txt('[R0]\n40000000 00000000 00000004\n04000000 0000010C 1E2F1000\n'), old)
++ self.assertEqual(bound, 1); self.assertIn('indexed by register 0', ' '.join(report))
++
++ def test_a_data_anchor_found_among_identical_copies_by_order_is_weak(self):
++ """Data references resolved among identical copies by order alone keep the weak mark."""
++ old = self.build('a', {0x100: reader(0x100, 0x4100), 0x300: reader(0x300, 0x4100)})
++ new = self.build('b', {0x500: reader(0x500, 0x4180), 0x900: reader(0x900, 0x4180)}, build=B2)
++ got, report, skipped = self.roundtrip(old, new, '[x]\n02000000 0000411E 00000001\n')
++ self.assertEqual(skipped, 0, report); self.assertEqual(got['x'][2][1], 0x419e)
++ self.assertIn('weak: 2 of them identical copies by order', got['x'][3]['how'])
++ self.assertTrue(any('resolved weakly' in r for r in report))
++
++ def test_a_multi_word_patch_with_a_rewritten_word_is_skipped_whole(self):
++ """A patch whose guard would skip one rewritten word and apply the other is refused instead of half-written."""
++ f = [0xaa1703e0, NOP, LDRH(0, 0, 0x34), 0x1e2e1000, RET]
++ old = self.build('a', {0x100: f})
++ new = self.build('b/extract/v1/ExeFS/main', {0x200: f}, build=B2)
++ rewritten = bytearray(new.img); struct.pack_into('<I', rewritten, 0x20c, 0x14000000)
++ (self.dir / 'b/patched_v1').mkdir(); (self.dir / 'b/patched_v1/main.patched.bin').write_bytes(rewritten)
++ new = ca.Build(self.dir / 'b/extract/v1/ExeFS/main')
++ _, report, skipped = self.roundtrip(old, new, '[Two]\n04000000 00000108 D2800020\n04000000 0000010C 1E2F1000\n')
++ self.assertEqual(skipped, 1); self.assertIn('partial hook', report[0])
++ self.assertTrue(any('the rewriter changed the word at 0x20C' in r for r in report), report)
++
++ # ---- the source and the outputs ----
++
++ def test_data_actions_and_values(self):
++ """The encodings of min, set with "ask", a pointer chain (register 15 zeroed after it), decimal offsets and the refusal of signed min / max."""
++ old = self.build('a', {0x100: reader(0x100, 0x4100), 0x200: reader(0x200, 0x4100, 0x20)})
++ refs = ', '.join(f'{{ old = "{old.word(s):08X}", size = 0x10, at = 0x0, use = 0x4, fp = "{old.digest(s, "fp")}" }}' for s in (0x100, 0x200))
++ self.source(f'''format = 1
++[[cheats]]
++name = "HP at least 50"
++target = "d_4100+0x1C"
++type = "u16"
++action = "min"
++value = 50
++[[cheats]]
++name = "Gold"
++section = "Items"
++target = "d_4100+0x40"
++type = "u32"
++action = "set"
++value = "ask"
++min = 0
++max = 9999
++default = 500
++[[cheats]]
++name = "Mog"
++target = "[d_4100+0x8]+0x38"
++type = "u32"
++value = 0
++[[cheats]]
++name = "Signed"
++target = "d_4100"
++type = "s16"
++action = "max"
++value = 10
++[[cheats]]
++name = "Leading zero"
++target = "d_4100+010"
++type = "u8"
++value = 1
++[[cheats]]
++name = "HP never decreases"
++target = "d_4100+0x1C"
++type = "s16"
++action = "never-decrease"
++[anchors.d_4100]
++data = [{refs}]
++''')
++ _, entries, report, skipped = ca.compile_source(self.dir / 's.cheats.toml', old)
++ got = {e[0]: e for e in entries}
++ self.assertEqual(got['HP at least 50'][2], [0x12030000, 0x411c, 50, 0x02000000, 0x411c, 50, 0x20000000])
++ self.assertEqual(got['Gold'][2], [0x04000000, 0x4140, 500]); self.assertEqual(got['Gold'][3]['ask'], '0..9999')
++ self.assertEqual(got['Gold'][3]['once'], '1'); self.assertEqual(got['Gold'][3]['value_words'], '2')
++ self.assertEqual(got['Mog'][2], [0x18060000, 0x4108, 0, 0, 0x580f0000, 0x4108, 0x780f0000, 0x38,
++ 0x640f0000, 0, 0, 0x400f0000, 0, 0, 0x20000000]) # r15 is zeroed after the chain
++ self.assertEqual(got['Leading zero'][2][1], 0x410a) # decimal 010 = 10
++ nd = got['HP never decreases'] # no Atmosphère program: the host runs it from the meta row
++ self.assertEqual((nd[2], nd[3]['action'], nd[3]['address'], nd[3]['type']), ([], 'never-decrease', '0:0x411C', 's16'))
++ self.assertIn('nxnative only', nd[3]['how'])
++ self.assertEqual(skipped, 1); self.assertIn('only unsigned types', [r for r in report if 'Signed' in r][0])
++ text = ca.render(entries)
++ self.assertIn('[--SectionStart:Items--]\n\n[Gold]\n04000000 00004140 000001F4\n\n[--SectionEnd:Items--]', text)
++ self.assertIn('[HP never decreases]\n\n', text) # an empty entry: an inert label on other engines
++ meta = ca.meta_text('s.cheats.toml', old, entries, {}, text).split('\n')
++ head = meta[2].split('\t'); row = dict(zip(head, next(l for l in meta if l.startswith('HP never')).split('\t')))
++ self.assertEqual((row['action'], row['address'], row['type']), ('never-decrease', '0:0x411C', 's16'))
++
++ def test_instruction_lengths_of_every_form(self):
++ """Instruction lengths of the forms the host VM does not run yet: a wrong length would misread every later word of a community file."""
++ cases = [([0x94100020], 1), ([0x94100100, 0], 2), ([0x98100100, 0, 0], 3), # 9: register / static value
++ ([0xA4100000], 1), ([0xA4100200, 0], 2), ([0xA4100400, 0x1234], 2), # A: none / fixed / region + address
++ # C0TcSX..: X (bits 8-11) 0 region + address, 1 region + register, 4 a static value, 5 another register
++ ([0xC0450000, 0], 2), ([0xC0450100], 1), ([0xC0450400, 0], 2), ([0xC0850400, 0, 0], 3), ([0xC0450500], 1),
++ ([0xC1000000], 1), ([0xC2000000], 1), ([0xC3000000], 1), ([0xC4000000, 0, 0], 3),
++ ([0xFF000000], 1), ([0xFFF40000, 0], 2), ([0xFFF40400], 1)]
++ for words, n in cases:
++ with self.subTest(word=f'{words[0]:08X}'): self.assertEqual(ca.decode(words, 0)['n'], n)
++ self.assertEqual(ca.decode([0xA4100400, 0x1234], 0)['rel'], 0x1234)
++ with self.assertRaisesRegex(ca.AnchorError, 'unknown opcode'): ca.decode([0xB0000000], 0)
++
++ def test_names_with_control_characters_survive_the_source(self):
++ """Names with control characters, quotes and backslashes survive the TOML source."""
++ src = {'format': 1, 'authored': '1111111111111111', 'cheats': [{'name': 'a\x01b"c\\d\x7f', 'label': True}], 'anchors': {}}
++ ca.write_toml(src, self.dir / 'x.cheats.toml', 'x.txt')
++ self.assertEqual(tomllib.loads((self.dir / 'x.cheats.toml').read_text())['cheats'][0]['name'], 'a\x01b"c\\d\x7f')
++
++ def test_an_output_this_tool_did_not_write_is_never_overwritten(self):
++ """Hand-made, edited or another source's .txt files are kept; only this source's unchanged output is rewritten."""
++ old = self.build('a', {0x100: reader(0x100, 0x4100), 0x200: reader(0x200, 0x4100, 0x20)})
++ src, _, _ = ca.import_file(self.txt('[x]\n02000000 0000411E 00000001\n'), old)
++ ca.write_toml(src, self.dir / 'g.cheats.toml', 'cheats.txt')
++ out = self.dir / 'cheats'; out.mkdir()
++ txt = out / '1111111111111111.txt'
++ txt.write_text('[mine]\n')
++ src, entries, _, _ = ca.compile_source(self.dir / 'g.cheats.toml', old)
++ compile = lambda path, replace=False: ca.write_compiled(out, path, old, entries, src, replace)
++ compile(self.dir / 'g.cheats.toml')
++ self.assertEqual(txt.read_text(), '[mine]\n'); self.assertTrue((out / '1111111111111111.txt.new').read_text().startswith('[x]'))
++ compile(self.dir / 'g.cheats.toml', replace=True)
++ self.assertEqual((out / '1111111111111111.txt.orig').read_text(), '[mine]\n'); self.assertTrue(txt.read_text().startswith('[x]'))
++ compile(self.dir / 'g.cheats.toml') # its own unchanged output: rewritten in place
++ self.assertFalse((out / '1111111111111111.txt.new').read_text() != (out / '1111111111111111.txt').read_text())
++ (out / '1111111111111111.txt.new').unlink()
++ compile(self.dir / 'other.cheats.toml') # another source's output for the same build
++ self.assertTrue((out / '1111111111111111.txt.new').exists()); (out / '1111111111111111.txt.new').unlink()
++ txt.write_text(txt.read_text() + '[edited]\n') # edited since it was compiled
++ lines = compile(self.dir / 'g.cheats.toml')
++ self.assertIn('edited since it was compiled', lines[0]); self.assertTrue(txt.read_text().endswith('[edited]\n'))
++
++
++if __name__ == '__main__': unittest.main()
+diff --git a/docs/development.md b/docs/development.md
+index 6b58a678..85cef1db 100644
+--- a/docs/development.md
++++ b/docs/development.md
+@@ -16,6 +16,113 @@ The README covers packing and playing. This page is for working on nxnative itse
+
+ On the Mac, `DM_KEYMAP=<name>=<key code>,…` puts a button, a stick direction (the right stick too, on no key by default) or `Shake` on another key, and `DM_PAD_MAP=<name>=<name>,…` changes what a controller's buttons send (`A=B,B=A` swaps them; `input_map.h`).
+
++## Cheats
++
++How a Switch with Atmosphère runs cheats, and where this host differs, is in [Cheats on a Switch](reference/cheats.md).
++
++Atmosphère-format cheat code files (`atmosphere/contents/<title ID>/cheats/<build ID>.txt` files that cheat sites share) apply to the running game (`dm/host/hle_cheats.c`): the file of the running build is chosen by the first 16 hex digits of the main NSO's build ID (FFCC 1.0.1: `DF154E1D08E39646`), from a folder holding either the flat `<build ID>.txt` layout, the Atmosphère tree under it, or both. The Mac window (`DM_WINDOW=1`) has a **Cheats** menu: each `[Name]` cheat is a checkmark row that toggles when clicked, a `{Name}` master code is always on and not toggleable, a cheat the VM cannot run shows its reason (`unsupported opcode FFF`) and stays off, and with no file of this build the menu lists `No cheats for build …` plus each other build's `.txt` in the folder as `another version of the game` (all disabled; `DM_CHEATS_ANY_BUILD=1` loads one, with a `[RED]` warning). The menu also reloads the file in place (**Reload cheats**, ⌘R) and opens the folder (creating it when missing). Which cheats are on is remembered per build in `<build ID>.enabled` (one name per line) in the folder, restored at the next launch. The menu's first item **Show Cheats Window** (⌘⇧C, or `DM_CHEATS_WINDOW=1` at launch) opens a **Cheats panel** (`dm/host/front_mac.m`, `DmCheatsPanel`), a floating utility panel beside the game. A click never takes the key window from the game, so the game keeps keyboard and controllers; the panel takes the keyboard only while the player types in its search field or a value field: Return gives it back with the value applied, Escape gives it back with the typed value abandoned, and a click anywhere else in the panel never keeps it. It shows:
++- a header with the build and its version ("1.0.3 (build E1D8…): 18 cheats, 5 on", or "No cheats for …"), and a line with **Restore** in safe mode;
++- **Cheats On** (the master switch), **Select All** / **Deselect All** (plain cheats only: never masters, disabled cheats, "set" cheats or the off half of a pair; both off while Cheats On is off) and a search field that filters by name and section;
++- the rows: section headers, labels, one row per cheat (an on / off pair is one row without its " - on"; a "set" cheat has an **Apply** button; an "ask" cheat a value field; ⓘ shows the cheat's dry run and note below the rows), then the cheats the compiler left out, the other builds' files with their versions, and, with no file of this build, the anchored sources with a **Copy Command** for compiling them;
++- **Reload**, **Open Folder**, **Find Cheats…** (this game's files in Ryujinx's mods tree, the yuzu family's load trees and SD cards' Atmosphère trees, this build's first) and **Report** (the load report).
++
++A `.txt` or `.cheats.toml` dropped on the panel (from a Finder window in the background: the panel hides while another app is in front), or picked in Find Cheats…, is copied into the cheats folder and the file reloaded: a build-ID name keeps its name, any other `.txt` (also one named after the title ID) becomes this build's after the player confirms, and a file already there is kept as `.bak` (replacing an older `.bak`). Find Cheats… lists only files named after a build ID, so Ryujinx's `enabled.txt` stays out. The menu shows the same rows in short, with Cheats On and, in safe mode, Restore Saved Cheats. Every click, a menu toggle and a ~1 s timer while the panel is visible refresh it. Closing the panel only hides it; its place and size are remembered. The enabled cheats run once per presented frame and at ~60 Hz from a host thread whenever the game is not presenting: one pass reads the keys once, then runs the masters, then the enabled cheats in file order, with the registers and the saved values reset once per pass and shared between the cheats, as dmnt's one concatenated program has them (a pointer chain compiled by `cheat_anchor.py` zeroes its register 15 behind itself for that reason); each cheat is still its own program, with its condition depth and loop tops (word indexes into its own words) starting fresh, so an unclosed block in one cannot swallow the next cheat's words, and a loop end without its start jumps to the first word of its own cheat, never into another cheat's. A failed conditional block is skipped like the reference's. An access to memory that is not mapped (a pointer the game has not set yet, at start-up or on a loading screen) is ignored as on a Switch: a load leaves the register as it was, a conditional compares against 0, a store writes nothing, and the cheat stays on and retries next pass; the first failure of a cheat logs one `[RED]` line, every one is counted, and the row shows ` (no effect: N accesses out of mapped memory)` while the cheat's latest pass had one (the note goes on the first pass without). A run of hex digits is cut into 8-digit words wherever whitespace falls, as dmnt reads it (`0400000000123456` is two words). A line that mixes code words with a token that is not one, or holds hex digits that are not whole words (`0400000`, `dead beef`), turns its cheat off (`malformed line N`): a silently dropped word could be a begin or an end whose absence leaves a body running every frame. A cheat that names the heap before the game's first `SetHeapSize` waits (logged once): it runs as soon as the game opens its heap. Writes into main's code pages go through a writable alias of the whole image (`mach_vm_remap`, same physical pages) mapped when a cheat file is picked: the game's own mapping never changes protection, so a running core cannot fetch a page mid-toggle (RWX is denied on Apple Silicon, and toggling the original page race-faults fetches, found on FFCC), and a run without a cheat file never maps one. If the alias fails to map the writes fall back to the per-page mprotect toggle with a `[RED]`, and every code-page write is passed through `sys_icache_invalidate`.
++
++Switches:
++
++- `DM_CHEATS=<folder>`: cheats folder. Default `<DM_ROOT>/cheats` (the game's work folder). A flat folder and the Atmosphère tree both work.
++- `DM_CHEATS_ANY_BUILD=1`: with no file of this build, load the folder's single `.txt` of another build with a `[RED]` warning that addresses may be wrong.
++- `DM_CHEATS_ON=<name>,…`: cheats turned on by name at launch (case-insensitive; the `<build ID>.enabled` states still apply).
++- `DM_CHEATS_DEBUG=1`: log every write the cheats make (cheat name, bytes, value, guest address), and with no file of this build the other-build `.txt` list.
++- `DM_CHEATS_WINDOW=1`: open the Cheats panel at launch.
++
++Implemented opcodes, all with the reference's word order and block-skipping (`dmnt_cheat_vm.cpp`):
++- 0 store static, 1 (the six memory comparisons), 2 end/else, 3 loop, 4/5 load register (a load narrower than 8 bytes keeps the register's upper bytes, as dmnt's does), 6 store static to a register address, 7 legacy arithmetic, 8 key-press conditional (a 28-bit mask of keys held on any controller: button bits 0–15, stick directions 16–23; the Joy-Cons' SL / SR on 24–27 are never held here, no input source reports them), 9 register arithmetic (add, sub, mul, shl, shr, and, or, not, xor, move, and float add / sub / mul / div at width 4 or 8, with a register or an immediate operand; the result truncated to the width, an unknown math type storing 0, a shift count taken modulo 64 as the Switch's own core does where dmnt's C++ leaves it undefined);
++- A, store register, with its six offset types and the increment;
++- C0, register conditional, against memory, a static value or another register;
++- C1 / C2, save and restore of registers (one by index, or by a 16-bit mask; save, restore, clear the saved value, clear the register): the 16 saved values reset once per pass like the registers and are shared by the cheats of the pass the same way;
++- C3, static registers: a cheat reads 0x00–0x7F and writes 0x80–0xFF; they persist across passes and are cleared when a file is loaded. On a Switch an overlay tool fills the readable ones; nothing does here yet, so a cheat reads 0;
++- C4, extended key-press conditional (a 64-bit mask; bits above 23 are never held here): with auto-repeat as 8, without it met only on the pass where the mask became fully held, against one previous-keys value shared by every C4 of the pass and set at the end of each pass that ran a VM cheat (a pass of only never-decrease cheats leaves it), as dmnt's static is (a dry run never changes it).
++
++The others (pause/resume, the debug log) mark the whole cheat `(unsupported opcode N)`, shown disabled in the menu and never run; so does an instruction whose last words are missing (`truncated`), where dmnt would run the whole words and end the pass. An else at depth 0 turns its cheat off (dmnt aborts there); an end at depth 0 is a no-op; a loop that never ends (a counter of 0) is stopped by a step cap and turns its cheat off, where dmnt's VM thread stays blocked. The memory-type nybble selects dmnt's regions from the host's own layout: 0 main NSO, 1 heap (a cheat that names it before the game's first `SetHeapSize` waits, logged once), 2 alias (virtual address memory), 3 aslr (the whole guest block), 4 absolute, 5–F main. What an access reaches is the kernel's rule as on a Switch, restricted to the game's own memory: a read any page of the guest block or of a module (a stack, the alias region, another NSO or NRO), a write main (through its alias), the opened heap, another module's data and bss, or any other mapped guest page, never another module's code or read-only data nor the host's key page. Pages the game maps and unmaps while a pass runs (stacks, the alias region) are copied through the kernel (`vm_read_overwrite`, `vm_write`), which fail instead of faulting on a page gone in between; the heap goes through `hle_svc.c`'s map lock as before. The state files (`<build ID>.enabled`, the safe-mode flag) are written by a serial dispatch queue, never on the presenting thread, in the order they were asked.
++
++On top of the format (`hle_cheats.c`; the `dm_cheat*` calls of `dm.h` give them to a front end, the Mac panel above):
++- **Labels and sections.** An entry without code words is a label, not a broken cheat: a credits line, or EdiZon's `[--SectionStart:Name--]` / `[--SectionEnd:Name--]`, whose entries in between carry that section. A header glued to the previous code word (`00000008[Next]`, found in a cheat-site file) still starts its own entry. Code words on the header's own line belong to the entry, as in dmnt. An entry whose lines were all dropped as prose is broken (`no code words`), not a label.
++- **On / off pairs.** "X - on" / "X - off" entries (also "X on", "X (off)", …, or a pair the meta file names) are one switch. Turning the on half on turns the off half off. Turning it off runs the off half, the restore, for one pass. A saved state is kept as it is.
++- **Duplicate names.** `<build ID>.enabled` saves the second entry of a name as `Name #2`, and so on. A plain name, as older files have it, turns on the next entry of that name that is still off. One-pass cheats ("set", a pending restore) are never saved as on.
++- **The meta file.** `<build ID>.meta.tsv` beside the file ([Cheats that survive game updates](#cheats-that-survive-game-updates)) adds per entry:
++ - its section, note and type, and its on / off pair;
++ - a typed value the panel may set ("ask", within its bounds, written into the program words the meta file names and kept in `<build ID>.values`);
++ - "set" cheats that run one pass and turn themselves off;
++ - never-decrease: a host action on a typed address that puts back the highest value seen since it was turned on (signed and float types compare as such). Atmosphère's VM keeps no state of a cheat between passes, so the `.txt` holds an empty entry that other engines show as a label.
++
++ The meta file also gives the display versions and lists the cheats the compiler left out, with their reasons.
++- **Toggles of a new build.** A compiled file (one with a meta file) of a build without `<build ID>.enabled` takes its toggles, by name, from the newest other build's `<build ID>.enabled` whose meta file names the same source.
++- **Dry run.** `dm_cheat_preview` lists what a cheat would write right now (`main+0x5607AAE (2 bytes): 37 -> 999`), or why nothing (a condition not met, a patch whose code is not the original any more, an access that fails). It replays the cheats a pass runs before it, so its registers are a real pass's; it writes nothing and changes no state.
++- **Master switch.** A `.cheats-off-<title ID>` file in the folder stops every cheat of that game, masters included, without touching the toggles.
++- **Safe mode** (Mac only: an iOS app usually ends killed). While some cheat runs, the folder holds `.cheats-running-<title ID>`; a clean exit (`exit`, or `dm_host_exit` before its `_exit`) removes it. A launch that finds it starts with every cheat off, masters too, with a `[RED]` line. The saved toggles are kept, and come back when the player restores them or turns a cheat on.
++- **Load report.** `dm_cheats_report` gives the counts, duplicate names, ignored or split lines, carried-over toggles, safe mode, the master switch, left-out cheats, and Atmosphère's limits (0x80 cheats, 0x100 words per cheat, 0x400 enabled words: a Switch refuses past them, this host does not).
++
++`dm/host/tests/t_cheats.c` covers the opcodes and this layer on a synthetic image.
++
++### Cheats that survive game updates
++
++`scripts/cheat_anchor.py` carries cheats from one build of a game to another. An Atmosphère file names fixed offsets of one build. The script first converts such a file into a version-independent source, `<game>.cheats.toml`, where each address is described by the game's own code. Then it compiles that source into the plain `<build ID>.txt` of any build. It needs only the build's `ExeFS/main`, which the NSP script extracts to `<title ID>_build/extract/v<version>/ExeFS/`. The compiled file is ordinary Atmosphère text: this host, a Switch, Ryujinx and yuzu forks all run it.
++
++```
++python3 scripts/cheat_anchor.py import E1D8B399B787AE41.txt --nso <build folder>/extract/v196608/ExeFS/main -o FFCC.cheats.toml
++python3 scripts/cheat_anchor.py compile FFCC.cheats.toml --nso <another build's ExeFS/main> -o <cheats folder>
++python3 scripts/cheat_anchor.py check FFCC.cheats.toml --nso <ExeFS/main> # the report only
++```
++
++- **Anchors** (written by `import`, kept at the end of the source):
++ - *data*: the nearest address at or below the target that the code references, plus a field offset. The nearest keeps the offset from crossing into an unrelated variable. The anchor stores up to four adrp + add / ldr / str pairs that compute it, in functions identified as below. With `deref = true` the pairs compute `.data` slots, and the anchor is the target of their relative relocations (RELA or RELR; FFCC's stats live in the object behind such a slot). At least two references must agree on the address (one when there is only one) and none may disagree. An anchor with a single reference is reported as weak, and so is one whose agreeing references were found only among identical copies by order.
++ - The anchor lies in the target's own segment (`.rodata`, `.data` or `.bss`, from the NSO header). An object never spans two segments, and an update moves them apart: a `.rodata` base for a `.data` target would land wrong once `.rodata` grows. `compile` also refuses an anchor whose field offset crosses into another segment.
++ - *code*: the words one cheat writes in one contiguous run (they move together), with their original words.
++ - *cave*: the zero padding between the end of the text and the read-only data, kept at the same distance before the read-only data. ASM cheats put their own code there.
++- **Finding a function:**
++ 1. a unique function with the same length and fingerprint (its body and its direct callees): the test of the rewriter's [function-matched cuts](reference/rewriter.md#function-matched-cuts-for-unregistered-builds) (`dm/tools/nso_match.py`);
++ 2. this tool's first fallback: a unique function with the same body digest alone (a callee changed);
++ 3. its second fallback: a window of 9 to 33 relocation-masked instructions around the site that occurs once in the whole text.
++
++ The first way that finds a candidate decides. No approximate similarity is used. A code site's original words must match at the new place, raw or, when only relocation bits moved, masked. A relocated word may be overwritten only by:
++ - its restore, which writes this build's own word;
++ - a branch token;
++ - a word with no address bits: NOP and other hints, MOVZ / MOVN / MOVK, register-only data processing, RET, FMOV register / immediate (`carries_address_bits`). Any other word would keep the old build's address bits, so it is refused.
++
++ The same rule holds for patches and for stores inside `code` programs, gated or not. Some more rules apply to every write into the code:
++ - Each write is checked by the whole word it leaves, 1- and 2-byte writes included.
++ - A new word that takes the page of an adrp up to 8 instructions before it (an add / ldr / str on the adrp's register) is bound to its build. Its low page bits hold only there, because the data can move inside its page while the code does not.
++ - Only opcode 0 literals carry values into the code. A register store (opcode A) into the code, or a store offset by a register the cheat sets (r0 included: the VM always adds it), stays bound to its build.
++ - An opcode 1 compare with a moved word's authored original compares with this build's word, so an "if still original" gate still opens.
++
++ Identical copies of a function are taken in address order. The copy is confirmed when the window finds the same one, refused when the window points to another, and otherwise reported as weak (`by order: weak`). Data references are checked by decoding the adrp pair at the found place.
++- **Cheats** in the source, in file order:
++ - `target` + `type` (u8…u64, s8…s64, f32, f64) + `action` + `value`, where the action is one of:
++ - `freeze`: written on every pass;
++ - `set`: the meta file marks it to be applied once;
++ - `min` / `max`: an opcode 1 comparison, which is unsigned, so only unsigned types;
++ - `never-decrease`: nxnative's host only. It puts back the highest value seen (static targets; the `.txt` gets an empty entry, the meta file the type and the `address`).
++
++ `value = "ask"` with `min`, `max` and `default` marks the value for the panel to ask for. A target can be a pointer chain, `[anchor+0x8]+0x38` (freeze and set only). The chain uses register 15 and zeroes it afterwards, because dmnt runs all enabled cheats as one program. `import` turns a single store into data into this form.
++ - `patch`: stores into the code and the cave.
++ - Each word is guarded with "if it still holds this build's original" (`--plain` drops the guards, for build-time baking). The optional off entry puts the originals back.
++ - A B / BL to outside the run it is written in is a token (`bl:cave+0x10`), re-encoded per build.
++ - A B.cond / CBZ / CBNZ / TBZ / TBNZ (the "flip b.ne to b.eq" cheat) whose target lies in the site's own function stays as written. `compile` writes it only when that function was found by fingerprint or body digest, which implies the same layout; a window match is refused. Any other PC-relative word aimed outside the cheat's own words is refused.
++ - The NSP script puts the rewriter's output of the build at `<title ID>_build/patched_v<version>/main.patched.bin`. When it is there, a word the rewriter changed is reported: the guard leaves such a word alone. A patch that changes other words as well is skipped whole, because the guards would apply a partial hook (`--plain` writes all of them).
++ - `import` merges an "X - on" / "X - off" pair whose off entry restores exactly the on entry's code sites. Both names, their order and their master flags stay (`master`, `off_master`), so saved toggles stay valid.
++ - `code`: any other program, kept word for word with `{anchor+offset}` tokens in place of its main-relative addresses.
++ - `label`: an empty entry (a credits line). `section` puts EdiZon's `[--SectionStart:Name--]` / `[--SectionEnd:Name--]` entries around a run of cheats.
++ - Addresses that cannot be anchored, such as heap or alias addresses or a store into the code indexed by a register, keep their words. They come with `builds = [...]` and compile only for those builds. A program the decoder cannot read is kept the same way and written word for word on those builds.
++ - Words glued together (`0400000000123456`) are split into 8-digit words, as Atmosphère reads them. A line with no code word is prose (a credits or author line) and is ignored with a warning, as the host ignores it; a token of hex digits only counts as a cut code word. Any other token on a code line makes the cheat malformed: it keeps the token, is bound to its build, is listed with its line, and never compiles. Dropping the token instead could lose an end-of-block word and let an open conditional swallow the next cheats.
++- **Outputs:**
++ - `compile` writes `<build ID>.txt` and `<build ID>.meta.tsv`. The meta file has one row per entry: kind, section, type, action, value, ask bounds, the program words that hold the value, on/off pair, how each anchor was resolved, and the reason a cheat was skipped. Its header names the source and the builds' display versions.
++ - Only an unchanged `.txt` that this source compiled is rewritten. The meta file records the `.txt`'s SHA-256 and the source's name. A hand-made, edited or other source's `.txt` is kept: the output goes to `<build ID>.txt.new`, or with `--replace` the old file is kept as `.orig`.
++ - Skipped cheats are left out of the `.txt` with a `[RED]` line in the report. Weak resolutions are listed, and so is a cheat over Atmosphère's 0x100 words, which a Switch refuses (the guards make patches longer).
++ - Exit status: 0 everything resolved, 2 some cheats skipped (or, for `import`, kept bound to one build), 1 an error.
++ - `import` refuses a file named after another build unless `--assume-build`; its unanchored cheats then stay bound to the file's own build. A file named after the game's title ID names no build, so it is taken as written for the NSO's build. `import` also counts the writes into the code that put back the word already there (restore entries): evidence that the file belongs to the NSO's build.
++- **Not yet:** `min` / `max` and never-decrease through pointer chains, anchors by IL2CPP names. Validation on FFCC and 13 Sentinels: [Cheats carried across game updates](reference/rewriter.md#cheats-carried-across-game-updates).
++
+ ## Guest memory SVCs
+
+ `dm/host/hle_svc.c` serializes heap resizing, physical map/unmap, stack
+diff --git a/docs/env_switches.tsv b/docs/env_switches.tsv
+index 044f8e27..4c4a3a4a 100644
+--- a/docs/env_switches.tsv
++++ b/docs/env_switches.tsv
+@@ -12,6 +12,11 @@ DM_AUDIO_MUTE switch `=1` runs the real Core Audio output path (callback pacing,
+ DM_AUDREN_TRACE diagnostic When set, the CPU audio renderer logs every update with the number of frames rendered since the previous one
+ DM_BOOTPROF diagnostic When set, logs boot timing: the loader's breakdown (mapping, relocation, probes), Metal library loading, pipeline creation, texture uploads and the first present
+ DM_BUNDLE_ID switch Overrides the iOS app's bundle ID in `build_ipa.sh` (default `org.nxnative.<title ID in lowercase>`)
++DM_CHEATS path Folder of Atmosphère cheat files: `<folder>/<build ID>.txt` or an SD-card layout (`atmosphere/contents/<title ID>/cheats/`) under it (default `<DM_ROOT>/cheats`); the Mac menu lists and toggles them
++DM_CHEATS_ANY_BUILD switch `1` loads a cheat file written for another build of the game when it is the only one (its addresses may not fit: for `cheat_anchor.py` checks)
++DM_CHEATS_DEBUG diagnostic Logs every memory write a cheat makes and the cheat file context the menu's "another version" rows come from
++DM_CHEATS_ON switch Comma-separated cheat names turned on at launch, besides the saved per-build enabled states
++DM_CHEATS_WINDOW switch `1` opens the Mac Cheats panel beside the game from the start
+ DM_COPY_GAME_RESOURCES switch `NO` skips the Xcode build phase that copies the game's resources into the app (`stage_resources.sh`, on by default); `build_ipa.sh` sets it for its unsigned build, which packs them itself
+ DM_COPY_ROMFS switch `NO` keeps the game files out of the app, in the Xcode build phase (`stage_resources.sh`) and in the unsigned IPA of `build_ipa.sh` (on by default): `main.m` takes the validated `Documents/romfs.img` copied by `scripts/push_romfs.sh`, then a `Documents/romfs` folder; the build writes the image's identity as `romfs.id` into the app, and `main.m` uses only a matching image (`--romfs separate` of the NSP script sets this)
+ DM_CTL diagnostic `=<file>` (Mac): the host polls the file every 100 ms and runs each appended line: button presses, `shot`, `passdump`, `texdump`, `env KEY=VALUE`, `peek`, `memdump`, `drag` and more
+diff --git a/docs/frontends.md b/docs/frontends.md
+index a22b9414..06e45d37 100644
+--- a/docs/frontends.md
++++ b/docs/frontends.md
+@@ -72,6 +72,20 @@ Each app keeps the player's choices in its own preferences domain, its bundle ID
+ - **`DM_SAVED_CHOICES=0`** (in the environment or an `env.txt`) starts with the tested defaults and leaves the saved choices as they are. **`DM_LAUNCHER=0`** only skips the settings screen (the iPhone's, or a Mac app's window): the saved choices still apply.
+ - **A sandboxed front end** cannot write another app's preferences domain; this store is for front ends outside the App Sandbox, as NX2Apple is.
+
++## Cheats
++
++Cheats are files, not settings: the host (`dm/host/hle_cheats.c`) reads Atmosphère-format cheat files for the running game's build and keeps the player's toggles beside them. A front end that wants to install cheats or pick which ones run, before the game starts, writes the same files; the Mac game window's Cheats menu and panel are one view of them. The engine itself and the format of a cheat line are described in [the cheats reference](reference/cheats.md); this section is the contract for the files.
++
++- **The folder.** `DM_CHEATS=<folder>`, else `<DM_ROOT>/cheats`, which for a Mac app is `~/Library/Application Support/nxnative/<title ID>/cheats` (the launcher sets `DM_ROOT` to that folder; once a `dataFolder` moves the app's files, the cheats folder moves with it, as everything under `DM_ROOT` does). Two layouts are read: flat, `<folder>/<build ID>.txt`, and a Switch SD card's tree under it, `<folder>/atmosphere/contents/<title ID>/cheats/<build ID>.txt` (or without `atmosphere/`). The build ID is the first 16 hex digits of the main NSO's build ID, upper case, as cheat sites name their files; the game note of a profile lists its builds. With no file for the running build nothing changes in the game, and the folder is never created by the host.
++- **The files beside `<build ID>.txt`**, all in the same folder, all plain text, written by the host and readable by anyone:
++ - `<build ID>.enabled`: the cheats that are on, one name per line, in the file's own spelling (`Max HP`); a duplicate name's later entries are `Name #2`, `Name #3`, …. Masters (`{Name}` entries) are always on and are not listed; labels and one-pass cheats never are. The host rewrites the file on every toggle (a temporary file renamed over it, so it is never half-written) and reads it when the file is loaded. A front end that installs a file and wants some cheats on from the first start writes this file before the start.
++ - `<build ID>.meta.tsv`: optional, written by `scripts/cheat_anchor.py` beside a file it compiled: one row per entry (columns by header name: `name`, `kind`, `section`, `type`, `action`, `ask`, `value_words`, `once`, `pair`, `resolved`, `note`, `address`), which gives the panel sections, notes, on / off pairs, typed values and run-once cheats. A hand-made or downloaded file has none, and needs none.
++ - `<build ID>.values`: the typed values of `ask` cheats, `name<TAB>value` per line, written when the player sets one.
++ - `.cheats-off-<title ID>`: the master switch. While this file exists no cheat of the game runs, toggles kept. `.cheats-running-<title ID>` is the host's own safe-mode flag (Mac only): it exists while cheats run and goes with a clean exit; found at the next start it means the last run crashed with cheats on, and the game starts with every cheat off until the player restores them. A front end leaves it alone.
++- **What a front end may write while the game runs.** Nothing the host reads back on its own: the host reads `<build ID>.enabled` and the cheat file when it loads them, at the start and on the player's "Reload cheats" (⌘R in the Mac window, which re-reads the same file and the toggles with it), and never watches the folder. So a front end writes before the start, or tells the player to reload. The panel's refresh while it is open reads the engine's state, not the files. For one start, `DM_CHEATS_ON=<name>,<name>,…` in the launch environment turns the named cheats on without touching `.enabled` (case-insensitive, by name); `DM_CHEATS_ANY_BUILD=1` loads the folder's single file of another build when the running build has none (its addresses may not fit: for checking a carried file), and `DM_CHEATS_DEBUG=1` logs every write. The three are diagnostics, not settings: they are not in `launcher.json`.
++- **The iPhone.** The engine is compiled into the iOS host too (without safe mode), with the same folder rule, but the iOS app sets neither `DM_CHEATS` nor `DM_ROOT`, so cheats are off there unless `Documents/env.txt` names a folder with `DM_CHEATS`. Giving the iOS app a default, `Documents/cheats`, is the natural next step once a front end wants to manage cheats on a device; it is not in this change.
++- **Carrying a file to another build.** `scripts/cheat_anchor.py` imports a cheat file into a version-independent source and compiles it for any build of the game ([the rewriter reference](reference/rewriter.md#cheats-carried-across-game-updates)). A front end need not know about it: the compiled `<build ID>.txt` is an ordinary cheat file, and its `.meta.tsv` makes the panel richer.
++
+ ## What a front end cannot see yet
+
+ While a game runs, the host says what happens only in its log, as text meant for people: a controller that connects or goes away, the preparing of shaders before the first frame, a red line. A front end that reads the log to show these would break when a line's wording changes. Events a program can read (one JSON object per line, as the NSP script's) would be the next piece of this interface; until then, treat log lines as diagnostics, not as an interface.
+diff --git a/docs/reference/README.md b/docs/reference/README.md
+index e6ad3757..53dd29d1 100644
+--- a/docs/reference/README.md
++++ b/docs/reference/README.md
+@@ -5,7 +5,7 @@ How the host meets each part of a Switch game, and every failure met so far, one
+ | File | Covers |
+ |---|---|
+ | [packing.md](packing.md) | NSP script, compressed inputs and build artifacts |
+-| [rewriter.md](rewriter.md) | The NSO rewriter `patch_nso.py`: jump tables, exclusive windows, patch area reach, cuts and observation gates, functions without unwind entries, stack and system registers, relocations |
++| [rewriter.md](rewriter.md) | The NSO rewriter `patch_nso.py`: jump tables, exclusive windows, patch area reach, cuts and observation gates (and cheats carried across builds with the same matcher), functions without unwind entries, stack and system registers, relocations |
+ | [memory.md](memory.md) | Guest layout, heap and application pool, virtual address memory and the alias region (the SDK's node area), engine allocators, mapping SVCs, running out of memory |
+ | [threads.md](threads.md) | Thread creation and cores, address arbitration, yields and spin waits, events |
+ | [services.md](services.md) | SDK calls and system services: sm connections, names that changed between SDKs, file system and saves, add-on content, input, keyboard and applets, display and operation mode, accounts and network, settings and fonts, C library and time, modules |
+@@ -15,6 +15,7 @@ How the host meets each part of a Switch game, and every failure met so far, one
+ | [nvn-objects.md](nvn-objects.md) | NVN object sizes, memory pools, command memory, queues and syncs, CPU-written textures, NVN entry points |
+ | [rendering.md](rendering.md) | The replay on Metal: textures, passes and clears, blend / depth / stencil, vertex input, uniforms and ordering, conditional rendering; the Vulkan and OpenGL layers |
+ | [shaders.md](shaders.md) | Shader containers by engine, control sections and code, translation, bindings and handles, shaders compiled at run time, pipelines and caches |
++| [cheats.md](cheats.md) | How cheats work on a Switch with Atmosphère (dmnt, the file, the VM, its behaviour on failure) and where this host differs |
+ | [game-state.md](game-state.md) | Saves, scripted state, and game behaviour that looks like a host bug but is not |
+
+ A new general finding goes into the file and section it belongs to, in the same form, with a line in the symptom index; a fact about one game goes into that game's note.
+diff --git a/docs/reference/cheats.md b/docs/reference/cheats.md
+new file mode 100644
+index 00000000..bc3f531b
+--- /dev/null
++++ b/docs/reference/cheats.md
+@@ -0,0 +1,251 @@
++# Cheats on a Switch
++
++How cheat codes work on a Switch running Atmosphère, read from Atmosphère's own source and documentation (tag 1.12.1, commit `6b0c077b`; [Sources](#sources)), so that the host's engine (`dm/host/hle_cheats.c`, described in [docs/development.md, Cheats](../development.md#cheats)) can be held to it. In the quotes below, `vm.cpp` is `stratosphere/dmnt/source/cheat/impl/dmnt_cheat_vm.cpp` and `api.cpp` is `dmnt_cheat_api.cpp` beside it. `main+X` and `heap+X` mean memory type 0 or 1 with offset X.
++
++## How cheats work on a Switch with Atmosphère
++
++### The pieces
++
++- **dmnt** (Atmosphère's debug monitor system module) holds the cheat manager. It hooks the creation of every application process (`pm::dmnt::HookToCreateApplicationProcess`), so it looks at the game before its first instruction runs, and attaches as a kernel debugger (`svc::DebugActiveProcess`) when the game has a cheat file. It then starts the process.
++- **The cheat file**, text on the SD card, parsed once at attach into up to 0x80 entries.
++- **The VM thread** runs every enabled cheat as one program, then writes the frozen addresses, then sleeps 1/12 s, forever.
++- **Overlays and homebrew** (EdiZon SE, Breeze, Tesla overlays) talk to dmnt through the `dmnt:cht` service: list, toggle, add and remove cheats, read and write the game's memory, read and write static registers, freeze addresses. dmnt itself has no on-screen menu.
++
++### When dmnt attaches
++
++At each application launch (`AttachToApplicationProcess(true)`, `api.cpp`):
++
++1. The loader's override status must say cheats are enabled. The key is `cheat_enable_key`, default `!L`: cheats load **unless L is held** at launch (`g_default_cheat_enable_key = { HidNpadButton_L, override_by_default = true }`; `IsOverrideMatch` is `override_by_default ^ (keys_held & key) != 0`). It is set globally in `/atmosphere/config/override_config.ini` (`[default_config]`) and per title in `/atmosphere/contents/<program id>/config.ini` (`[override_config]`). Never for the Homebrew Loader.
++2. The process must have two modules (rtld and main); main is the second.
++3. `/atmosphere/contents/<program id>/cheats/<build id>.txt` must open and parse, where `<program id>` is 16 hex digits and `<build id>` is the first 8 bytes of main's build ID as 16 hex digits (both printed lowercase, `%016lx` and `%02x`). The file must be under 64 KiB (`file_size >= sizeof(g_text_file_buffer)` fails).
++4. `toggles.txt` in the same folder, if present, must parse.
++
++Any failure in 3 or 4 means dmnt does not attach: **no cheat of that file runs**, not even the valid ones. Homebrew can still force an attach (`ForceOpenCheatProcess`) or detach (`ForceCloseCheatProcess`).
++
++There is **no in-game button combination** that toggles cheats in dmnt. The only buttons dmnt reads are the launch-time key above and the key-press opcodes 8 and C4 inside cheats. Toggling at run time is the overlays' `ToggleCheat`.
++
++### The file
++
++`ParseCheats` (`api.cpp`) reads the text left to right:
++
++- Whitespace is skipped.
++- `[Name]` opens a toggleable cheat in the first free entry (1…0x7F; free means no opcodes). An entry with no opcodes stays free, so the next `[Name]` reuses it: empty entries (labels, EdiZon's section markers) vanish.
++- `{Name}` opens the **master** cheat, entry 0. A second `{…}` with opcodes already in entry 0 fails the file.
++- A hex digit starts one opcode word: exactly 8 hex digits (`strtoul` base 16). A longer run of hex digits is split into 8-digit words. A word before any `[` or `{` fails the file.
++- **Anything else fails the file**: there is no comment syntax, and `0x`, prose lines or a stray `]` all fail.
++- Names are copied up to 0x40 bytes (`readable_name[0x40]`; the terminator is then written one past the copy, so names should stay under 64 characters).
++- More than 0x100 words in one cheat, or no free entry left (127 toggleable cheats + 1 master), fails the file.
++
++Then the master is enabled and every other parsed entry is set to `dmnt_cheats_enabled_by_default` (system setting `atmosphere!dmnt_cheats_enabled_by_default`, `u8`, default 1: **all cheats on**). `toggles.txt` then overrides by name: `[Name]` followed by one token, `1`/`true`/`on` or `0`/`false`/`off` (case-insensitive); unknown names and unknown tokens are ignored, a token of 8 characters or more fails the file. The master cannot be toggled (`ResultCheatCannotDisable`).
++
++### What persists
++
++- Toggles persist **per program ID** (not per build) in `toggles.txt`, written at detach (`SaveCheatToggles`: `[Name]` then `true`/`false` per non-master cheat) only if `toggles.txt` existed and parsed at attach, or the setting `atmosphere!dmnt_always_save_cheat_toggles` (default 0) is set.
++- Cheat entries, frozen addresses and static registers are cleared at detach (`CloseActiveCheatProcess` → `ResetAllCheatEntries` → `ResetStaticRegisters`). Nothing else carries over between launches.
++
++### Memory regions
++
++At attach dmnt records the process's regions (`svc::GetInfo`) in its metadata; a memory-type nybble selects the base (`GetCheatProcessAddress`, `vm.cpp`):
++
++| M | Name | Base |
++|---|---|---|
++| 0 | Main NSO | main module's load address (the loader's module info) |
++| 1 | Heap | `InfoType_HeapRegionAddress`: the heap region's start. `svcSetHeapSize` maps the heap from that start upward (`KPageTableBase::SetHeapSize`), so `heap+0` is the first heap byte |
++| 2 | Alias | `InfoType_AliasRegionAddress` |
++| 3 | Aslr | `InfoType_AslrRegionAddress` |
++| 4 | Non-relative | 0: the offset is an absolute address |
++| 5–F | | main (the `default:` case shares main's) |
++
++The bases are fixed for the life of the attach. Games with virtual address memory map their memory with `svcMapPhysicalMemory`, which the kernel accepts only inside the alias region (`R_UNLESS(page_table.IsInAliasRegion(address, size), ...)`, `kern_svc_physical_memory.cpp`), so their objects are found through type 2 or through pointers, not through `heap+` ([memory.md, the alias region](memory.md#virtual-address-memory-and-the-alias-region)). There is no stack selector: a stack is reached by an absolute address or a register.
++
++What a read or write can reach is the kernel's rule, not the region (`KPageTableBase::ReadDebugMemory` / `WriteDebugMemory`, `CanReadWriteDebugMemory`): a **read** succeeds on any mapped, user-readable page anywhere in the process; a **write** on any mapped user-read-write page, or on debuggable memory that is user-readable, which includes main's code and read-only data (so code patches work without changing protection). Unmapped pages fail. A region's size is never checked by the VM.
++
++### Cadence
++
++`VirtualMachineThread` (`api.cpp`), each iteration under the cheat lock: reload the program if a cheat was toggled, added or removed; execute it if it has words; write each frozen address; then
++
++```cpp
++constexpr s64 TimesPerSecond = 12;
++constexpr s64 DelayNanoSeconds = TimeSpan::FromSeconds(1).GetNanoSeconds() / TimesPerSecond;
++os::SleepThread(Delay);
++```
++
++So **about 12 passes per second**, not tied to the game's frames (a pass plus 83 ms of sleep). The game is not stopped during a pass: dmnt continues every debug event (`ContinueFlag_ContinueAll`), and the VM reads and writes while the game's threads run, except between opcodes FF0 and FF1.
++
++### Frozen addresses
++
++Beside the VM, `dmnt:cht` keeps up to 0x80 frozen addresses (`EnableFrozenAddress(address, width)`): dmnt reads the current value once (the call fails if that read fails) and writes it back after every VM pass with the raw write SVC. A VM write that covers a frozen address updates the frozen value (`WriteCheatProcessMemoryUnsafe`), but only when the write succeeded. This is what overlays' "freeze" uses; it is not part of the cheat file.
++
++## The VM, as the reference implements it
++
++State (`dmnt_cheat_vm.hpp`): 16 registers of 64 bits, 16 saved values, 16 loop tops, a condition depth, a program of at most `MaximumProgramOpcodeCount = 0x400` words, and 0x100 static registers.
++
++### One program per pass
++
++`LoadProgram` concatenates the words of every enabled entry in entry order: the master (entry 0) first, then the toggleable cheats in file order.
++
++```cpp
++for (size_t i = 0; i < num_cheats; i++) {
++ if (cheats[i].enabled) {
++ if (cheats[i].definition.num_opcodes + m_num_opcodes > MaximumProgramOpcodeCount) {
++ m_num_opcodes = 0;
++ return false;
++ }
++ ...
++```
++
++`Execute` reads the buttons once, then resets the state **once per pass over that whole program**:
++
++```cpp
++R_DISCARD(hid::GetKeysHeld(std::addressof(kHeld)));
++...
++this->ResetState(); /* registers, saved values, loop tops = 0; ip = 0; depth = 0; decode_success = true */
++while (this->DecodeNextOpcode(std::addressof(cur_opcode))) { ... }
++s_keyold = kHeld;
++```
++
++So registers, saved values, loop tops and the condition depth carry from one cheat into the next within a pass, and a block left open by one cheat contains the following cheats. Static registers are not reset by a pass.
++
++### Decoding
++
++The opcode is the top nybble; C, D, E, F take the next nybble (`0xC0`…), and `0xF0`… takes a third (`0xFF0`…). Valid opcodes: 0–A, C0–C4, FF0, FF1, FFF. Anything else (B, C5–CF, D0–EF, F00–FEF, FF2–FFE) fails decoding. A width T outside 1, 2, 4, 8 is decoded but makes the access or comparison a no-op (`GetVmInt` returns 0, the read or write `switch` has no case for it). Immediate offsets are 40 bits in opcodes 0, 1 and 5 (`AA AAAAAAAA`) and 36 bits in A, C0 and FFF (`a aaaaaaaa`).
++
++### 0: store static
++
++`0TMR00AA AAAAAAAA V…`: writes the low T bytes of V (one word, two for T = 8) to `base(M) + A + reg[R]`. **Register R is always added**; there is no enable flag (with R = 0, register 0 is added).
++
++### 1: memory conditional
++
++`1TMCXrAA AAAAAAAA V…`: reads T bytes at `base(M) + A`, plus `reg[r]` when X ≠ 0, into a zeroed value and compares it, unsigned, with V: C = 1 `>`, 2 `>=`, 3 `<`, 4 `<=`, 5 `==`, 6 `!=` (any other C is never met). Not met: skip to the matching else or end.
++
++### 2: end / else
++
++`20000000` ends a block: depth − 1, and **at depth 0 a no-op** ("We will assume, graciously, that mismatched conditional block ends are a nop"). `21000000` (else), reached while executing, skips to the matching end. Any other X is an end.
++
++### 3: loop
++
++`300R0000 N`: `reg[R] = N`, loop top = the next word. `310R0000`: `reg[R]--`; if it is not 0, jump to the loop top. The body runs N times for N ≥ 1, at least once in every case (the test is at the end). Loops are tracked per register, so loops nest only with different registers.
++
++### 4, 5: load register
++
++`400R0000 VVVVVVVV VVVVVVVV`: `reg[R] = V` (64 bits).
++
++`5TMRI0AA AAAAAAAA` reads T bytes **directly into `reg[R]`'s storage**:
++
++| I | Address |
++|---|---|
++| 1 | `reg[R] + A` (M ignored) |
++| 2 | `reg[S] + A`, S in the nybble after I |
++| 3 | `base(M) + reg[S] + A` |
++| 0 or 4–F | `base(M) + A` |
++
++The read copies only T bytes into the 64-bit register (`ReadCheatProcessMemoryUnsafe(src_address, std::addressof(m_registers[...]), bit_width)`): on the Switch's little-endian core **a T < 8 load replaces the low T bytes and keeps the register's upper bytes**. It does not zero-extend.
++
++### 6: store static to a register address
++
++`6T0RIor0 VVVVVVVV VVVVVVVV`: writes the low T bytes of the 64-bit V to `reg[R]` (+ `reg[r]` when o ≠ 0), an absolute address with no region base; then `reg[R] += T` when I ≠ 0.
++
++### 7 and 9: arithmetic
++
++- **7** (legacy) `7T0RC000 VVVVVVVV`: `reg[R] op= V`, V a 32-bit value zero-extended, C = 0 add, 1 sub, 2 mul, 3 shl, 4 shr. Other C: no operation. Then `reg[R]` is truncated to T bytes in place (T outside 1/2/4/8: not truncated).
++- **9** `9TCRS0s0` (register operand) or `9TCRS100 V…` (immediate of T bytes, two words for T = 8): `reg[R] = reg[S] op operand`, C = 0 add, 1 sub, 2 mul, 3 shl, 4 shr, 5 and, 6 or, 7 not (`~reg[S]`), 8 xor, 9 move, 10–13 float add / sub / mul / div (T = 4 single, T = 8 double; any other T gives 0). The result is truncated to T bytes. An unknown C stores 0. Shifts are C++ shifts of a 64-bit value; amounts of 64 or more are undefined in C++, so the source does not define them.
++
++### 8 and C4: key-press conditionals
++
++`kHeld` is `hid::GetKeysHeld`: the **held** buttons (not newly pressed, whatever the format doc's "hidKeysDown()" says), OR-ed over handheld and players 1–8, from the system-extended npad state, read once at the start of the pass (0 if the read fails).
++
++- **8** `8kkkkkkk`: a 28-bit mask; met when every bit of the mask is held (`(mask & kHeld) == mask`). Other buttons may be held too; a mask of 0 is always met. Bits 24–27 are SL / SR of the Joy-Cons.
++- **C4** `C4r00000 kkkkkkkk kkkkkkkk`: a 64-bit mask. r ≠ 0 (auto-repeat): as 8. r = 0: met only on the pass where the mask is fully held and **was not fully held on the previous pass** (`s_keyold`, one static for every C4 in the program, updated at the end of each executed pass).
++
++### A: store register
++
++`ATSRIOxa (aaaaaaaa)`: writes the low T bytes of `reg[S]`. Address by O: 0 `reg[R]`; 1 `reg[R] + reg[x]`; 2 `reg[R] + a`; 3 `base(x) + reg[R]`; 4 `base(x) + a` (R ignored); 5 `base(x) + reg[R] + a`; any other O is treated as 0. Then `reg[R] += T` when I ≠ 0 (for every O).
++
++### C0: register conditional
++
++`C0TcSX…`: compares the low T bytes of `reg[S]` with an operand, unsigned, with the conditions of opcode 1. X: 0 memory at `base(M) + a`; 1 memory at `base(M) + reg[r]` (no immediate); 2 memory at `reg[R] + a`; 3 memory at `reg[R] + reg[r]`; 4 a static value of T bytes; 5 the low T bytes of `reg[X]`. Memory operands are read into a zeroed value.
++
++### C1, C2: save and restore
++
++`C10D0Sx0`: x = 0 `reg[D] = saved[S]`, 1 `saved[D] = reg[S]`, 2 `saved[D] = 0`, 3 `reg[D] = 0` (other x: restore). `C2x0MMMM`: the same per bit of a 16-bit mask, `reg[i]` ↔ `saved[i]`. Saved values are zeroed every pass.
++
++### C3: static registers
++
++`C3000XXx`: XX < 0x80 loads `reg[x] = static[XX]`; XX ≥ 0x80 stores `static[XX] = reg[x]`. A cheat can only read 0x00–0x7F (homebrew writes them through `WriteStaticRegister`) and only write 0x80–0xFF (homebrew reads them). They keep their values across passes and toggles, until detach or a homebrew `ResetStaticRegisters`.
++
++### FF0, FF1, FFF
++
++- **FF0** breaks the game process (`svc::BreakDebugProcess`); **FF1** continues it. The break lasts across passes until an FF1 runs.
++- **FFF** `FFFTIX…` appends one line, `%016lx\n`, to `/atmosphere/cheat_vm_logs/<I as %08x>.log` on every pass it runs. X: 0 memory at `base(M) + a`, 1 `base(M) + reg[r]`, 2 `reg[R] + a`, 3 `reg[R] + reg[r]`, 4 the low T bytes of `reg[X]`.
++
++### Behaviour on failure
++
++| Case | What the reference does |
++|---|---|
++| A read fails (unmapped address, wrong permission) | The result is discarded (`R_DISCARD`). The destination keeps what it had: opcode 5 leaves the register unchanged (0 if nothing set it earlier in the pass); opcodes 1 and C0 compare against 0; FFF logs 0. **The cheat stays enabled and the pass goes on.** It is retried on the next pass. |
++| A read crosses a block boundary and only the second block fails | `KDebugBase::ReadMemory` copies block by block, so the first bytes may already be in the destination. Only an unaligned access can do this. |
++| A write fails | Discarded; nothing written, the frozen value is not updated, the cheat stays enabled, the pass goes on. |
++| `20000000` at depth 0 | No-op. |
++| `21000000` (else) at depth 0 | `SkipConditionalBlock` reaches `R_ABORT_UNLESS(ResultVirtualMachineInvalidConditionDepth())`: **dmnt aborts**. What the player then sees is not in the files read. |
++| A block whose end is missing | If the condition is not met, skipping runs to the end of the program: the rest of the pass, every later cheat included, is skipped. If met, the depth simply stays raised. |
++| An unknown opcode | Decoding fails and the failure is sticky for the pass (`m_decode_success &= valid`): **the pass stops there**. Earlier words (the master, earlier cheats) ran; that cheat's remaining words and every later enabled cheat do not, on every pass. Nothing is marked or disabled, and no opcode is validated at load. Inside a skipped block an unknown opcode stops the pass the same way. |
++| Running past the end | Reading a word past the program fails decoding: the pass ends. An instruction whose last words are missing is not executed. |
++| Loop with N = 0 | The body runs, the counter goes from 0 to 2^64 − 1: the loop practically never ends. |
++| `310R0000` without its start | Loop top is 0: if `reg[R] − 1 ≠ 0` it jumps to the first word of the whole program (the master's). |
++| A pass that never ends | There is no instruction budget. The VM thread keeps the cheat lock, so later passes, frozen addresses and every `dmnt:cht` call that takes the lock wait. |
++| Nesting | Condition depth is a `size_t`: no limit. One active loop per register. |
++| Program size | 0x100 words per cheat (more fails the file). 0x400 words for all enabled cheats together: past that `LoadProgram` returns false with an empty program, so **no cheat runs, the master included**, and the load is retried each pass until toggles bring it under. 0x80 entries. |
++
++## What this host does differently
++
++The host side is what [docs/development.md, Cheats](../development.md#cheats) states, each row checked against `hle_cheats.c` and `dm/host/tests/t_cheats.c` on 2026-10-26.
++
++| Point | Switch (Atmosphère 1.12.1) | Host (development.md) | | Consequence for a player |
++|---|---|---|---|---|
++| File name and place | `/atmosphere/contents/<program id>/cheats/<build id>.txt` | same name, in a flat folder or the Atmosphère tree | same | Files from cheat sites drop in unchanged. |
++| A file with prose, comments or a bad word | whole file rejected, nothing runs; a run of hex digits is cut into 8-digit words wherever whitespace falls | glued words are cut the same way; a line of prose (a token with a non-hex character, no words) is dropped, labels kept; a line mixing code and a non-code token, or holding hex digits that are not whole words (`0400000`, `dead beef`), turns only its cheat off (`malformed line N`) | different | A file that runs here can do nothing on a Switch; glued words run on both. |
++| Limits 0x80 / 0x100 / 0x400 | file rejected / nothing runs | reported, not enforced | different | Long cheat sets run here and not on a Switch. |
++| Enabled at load | master on; every cheat on (`dmnt_cheats_enabled_by_default`, default 1) | master on; others from `<build id>.enabled` and `DM_CHEATS_ON`; the default for a new file is not stated | different (as implied) | A new file starts with fewer cheats on than on a Switch. |
++| Launch gate | holding L at launch loads no cheats | `.cheats-off-<title ID>` and safe mode | different | No button skips cheats here. |
++| Toggles saved | `toggles.txt` per program ID, only if it exists or `dmnt_always_save_cheat_toggles` | `<build id>.enabled` per build, always | different | Toggle files do not carry between the two. |
++| One program per pass | all enabled cheats concatenated, master first; registers, saved values, depth and loops reset once per pass and shared between cheats; the keys read once per pass | masters first, then the enabled cheats in file order; registers and saved values reset once per pass and shared, the keys read once per pass; each cheat is its own program, so the condition depth and the loop tops (word indexes into the cheat's own program) start fresh for each, and a loop end without its start jumps to the first word of its own cheat | same, except open blocks and stray loop ends | A block left open by one cheat does not contain the later cheats here; a stray loop end never jumps into another cheat's words. |
++| Cadence | about 12 passes per second, game running | once per presented frame, ~60 Hz when not presenting | different | Per-pass effects (adding to a value) happen about 5 times as often; a C4 edge still fires once per press. |
++| A failed read | ignored; register unchanged, compare with 0; cheat stays on and retries | same; the first failure of a cheat logs one `[RED]` line, every one is counted into a note on its row (` (no effect: N accesses out of mapped memory)`, gone after a pass without one) | same | A pointer cheat enabled while its pointer is still null starts working once the pointer is set, as on a Switch. |
++| A failed write | ignored; cheat stays on | same, counted as above; only a write into the host's own key page inside main turns the cheat off | same | |
++| Reachable memory | any mapped user-readable page (read), user-writable or code / read-only data (write); all five memory types | a read: any page the guest block (stacks, the alias region, MapMemory'd pages) or a module (NSO, NRO) maps; a write: main (code included, through its alias), the opened heap, another module's data and bss, any other mapped guest page; never another module's code or read-only data, never the host's own memory | same for the game's memory | A write into another module's code, which the debug SVC allows, fails here (counted). |
++| Heap before `SetHeapSize` | heap base known at attach; accesses fail silently until mapped | the cheat waits until the heap opens | different | None visible. |
++| Memory types 2, 3, 4, 5–F | alias, ASLR, absolute, main | the same, from the host's layout (`region_base`: the alias region is checked against the block's partition, else refused with `[RED]`) | same | |
++| Else at depth 0 | dmnt aborts | that cheat is turned off for the session (`mismatched else`), the others run | lenient | A file that would crash dmnt runs here without that cheat. |
++| End at depth 0 | no-op | no-op | same | |
++| Unknown opcode | the pass stops at it; later cheats do not run; nothing marked | the cheat is marked unsupported and never runs; others run | different | One bad cheat does not stop the others here. |
++| Opcodes 9, C1, C2 | implemented: all math types, the float ones at T = 4 / 8; saved values zeroed per pass | implemented the same (`t_cheats.c` holds every math type and width, the shifts, save / restore across cheats and their reset) | same | |
++| Opcode 9 shift count ≥ 64 | undefined in C++; the Switch's core (LSLV / LSRV) takes it modulo 64 | taken modulo 64, as opcode 7's | same as the hardware | |
++| Opcode 9 unknown math type (14, 15) | stores 0 | stores 0 | same | |
++| Opcode C4 | 64-bit mask; `r = 0` met on the pass where the mask became held, against `s_keyold`, one static for every C4, set at the end of each executed pass | the same, against one value set at the end of each pass that ran a VM cheat (a pass of only never-decrease cheats leaves it); a dry run never changes it; bits above 23 are never held (as for 8) | same | A one-shot C4 cheat fires once per press here too. |
++| Opcodes FF0, FF1, FFF | implemented | cheat marked unsupported, never runs | different | Cheats that pause the game or log stay off here. |
++| Opcode 8 mask | 28 bits, held keys of every controller; bits 24–27 SL / SR | 28 bits, the keys held on any input source (`dm_cheats_keys`), read once per pass; bits 24–27 are never held, no input source reports SL / SR | same, but SL / SR | Cheats bound to SL / SR never trigger. |
++| Opcode 5 with T < 8 | upper register bytes kept | upper register bytes kept | same | |
++| Opcode 0 offset register | always added | always added | same | |
++| Running past the end, truncated words | pass ends, partial instruction not run | the cheat is marked `(truncated)` at load and never runs; its whole words do not run either | different | A cheat cut short does nothing here; on a Switch its first instructions run. |
++| Loop with N = 0, endless loop | effectively endless; VM thread blocked | a step cap (4,000,000 instructions in one pass) turns that cheat off with `[RED]`; the frame goes on | different | A file that would hang dmnt runs here without that cheat. |
++| Nesting | unlimited depth; one loop per register | unlimited depth; one loop per register | same | |
++| Static registers | persist across passes; cleared at detach; homebrew fills 0x00–0x7F | persist; cleared when a file loads; nothing fills them (cheats read 0) | same, no writer | Cheats driven by an overlay's static registers do nothing here. |
++| Frozen addresses | `dmnt:cht` list, written after each pass | no such list; `freeze` is compiled into cheats, plus host-only never-decrease | different | Overlay freezes have no equivalent; compiled freezes behave like cheats. |
++| Writes into main's code | allowed by the debug write SVC | through a writable alias of the image, with an icache flush | same | Code patches apply. |
++
++## Sources
++
++All read on 2026-10-26 at Atmosphère commit [`6b0c077b4c608a3a2ee712b8dc35fee87ceb62e8`](https://github.com/Atmosphere-NX/Atmosphere/tree/6b0c077b4c608a3a2ee712b8dc35fee87ceb62e8) (2026-10-15), identical to tag 1.12.1 and to `master` that day. Files under `https://raw.githubusercontent.com/Atmosphere-NX/Atmosphere/6b0c077b4c608a3a2ee712b8dc35fee87ceb62e8/`:
++
++- `docs/features/cheats.md`: loading, the format, opcode encodings.
++- `docs/components/modules/dmnt.md`: the `dmnt:cht` interface.
++- `docs/features/configurations.md`, `config_templates/override_config.ini`, `config_templates/system_settings.ini`: `cheat_enable_key`, `dmnt_cheats_enabled_by_default`, `dmnt_always_save_cheat_toggles`.
++- `stratosphere/dmnt/source/cheat/impl/dmnt_cheat_vm.hpp`, `dmnt_cheat_vm.cpp`: `DecodeNextOpcode`, `SkipConditionalBlock`, `GetCheatProcessAddress`, `ResetState`, `LoadProgram`, `Execute`, `DebugLog`.
++- `stratosphere/dmnt/source/cheat/impl/dmnt_cheat_api.cpp`, `.hpp`: `CheatProcessManager` (`AttachToApplicationProcess`, `VirtualMachineThread`, `ParseCheats`, `ParseCheatToggles`, `LoadCheats`, `LoadCheatToggles`, `SaveCheatToggles`, `CloseActiveCheatProcess`, frozen addresses).
++- `stratosphere/dmnt/source/cheat/impl/dmnt_cheat_debug_events_manager.cpp`, `dmnt_cheat_service.cpp`: debug event continuation, the service.
++- `libraries/libstratosphere/include/stratosphere/dmnt/dmnt_cheat_types.hpp`: `CheatProcessMetadata`, `CheatDefinition`, `CheatEntry`.
++- `libraries/libstratosphere/source/cfg/cfg_override.board.nintendo_nx.inc`: `CaptureOverrideStatus`, `IsOverrideMatch`, the default cheat key.
++- `libraries/libstratosphere/source/hid/hid_api.cpp`: `GetKeysHeld`.
++- `libraries/libmesosphere/source/kern_k_debug_base.cpp` (`ReadMemory`, `WriteMemory`), `kern_k_page_table_base.cpp` (`CanReadWriteDebugMemory`, `ReadDebugMemory`, `WriteDebugMemory`, `SetHeapSize`), `svc/kern_svc_debug.cpp`, `svc/kern_svc_physical_memory.cpp` (`MapPhysicalMemory`): which pages a debugger reaches, where the heap and virtual address memory live.
++
++No secondary source was needed. The host column comes from [docs/development.md, Cheats](../development.md#cheats) and `dm/host/hle_cheats.c` as of 2026-10-26 (the engine was brought to this table's reference semantics that day: failed accesses, reachable memory, the per-pass register reset).
+diff --git a/docs/reference/rewriter.md b/docs/reference/rewriter.md
+index e1429b2a..5e24914f 100644
+--- a/docs/reference/rewriter.md
++++ b/docs/reference/rewriter.md
+@@ -23,6 +23,20 @@ To enroll a cut for any game's own module:
+ 3. Add the rule under `MATCH_CUTS = {'main': [rule]}` (or the appropriate non-SDK module) in that game's `patches.py`. Record the evidence and remaining runtime validation in the game's note. Do not transplant a workaround into unrelated games.
+ 4. Verify an unregistered build-ID copy through the rewriter, comparing its output with the known fixed cut, and run `test_nso_match.py`, `test_patches.py` and `test_nro_pack.py`. The matching tests use synthetic modules from two profiles to check relocation, rejection and isolation without game files.
+
++### Cheats carried across game updates
++
++- **Symptom:** after a game update, the Cheats menu lists only `Cheats for build … (another version of the game)`, and nothing runs. Or a cheat file converted to the new build by hand writes into the wrong place: a table instead of a variable, or code that moved.
++- **Cause:** Atmosphère cheats name fixed offsets into the main NSO, valid for the one build the file is named after. An update moves code and data by different amounts in different parts of the image; a single shift is a guess.
++- **Fix:** `scripts/cheat_anchor.py` anchors each address to the game's code and compiles the cheats for any build ([Cheats that survive game updates](../development.md#cheats-that-survive-game-updates)):
++ - data through the adrp pairs (and relocated `.data` slots) that reference the nearest address at or below it;
++ - code sites through `nso_match.py`'s function fingerprints, then the tool's own fallbacks (the body digest, then a unique masked window), with a code site's original words always checked;
++ - ASM code caves through the padding before the read-only data.
++
++ The result is plain Atmosphère text, so it runs on any engine.
++- **Found on:**
++ - FINAL FANTASY CRYSTAL CHRONICLES Remastered Edition: the 1.0.1 cheatslips file, anchored on the cartridge's `main`, compiles to exactly the hand-verified +0x43680 on 1.0.3 (12 of 12 cheats, 4 of 4 references each). The 1.0.3 file (5 ASM cheats with a code cave, 7 stat cheats, Mog's fatigue) compiles back to identical writes on 1.0.3 and to all 18 entries on the cartridge's build (code sites: 4 exact, 3 by body digest, 2 by window).
++ - [13 Sentinels: Aegis Rim](../../dm/games/01003FC01670C000/README.md#cheats): a 1.10 Ryujinx list compiles back to identical writes and to 1.00, where every site lies 0x330 lower and the hook site was found by its body digest.
++
+ ## Jump tables
+
+ ### Offset jump tables through x18 read at rewrite time
+diff --git a/scripts/cheat_anchor.py b/scripts/cheat_anchor.py
+new file mode 100644
+index 00000000..0ea50937
+--- /dev/null
++++ b/scripts/cheat_anchor.py
+@@ -0,0 +1,1443 @@
++#!/usr/bin/env python3
++# Cheats that survive game updates: anchor the addresses of Atmosphère cheat codes to the game's own code, then compile
++# them into the plain Atmosphère file (<build ID>.txt) of any build of the game.
++#
++# An Atmosphère cheat names fixed offsets into the main NSO ("main+0x5607AAE"), valid for one build: every update moves
++# them. The source file this tool writes (<game>.cheats.toml) describes each address by what the game's code does instead:
++# - data: the address that adrp + add / ldr / str pairs in identified functions compute, plus a field offset;
++# optionally through a relocated .data pointer slot ("deref");
++# - code: the instructions at an offset of an identified function, with their original words;
++# - cave: the zero padding between the end of the code and the read-only data, where ASM cheats put their own code.
++# A function is found first the way the rewriter carries cuts across builds (dm/tools/nso_match.py: a unique function of
++# the same length and SHA-256 fingerprint, its body and its direct callees), then by this tool's two fallbacks: the same
++# body digest alone (a callee changed), then a window of relocation-masked instructions that occurs once in the whole
++# text. No approximate similarity is used, and the original words of a code site are checked however it was found.
++# The compiled file is plain Atmosphère text, so every engine runs it: nxnative's host, a Switch, Ryujinx, yuzu forks.
++# The source format and the commands are described in docs/development.md, "Cheats that survive game updates".
++#
++# Usage:
++# cheat_anchor.py import <cheats.txt> --nso <ExeFS/main of the file's build> -o <game>.cheats.toml
++# cheat_anchor.py compile <game>.cheats.toml --nso <ExeFS/main of the target build> -o <cheats folder> [--plain] [--replace]
++# cheat_anchor.py check <game>.cheats.toml --nso <ExeFS/main of the target build>
++# Needs Python 3.11+ (tomllib) and the README's packages (lz4, capstone). Exit status: 0 everything resolved, 2 some cheats
++# were skipped or kept bound to one build (the file is still written; the report says why), 1 an error (nothing written).
++import argparse, bisect, datetime, hashlib, re, struct, sys, tomllib
++from pathlib import Path
++
++TOOLS = Path(__file__).resolve().parent.parent / 'dm' / 'tools' # the repository's tools, found from this script's place
++sys.path.insert(0, str(TOOLS))
++import nso_match # function boundaries and fingerprints: the rewriter's cross-build matcher
++from nso_syms import load as load_nso
++import nacp # the display version of a build, from the control.nacp beside its ExeFS
++
++FORMAT = 1 # the source format version this tool reads and writes
++MAX_FIELD = 0x10000 # a data target may lie this far past the address the code references (a field of a large object)
++MAX_REFS = 4 # code references kept per data anchor (each one is resolved independently)
++REFS_TRIED = 12 # functions examined per data anchor to find MAX_REFS references in functions unique in the build
++WINDOW_HALVES = (4, 8, 16) # instructions kept on each side of a code site for the window search, smallest unique first
++KEYS_COUNTED = 4 # window words whose frequency is counted to pick the rarest one as the search key
++LOOKBACK = 8 # an add / ldr / str up to 8 instructions after an adrp takes the page's low bits (nso_match's rule)
++BASES_TRIED = 6 # nearest referenced addresses (and pointer targets) below a data target considered at import
++ATMOSPHERE_WORDS = 0x100 # code words Atmosphère's dmnt accepts per cheat (its program of all enabled cheats: 0x400)
++REGION_BITS = 40 # a region-relative address of opcodes 0 / 1 / 5 has 40 bits
++R_AARCH64_RELATIVE = 1027
++DATA_KINDS = ('ro', 'data', 'bss') # Build.where's segments that hold data: the ones a data anchor may describe
++TODAY = datetime.date.today().isoformat()
++
++
++class AnchorError(Exception):
++ """A cheat or an anchor that cannot be resolved (the message is the reason the report and the meta file show)."""
++
++
++def hexu(n):
++ """An offset as the report and the anchor names print it: 0x upper-case hex."""
++ return f'0x{n:X}'
++
++
++# ---------- AArch64 words: the PC-relative forms and their relocation masks ----------
++
++def _signed(n, bits):
++ """The two's-complement value of the low bits of n (an instruction's signed immediate field)."""
++ return n - (1 << bits) if n & (1 << (bits - 1)) else n
++
++
++def branch_target(w, pc):
++ """Target of a B / BL at pc, or None for any other word (the only PC-relative forms the tool re-encodes)."""
++ if w & 0x7c000000 == 0x14000000: return pc + _signed(w & 0x3ffffff, 26) * 4
++ return None
++
++
++def pc_relative_target(w, pc):
++ """Target of any PC-relative word (B / BL, B.cond, CBZ / CBNZ, TBZ / TBNZ, ADR, ADRP's page, literal load), else None."""
++ t = branch_target(w, pc)
++ if t is not None: return t
++ if w & 0xff000010 == 0x54000000 or w & 0x7e000000 == 0x34000000: return pc + _signed((w >> 5) & 0x7ffff, 19) * 4
++ if w & 0x7e000000 == 0x36000000: return pc + _signed((w >> 5) & 0x3fff, 14) * 4
++ if w & 0x1f000000 == 0x10000000:
++ imm = _signed(((w >> 29) & 3) | ((w >> 5) & 0x7ffff) << 2, 21)
++ return (pc & ~0xfff) + (imm << 12) if w & 0x80000000 else pc + imm
++ if w & 0x3b000000 == 0x18000000: return pc + _signed((w >> 5) & 0x7ffff, 19) * 4
++ return None
++
++
++def encode_branch(link, pc, target):
++ """A B (link False) or BL (link True) from pc to target; refused when out of the +-128 MB range or unaligned."""
++ d = target - pc
++ if d % 4 or not -(1 << 27) <= d < (1 << 27): raise AnchorError(f'branch from {hexu(pc)} to {hexu(target)} is out of range')
++ return (0x94000000 if link else 0x14000000) | ((d >> 2) & 0x3ffffff)
++
++
++def mask_word(w):
++ """One word with its relocation-dependent immediates cleared (nso_fnmap's masks): what stays equal when the same
++ instruction moves to another address. The low page bits after an adrp are cleared separately (Build._masked)."""
++ for msk, val, keep in ((0x7c000000, 0x14000000, 0xfc000000), # b / bl
++ (0xff000010, 0x54000000, 0xff00001f), # b.cond
++ (0x7e000000, 0x34000000, 0xff00001f), # cbz / cbnz
++ (0x7e000000, 0x36000000, 0xfff8001f), # tbz / tbnz
++ (0x1f000000, 0x10000000, 0x9f00001f), # adr / adrp
++ (0x3b000000, 0x18000000, 0xff00001f)): # literal ldr
++ if w & msk == val: return w & keep
++ return w
++
++
++# Encodings that cannot hold an address or a PC-relative offset: (mask, value) per ARMv8 encoding class. Anything not
++# listed carries address bits as far as this tool knows (B / BL / B.cond / CBZ / TBZ, ADR / ADRP, literal loads, loads
++# and stores with an immediate offset, ADD / SUB immediate, unknown words). The list only widens what may be written
++# over a relocated instruction, so it holds only forms whose every field is a register, a condition or a constant.
++NO_ADDRESS_FORMS = (
++ (0xfffff01f, 0xd503201f), # HINT (NOP, YIELD, WFE, BTI, ...): System, CRn = 0010, Rt = 11111
++ (0x1f800000, 0x12800000), # Move wide (immediate): MOVN / MOVZ / MOVK (opc 01 is unallocated: carries_address_bits)
++ (0x1f000000, 0x0a000000), # Logical (shifted register): AND, BIC, ORR (MOV register), ORN (MVN), EOR, EON, ANDS, BICS
++ (0x1f000000, 0x0b000000), # Add/subtract (shifted and extended register): ADD, ADDS (CMN), SUB (NEG), SUBS (CMP)
++ (0x1fe00000, 0x1a000000), # Add/subtract (with carry): ADC, ADCS, SBC (NGC), SBCS
++ (0x1fe00000, 0x1a800000), # Conditional select: CSEL, CSINC (CSET), CSINV, CSNEG
++ (0x5fe00000, 0x1ac00000), # Data-processing (2 source): UDIV, SDIV, LSLV, LSRV, ASRV, RORV
++ (0x5fe00000, 0x5ac00000), # Data-processing (1 source): RBIT, REV, CLZ, CLS
++ (0x1f000000, 0x1b000000), # Data-processing (3 source): MADD (MUL), MSUB (MNEG), SMADDL, UMULH, ...
++ (0xfffffc1f, 0xd65f0000), # RET (Unconditional branch, register): the target is a register
++ (0xff3ffc00, 0x1e204000), # FMOV (register): Floating-point data-processing (1 source), opcode 000000
++ (0xff201fe0, 0x1e201000), # FMOV (scalar, immediate): Floating-point immediate, imm5 = 00000
++)
++
++
++def carries_address_bits(w):
++ """False only when w is one of NO_ADDRESS_FORMS: a word that means the same at any address, so a cheat may write it
++ over an instruction that moved with its function (NOP a moved BL, a MOV over a moved adrp's user). True for every
++ other word, unknown ones included: there a word of the old build would keep the old build's address bits."""
++ if w & 0x1f800000 == 0x12800000 and (w >> 29) & 3 == 1: return True # opc 01 of move wide: unallocated, not a MOV
++ return not any(w & m == v for m, v in NO_ADDRESS_FORMS)
++
++
++def is_conditional_branch(w):
++ """True for B.cond, CBZ / CBNZ and TBZ / TBNZ: the PC-relative branches a cheat flips without re-encoding."""
++ return w & 0xff000010 == 0x54000000 or w & 0x7e000000 in (0x34000000, 0x36000000)
++
++
++def carry_write(authored, here, new, a, width):
++ """The value (width bytes) a store at a writes on this build, or None when it must be refused. authored and here
++ are the aligned words that hold a on the authored build and on this one. Equal words: new as written. Different
++ words mean the instruction moved (a branch, an adrp, the low page bits after one), so new was meant for the old
++ address: a restore of the authored bytes writes this build's own bytes instead, and any other value is kept only
++ when the word it makes here is the word it made on the authored build (the bytes it leaves are equal) and that
++ word carries no address bits. The one rule patches and code templates share."""
++ if authored == here: return new
++ sh, mask = 8 * (a & 3), (1 << 8 * width) - 1
++ if new == (authored >> sh) & mask: return (here >> sh) & mask # the restore: this build's own bytes
++ made_here = here & ~(mask << sh) | new << sh
++ made_there = authored & ~(mask << sh) | new << sh
++ return new if made_here == made_there and not carries_address_bits(made_here) else None
++
++
++def adrp_user_lo(u, rd):
++ """The low page offset an add (64-bit immediate) or a ldr / str (unsigned offset) with base register rd adds to an
++ adrp's page, or None when u is not such an instruction (the pairing rule of nso_match and nso_fnmap)."""
++ if (u >> 5) & 31 != rd: return None
++ if u & 0xff800000 == 0x91000000: return (u >> 10) & 0xfff
++ if u & 0x3b000000 == 0x39000000:
++ sh = 4 if u & 0x04800000 == 0x04800000 else u >> 30 # 128-bit SIMD / FP registers scale by 16
++ return ((u >> 10) & 0xfff) << sh
++ return None
++
++
++def ends_pairing(u, rd):
++ """True when u ends the search for an adrp's user: any branch, or an instruction that writes rd other than a store.
++ Conservative on purpose: a missed pair only costs one reference, a wrong pair would anchor a wrong address."""
++ if u & 0x7c000000 == 0x14000000 or u & 0xff000010 == 0x54000000 or u & 0x7e000000 in (0x34000000, 0x36000000): return True
++ if u & 0xfffffc1f in (0xd61f0000, 0xd63f0000, 0xd65f0000): return True # br / blr / ret
++ is_store = u & 0x3b000000 == 0x39000000 and not (u >> 22) & 1 # str (unsigned offset): Rt is read, not written
++ return u & 31 == rd and not is_store
++
++
++# ---------- one build of the game ----------
++
++class Build:
++ """One NSO build: its memory image, segments, build ID, unwind functions and lazy indexes (fingerprints by size, adrp
++ pairs, relocations), and the rewriter's output for it when the NSP script's layout has one. Only reads files."""
++
++ def __init__(self, path):
++ """Load the NSO at path (AnchorError when it cannot be read or holds no unwind table)."""
++ self.path = Path(path)
++ try:
++ with open(self.path, 'rb') as f: hdr = f.read(0x100)
++ except OSError as e: raise AnchorError(f'{self.path.resolve()}: {e.strerror}') from e
++ if hdr[:4] != b'NSO0': raise AnchorError(f'{self.path.resolve()}: not an NSO file')
++ self.img = bytes(load_nso(str(self.path))) # the whole memory image, text at 0, bss included
++ segs = [struct.unpack_from('<III', hdr, 0x10 + i * 0x10) for i in range(3)] # file offset, memory offset, size
++ self.text_end, self.ro_start = segs[0][2], segs[1][1]
++ # .data from its memory offset; .bss right after it up to the image's end (nso_syms.load sizes the image to
++ # data offset + data size + the bss size at 0x3C). where() keeps a data anchor inside its target's segment
++ self.data_start, self.bss_start = segs[2][1], segs[2][1] + segs[2][2]
++ self.build_id = hdr[0x40:0x48].hex().upper() # the first 8 bytes, as cheat files are named
++ nacp_path = self.path.parent.parent / 'control.nacp' # nx_extract writes it beside ExeFS
++ self.version = nacp.version(nacp_path) if nacp_path.is_file() else ''
++ self.title = self._title()
++ # The rewriter's output of this build, where the NSP script puts it: <id>_build/extract/v<N>/ExeFS/main ->
++ # <id>_build/patched_v<N>/main.patched.bin (a flat image, same layout). Used only to warn about rewritten words
++ p = self.path.resolve()
++ rw = p.parents[3] / f'patched_{p.parents[1].name}' / f'{p.name}.patched.bin' if len(p.parents) > 3 else None
++ self.patched = rw if rw is not None and rw.is_file() else None
++ try: self.mod = nso_match.Image(self.img, self.text_end)
++ except nso_match.MatchError as e: raise AnchorError(f'{self.path.resolve()}: {e}') from e
++ self.starts = sorted(self.mod.functions)
++ self.by_size = {}
++ for s in self.starts: self.by_size.setdefault(self.mod.functions[s] - s, []).append(s)
++ self._pairs = self._keys = self._relocs = self._ptrs = None
++
++ def _title(self):
++ """The program ID from main.npdm beside the NSO (its ACI0 section), '' when it cannot be read."""
++ try:
++ d = (self.path.parent / 'main.npdm').read_bytes()
++ aci = struct.unpack_from('<I', d, 0x70)[0]
++ return f'{struct.unpack_from("<Q", d, aci + 0x10)[0]:016X}' if d[aci:aci + 4] == b'ACI0' else ''
++ except (OSError, struct.error): return ''
++
++ def word(self, off):
++ """The little-endian word at image offset off."""
++ return struct.unpack_from('<I', self.img, off)[0]
++
++ def words(self, off, n):
++ """The n little-endian words from image offset off."""
++ return list(struct.unpack_from(f'<{n}I', self.img, off))
++
++ def rewritten(self, off, n):
++ """The n bytes at off in the rewriter's output of this build, or None when there is none beside the NSO."""
++ if self.patched is None: return None
++ with open(self.patched, 'rb') as f:
++ f.seek(off); return f.read(n)
++
++ def func_at(self, off, n=4):
++ """Start of the unwind function that holds [off, off + n), or None."""
++ i = bisect.bisect_right(self.starts, off) - 1
++ if i < 0: return None
++ s = self.starts[i]
++ return s if off + n <= self.mod.functions[s] else None
++
++ def digest(self, start, kind):
++ """The full fingerprint ('fp': body and direct callees) or the body digest alone ('body') of a function, or None
++ when nso_match cannot compute it (an undecodable word, a callee without a boundary)."""
++ try: return self.mod.fingerprint(start) if kind == 'fp' else self.mod._body(start)[0] # _body: nso_match's own body digest
++ except nso_match.MatchError: return None
++
++ def same(self, size, key, kind):
++ """The functions of this size whose digest of this kind is key, in address order (digests are cached by nso_match)."""
++ return [s for s in self.by_size.get(size, ()) if self.digest(s, kind) == key]
++
++ def _masked(self, start, n):
++ """(the relocation-masked words of [start, start + 4n), the indexes of words whose low page bits were cleared
++ because an adrp up to LOOKBACK words before them set their base), or None when the range leaves the text."""
++ if start < 0 or start % 4 or start + 4 * n > self.text_end: return None
++ lo = max(0, start - 4 * LOOKBACK)
++ raw = self.words(lo, (start + 4 * n - lo) // 4)
++ out, users = [mask_word(w) for w in raw], set()
++ for i, w in enumerate(raw):
++ if w & 0x9f000000 != 0x90000000: continue
++ rd = w & 31
++ for j in range(i + 1, min(i + 1 + LOOKBACK, len(raw))):
++ if adrp_user_lo(raw[j], rd) is not None: out[j] &= ~0x3ffc00; users.add(j); break
++ if ends_pairing(raw[j], rd): break
++ k = (start - lo) // 4
++ return out[k:], {j - k for j in users if j >= k}
++
++ def masked(self, start, n):
++ """The relocation-masked words of [start, start + 4n), or None outside the text."""
++ r = self._masked(start, n)
++ return r and r[0]
++
++ def window_find(self, window, key):
++ """Every start where the masked words equal window. key indexes a word that masking leaves unchanged: its raw bytes
++ are searched (fast), and the whole masked window compared at each hit."""
++ needle, hits = struct.pack('<I', window[key]), []
++ p = self.img.find(needle, 0, self.text_end)
++ while p >= 0:
++ if p % 4 == 0 and self.masked(p - 4 * key, len(window)) == window: hits.append(p - 4 * key)
++ p = self.img.find(needle, p + 1, self.text_end)
++ return hits
++
++ def pairs(self):
++ """{computed address: [(adrp offset, user offset)]} for every adrp in the text and its first user."""
++ if self._pairs is None:
++ self._pairs = {}
++ text = self.img[:self.text_end]
++ for m in re.finditer(rb'[\x90\xb0\xd0\xf0]', text): # an adrp's top byte: bit 31 set, bits 28..24 = 1 0000
++ p = m.start() - 3
++ if p % 4: continue
++ w = struct.unpack_from('<I', text, p)[0]
++ if w & 0x9f000000 != 0x90000000: continue
++ rd, page = w & 31, pc_relative_target(w, p)
++ if page is None: continue # cannot happen for an adrp (checked above); narrows the type
++ for j in range(p + 4, min(p + 4 * (LOOKBACK + 1), self.text_end), 4):
++ u = struct.unpack_from('<I', text, j)[0]
++ lo = adrp_user_lo(u, rd)
++ if lo is not None: self._pairs.setdefault(page + lo, []).append((p, j)); break
++ if ends_pairing(u, rd): break
++ self._keys = sorted(self._pairs)
++ return self._pairs
++
++ def pair_at(self, a, b):
++ """The address the adrp at a and its user at b compute, or None when they are not such a pair."""
++ if not (0 <= a < b <= self.text_end - 4): return None
++ w, u = self.word(a), self.word(b)
++ if w & 0x9f000000 != 0x90000000: return None
++ lo = adrp_user_lo(u, w & 31); page = pc_relative_target(w, a)
++ return None if lo is None or page is None else page + lo
++
++ def relocs(self):
++ """{slot offset: pointer offset} of the image's relative relocations (DT_RELA R_AARCH64_RELATIVE and DT_RELR)."""
++ if self._relocs is None:
++ self._relocs = {}
++ img = self.img
++ try:
++ mod = struct.unpack_from('<I', img, 4)[0]
++ dyn = mod + struct.unpack_from('<i', img, mod + 4)[0]
++ tags = {}
++ for pos in range(dyn, min(len(img) - 15, dyn + 4096 * 16), 16):
++ tag, value = struct.unpack_from('<qQ', img, pos)
++ if tag == 0: break
++ tags[tag] = value
++ if 7 in tags: # DT_RELA, DT_RELASZ (8); entries of 24 bytes: offset, info, addend
++ for slot, info, addend in struct.iter_unpack('<QQq', img[tags[7]:tags[7] + tags.get(8, 0)]):
++ if info & 0xffffffff == R_AARCH64_RELATIVE: self._relocs[slot] = addend
++ if 36 in tags: # DT_RELR, DT_RELRSZ (35): addresses and bitmaps, the addends in place
++ base = 0
++ for (e,) in struct.iter_unpack('<Q', img[tags[36]:tags[36] + tags.get(35, 0)]):
++ if not e & 1:
++ self._relocs[e] = struct.unpack_from('<Q', img, e)[0]; base = e + 8
++ else:
++ for i in range(63):
++ if e >> (i + 1) & 1:
++ s = base + 8 * i; self._relocs[s] = struct.unpack_from('<Q', img, s)[0]
++ base += 63 * 8
++ except (struct.error, IndexError): self._relocs = {}
++ return self._relocs
++
++ def slots_of(self, ptr):
++ """The relocated slots whose pointer is ptr."""
++ if self._ptrs is None:
++ self._ptrs = {}
++ for slot, p in self.relocs().items(): self._ptrs.setdefault(p, []).append(slot)
++ self._ptr_keys = sorted(self._ptrs)
++ return self._ptrs.get(ptr, [])
++
++ def _below(self, keys, target):
++ """The nearest BASES_TRIED values of the sorted keys at or below target, within MAX_FIELD of it and in its
++ segment. A base in another segment is never an object the target is a field of, and segments move apart
++ across builds (a grown .rodata shifts .data), so such a base would resolve to a wrong address."""
++ seg, i, out = self.where(target), bisect.bisect_right(keys, target), []
++ while i > 0 and len(out) < BASES_TRIED:
++ i -= 1
++ if target - keys[i] > MAX_FIELD or self.where(keys[i]) != seg: break # segments are contiguous: all lower keys are out too
++ out.append(keys[i])
++ return out
++
++ def referenced_below(self, target):
++ """The distinct addresses the code computes at or below target and within MAX_FIELD of it, nearest first."""
++ self.pairs()
++ return self._below(self._keys, target)
++
++ def pointers_below(self, target):
++ """The distinct relocated pointers at or below target and within MAX_FIELD of it, nearest first."""
++ self.slots_of(0)
++ return self._below(self._ptr_keys, target)
++
++ def where(self, off, n=1):
++ """The segment of [off, off + n) of the image: 'text', 'pad' (the zero padding after the text), 'ro' (.rodata, up
++ to .data), 'data', 'bss' (DATA_KINDS are the last three), or None outside the image or across a boundary."""
++ if off < 0 or off + n > len(self.img): return None
++ for kind, lo, hi in (('text', 0, self.text_end), ('pad', self.text_end, self.ro_start), ('ro', self.ro_start, self.data_start),
++ ('data', self.data_start, self.bss_start), ('bss', self.bss_start, len(self.img))):
++ if lo <= off and off + n <= hi: return kind
++ return None
++
++
++# ---------- authoring anchors (import) ----------
++
++def locator(build, site, n):
++ """The ways to find the n bytes at code offset site again in another build: the containing function's fingerprint and
++ body digest (with [index, count] among identical copies when there are several), the site's offset in it, its
++ original words and a masked window around it ('wunique' when it occurs once in this build). Raises AnchorError when
++ nothing describes the site."""
++ words = (n + 3) // 4
++ loc: dict[str, object] = {'old': ' '.join(f'{w:08X}' for w in build.words(site, words))}
++ f = build.func_at(site, 4 * words)
++ if f is not None:
++ size = build.mod.functions[f] - f
++ loc.update(size=size, at=site - f)
++ for kind in ('fp', 'body'):
++ key = build.digest(f, kind)
++ if key is None: continue
++ same = build.same(size, key, kind)
++ loc[kind] = key
++ if len(same) > 1: loc[kind + '_copy'] = [same.index(f), len(same)]
++ for h in WINDOW_HALVES:
++ r = build._masked(site - 4 * h, words + 2 * h)
++ if r is None: continue
++ win, users = r
++ raw = build.words(site - 4 * h, len(win))
++ # search keys: words masking leaves unchanged, that are not PC-relative and not an adrp's user (their raw bits
++ # may differ in another build even when the masked ones agree); the rarest of a few is searched
++ keys = [i for i, (m, w) in enumerate(zip(win, raw)) if m == w and i not in users and pc_relative_target(w, 0) is None]
++ if not keys: continue
++ keys = sorted(keys, key=lambda i: (raw[i] in (0xd503201f, 0xd65f03c0), abs(i - h)))[:KEYS_COUNTED] # nop / ret last
++ key = min(keys, key=lambda i: build.img.count(struct.pack('<I', raw[i]), 0, build.text_end))
++ loc.update(window=' '.join(f'{w:08X}' for w in win), wat=h, wkey=key)
++ if build.window_find(win, key) == [site - 4 * h]: loc['wunique'] = True; break
++ if 'fp' not in loc and 'body' not in loc and not loc.get('wunique'):
++ raise AnchorError(f'code at {hexu(site)}: no function boundary and no unique instruction window describe it')
++ return loc
++
++
++class Authoring:
++ """The anchors an import creates, by name, on the build the cheats were written for, and notes for the report."""
++
++ def __init__(self, build):
++ """Start with no anchors; the cave's base is set by set_cave when the file touches the padding."""
++ self.b, self.anchors, self.cave_base, self.notes = build, {}, None, []
++
++ def site(self, off, n):
++ """The anchor of code [off, off + n) (off aligned): one per distinct offset and length, named s_<offset>[_<n>]."""
++ name = f's_{off:X}' + (f'_{n}' if n != 4 else '')
++ if name not in self.anchors: self.anchors[name] = {'code': locator(self.b, off, n), 'authored': hexu(off)}
++ return name
++
++ def set_cave(self, lowest):
++ """The cave's base: the lowest padding address the imported file touches, as a distance before the read-only data."""
++ self.cave_base = lowest & ~3
++ self.anchors['cave'] = {'pad': self.b.ro_start - self.cave_base, 'authored': hexu(self.cave_base)}
++
++ def cave(self, off):
++ """The expression of an address in the padding after the text: cave[+offset]."""
++ if self.cave_base is None or off < self.cave_base: raise AnchorError(f'padding address {hexu(off)} below the cave')
++ return 'cave' if off == self.cave_base else f'cave+{hexu(off - self.cave_base)}'
++
++ def data(self, target):
++ """The expression of a data address: <anchor>[+field offset]. The anchor is the nearest address at or below target
++ that the code references (directly, or as the target of a relocated slot the code references; direct first at
++ the same distance) and whose references can be described; the nearest keeps the field offset from crossing into
++ an unrelated variable. An anchor with a single reference is noted as weak."""
++ cands = sorted([(target - p, 0, p) for p in self.b.referenced_below(target)] +
++ [(target - p, 1, p) for p in self.b.pointers_below(target)])
++ for _, deref, base in cands:
++ name = f'{"p" if deref else "d"}_{base:X}'
++ if name not in self.anchors:
++ refs = self._refs(self._sites(base, deref))
++ if not refs: continue
++ self.anchors[name] = dict({'data': refs, 'authored': hexu(base)}, **({'deref': True} if deref else {}))
++ self.notes.append(f'anchor {name}: {len(refs)} code reference{"s" if len(refs) > 1 else ", weak"} to '
++ + (f'the pointer slots of {hexu(base)}' if deref else hexu(base)))
++ return name if target == base else f'{name}+{hexu(target - base)}'
++ raise AnchorError(f'data at {hexu(target)}: no describable code reference within {hexu(MAX_FIELD)} below it')
++
++ def _sites(self, base, deref):
++ """The (adrp, user) pairs that compute base, or one of the relocated slots that point to base (deref)."""
++ pairs = self.b.pairs()
++ if deref: return sorted(p for slot in self.b.slots_of(base) for p in pairs.get(slot, ()))
++ return sorted(pairs.get(base, ()))
++
++ def _refs(self, sites):
++ """Locators of up to MAX_REFS of the pairs, one per function, those in functions unique in this build first."""
++ unique, other, seen = [], [], set()
++ for a, u in sites:
++ f = self.b.func_at(a, u + 4 - a)
++ if f is None or f in seen: continue
++ seen.add(f)
++ try: loc = locator(self.b, a, 4)
++ except AnchorError: continue
++ loc['use'] = u - a
++ (unique if 'fp' in loc and 'fp_copy' not in loc else other).append(loc)
++ if len(unique) >= MAX_REFS or len(seen) >= REFS_TRIED: break
++ return (unique + other)[:MAX_REFS]
++
++
++# ---------- Atmosphère text and its instructions ----------
++
++# A header, a master header, a run of whole 8-digit words (Atmosphère reads 8 digits at a time, so "0400000000123456" is
++# two words), or any other token; the last stops before a bracket so that "junk[Next]" still starts the next cheat.
++TOKEN = re.compile(r'\[([^\]\n]*)\]|\{([^}\n]*)\}|((?:[0-9A-Fa-f]{8})+)(?![0-9A-Fa-f])|([^\s\[{]+|\S)')
++
++
++def parse_atmosphere(text):
++ """[(name, master, [words], [(word index, line, token)]), ...] and [warnings] of an Atmosphère cheat file. Lenient
++ like the host's loader where nothing is lost: prose before the first header is ignored; a header glued to the
++ previous code word ("00000008[Next]") still starts a new cheat; words glued together are split; a line with no code
++ word at all is prose (a credits or author line) and is ignored with a warning, as the host's loader ignores it. A
++ token of hex digits only counts as a (botched) code word: "2000000" alone on a line is a cut end-of-block, not prose.
++ A stray token on a line that also holds code words makes the cheat malformed: it is listed with its line and the
++ place it stood, never dropped, because a shortened program can change meaning (a lost end-of-block word lets an
++ open conditional swallow the next cheats)."""
++ entries, warns, cur = [], [], None
++ pending, has_word, cur_line = [], False, 0 # the stray tokens of the current line, and whether it holds a code word
++
++ def flush():
++ """Settle the current line's stray tokens: malformed when the line holds code words, prose otherwise."""
++ for entry, index, ln, tok in pending:
++ if has_word: entry[3].append((index, ln, tok))
++ else: warns.append(f'line {ln}: "{tok}" in "{entry[0]}" is not a code word, ignored (no code word on the line)')
++ pending.clear()
++ for m in TOKEN.finditer(text):
++ line = text.count('\n', 0, m.start()) + 1
++ if line != cur_line: flush(); cur_line, has_word = line, False
++ if m.group(1) is not None or m.group(2) is not None:
++ flush(); has_word = False # tokens before a header glued on the same line belong to the previous cheat
++ cur = [(m.group(1) if m.group(1) is not None else m.group(2)).strip(), m.group(2) is not None, [], []]
++ entries.append(cur)
++ elif m.group(3):
++ if cur is None: warns.append(f'line {line}: code word before any [name], ignored')
++ else: cur[2] += [int(m.group(3)[k:k + 8], 16) for k in range(0, len(m.group(3)), 8)]; has_word = True
++ elif cur is not None:
++ pending.append((cur, len(cur[2]), line, m.group(4)))
++ if re.fullmatch(r'[0-9A-Fa-f]+', m.group(4)): has_word = True # a code word of the wrong length
++ flush()
++ return [tuple(e) for e in entries], warns
++
++
++def malformed_code(words, bad):
++ """A malformed cheat's program for the source: its words with each stray token back where it stood, four per line.
++ The compiler refuses the stray token ("not a code word"), so the cheat is never run shortened."""
++ toks = []
++ for i in range(len(words) + 1):
++ toks += [t for j, _, t in bad if j == i]
++ if i < len(words): toks.append(f'{words[i]:08X}')
++ return ''.join(' '.join(toks[k:k + 4]) + '\n' for k in range(0, len(toks), 4))
++
++
++def decode(words, i):
++ """One instruction at words[i]: a dict with op (the extended opcode: 0x9, 0xC0, 0xFF0, ...), n (its length in words),
++ its address field when it has a region-relative one ('rel', 'bits' 40 or 36, 'mem' the region), and for an opcode 0
++ store 'width', 'reg' and 'value'. 'regs' is True when it can change a VM register (loads, arithmetic, loops, the
++ incrementing forms of 6 and A). Raises AnchorError on an unknown or truncated form. The layouts are the ones of
++ Atmosphère's own docs/features/cheats.md (dmnt), as dm/host/hle_cheats.c decodes opcodes 0-8."""
++ w = words[i]; op = w >> 28
++ if op >= 0xC: op = op << 4 | (w >> 24) & 0xF
++ if op >= 0xF0: op = op << 4 | (w >> 20) & 0xF
++ d = {'op': op, 'n': 1, 'regs': op in (3, 4, 5, 6, 7, 9, 0xA, 0xC1, 0xC2, 0xC3)}
++
++ def wid(t):
++ """A width nibble, which must be 1, 2, 4 or 8."""
++ if t not in (1, 2, 4, 8): raise AnchorError(f'word {i}: width {t} in {w:08X}')
++ return t
++ if op in (0, 1): # 0TMR00AA / 1TMCXrAA AAAAAAAA VVVVVVVV (VVVVVVVV)
++ d.update(n=4 if wid((w >> 24) & 0xF) == 8 else 3, mem=(w >> 20) & 0xF, bits=REGION_BITS)
++ if op == 0: d.update(width=(w >> 24) & 0xF, reg=(w >> 16) & 0xF)
++ elif op in (2, 8, 0xC1, 0xC2, 0xC3, 0xFF0, 0xFF1): pass # one word each
++ elif op == 3: d['n'] = 1 if (w >> 24) & 0xF else 2 # 300R0000 VVVVVVVV / 310R0000
++ elif op in (4, 6): d['n'] = 3 # 400R0000 / 6T0RIor0 + a 64-bit value
++ elif op == 5: # 5TMRI0AA AAAAAAAA: I = 0 / 3 are region-relative
++ d['n'] = 2
++ if (w >> 12) & 0xF in (0, 3): d.update(mem=(w >> 20) & 0xF, bits=REGION_BITS)
++ elif op == 7: d['n'] = 2 # 7T0RC000 VVVVVVVV
++ elif op == 9: d['n'] = 1 + ((2 if wid((w >> 24) & 0xF) == 8 else 1) if (w >> 8) & 0xF else 0) # 9TCRSIs0 (value)
++ elif op == 0xA: # ATSRIOxa (aaaaaaaa): O = 4 / 5 are region-relative
++ o = (w >> 8) & 0xF
++ d['n'] = 2 if o in (2, 4, 5) else 1
++ if o in (4, 5): d.update(mem=(w >> 4) & 0xF, bits=36)
++ elif op == 0xC0: # C0TcSX..: X = 0 is region-relative, 4 a static value
++ x = (w >> 8) & 0xF
++ d['n'] = 1 + (2 if wid((w >> 20) & 0xF) == 8 else 1) if x == 4 else 2 if x in (0, 2) else 1
++ if x == 0: d.update(mem=(w >> 4) & 0xF, bits=36)
++ elif op == 0xC4: d['n'] = 3 # C4r00000 + a 64-bit key mask
++ elif op == 0xFFF: # FFFTIX..: X = 0 is region-relative
++ x = (w >> 8) & 0xF
++ d['n'] = 2 if x in (0, 2) else 1
++ if x == 0: d.update(mem=(w >> 4) & 0xF, bits=36)
++ else: raise AnchorError(f'word {i}: unknown opcode in {w:08X}')
++ if i + d['n'] > len(words): raise AnchorError(f'word {i}: {w:08X} is cut short')
++ if 'bits' in d: d['rel'] = ((w & (0xFF if d['bits'] == 40 else 0xF)) << 32) | words[i + 1]
++ if op == 0: d['value'] = (words[i + 2] << 32 | words[i + 3]) if d['width'] == 8 else words[i + 2]
++ return d
++
++
++def decode_all(words):
++ """[(word index, instruction)] of a whole program (AnchorError on the first bad one)."""
++ out, i = [], 0
++ while i < len(words):
++ d = decode(words, i); out.append((i, d)); i += d['n']
++ return out
++
++
++def mem_words(width, value):
++ """An opcode 0 value as it lies in memory: 4-byte words, low word first (an 8-byte store is two words)."""
++ return [value & 0xffffffff, value >> 32] if width == 8 else [value]
++
++
++def value_index(i, width, k):
++ """The index in the program of the k-th memory word (mem_words order) of the opcode 0 store at word i: an 8-byte value
++ is written high word first (word i + 2 is the high word, at the store's address + 4)."""
++ return i + 2 + (1 - k if width == 8 else k)
++
++
++def runs(ranges):
++ """Merged [start, end) runs of byte ranges (the contiguous areas one cheat writes)."""
++ out = []
++ for s, e in sorted(ranges):
++ if out and s <= out[-1][1]: out[-1][1] = max(out[-1][1], e)
++ else: out.append([s, e])
++ return out
++
++
++def format_words(words, ins=None, tokens=None):
++ """Atmosphère words, one instruction per line when the instructions are known; tokens replaces words by index."""
++ tokens = tokens or {}
++
++ def word(i):
++ """Word i as text, or its token."""
++ return tokens.get(i, f'{words[i]:08X}')
++ if not ins: return ''.join(' '.join(word(i) for i in range(k, min(k + 4, len(words)))) + '\n' for k in range(0, len(words), 4))
++ return ''.join(' '.join(word(k) for k in range(i, i + d['n'])) + '\n' for i, d in ins)
++
++
++# ---------- import: an Atmosphère file into anchored cheats ----------
++
++ON_OFF = re.compile(r'^(.*?)(?:\s*[-:_]\s*|\s+|\s*[(\[]\s*)(on|off)\s*[)\]]?$', re.I)
++
++
++def import_file(txt, build, assume_build=False):
++ """(the anchored source as a dict for write_toml, the report lines, the number of cheats kept bound to one build) of
++ the Atmosphère file txt, written for build. Every main-relative address is anchored; a cheat that cannot be fully
++ anchored keeps its words, bound to the file's own build."""
++ text = Path(txt).read_text(encoding='utf-8', errors='replace')
++ entries, warns = parse_atmosphere(text)
++ report = [f'warning: {w}' for w in warns]
++ stem, own_build = Path(txt).name[:16], build.build_id
++ # a file named after the title ID (as some sites name them) names no build: it is taken as this build's
++ if re.fullmatch(r'[0-9A-Fa-f]{16}', stem) and stem.upper() not in (build.build_id, build.title):
++ if not assume_build:
++ raise AnchorError(f'{Path(txt).name} names build {stem.upper()}, the NSO is build {build.build_id}; '
++ '--assume-build anchors it on this build anyway (only if both builds share the layout)')
++ own_build = stem.upper() # cheats left unanchored keep the addresses of the file's own build
++ report.append(f'[RED] {Path(txt).name} is for build {own_build}: anchored with the code of build {build.build_id} (--assume-build)')
++ auth = Authoring(build)
++ decoded = []
++ malformed = {} # entry index -> the stray tokens of a malformed cheat (parse_atmosphere)
++ for name, master, words, bad in entries: # first pass: decode everything, to place the cave before any anchor names it
++ if bad:
++ malformed[len(decoded)] = bad
++ decoded.append((name, master, words, None, 'malformed: ' + ', '.join(f'line {ln}: "{t}" is not a code word' for _, ln, t in bad)))
++ continue
++ try: decoded.append((name, master, words, decode_all(words), None))
++ except AnchorError as e: decoded.append((name, master, words, None, str(e)))
++ pad = [] # every padding address the file touches: addresses, and B / BL targets of the words it writes
++ for _, _, _, ins, _ in decoded:
++ for _, d in ins or ():
++ if d.get('mem') != 0 or 'rel' not in d: continue
++ if build.where(d['rel'], 1) == 'pad': pad.append(d['rel'])
++ if d['op'] == 0 and d['width'] >= 4 and build.where(d['rel'], d['width']) in ('text', 'pad'):
++ for k, w in enumerate(mem_words(d['width'], d['value'])):
++ t = branch_target(w, d['rel'] + 4 * k)
++ if t is not None and build.where(t, 4) == 'pad': pad.append(t)
++ if pad: auth.set_cave(min(pad))
++ cheats, bound = [], 0
++ for n, (name, master, words, ins, err) in enumerate(decoded):
++ c = {'name': name}
++ if master: c['master'] = True
++ if not words and n not in malformed: c['label'] = True; cheats.append(c); continue
++ try:
++ if err: raise AnchorError(err)
++ c.update(convert(auth, words, ins))
++ except AnchorError as e:
++ c['code'] = malformed_code(words, malformed[n]) if n in malformed else format_words(words, ins)
++ c['builds'] = [own_build]; bound += 1
++ report.append(f'[RED] "{name}": kept for build {own_build} only: {e}')
++ cheats.append(c)
++ # evidence the file is for this build: writes into the code (not the zero cave) of the words already there, as the
++ # "off" / restore entries of ASM cheats do; counted before pair_on_off merges those entries away
++ code = [w for c in cheats for w in c.get('patch', ()) if not w['at'].startswith('cave')]
++ same = sum(1 for w in code if w.get('same'))
++ if code: report.append(f'{same} of {len(code)} writes into the code put back the word already there in build {build.build_id}'
++ + (' (restore entries: evidence the file is for this build)' if same else ''))
++ cheats = pair_on_off(cheats)
++ for c in cheats:
++ for w in c.get('patch', ()): w.pop('same', None)
++ report += auth.notes
++ src = {'format': FORMAT, 'title': build.title, 'authored': build.build_id,
++ 'builds': {build.build_id: build.version} if build.version else {}, 'cheats': cheats, 'anchors': auth.anchors}
++ report.append(f'{len(cheats)} cheats, {len(auth.anchors)} anchors on build {build.build_id}' + (f' ({build.version})' if build.version else '')
++ + (f', {bound} kept for build {own_build} only' if bound else ''))
++ return src, report, bound
++
++
++def convert(auth, words, ins):
++ """One cheat's anchored form: a patch (only opcode 0 stores into the code and the cave), a data freeze (a single
++ store into data), or code (any other program) whose address words became {anchor} tokens. The code words one cheat
++ writes contiguously form one run and share one anchor, so they move together. Raises AnchorError when an address or
++ a PC-relative word cannot be carried to another build."""
++ b = auth.b
++ stores = [d for _, d in ins if d['op'] == 0 and d['mem'] == 0]
++ regs = any(d['regs'] for _, d in ins)
++ own = runs((d['rel'], d['rel'] + d['width']) for d in stores)
++
++ def run_of(rel, n):
++ """The word-aligned text run of this cheat's stores that holds [rel, rel + n), or None."""
++ for s, e in own:
++ s4, e4 = s & ~3, (e + 3) & ~3
++ if s <= rel and rel + n <= e and e4 <= b.text_end: return s4, e4
++ return None
++
++ def addr_expr(rel, n, store=False):
++ """An anchor expression for [rel, rel + n) of main; a store into the code is anchored by its whole run."""
++ kind = b.where(rel, n)
++ if kind == 'text':
++ start, end = (run_of(rel, n) if store else None) or (rel & ~3, (rel + n + 3) & ~3)
++ return auth.site(start, end - start) + (f'+{hexu(rel - start)}' if rel != start else '')
++ if kind == 'pad': return auth.cave(rel)
++ if kind in DATA_KINDS: return auth.data(rel)
++ raise AnchorError(f'address {hexu(rel)} is outside the main NSO image or crosses a segment')
++
++ def keeps(w, a, t):
++ """True when the PC-relative word w at a, aimed at t, stays right as written: t in the run w is written in, or
++ a conditional branch inside the site's own function (same_function_branch)."""
++ return any(s <= a < e and s <= t < e for s, e in own) or same_function_branch(b, w, a, t)
++
++ def value_tokens(d):
++ """The stored memory words; a B / BL to outside the run the word is written in becomes a relocatable token.
++ Every word a store makes, a 1- or 2-byte store's whole word included, must be carried as written: a
++ PC-relative word only when keeps() holds, and never a new adrp user (adrp_paired: its low page bits are this
++ build's, and the data can move inside its page while the code does not)."""
++ out = []
++ for k, w in enumerate(mem_words(d['width'], d['value'])):
++ a = d['rel'] + 4 * k
++ a4, here = a & ~3, b.word(a & ~3)
++ sh, mask = 8 * (a & 3), (1 << 8 * min(d['width'], 4)) - 1
++ made = here & ~(mask << sh) | w << sh # the whole word this store leaves in memory
++ if made != here and b.where(a4, 4) == 'text' and adrp_paired(b.word, a4, made) is not None:
++ raise AnchorError(f'the word {made:08X} written at {hexu(a4)} takes the page of the adrp at {hexu(adrp_paired(b.word, a4, made))}: '
++ 'its low page bits hold for this build only')
++ if d['width'] < 4:
++ t = pc_relative_target(made, a4) if made != here else None
++ if t is not None and not keeps(made, a, t):
++ raise AnchorError(f'the {d["width"]}-byte write at {hexu(a)} makes {made:08X}, PC-relative to {hexu(t)}, outside what the cheat writes')
++ out.append(f'{w:0{2 * d["width"]}X}'); continue
++ t = pc_relative_target(w, a)
++ if t is None or keeps(w, a, t): out.append(f'{w:08X}'); continue
++ if branch_target(w, a) is None: raise AnchorError(f'the word {w:08X} written at {hexu(a)} is PC-relative to {hexu(t)}, outside what the cheat writes')
++ out.append(('bl:' if w & 0x80000000 else 'b:') + addr_expr(t, 4))
++ return out
++
++ simple = not regs and all(d['op'] == 0 and d['mem'] == 0 for _, d in ins)
++ if simple and all(b.where(d['rel'], d['width']) in ('text', 'pad') for d in stores):
++ patch = []
++ for d in stores:
++ vals = value_tokens(d)
++ item = {'at': addr_expr(d['rel'], d['width'], store=True), 'new': ' '.join(vals)}
++ if d['width'] < 4: item['width'] = d['width']
++ if b.img[d['rel']:d['rel'] + d['width']] == d['value'].to_bytes(d['width'], 'little'):
++ item['same'] = True # writes the word already there: a restore (pair_on_off and the import report use it)
++ patch.append(item)
++ return {'patch': patch}
++ if simple and len(stores) == 1 and b.where(stores[0]['rel'], stores[0]['width']) in DATA_KINDS:
++ d = stores[0]
++ return {'target': addr_expr(d['rel'], d['width']), 'type': f'u{8 * d["width"]}', 'action': 'freeze', 'value': d['value']}
++ words, tokens, written = list(words), {}, registers_written(words, ins)
++ for i, d in ins:
++ if 'rel' not in d: continue
++ if d['mem'] != 0: raise AnchorError(f'an address in memory region {d["mem"]} (not the main NSO) cannot be anchored')
++ if d['op'] == 0xA and b.where(d['rel'], 1) in ('text', 'pad'): # only opcode 0 literals pass value_tokens / carry_write
++ raise AnchorError(f'a store of a register into the code at {hexu(d["rel"])}: its value is not a word the compiler can check')
++ # a store at base + a register the cheat sets: only the base is anchored. The VM always adds the offset
++ # register, r0 included, so r0 counts once the cheat writes it; another register counts whenever the cheat
++ # changes any (all enabled cheats run as one program, so another cheat may have set it)
++ indexed = d['op'] == 0 and ((d['reg'] and regs) or (d['reg'] == 0 and 0 in written))
++ if indexed and b.where(d['rel'], 1) not in DATA_KINDS: raise AnchorError(f'a store into code at {hexu(d["rel"])} indexed by register {d["reg"]}')
++ store = d['op'] == 0 and not indexed
++ tokens[i + 1] = '{' + addr_expr(d['rel'], d['width'] if store else 1, store=store) + '}'
++ words[i] &= ~(0xFF if d['bits'] == 40 else 0xF) # the template keeps the address bits of the first word zero
++ if store and b.where(d['rel'], d['width']) in ('text', 'pad'):
++ for k, v in enumerate(value_tokens(d)):
++ if ':' in v: tokens[value_index(i, d['width'], k)] = '{' + v + '}'
++ return {'code': format_words(words, ins, tokens)}
++
++
++def adrp_paired(word_at, a, w):
++ """The offset of an adrp up to LOOKBACK words before text offset a whose page the word w written at a would use
++ (an add / ldr / str with the adrp's register as base, nothing between them writing that register or branching),
++ or None. Such a w holds the low 12 bits of a data address on the build it was written for; the data can move inside
++ its page while the code around it does not, so w is never carried as written. word_at(off) reads the build."""
++ for p in range(max(0, a - 4 * LOOKBACK), a, 4):
++ u = word_at(p)
++ if u & 0x9f000000 != 0x90000000 or adrp_user_lo(w, u & 31) is None: continue
++ if not any(ends_pairing(word_at(j), u & 31) for j in range(p + 4, a, 4)): return p
++ return None
++
++
++def registers_written(words, ins):
++ """The VM registers a program may write: the R field (bits 16-19) of opcodes 3 (loop counter), 4, 5, 7, 9 and of
++ 6 / A (their incrementing forms), and every register for C1-C3 (save, restore, static registers)."""
++ out = set()
++ for i, d in ins:
++ if d['op'] in (3, 4, 5, 6, 7, 9, 0xA): out.add((words[i] >> 16) & 0xF)
++ elif d['op'] in (0xC1, 0xC2, 0xC3): out.update(range(16))
++ return out
++
++
++def same_function_branch(build, w, a, t):
++ """True when w, written at text offset a, is a conditional branch (B.cond, CBZ / CBNZ, TBZ / TBNZ: no token form)
++ whose target t lies in the unwind function that holds a, and that function has a fingerprint or a body digest.
++ A match by either implies the same layout, so the offset stays right wherever the function moves; compile writes
++ it only when the site's function was found that way, not by its window (Compiler._check_pc_relative)."""
++ if not is_conditional_branch(w): return False
++ f = build.func_at(a)
++ if f is None or not f <= t < build.mod.functions[f]: return False
++ return build.digest(f, 'fp') is not None or build.digest(f, 'body') is not None
++
++
++def pair_on_off(cheats):
++ """Merge "<name> - on" / "<name> - off" patches into one patch cheat when the off entry puts back exactly the original
++ words of the code sites the on entry changes (its cave writes need no restore). The merged cheat keeps both names
++ (on_name / off_name) and their order (off_first), so the compiled file has the same two entries in the same order and
++ the saved toggles stay valid, and each entry's master flag ({name}: always on): master, off_master."""
++ by = {}
++ for i, c in enumerate(cheats):
++ m = ON_OFF.match(c['name'])
++ if m and 'patch' in c: by.setdefault(m.group(1).strip().lower(), {})[m.group(2).lower()] = i
++ drop = set()
++ for two in by.values():
++ if set(two) != {'on', 'off'}: continue
++ on, off = cheats[two['on']], cheats[two['off']]
++ changed = {w['at'] for w in on['patch'] if not w['at'].startswith('cave') and not w.get('same')}
++ if not changed or {w['at'] for w in off['patch']} != changed or not all(w.get('same') for w in off['patch']): continue
++ m = ON_OFF.match(on['name']); assert m # matched when `by` was built
++ merged = {'name': m.group(1).strip(), 'on_name': on['name'], 'off_name': off['name']}
++ if on.get('master'): merged['master'] = True
++ if off.get('master'): merged['off_master'] = True # an optional key: the off entry keeps its own flag
++ if two['off'] < two['on']: merged['off_first'] = True
++ merged['patch'] = on['patch']
++ first, second = sorted((two['on'], two['off']))
++ cheats[first] = merged; drop.add(second)
++ return [c for i, c in enumerate(cheats) if i not in drop]
++
++
++# ---------- the source file (TOML) ----------
++
++def toml_str(s):
++ """A TOML basic string; control characters (which TOML forbids raw) as \\uXXXX escapes."""
++ s = s.replace('\\', '\\\\').replace('"', '\\"').replace('\n', '\\n').replace('\t', '\\t')
++ return '"' + re.sub(r'[\x00-\x1f\x7f]', lambda m: f'\\u{ord(m.group()):04X}', s) + '"'
++
++
++def toml_key(k):
++ """A TOML key: bare when it can be, quoted otherwise."""
++ return k if re.fullmatch(r'[A-Za-z0-9_-]+', k) else toml_str(k)
++
++
++def toml_value(v, key=''):
++ """A TOML value: offsets and sizes in hex (keys at, use, size, pad), code as a multi-line string."""
++ if isinstance(v, bool): return 'true' if v else 'false'
++ if isinstance(v, int): return hexu(v) if key in ('at', 'use', 'size', 'pad') else str(v)
++ if isinstance(v, float): return repr(v)
++ if isinstance(v, str):
++ if '\n' in v and not re.search(r'[\x00-\x09\x0b-\x1f\x7f]', v): # code: hex words, tokens and newlines only
++ # every quote escaped: escaping only '"""' leaves a run of four or more (or one before the closing
++ # delimiter) that TOML reads as the end of the string; a malformed cheat's stray token can hold any
++ return '"""\n' + v.replace('\\', '\\\\').replace('"', '\\"') + '"""'
++ return toml_str(v)
++ if isinstance(v, list):
++ if v and all(isinstance(x, dict) for x in v): return '[\n' + ''.join(f' {toml_value(x)},\n' for x in v) + ']'
++ return '[' + ', '.join(toml_value(x) for x in v) + ']'
++ if isinstance(v, dict): return '{ ' + ', '.join(f'{toml_key(k)} = {toml_value(x, k)}' for k, x in v.items()) + ' }'
++ raise TypeError(v)
++
++
++def write_toml(src, path, origin):
++ """Write the anchored source: a header comment, the top keys, the cheats in file order, then the anchors."""
++ out = [f'# Version-independent cheats for nxnative (scripts/cheat_anchor.py, format {FORMAT}).',
++ f'# Imported from {origin} on {TODAY} with the code of build {src["authored"]}. Compile it for a build with',
++ '# cheat_anchor.py compile <this file> --nso <that build\'s ExeFS/main> -o <cheats folder>',
++ '# The anchors at the end are the tool\'s; the cheats can be edited (names, sections, notes, values, "ask").', '']
++ for k in ('format', 'title', 'authored'):
++ if src.get(k, '') != '': out.append(f'{k} = {toml_value(src[k])}')
++ if src.get('builds'):
++ out += ['', '[builds]'] + [f'{toml_key(k)} = {toml_value(v)}' for k, v in src['builds'].items()]
++ for c in src['cheats']:
++ out += ['', '[[cheats]]'] + [f'{toml_key(k)} = {toml_value(v, k)}' for k, v in c.items()]
++ for name, a in src['anchors'].items():
++ out += ['', f'[anchors.{toml_key(name)}]'] + [f'{toml_key(k)} = {toml_value(v, k)}' for k, v in a.items()]
++ Path(path).write_text('\n'.join(out) + '\n', encoding='utf-8')
++
++
++# ---------- compile: resolving anchors on a target build ----------
++
++class Resolver:
++ """The anchors of a source resolved on one build: name -> (main offset, how), cached, failures cached too."""
++
++ def __init__(self, anchors, build):
++ """Resolve the anchors table of a source on build, lazily."""
++ self.a, self.b, self.done = anchors, build, {}
++
++ def resolve(self, name):
++ """(main offset, how) of the named anchor; AnchorError (naming the anchor) when it cannot be resolved."""
++ if name not in self.done:
++ try: self.done[name] = self._resolve(name)
++ except AnchorError as e: self.done[name] = AnchorError(f'anchor {name}: {e}')
++ except (KeyError, ValueError, TypeError) as e: self.done[name] = AnchorError(f'anchor {name}: malformed in the source ({e!r})')
++ r = self.done[name]
++ if isinstance(r, AnchorError): raise r
++ return r
++
++ def _resolve(self, name):
++ """One anchor by its kind: code, data or the cave."""
++ a = self.a.get(name)
++ if a is None: raise AnchorError('not defined in the source')
++ if 'code' in a: return self.code(a['code'])
++ if 'data' in a: return self.data(a)
++ if 'pad' in a:
++ base = self.b.ro_start - a['pad']
++ if base < self.b.text_end or base % 4: raise AnchorError(f'the cave ({hexu(a["pad"])} bytes before the read-only data) does not fit in the padding after the text')
++ return base, 'cave'
++ raise AnchorError('has no code, data or pad key')
++
++ def _window_sites(self, loc):
++ """The sites the locator's window finds in this build, or None when the window was not unique on its own build."""
++ if not loc.get('wunique'): return None
++ return [h + 4 * loc['wat'] for h in self.b.window_find([int(x, 16) for x in loc['window'].split()], loc['wkey'])]
++
++ def code(self, loc, verify=True):
++ """The site of a code locator and how it was found. By function fingerprint, then body digest, then the unique
++ window; the first way that finds candidates of the right count decides (a word mismatch there is an error,
++ never a reason to try the next way). Among identical copies the one at the same position in address order is
++ taken: confirmed when the window finds it too, an error when the window finds another one, otherwise reported as
++ weak. verify checks the original words (_check_words)."""
++ b, old = self.b, [int(x, 16) for x in loc['old'].split()]
++ for kind in ('fp', 'body'):
++ if kind not in loc: continue
++ idx, cnt = loc.get(kind + '_copy', [0, 1])
++ same = b.same(loc['size'], loc[kind], kind)
++ if len(same) != cnt: continue
++ site, how = same[idx] + loc['at'], 'exact' if kind == 'fp' else 'body'
++ if cnt > 1:
++ w = self._window_sites(loc)
++ if w is not None and len(w) == 1 and w[0] != site:
++ raise AnchorError(f'identical copies: copy {idx + 1} of {cnt} by order is {hexu(site)}, its window says {hexu(w[0])}')
++ how += f', copy {idx + 1} of {cnt} ' + ('confirmed by its window' if w is not None and len(w) == 1 else 'by order: weak')
++ if verify: self._check_words(loc, site, old)
++ return site, how
++ w = self._window_sites(loc)
++ if w is not None:
++ if len(w) == 1:
++ if verify: self._check_words(loc, w[0], old)
++ return w[0], 'window'
++ raise AnchorError(f'its function is not in this build and {len(w)} places match its instruction window (need exactly one)')
++ raise AnchorError('its function is not in this build and it has no unique instruction window')
++
++ def _check_words(self, loc, site, old):
++ """The site must hold the authored original words: raw, or, when only relocation bits differ (an instruction that
++ moved with its function: a branch, an adrp, the low page bits after one), the same masked words as the authored
++ window. What may then be written over such a relocated word is decided by carry_write (Compiler.site_word)."""
++ b = self.b
++ if site < 0 or site + 4 * len(old) > b.text_end: raise AnchorError(f'code site {hexu(site)} is outside the text')
++ now = b.words(site, len(old))
++ if now == old: return
++ win, h = [int(x, 16) for x in loc.get('window', '').split()], loc.get('wat', 0)
++ if win and b.masked(site, len(old)) == win[h:h + len(old)]: return
++ raise AnchorError(f'code site {hexu(site)}: the original words differ ({" ".join(f"{w:08X}" for w in now)}, expected {loc["old"]})')
++
++ def data(self, a):
++ """A data anchor: each reference resolved alone (each site counted once) and decoded as an adrp pair; with deref,
++ each slot it computes followed through its relative relocation. At least two results must agree (one when the
++ anchor has one reference) and none may disagree. A reference found among identical copies by order alone
++ counts for the address, but when fewer than that many strong references agree the anchor is marked weak."""
++ got, seen, slots, weak = {}, set(), set(), {}
++ for loc in a['data']:
++ try: site, tier = self.code(loc, verify=False)
++ except AnchorError: continue
++ if site in seen: continue
++ seen.add(site)
++ addr = self.b.pair_at(site, site + loc['use'])
++ if addr is None: continue
++ if a.get('deref'):
++ slot, addr = addr, self.b.relocs().get(addr)
++ if addr is None: continue # a slot without a relative relocation: this reference counts as missing
++ slots.add(slot)
++ got.setdefault(addr, []).append(tier.split(',')[0])
++ if 'weak' in tier: weak[addr] = weak.get(addr, 0) + 1 # "copy k of n by order: weak": kept apart from the tier
++ n = len(a['data'])
++ if not got: raise AnchorError(f'none of its {n} code references was found')
++ if len(got) > 1: raise AnchorError('its code references disagree: ' + ', '.join(f'{hexu(k)} ({len(v)})' for k, v in got.items()))
++ (addr, tiers), = got.items()
++ if len(tiers) < min(2, n): raise AnchorError(f'only 1 of its {n} code references was found (need 2)')
++ how = f'{len(tiers)}/{n} refs (' + ', '.join(f'{tiers.count(t)} {t}' for t in ('exact', 'body', 'window') if t in tiers) + ')'
++ if n == 1: how += ', weak: one reference'
++ elif len(tiers) - weak.get(addr, 0) < 2: how += f', weak: {weak[addr]} of them identical copies by order'
++ if slots: how += ' through the slot' + ('s ' if len(slots) > 1 else ' ') + ', '.join(hexu(s) for s in sorted(slots))
++ return addr, how
++
++
++OFFSET = re.compile(r'\s*([+-])\s*(?:0[xX]([0-9A-Fa-f]+)|(\d+))')
++
++
++def parse_expr(s):
++ """An address expression: NAME | main | heap | [EXPR], each followed by +/- offsets (hex 0x..., or decimal). Returns
++ ('name', name, off) or ('deref', inner, off) (the value read at inner, plus off)."""
++ def term(i):
++ """One term from position i: (node, the position after it and its offsets)."""
++ m = re.compile(r'\s*(?:(\[)|([A-Za-z_][A-Za-z0-9_]*))').match(s, i)
++ if not m: raise AnchorError(f'bad address "{s}"')
++ if m.group(1):
++ inner, i = term(m.end())
++ m2 = re.compile(r'\s*\]').match(s, i)
++ if not m2: raise AnchorError(f'bad address "{s}": missing ]')
++ kind, val, i = 'deref', inner, m2.end()
++ else: kind, val, i = 'name', m.group(2), m.end()
++ off = 0
++ while (m := OFFSET.match(s, i)):
++ n = int(m.group(2), 16) if m.group(2) is not None else int(m.group(3), 10)
++ off += n if m.group(1) == '+' else -n; i = m.end()
++ return (kind, val, off), i
++ node, i = term(0)
++ if s[i:].strip(): raise AnchorError(f'bad address "{s}"')
++ return node
++
++
++TYPES = {'u8': (1, 'B'), 'u16': (2, 'H'), 'u32': (4, 'I'), 'u64': (8, 'Q'), 's8': (1, 'b'), 's16': (2, 'h'),
++ 's32': (4, 'i'), 's64': (8, 'q'), 'f32': (4, 'f'), 'f64': (8, 'd')}
++
++
++class Compiler:
++ """Compiles the cheats of a source for one build into Atmosphère entries: (name, master, [words], meta row). Warnings
++ that do not stop a cheat (rewritten words, Atmosphère's size limit) collect in self.warnings."""
++
++ def __init__(self, src, build, plain):
++ """Compile src for build; plain writes patches without their guards."""
++ self.src, self.b, self.plain, self.warnings = src, build, plain, []
++ self.r = Resolver(src.get('anchors', {}), build)
++
++ def addr(self, node, cheat):
++ """(region, offset, how) of a static address node: region 0 main, 1 heap. A fixed main / heap address is valid
++ only when the cheat's builds name this build; a main address must lie in the image, a heap one in 40 bits; a
++ data anchor plus its field offset must stay in the anchor's segment."""
++ kind, name, off = node
++ if kind == 'deref': raise AnchorError('a pointer chain is not allowed here')
++ if name in ('main', 'heap'):
++ if self.b.build_id not in cheat.get('builds', []):
++ raise AnchorError(f'a fixed {name} address is valid only on the builds the cheat lists ({", ".join(cheat.get("builds", [])) or "none"})')
++ region, addr, how = (0 if name == 'main' else 1), off, 'fixed'
++ else:
++ base, how = self.r.resolve(name)
++ region, addr = 0, base + off
++ # a field never leaves its object's segment: an anchor in .rodata with an offset into .data (sources written
++ # before import kept bases in the target's segment) would land elsewhere once .rodata grows
++ if 'data' in self.src.get('anchors', {}).get(name, {}) and self.b.where(base) != self.b.where(addr):
++ raise AnchorError(f'{name}{"+" if off >= 0 else "-"}{hexu(abs(off))} crosses from {self.b.where(base)} into {self.b.where(addr)}: '
++ 'a field offset never leaves its anchor\'s segment')
++ if not (0 <= addr < (len(self.b.img) if region == 0 else 1 << REGION_BITS)):
++ raise AnchorError(f'address {hexu(addr)} is outside the {"main NSO image" if region == 0 else "region"}')
++ return region, addr, how
++
++ def code_words(self, text, cheat):
++ """The words of a code template: {EXPR} address tokens (the second word of an instruction with a region-relative
++ address, whose first word keeps the address bits zero) and {bl:EXPR} / {b:EXPR} value tokens of opcode 0 stores.
++ A store into the code or the cave goes through site_word, the rules patches follow, whatever gates it. A program
++ the decoder cannot read has no tokens to fill: it is kept verbatim on the builds its cheat names, else refused."""
++ words, special, how = [], {}, set()
++ for t in re.findall(r'\{[^}]*\}|[0-9A-Fa-f]{8}|\S+', text):
++ if t.startswith('{'): special[len(words)] = t[1:-1].strip(); words.append(0)
++ elif re.fullmatch(r'[0-9A-Fa-f]{8}', t): words.append(int(t, 16))
++ else: raise AnchorError(f'"{t}" is not a code word')
++ try: decode_all(words)
++ except AnchorError:
++ if special or self.b.build_id not in cheat.get('builds', []): raise
++ return words, {'fixed, kept verbatim (not decoded)'}
++ i = 0
++ while i < len(words):
++ d, node = decode(words, i), None
++ if i + 1 in special and ':' not in special[i + 1]:
++ if 'bits' not in d: raise AnchorError(f'word {i + 1}: an address token where {words[i]:08X} has no address')
++ node = parse_expr(special.pop(i + 1))
++ region, off, h = self.addr(node, cheat); how.add(h)
++ if region != d['mem']: raise AnchorError(f'word {i + 1}: the address is in another region than {words[i]:08X} names')
++ if not 0 <= off < 1 << d['bits']: raise AnchorError(f'word {i + 1}: address {hexu(off)} does not fit')
++ words[i] = (words[i] & ~(0xFF if d['bits'] == 40 else 0xF)) | (off >> 32); words[i + 1] = off & 0xffffffff
++ d = decode(words, i)
++ if d['op'] == 0:
++ tokens = set()
++ for k in range(len(mem_words(d['width'], 0))):
++ j = value_index(i, d['width'], k)
++ if j in special and ':' in special[j]:
++ link, expr = special.pop(j).split(':', 1)
++ if link not in ('b', 'bl') or d['width'] < 4: raise AnchorError(f'word {j}: bad token "{link}:"')
++ region, target, h = self.addr(parse_expr(expr), cheat); how.add(h)
++ words[j] = encode_branch(link == 'bl', d['rel'] + 4 * k, target); tokens.add(j)
++ if node is not None and d['mem'] == 0: self._store_values(node, d, i, words, tokens)
++ if d['op'] == 1 and node is not None and d['mem'] == 0: self._compare_values(node, d, i, words)
++ i += d['n']
++ if special: raise AnchorError(f'word {min(special)}: a token where none can stand')
++ return words, how
++
++ def _store_values(self, node, d, i, words, tokens):
++ """Apply site_word to the value words (in place) of the anchored opcode 0 store d at word i of a template, for
++ each of its 4-byte memory words that lies in the code or the cave; tokens are the indexes already re-encoded."""
++ for k in range(len(mem_words(d['width'], 0))):
++ a, width, j = d['rel'] + 4 * k, min(d['width'], 4), value_index(i, d['width'], k)
++ if self.b.where(a, width) in ('text', 'pad'): words[j] = self.site_word(node, a, width, words[j], j in tokens)
++
++ def _compare_values(self, node, d, i, words):
++ """Map the value words (in place) of the anchored opcode 1 compare d at word i the way a restore is mapped: a
++ 4-byte memory word of the code compared with its authored original is compared with this build's word, so an
++ "if [X] == original" gate still opens where that instruction moved. Other values, and words outside the code
++ anchor's verified words, are left as written (a compare only gates; it writes nothing)."""
++ width = (words[i] >> 24) & 0xF
++ if width < 4: return
++ for k in range(width // 4):
++ a, j = d['rel'] + 4 * k, value_index(i, width, k)
++ if self.b.where(a, 4) != 'text': continue
++ try: authored = self._site_old(node, a, 4)
++ except AnchorError: continue # beyond the anchored words: nothing recorded to map from
++ if words[j] == authored: words[j] = self.b.word(a)
++
++ def value(self, cheat, v):
++ """(width, the value as an unsigned integer) of a data cheat's value in its type."""
++ t = cheat.get('type', 'u32')
++ if t not in TYPES: raise AnchorError(f'unknown type "{t}"')
++ width, fmt = TYPES[t]
++ try: raw = struct.pack('<' + fmt, float(v) if fmt in 'fd' else int(v))
++ except (struct.error, ValueError, TypeError) as e: raise AnchorError(f'value {v!r} does not fit {t}') from e
++ return width, int.from_bytes(raw, 'little')
++
++ def data(self, cheat):
++ """The program of a data cheat (freeze, set, min, max), how it resolved, and its meta (where its value words are,
++ the static target as region:offset). never-decrease has no Atmosphère program: Atmosphère's VM keeps no state of
++ a cheat between passes, so nxnative's host runs it from the meta row (type and address) and the .txt holds an
++ empty entry of that name, which other engines show as an inert label."""
++ action, v = cheat.get('action', 'freeze'), cheat.get('value', 0)
++ ask = v == 'ask'
++ if ask: v = cheat.get('default', cheat.get('min', 0))
++ width, val = self.value(cheat, v)
++ vw = [val >> 32, val & 0xffffffff] if width == 8 else [val] # as Atmosphère writes a value: high word first
++ node = parse_expr(cheat['target'])
++ meta = {'type': cheat.get('type', 'u32'), 'action': action, 'value': str(v)}
++ if ask: meta['ask'] = f'{cheat.get("min", "")}..{cheat.get("max", "")}'
++ if action == 'never-decrease':
++ if node[0] == 'deref': raise AnchorError('never-decrease through a pointer chain is not supported yet')
++ region, off, how = self.addr(node, cheat)
++ meta.update(address=f'{region}:{hexu(off)}', value='')
++ return [], how + '; nxnative only: the host keeps the highest value, other engines see an empty entry', meta
++ if action in ('freeze', 'set'):
++ if node[0] == 'deref': words, how = self.chain(node, width, vw, cheat)
++ else:
++ region, off, how = self.addr(node, cheat)
++ words = [width << 24 | region << 20 | off >> 32, off & 0xffffffff] + vw
++ meta['value_words'] = ','.join(str(2 + k) for k in range(len(vw)))
++ meta['address'] = f'{region}:{hexu(off)}'
++ if action == 'set': meta['once'] = '1'
++ return words, how, meta
++ if action in ('min', 'max'):
++ if node[0] == 'deref': raise AnchorError(f'"{action}" through a pointer chain needs a register conditional (C0), not supported yet')
++ if cheat.get('type', 'u32')[0] in 'sf': # opcode 1 compares unsigned: a negative value in memory would compare huge
++ raise AnchorError(f'"{action}" compares unsigned (Atmosphère\'s opcode 1): only unsigned types')
++ region, off, how = self.addr(node, cheat)
++ cond = 3 if action == 'min' else 1 # min: raise it when below (<); max: lower it when above (>)
++ hi, lo = off >> 32, off & 0xffffffff
++ words = [0x10000000 | width << 24 | region << 20 | cond << 16 | hi, lo] + vw + [width << 24 | region << 20 | hi, lo] + vw + [0x20000000]
++ meta['value_words'] = ','.join(str(k) for k in [*range(2, 2 + len(vw)), *range(4 + len(vw), 4 + 2 * len(vw))])
++ meta['address'] = f'{region}:{hexu(off)}'
++ return words, how, meta
++ raise AnchorError(f'action "{action}" is not supported by this version of the tool')
++
++ def chain(self, node, width, vw, cheat):
++ """A freeze through a pointer chain [..[base]+o1..]+o: while the first pointer is not 0, load it, follow each
++ level, add the last offset, store, then zero register 15 again (dmnt runs all enabled cheats as one program, so a
++ register left set would shift a later cheat that adds it). Opcodes 1, 5, 7, 6, 4 and 2: all in the host's VM."""
++ levels = []
++ while node[0] == 'deref': levels.append(node[2]); node = node[1]
++ levels.reverse() # levels[i] is added after the (i + 1)-th load; the last one is the field offset
++ region, base, how = self.addr(node, cheat)
++ if any(not 0 <= o < 1 << 32 for o in levels): raise AnchorError('pointer chain offsets must be 0 .. 0xFFFFFFFF')
++ hi, lo = base >> 32, base & 0xffffffff
++ words = [0x18060000 | region << 20 | hi, lo, 0, 0] # if u64 [region + base] != 0
++ words += [0x580F0000 | region << 20 | hi, lo] # r15 = u64 [region + base]
++ for o in levels[:-1]: words += [0x580F1000, o] # r15 = u64 [r15 + o]
++ if levels[-1]: words += [0x780F0000, levels[-1]] # r15 += o
++ words += [0x600F0000 | width << 24] + [0] * (2 - len(vw)) + vw # [r15] = value (two value words)
++ words += [0x400F0000, 0, 0] # r15 = 0
++ return words + [0x20000000], how # end of the "not 0" block
++
++ def _site_old(self, node, a, width):
++ """The authored original aligned word that holds a store of width bytes at a into the code, from its code
++ anchor's recorded words. Raises AnchorError when [a, a + width) is not inside those words."""
++ name = node[1]
++ loc = self.src.get('anchors', {}).get(name, {}).get('code')
++ if loc is None: raise AnchorError(f'patch word at {hexu(a)} is in the code but "{name}" is not a code anchor')
++ base, _ = self.r.resolve(name)
++ old = b''.join(struct.pack('<I', int(x, 16)) for x in loc['old'].split())
++ if not (base <= a and a + width <= base + len(old)): raise AnchorError(f'patch word at {hexu(a)} is outside the verified words of {name}')
++ return int.from_bytes(old[(a & ~3) - base:(a & ~3) - base + 4], 'little') # code sites are whole aligned words
++
++ def site_word(self, node, a, width, new, token=False):
++ """The value a store of width bytes at a writes on this build: the one place where patches and code templates
++ (gated or not) learn what may be written. In the code: carry_write over a relocated original; then the whole
++ word the store makes (a 1- or 2-byte store's too), when it is not this build's own, must not be a new adrp user
++ (adrp_paired; allowed on the source's own build) and goes through _check_pc_relative. In the cave: a PC-relative
++ word must stay inside the cave. A fixed main address (the cheat names its builds) and a token (re-encoded for
++ this build) are written as they are. AnchorError when refused."""
++ if node[1] == 'main' or token: return new
++ where, a4 = self.b.where(a, width), a & ~3
++ sh, mask = 8 * (a & 3), (1 << 8 * width) - 1
++ if where == 'text':
++ authored, here = self._site_old(node, a, width), self.b.word(a4)
++ got = carry_write(authored, here, new, a, width)
++ if got is None:
++ raise AnchorError(f'the word at {hexu(a4)} is relocated in this build ({here:08X}, was {authored:08X}): '
++ 'the new word would keep the old build\'s address bits')
++ made = here & ~(mask << sh) | got << sh
++ if made != here:
++ p = adrp_paired(self.b.word, a4, made)
++ if p is not None and self.b.build_id != self.src.get('authored'):
++ raise AnchorError(f'the word {made:08X} written at {hexu(a4)} takes the page of the adrp at {hexu(p)}: '
++ 'its low page bits hold for the source\'s own build only')
++ self._check_pc_relative(node, a4, made)
++ return got
++ if where == 'pad':
++ made = self.b.word(a4) & ~(mask << sh) | new << sh
++ t = pc_relative_target(made, a4)
++ if t is not None and self.b.where(t) != 'pad': # the cave moves as one block: only offsets inside it hold
++ raise AnchorError(f'the word {made:08X} written at {hexu(a4)} in the cave is PC-relative to {hexu(t)}, outside the cave')
++ return new
++
++ def _check_pc_relative(self, node, a, w):
++ """Refuse the PC-relative word w written at a when its target may not be the authored one. Its offset holds
++ when the target lies in the same code anchor's words (they move together; not for an adrp, whose page depends
++ on the page of its own address), or, for a branch, in the site's function found by fingerprint or body digest
++ (the same layout). A function found by its window proves only the words around the site, so then it is refused."""
++ t = pc_relative_target(w, a)
++ if t is None: return
++ loc, (site, how) = self.src['anchors'][node[1]]['code'], self.r.resolve(node[1])
++ if site <= t < site + 4 * len(loc['old'].split()) and w & 0x9f000000 != 0x90000000: return
++ start = site - loc.get('at', 0)
++ if (branch_target(w, a) is not None or is_conditional_branch(w)) and 'size' in loc and how.startswith(('exact', 'body')) \
++ and start <= t < start + loc['size']: return
++ raise AnchorError(f'the word {w:08X} written at {hexu(a)} is PC-relative to {hexu(t)}: its offset is right only inside its own '
++ 'function found by fingerprint or body digest' + (f' (found here by {how})' if 'size' in loc else ''))
++
++ def patch(self, cheat):
++ """The on and off programs of a patch. Per word: "if it still holds this build's original, write the new word"
++ (--plain: just write it); a word equal to the original is written plainly; off puts the originals back where the
++ new words are. Cave words need zeros there in this build; code words must lie inside their verified site, and
++ site_word decides what may be written over a relocated or PC-relative word. Words the rewriter changed are
++ reported: the guard leaves them, so a patch that changes other words too is refused whole (the guard would
++ apply a partial hook, the cave and the branch to it without the rest, or half of a two-word change)."""
++ on, off, how, rewritten, changed = [], [], set(), [], 0
++ for w in cheat['patch']:
++ if 'at' not in w or 'new' not in w: raise AnchorError('a patch item needs at and new')
++ node = parse_expr(w['at'])
++ region, base, h = self.addr(node, cheat); how.add(h)
++ if region != 0: raise AnchorError('a patch writes into the main NSO only')
++ width = w.get('width', 4)
++ if width not in (1, 2, 4): raise AnchorError(f'patch width {width}')
++ for k, v in enumerate(w['new'].split()):
++ a = base + width * k
++ where = self.b.where(a, width)
++ if where not in ('text', 'pad'): raise AnchorError(f'patch address {hexu(a)} is neither code nor the cave')
++ orig = int.from_bytes(self.b.img[a:a + width], 'little')
++ token = ':' in v
++ if token:
++ link, expr = v.split(':', 1)
++ if width != 4 or link not in ('b', 'bl'): raise AnchorError(f'bad token "{v}"')
++ new = encode_branch(link == 'bl', a, self.addr(parse_expr(expr), cheat)[1])
++ else:
++ try: new = int(v, 16)
++ except ValueError as e: raise AnchorError(f'"{v}" is not a hex word') from e
++ if where == 'pad' and orig: raise AnchorError(f'the cave at {hexu(a)} is not free in this build')
++ new = self.site_word(node, a, width, new, token)
++ rw = self.b.rewritten(a, width)
++ if rw is not None and int.from_bytes(rw, 'little') != orig:
++ rewritten.append((a, rw, new != orig))
++ self.warnings.append(f'warning: "{cheat["name"]}": the rewriter changed the word at {hexu(a)} ({rw[::-1].hex().upper()}): '
++ + ('--plain overwrites the rewritten instruction' if self.plain else 'the guard leaves it, so the cheat has no effect there'))
++ hi, lo = a >> 32, a & 0xffffffff
++ store = [width << 24 | hi, lo, new]
++ if new == orig: on += store; continue
++ changed += 1
++ on += store if self.plain else [0x10050000 | width << 24 | hi, lo, orig] + store + [0x20000000] # if [a] == orig
++ if where == 'text':
++ back = [width << 24 | hi, lo, orig]
++ off += back if self.plain else [0x10050000 | width << 24 | hi, lo, new] + back + [0x20000000] # if [a] == new
++ skipped = [a for a, _, changes in rewritten if changes]
++ if skipped and changed > 1 and not self.plain:
++ raise AnchorError(f'the rewriter changed the word at {hexu(skipped[0])}: its guard would skip it and apply the other '
++ f'{changed - 1} changed word{"s" if changed > 2 else ""} alone (a partial hook); --plain writes them all')
++ return on, off, how
++
++ def cheat(self, c):
++ """[(name, master, words, meta)] for one cheat (two for a patch with an off entry, in the source's order)."""
++ base = {'section': c.get('section', ''), 'note': c.get('note', '')}
++ master = bool(c.get('master'))
++ if c.get('label'): return [(c['name'], master, [], dict(base, kind='label'))]
++ if 'patch' in c:
++ on, off, how = self.patch(c)
++ on_name = c.get('on_name', c['name'])
++ off_name = c.get('off_name') or (f'{c["name"]} - off' if c.get('restore') else '')
++ out = [(on_name, master, on, dict(base, kind='patch', pair=off_name, how=summary(how)))]
++ if off_name:
++ out.append((off_name, bool(c.get('off_master')), off, dict(base, kind='patch-off', pair=on_name, how=summary(how))))
++ if c.get('off_first'): out.reverse()
++ return out
++ if 'code' in c:
++ words, how = self.code_words(c['code'], c)
++ return [(c['name'], master, words, dict(base, kind='code', how=summary(how)))]
++ if 'target' in c:
++ words, how, meta = self.data(c)
++ return [(c['name'], master, words, dict(base, kind='data', how=summary({how}), **meta))]
++ raise AnchorError('a cheat needs target, patch, code or label')
++
++
++def summary(how):
++ """How the anchors of one cheat were resolved, for the report and the meta file."""
++ return '; '.join(sorted(h for h in how if h)) or 'no anchors'
++
++
++def compile_source(src_path, build, plain=False):
++ """(the source, [(name, master, words or None when skipped, meta)], report lines, skipped count) for one build."""
++ try: src = tomllib.loads(Path(src_path).read_text(encoding='utf-8'))
++ except (OSError, tomllib.TOMLDecodeError) as e: raise AnchorError(f'{Path(src_path).resolve()}: {e}') from e
++ if src.get('format') != FORMAT: raise AnchorError(f'{Path(src_path).resolve()}: format {src.get("format")!r}, this tool reads {FORMAT}')
++ comp = Compiler(src, build, plain)
++ entries, report, skipped = [], [], 0
++ for c in src.get('cheats', []):
++ if 'name' not in c: raise AnchorError(f'{Path(src_path).resolve()}: a cheat without a name')
++ try:
++ if c.get('builds') and build.build_id not in c['builds']: raise AnchorError(f'written for build {", ".join(c["builds"])} only')
++ try: got = comp.cheat(c)
++ except (KeyError, ValueError, TypeError) as e: raise AnchorError(f'malformed in the source ({e!r})') from e
++ except AnchorError as e:
++ report.append(f'[RED] "{c["name"]}" skipped: {e}'); skipped += 1
++ entries.append((c['name'], False, None, {'kind': 'unresolved', 'section': c.get('section', ''), 'note': str(e)}))
++ continue
++ entries += got
++ if not c.get('label'): report.append(f'ok "{c["name"]}": {got[0][3].get("how", "")}')
++ for name, _, words, _ in got: # dmnt refuses a cheat over 0x100 words (this host takes 0x2000); guards make patches longer
++ if len(words) > ATMOSPHERE_WORDS:
++ report.append(f'warning: "{name}" has {len(words)} words, over the {ATMOSPHERE_WORDS} a Switch accepts per cheat'
++ + (' (--plain drops the guards)' if 'patch' in c and not plain else ''))
++ weak = [e[0] for e in entries if 'weak' in e[3].get('how', '')]
++ if weak: report.append(f'warning: {len(weak)} entries resolved weakly (one reference, or identical copies by order): ' + ', '.join(f'"{n}"' for n in weak))
++ return src, entries, report + comp.warnings, skipped
++
++
++def render(entries):
++ """The Atmosphère text of the compiled entries, one instruction per line, with EdiZon's section pseudo-cheats
++ ([--SectionStart:Name--] ... [--SectionEnd:Name--]) around each run of one section; skipped cheats are left out."""
++ out, cur = [], ''
++ for name, master, words, meta in entries + [('', False, None, {'section': ''})]:
++ sec = meta.get('section', '')
++ if sec != cur:
++ if cur: out.append(f'[--SectionEnd:{cur}--]\n\n')
++ if sec: out.append(f'[--SectionStart:{sec}--]\n\n')
++ cur = sec
++ if words is None: continue
++ out.append(('{' + name + '}' if master else '[' + name + ']') + '\n')
++ try: out.append(format_words(words, decode_all(words)))
++ except AnchorError: out.append(format_words(words)) # a program kept verbatim (Compiler.code_words): four words per line
++ out.append('\n')
++ return ''.join(out)
++
++
++META_HEAD = 'name\tkind\tsection\ttype\taction\tvalue\task\tvalue_words\tonce\tpair\tresolved\tnote\taddress' # the host reads it by column name
++META_FIRST = re.compile(r'# cheat_anchor\.py: compiled from (.*) for build ([0-9A-F]{16}) on ')
++META_HASH = re.compile(r'# txt sha256 ([0-9a-f]{64})$')
++
++
++def meta_text(src_name, build, entries, src, txt):
++ """The compiled file's companion: header lines naming the source, the .txt's SHA-256 (so a later compile can tell a
++ file it wrote from one edited since) and the builds' version names; then one row per entry, what the Mac panel can
++ show beside the plain Atmosphère text."""
++ out = [f'# cheat_anchor.py: compiled from {src_name} for build {build.build_id} on {TODAY}',
++ f'# txt sha256 {hashlib.sha256(txt.encode("utf-8")).hexdigest()}']
++ names = dict(src.get('builds', {}))
++ if build.version: names.setdefault(build.build_id, build.version)
++ out += [f'# build {k} {v}' for k, v in names.items()] + [META_HEAD]
++ for name, _, _, m in entries:
++ row = [name, m.get('kind', ''), m.get('section', ''), m.get('type', ''), m.get('action', ''), m.get('value', ''),
++ m.get('ask', ''), m.get('value_words', ''), m.get('once', ''), m.get('pair', ''), m.get('how', ''), m.get('note', ''),
++ m.get('address', '')]
++ out.append('\t'.join(str(x).replace('\t', ' ').replace('\n', ' ') for x in row))
++ return '\n'.join(out) + '\n'
++
++
++def ours(txt, meta, src_name):
++ """'' when txt is this tool's unchanged output of this source (its meta names the source and the .txt's hash still
++ matches), else why it is not."""
++ if not meta.is_file(): return 'no meta file of this tool beside it'
++ head = meta.read_text(encoding='utf-8', errors='replace').split('\n')[:2]
++ m1, m2 = META_FIRST.match(head[0]), META_HASH.match(head[1]) if len(head) > 1 else None
++ if not m1 or not m2: return 'its meta file is not this tool\'s'
++ if hashlib.sha256(txt.read_bytes()).hexdigest() != m2.group(1): return 'it was edited since it was compiled'
++ if m1.group(1) != src_name: return f'it was compiled from another source ({m1.group(1)})'
++ return ''
++
++
++def write_compiled(out_dir, src_path, build, entries, src, replace):
++ """Write <build>.txt and <build>.meta.tsv. A .txt that is not this tool's unchanged output of this source (hand-made,
++ edited, or another source's) is never overwritten: the output goes to <build>.txt.new, or with replace the old
++ file is kept as <build>.txt.orig."""
++ out_dir = Path(out_dir); out_dir.mkdir(parents=True, exist_ok=True)
++ txt, meta = out_dir / f'{build.build_id}.txt', out_dir / f'{build.build_id}.meta.tsv'
++ lines, why = [], ours(txt, meta, Path(src_path).name) if txt.exists() else ''
++ if why:
++ if replace:
++ orig = txt.with_name(txt.name + '.orig')
++ if orig.exists(): raise AnchorError(f'{orig.resolve()} already exists: move it away first')
++ txt.rename(orig); lines.append(f'kept the old file as {orig.resolve()} ({why})')
++ else:
++ lines.append(f'{txt.resolve()} is kept ({why}): the output goes to {txt.name}.new (--replace keeps the old one as .orig)')
++ txt, meta = txt.with_name(txt.name + '.new'), meta.with_name(meta.name + '.new')
++ text = render(entries)
++ txt.write_text(text, encoding='utf-8')
++ meta.write_text(meta_text(Path(src_path).name, build, entries, src, text), encoding='utf-8')
++ lines.append(f'wrote {txt.resolve()} and {meta.name}')
++ return lines
++
++
++def main(argv=None):
++ """The command line: import, compile or check (see the header); returns the exit status."""
++ ap = argparse.ArgumentParser(description='Anchor Atmosphère cheats to the game\'s code (import) and compile them for any build (compile, check).')
++ sub = ap.add_subparsers(dest='cmd', required=True)
++ p = sub.add_parser('import', help='an Atmosphère .txt into an anchored <game>.cheats.toml')
++ p.add_argument('txt'); p.add_argument('--nso', required=True, help='ExeFS/main of the build the file was written for')
++ p.add_argument('-o', required=True, help='the .cheats.toml to write'); p.add_argument('--force', action='store_true', help='overwrite an existing source')
++ p.add_argument('--assume-build', action='store_true', help='the file names another build: anchor it on this NSO anyway')
++ for name in ('compile', 'check'):
++ p = sub.add_parser(name, help='the anchored source into <build ID>.txt for the NSO\'s build' if name == 'compile' else 'compile without writing anything')
++ p.add_argument('src'); p.add_argument('--nso', required=True, help='ExeFS/main of the target build')
++ p.add_argument('--plain', action='store_true', help='patches as plain stores, without "still original?" guards (for build-time baking)')
++ if name == 'compile':
++ p.add_argument('-o', required=True, help='the cheats folder')
++ p.add_argument('--replace', action='store_true', help='replace a <build>.txt this tool did not write, kept as .orig')
++ a = ap.parse_args(argv)
++ try:
++ build = Build(a.nso)
++ if a.cmd == 'import':
++ if Path(a.o).exists() and not a.force: raise AnchorError(f'{Path(a.o).resolve()} exists (--force overwrites it)')
++ src, report, bound = import_file(a.txt, build, a.assume_build)
++ write_toml(src, a.o, Path(a.txt).name)
++ print('\n'.join(report + [f'wrote {Path(a.o).resolve()}']))
++ return 2 if bound else 0
++ src, entries, report, skipped = compile_source(a.src, build, a.plain)
++ if a.cmd == 'compile': report += write_compiled(a.o, a.src, build, entries, src, a.replace)
++ done = sum(1 for e in entries if e[2] is not None and e[3].get('kind') != 'label')
++ report.append(f'build {build.build_id}' + (f' ({build.version})' if build.version else '') + f': {done} entries compiled, {skipped} cheats skipped')
++ print('\n'.join(report))
++ return 2 if skipped else 0
++ except AnchorError as e:
++ print(f'[RED] {e}', file=sys.stderr)
++ return 1
++
++
++if __name__ == '__main__': sys.exit(main())
diff --git a/patches/0029-cheats-mac-panel.patch b/patches/0029-cheats-mac-panel.patch
new file mode 100644
index 00000000..fa34b008
--- /dev/null
+++ b/patches/0029-cheats-mac-panel.patch
@@ -0,0 +1,909 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Amost <[email protected]>
+Date: Thu, 29 Oct 2026 20:02:49 +0100
+Subject: [PATCH] Cheats: the Mac Cheats menu and panel
+
+The Cheats menu of the Mac game window and the floating Cheats panel
+(sections, search, master switch, values, import of cheat files) in
+dm/host/front_mac.m. Ported onto the pinned tree from seedds/nxnative#406.
+
+Upstream-Status: forwarded seedds/nxnative#406
+Reason: the launcher's cheat manager builds on its file contract until upstream merges it
+Issue: LNPANDY/NX2Apple#97
+
+---
+ dm/host/front_mac.m | 860 ++++++++++++++++++++++++++++++++++++++++++++
+ 1 file changed, 860 insertions(+)
+
+diff --git a/dm/host/front_mac.m b/dm/host/front_mac.m
+index 3df6394d..664b7753 100644
+--- a/dm/host/front_mac.m
++++ b/dm/host/front_mac.m
+@@ -1,6 +1,9 @@
+ // Mac front end: with DM_WINDOW=1 open a window (CAMetalLayer, for the graphics backend to present frames) + keyboard and controllers → dm_input; the guest runs on a large-stack thread instead and the main thread belongs to AppKit.
+ // Without DM_WINDOW: the guest runs directly on the current thread, behaving the same as with no front end (windowless tests use this).
+ // The window is fullscreen-capable (the green button and ⌃⌘F); DM_FULLSCREEN=1 starts it that way. ⌘Q quits; the left mouse button is the touchscreen.
++// Cheats (hle_cheats.c): the Cheats menu's rows toggle, reload (⌘R) and open the cheats folder; its first item "Show Cheats
++// Window" (⌘⇧C, or DM_CHEATS_WINDOW=1 at launch) opens a Cheats panel beside the game: sections, search, the master switch,
++// safe mode, values, details and the import of cheat files (see the code below).
+ // Key map (Nintendo layout): WASD left stick, arrow keys D-pad, J=A K=B U=X I=Y, Q=L E=R, Z=ZL C=ZR, F=press left stick G=press right stick, Return=+ Tab=−, Space=shake the controller;
+ // DM_KEYMAP moves a function to another key (the right stick too), DM_PAD_MAP changes what a controller's buttons send (input_map.h).
+ // Controllers: buttons by position as on the iPhone (right A, bottom B, top X, left Y), shoulders L R, triggers ZL ZR, Menu + Options −, both sticks and their presses.
+@@ -21,6 +24,7 @@
+ #include "motion_pro_mac.h"
+ #include <signal.h>
+ #include <math.h>
++#include <sys/stat.h>
+
+ static CAMetalLayer *g_layer;
+ static uint64_t g_btn;
+@@ -245,6 +249,850 @@ - (void)viewDidChangeBackingProperties { [super viewDidChangeBackingProperties];
+
+ // Metal reads MTL_HUD_ENABLED when the process makes its first device, which can be before the window: set from DM_METAL_HUD before main (set in front_run, the HUD did not show)
+ __attribute__((constructor)) static void hud_env(void) { front_hud_env(); }
++
++// ---------- Cheats: the menu and the panel (hle_cheats.c holds every state; these only show it and call it) ----------
++
++// A string of the engine as an NSString that is never nil: cheat names, sections and notes come from the player's files,
++// which may be Shift-JIS or Latin-1, and a UTF-8 name cut at the engine's buffer size may end in half a character. UTF-8
++// first, then UTF-8 without up to three trailing bytes, then Shift-JIS, then Windows-1252 (which decodes any byte)
++static NSString *engine_str(const char *s) {
++ if (!s) return @"";
++ size_t n = strlen(s);
++ for (size_t cut = 0; cut <= 3 && cut <= n; cut++) {
++ NSString *u = [[NSString alloc] initWithBytes:s length:n - cut encoding:NSUTF8StringEncoding];
++ if (u) return u;
++ }
++ return [[NSString alloc] initWithBytes:s length:n encoding:NSShiftJISStringEncoding]
++ ?: [[NSString alloc] initWithBytes:s length:n encoding:NSWindowsCP1252StringEncoding] ?: @"";
++}
++
++// A path quoted for the shell (single quotes; a quote inside becomes '\'')
++static NSString *shell_quote(NSString *p) { return [NSString stringWithFormat:@"'%@'", [p stringByReplacingOccurrencesOfString:@"'" withString:@"'\\''"]]; }
++
++// The name a row shows: the on half of an on / off pair loses its " - on" (the pair is one switch, its off half has no row)
++static NSString *cheat_display_name(int i) {
++ NSString *n = engine_str(dm_cheat_name_at(i));
++ if (!(dm_cheat_flags_at(i) & DM_CHEAT_PAIR_ON)) return n;
++ static NSRegularExpression *re;
++ if (!re) re = [NSRegularExpression regularExpressionWithPattern:@"(\\s*[-:_]\\s*|\\s+|\\s*[(\\[]\\s*)on\\s*[)\\]]?\\s*$" options:NSRegularExpressionCaseInsensitive error:nil];
++ NSString *base = [re stringByReplacingMatchesInString:n options:0 range:NSMakeRange(0, n.length) withTemplate:@""];
++ return base.length ? base : n;
++}
++
++// Does entry i get a row of its own? Not the off half of a pair (its on half is the switch) and not a section marker
++// (the section shows as a header above its entries)
++static BOOL cheat_has_row(int i) {
++ int f = dm_cheat_flags_at(i);
++ return !(f & (DM_CHEAT_PAIR_OFF | DM_CHEAT_SECTION_START | DM_CHEAT_SECTION_END));
++}
++
++// The row's whole title, the same string the menu's row carries: the name, plus the run-time reason when there is one,
++// "— master code (always on)" for a master code, "(nxnative only)" for a cheat this host runs itself (never-decrease)
++static NSString *cheat_row_title(int i) {
++ const char *why = dm_cheat_why_at(i);
++ int kind = dm_cheat_kind_at(i), f = dm_cheat_flags_at(i);
++ NSString *n = cheat_display_name(i);
++ if (kind == 1) return [n stringByAppendingString:@" — master code (always on)"];
++ if (why && *why) return [n stringByAppendingString:engine_str(why)];
++ if (f & DM_CHEAT_HOST) return [n stringByAppendingString:@" (nxnative only)"];
++ return n;
++}
++
++// The row's tooltip: the title, the meta file's note (how scripts/cheat_anchor.py compiled it), what a host-only or a
++// one-pass cheat does
++static NSString *cheat_row_tip(int i) {
++ NSMutableString *t = [cheat_row_title(i) mutableCopy];
++ int f = dm_cheat_flags_at(i);
++ const char *note = dm_cheat_note_at(i);
++ if (note && *note) [t appendFormat:@"\n%@", engine_str(note)];
++ if (f & DM_CHEAT_HOST) [t appendString:@"\nRun by nxnative itself: it keeps the highest value seen since it was turned on; other engines see an empty entry."];
++ if (f & DM_CHEAT_ONCE) [t appendString:@"\nApplied once: it writes one pass, then turns itself off."];
++ if (f & DM_CHEAT_PAIR_ON) [t appendString:@"\nSwitching it off puts the game's original code back."];
++ if (f & DM_CHEAT_WEAK) [t appendString:@"\nResolved weakly for this build: check its effect."];
++ return t;
++}
++
++// The row's state as hle_cheats.c has it: a plain cheat carries its own on state, a master code is always on, and a
++// disabled row (unsupported opcode, malformed, or killed at run time) or a label is off, its checkbox not clickable
++static NSControlStateValue cheat_row_state(int i) {
++ int kind = dm_cheat_kind_at(i);
++ return kind == 1 || (kind == 0 && dm_cheat_on_at(i)) ? NSControlStateValueOn : NSControlStateValueOff;
++}
++
++// A build's name for a player: "1.0.3 (build E1D8B399B787AE41)", or the build ID alone when its version is unknown
++static NSString *build_label(const char *bid, const char *ver) {
++ return ver && *ver ? [NSString stringWithFormat:@"%@ (build %@)", engine_str(ver), engine_str(bid)] : [NSString stringWithFormat:@"build %@", engine_str(bid)];
++}
++
++// "Open cheats folder": the menu's and the panel's action, one helper — create the folder when missing, then reveal it in Finder
++static void cheats_open_folder(void) {
++ const char *dir = dm_cheats_dir_path();
++ if (dir && *dir) { mkdir(dir, 0755); [[NSWorkspace sharedWorkspace] openURL:[NSURL fileURLWithPath:@(dir)]]; }
++}
++
++// The Cheats panel (the menu's "Show Cheats Window", ⌘⇧C, or DM_CHEATS_WINDOW=1 at launch): a utility NSPanel that stays
++// open beside the game window, toggles applied live, scrollable. It never takes the key window from the game for a click
++// (becomesKeyOnlyIfNeeded, shown with orderFront), so the game keeps the keyboard and the controllers; it becomes key only
++// while the player types in its search field or a value field, and Return or Escape there hands the keyboard back.
++// Created once lazily and kept for the process's lifetime, closed only to hide (its place and size survive in the frame
++// autosave "DmCheatsPanel"). Every row comes from the C API (dm_cheat* in dm.h); the class holds no cheats state of its own
++// beyond the controls. Top to bottom:
++// - the header (game build and version, counts) and, when it applies, a line about safe mode with Restore;
++// - Cheats On (the master switch), Select All / Deselect All and the search field;
++// - the rows: section headers, labels, one row per cheat (an on / off pair is one row; a "set" cheat has an Apply button
++// instead of a checkbox; an "ask" cheat a value field; ⓘ shows its details), then the cheats the compiler left out,
++// the other builds' files, and the anchored sources not compiled for this build;
++// - a details line (a cheat's dry run and note, or the load report);
++// - Reload, Open folder, Find Cheats… (in Ryujinx, the yuzu family and SD cards) and Report.
++// A .txt or a .cheats.toml dropped on the panel is copied into the cheats folder (import below; the drop works from a
++// background Finder window, see DmCheatsDropView). The rows are rebuilt
++// when what they were built from changes (a reload, the search text), updated in place otherwise; a ~1 s timer runs only
++// while the panel is visible
++@interface DmCheatsPanel : NSObject <NSWindowDelegate, NSTextFieldDelegate, NSSearchFieldDelegate>
++- (void)show; // create the panel if needed, order it front (not key) and refresh
++- (void)refresh; // the one refresh for every trigger: shown, a click, Reload, a Cheats-menu toggle, the 1 s timer
++- (BOOL)importFiles:(NSArray<NSURL *> *)urls; // copy dropped / found cheat files into the cheats folder, reload
++@end
++static DmCheatsPanel *g_cheats_panel; // created on the first Show Cheats Window, kept for the process's lifetime
++
++// The panel class: a panel may become key (its search and value fields need the keyboard); becomesKeyOnlyIfNeeded keeps a
++// checkbox click from making it key
++@interface DmCheatsNSPanel : NSPanel @end
++@implementation DmCheatsNSPanel
++- (BOOL)canBecomeKeyWindow { return YES; }
++@end
++
++// The panel's content view: it takes dropped files (a .txt or .cheats.toml) for the import. The utility panel hides while
++// another app is in front, so a drop works from a Finder window dragged without activating Finder first (a background
++// window), not after clicking into Finder; Find Cheats… covers the usual places without a drag
++@interface DmCheatsDropView : NSView @end
++@implementation DmCheatsDropView
++// A drag enters: accept it as a copy when it carries a cheat file
++- (NSDragOperation)draggingEntered:(id<NSDraggingInfo>)info {
++ NSArray *urls = [info.draggingPasteboard readObjectsForClasses:@[NSURL.class] options:@{NSPasteboardURLReadingFileURLsOnlyKey: @YES}];
++ for (NSURL *u in urls) {
++ NSString *e = u.lastPathComponent.lowercaseString;
++ if ([e hasSuffix:@".txt"] || [e hasSuffix:@".cheats.toml"]) return NSDragOperationCopy;
++ }
++ return NSDragOperationNone;
++}
++// The drop: the import runs a main-queue turn later, so its questions (modal alerts) do not hold Finder's drag session open
++- (BOOL)performDragOperation:(id<NSDraggingInfo>)info {
++ NSArray *urls = [info.draggingPasteboard readObjectsForClasses:@[NSURL.class] options:@{NSPasteboardURLReadingFileURLsOnlyKey: @YES}];
++ if (!urls.count || !g_cheats_panel) return NO;
++ dispatch_async(dispatch_get_main_queue(), ^{ [g_cheats_panel importFiles:urls]; });
++ return YES;
++}
++@end
++
++// The scroll view's document view: flipped, so the stack view's rows start at the top and the scroll position counts
++// downward like the rows (unflipped, everything would sit at the bottom of the document view)
++@interface DmCheatsDocView : NSView @end
++@implementation DmCheatsDocView
++- (BOOL)isFlipped { return YES; }
++@end
++
++// The Cheats menu of the game window (hle_cheats.c's rows, only meaningful with a window): rebuilt on every open, so the
++// loaded file's state, the menu's toggles and the cheats the VM disabled at run time are what the player sees. Rows: Show
++// Cheats Window (⌘⇧C), Cheats On (the master switch) and, in safe mode, Restore Saved Cheats; then the panel's rows in
++// short (section headers, labels, one row per cheat, a pair as one row, "set" cheats applied on click), the other builds'
++// files when none of this build is loaded, and Reload cheats (⌘R) / Open cheats folder. A click here also refreshes the
++// panel when one exists, so the two never disagree
++@interface DmCheatsMenuDelegate : NSObject <NSMenuDelegate>
++@end
++@implementation DmCheatsMenuDelegate
++// Rebuild the menu's rows from the engine (every open, and once at launch so its key equivalents exist)
++- (void)menuNeedsUpdate:(NSMenu *)menu {
++ [menu removeAllItems];
++ NSMenuItem *sh = [menu addItemWithTitle:@"Show Cheats Window" action:@selector(showPanel:) keyEquivalent:@"c"];
++ sh.target = self;
++ sh.keyEquivalentModifierMask = NSEventModifierFlagCommand | NSEventModifierFlagShift; // ⌘⇧C (the plain "c" already maps ZR)
++ NSMenuItem *ms = [menu addItemWithTitle:@"Cheats On" action:@selector(toggleMaster:) keyEquivalent:@""];
++ ms.target = self; ms.state = dm_cheats_master() ? NSControlStateValueOn : NSControlStateValueOff;
++ if (dm_cheats_safe()) [menu addItemWithTitle:@"Restore Saved Cheats (safe mode)" action:@selector(restoreSafe:) keyEquivalent:@""].target = self;
++ [menu addItem:NSMenuItem.separatorItem];
++ const char *sec = "";
++ for (int i = 0, n = dm_cheats_ncheats(); i < n; i++) {
++ if (!cheat_has_row(i)) continue;
++ const char *s = dm_cheat_section_at(i);
++ if (strcmp(s, sec)) { // a section header before its first entry
++ sec = s;
++ if (*s) [menu addItemWithTitle:[NSString stringWithFormat:@"— %@ —", engine_str(s)] action:nil keyEquivalent:@""].enabled = NO;
++ }
++ int kind = dm_cheat_kind_at(i), f = dm_cheat_flags_at(i);
++ NSString *title = cheat_row_title(i);
++ if (f & DM_CHEAT_ONCE) title = [title stringByAppendingString:@" (apply once)"];
++ NSMenuItem *it = [menu addItemWithTitle:title action:nil keyEquivalent:@""];
++ if (kind == 0) { it.target = self; it.action = @selector(toggleCheat:); it.tag = i; }
++ it.enabled = kind == 0;
++ it.state = cheat_row_state(i);
++ it.toolTip = cheat_row_tip(i);
++ }
++ for (int i = 0, n = dm_cheats_nothers(); i < n; i++) // .txt files of other builds, lightly disabled (the brief's wording)
++ [menu addItemWithTitle:[NSString stringWithFormat:@"Cheats for %@ (another version of the game)", build_label(dm_cheats_other(i), dm_cheats_other_version(i))] action:nil keyEquivalent:@""].enabled = NO;
++ if (!dm_cheats_found())
++ [menu addItemWithTitle:[NSString stringWithFormat:@"No cheats for %@", build_label(dm_cheats_build(), dm_cheats_version())] action:nil keyEquivalent:@""].enabled = NO;
++ [menu addItem:[NSMenuItem separatorItem]];
++ NSMenuItem *re = [menu addItemWithTitle:@"Reload cheats" action:@selector(reloadCheats:) keyEquivalent:@"r"];
++ re.target = self;
++ const char *dir = dm_cheats_dir_path();
++ NSMenuItem *op = [menu addItemWithTitle:@"Open cheats folder" action:dir && *dir ? @selector(openCheatsFolder:) : nil keyEquivalent:@""];
++ op.target = self;
++ op.enabled = dir && *dir != 0;
++}
++// A cheat row: toggle it (a "set" cheat runs one pass)
++- (void)toggleCheat:(NSMenuItem *)it {
++ dm_cheat_toggle((int)it.tag);
++ it.state = dm_cheat_on_at((int)it.tag) ? NSControlStateValueOn : NSControlStateValueOff; // The new state right now; a run-time [RED] kill shows its reason when the menu next opens
++ if (g_cheats_panel) [g_cheats_panel refresh]; // the panel (if created) follows the menu so the two never disagree; its visibility is checked there
++}
++// Cheats On: the master switch
++- (void)toggleMaster:(NSMenuItem *)it { (void)it; dm_cheats_master_set(!dm_cheats_master()); if (g_cheats_panel) [g_cheats_panel refresh]; }
++// Restore Saved Cheats: leave safe mode
++- (void)restoreSafe:(NSMenuItem *)it { (void)it; dm_cheats_safe_restore(); if (g_cheats_panel) [g_cheats_panel refresh]; }
++// Reload cheats (⌘R): re-read the file in place
++- (void)reloadCheats:(NSMenuItem *)it { (void)it; dm_cheats_reload(); if (g_cheats_panel) [g_cheats_panel refresh]; }
++// Open cheats folder: create it when missing, reveal it in Finder
++- (void)openCheatsFolder:(NSMenuItem *)it { (void)it; cheats_open_folder(); }
++// Lazily create the panel on the first Show Cheats Window (it is kept for the process's lifetime) and order it front:
++// orderFront keeps the game the key window
++- (void)showPanel:(NSMenuItem *)it {
++ (void)it;
++ if (!g_cheats_panel) g_cheats_panel = [DmCheatsPanel new]; // created here, on the first Show Cheats Window
++ [g_cheats_panel show];
++}
++@end
++static DmCheatsMenuDelegate *g_cheats_menu; // NSMenu keeps its delegate unretained
++
++@implementation DmCheatsPanel {
++ NSPanel *_panel; // created once in show, kept for the process's lifetime
++ NSTextField *_header; // the one-line status line above the rows
++ NSStackView *_safeRow; // safe mode's line and Restore, hidden otherwise
++ NSButton *_master; // Cheats On: the master switch
++ NSButton *_selectAll; // enabled while some plain cheat is off
++ NSButton *_deselectAll; // enabled while some plain cheat is on
++ NSSearchField *_search; // filters the rows by name and section
++ NSScrollView *_scroll; // scrolls the rows
++ NSStackView *_stack; // the rows (vertical, leading alignment), inside _doc
++ NSView *_doc; // the flipped document view the stack is pinned to
++ NSTextField *_details; // a cheat's dry run and note, or the load report
++ NSButton *_openFolder; // disabled while dm_cheats_dir_path() is empty
++ NSMutableDictionary<NSNumber *, NSButton *> *_checks; // cheat index -> its checkbox (or Apply button), to update in place
++ NSMutableDictionary<NSNumber *, NSTextField *> *_values; // cheat index -> its value field
++ NSMutableDictionary<NSNumber *, NSTextField *> *_labels; // cheat index -> the name label of a "set" cheat's row
++ BOOL _rebuilding; // the rows are being replaced: a field's end of editing then applies nothing
++ NSString *_rows_sig; // what the rows on screen were built from: a change rebuilds
++ int _detailsFor; // the cheat whose details are shown (-1: the report, -2: nothing)
++ NSTimer *_refreshTimer; // ~1 s, scheduled only while the panel is on screen; invalidated when it hides
++ BOOL _upOnDeactivate; // the panel was on screen when the app was deactivated: AppKit brings it back on activation
++ BOOL _finding; // a Find Cheats… scan is running on a background queue: another click does not start a second one
++}
++
++// A button of the panel's toolbar rows
++static NSButton *panel_button(NSString *title, id target, SEL action) { return [NSButton buttonWithTitle:title target:target action:action]; }
++
++// A horizontal row of views, leading-aligned
++static NSStackView *panel_hrow(NSArray<NSView *> *views) {
++ NSStackView *s = [NSStackView stackViewWithViews:views];
++ s.orientation = NSUserInterfaceLayoutOrientationHorizontal; s.spacing = 8; s.translatesAutoresizingMaskIntoConstraints = NO;
++ return s;
++}
++
++// A secondary-colour label that truncates instead of widening the panel, its whole text in the tooltip
++static NSTextField *panel_note(NSString *text) {
++ NSTextField *l = [NSTextField labelWithString:text];
++ l.textColor = NSColor.secondaryLabelColor; l.lineBreakMode = NSLineBreakByTruncatingTail; l.toolTip = text;
++ [l setContentCompressionResistancePriority:NSLayoutPriorityDefaultLow forOrientation:NSLayoutConstraintOrientationHorizontal];
++ return l;
++}
++
++// Create the panel, the content view and the fixed layout once (header, safe-mode line, toolbar, scrolled rows, details,
++// bottom buttons); refresh fills the rows afterwards
++- (void)makePanel {
++ _panel = [[DmCheatsNSPanel alloc] initWithContentRect:NSMakeRect(0, 0, 480, 560)
++ styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable
++ | NSWindowStyleMaskUtilityWindow
++ backing:NSBackingStoreBuffered defer:NO];
++ _panel.title = @"Cheats";
++ _panel.releasedWhenClosed = NO; // the close button only hides (windowShouldClose)
++ _panel.floatingPanel = YES; // above the game window
++ _panel.becomesKeyOnlyIfNeeded = YES; // a checkbox click never takes the key window: the game keeps keyboard and controllers
++ _panel.collectionBehavior = NSWindowCollectionBehaviorFullScreenAuxiliary; // shows over the fullscreen game too
++ _panel.frameAutosaveName = @"DmCheatsPanel"; // place and size remembered (set after the frame is read back: makePanel's end)
++ _panel.minSize = NSMakeSize(360, 260);
++ _panel.delegate = self;
++ NSNotificationCenter *nc = NSNotificationCenter.defaultCenter;
++ [nc addObserver:self selector:@selector(appResignedActive:) name:NSApplicationDidResignActiveNotification object:NSApp];
++ [nc addObserver:self selector:@selector(appBecameActive:) name:NSApplicationDidBecomeActiveNotification object:NSApp];
++ DmCheatsDropView *content = [[DmCheatsDropView alloc] initWithFrame:NSMakeRect(0, 0, 480, 560)];
++ [content registerForDraggedTypes:@[NSPasteboardTypeFileURL]];
++ _panel.contentView = content;
++
++ _header = [NSTextField labelWithString:@""];
++ _header.translatesAutoresizingMaskIntoConstraints = NO;
++ _header.lineBreakMode = NSLineBreakByTruncatingTail;
++ [_header setContentCompressionResistancePriority:NSLayoutPriorityDefaultLow forOrientation:NSLayoutConstraintOrientationHorizontal];
++ NSTextField *safeText = panel_note(@"Last run ended unexpectedly with cheats on: all are off.");
++ safeText.textColor = NSColor.systemOrangeColor;
++ _safeRow = panel_hrow(@[safeText, panel_button(@"Restore", self, @selector(restoreSafe:))]);
++ _master = [NSButton checkboxWithTitle:@"Cheats On" target:self action:@selector(toggleMaster:)];
++ _selectAll = panel_button(@"Select All", self, @selector(selectAllCheats:));
++ _deselectAll = panel_button(@"Deselect All", self, @selector(deselectAllCheats:));
++ _search = [NSSearchField new];
++ _search.placeholderString = @"Search";
++ _search.delegate = self;
++ _search.sendsSearchStringImmediately = YES;
++ [_search setContentHuggingPriority:NSLayoutPriorityDefaultLow forOrientation:NSLayoutConstraintOrientationHorizontal];
++ NSStackView *tools = panel_hrow(@[_master, _selectAll, _deselectAll, _search]);
++
++ _scroll = [[NSScrollView alloc] initWithFrame:NSZeroRect];
++ _scroll.hasVerticalScroller = YES; _scroll.autohidesScrollers = YES;
++ _scroll.translatesAutoresizingMaskIntoConstraints = NO;
++ _doc = [[DmCheatsDocView alloc] initWithFrame:NSZeroRect];
++ _doc.translatesAutoresizingMaskIntoConstraints = NO;
++ _scroll.documentView = _doc;
++ _stack = [[NSStackView alloc] initWithFrame:NSZeroRect];
++ _stack.orientation = NSUserInterfaceLayoutOrientationVertical;
++ _stack.alignment = NSLayoutAttributeLeading;
++ _stack.spacing = 4;
++ _stack.edgeInsets = NSEdgeInsetsMake(8, 8, 8, 8);
++ _stack.translatesAutoresizingMaskIntoConstraints = NO;
++ [_doc addSubview:_stack];
++ [NSLayoutConstraint activateConstraints:@[
++ [_stack.topAnchor constraintEqualToAnchor:_doc.topAnchor],
++ [_stack.leadingAnchor constraintEqualToAnchor:_doc.leadingAnchor],
++ [_stack.trailingAnchor constraintEqualToAnchor:_doc.trailingAnchor],
++ [_doc.leadingAnchor constraintEqualToAnchor:_scroll.contentView.leadingAnchor],
++ [_doc.widthAnchor constraintEqualToAnchor:_scroll.contentView.widthAnchor], // no horizontal scrolling
++ [_doc.topAnchor constraintEqualToAnchor:_scroll.contentView.topAnchor],
++ [_doc.bottomAnchor constraintEqualToAnchor:_stack.bottomAnchor],
++ ]];
++
++ _details = [NSTextField wrappingLabelWithString:@""];
++ _details.translatesAutoresizingMaskIntoConstraints = NO;
++ _details.selectable = NO; // a selectable label would make the panel key on a click and keep the keyboard from the game
++ _details.font = [NSFont monospacedSystemFontOfSize:NSFont.smallSystemFontSize weight:NSFontWeightRegular];
++ _details.maximumNumberOfLines = 8;
++ [_details setContentCompressionResistancePriority:NSLayoutPriorityDefaultLow forOrientation:NSLayoutConstraintOrientationHorizontal];
++ _detailsFor = -2;
++
++ _openFolder = panel_button(@"Open Folder", self, @selector(openFolder:));
++ NSStackView *bottom = panel_hrow(@[panel_button(@"Reload", self, @selector(reload:)), _openFolder,
++ panel_button(@"Find Cheats…", self, @selector(findCheats:)), panel_button(@"Report", self, @selector(showReport:))]);
++ // the header, the safe-mode line and the toolbar in one column: a stack view detaches a hidden view, so the safe-mode
++ // line takes no room while it is hidden
++ NSStackView *top = [NSStackView stackViewWithViews:@[_header, _safeRow, tools]];
++ top.orientation = NSUserInterfaceLayoutOrientationVertical; top.alignment = NSLayoutAttributeLeading; top.spacing = 6;
++ top.translatesAutoresizingMaskIntoConstraints = NO;
++ for (NSView *v in @[top, _scroll, _details, bottom]) [content addSubview:v];
++ [NSLayoutConstraint activateConstraints:@[
++ [top.topAnchor constraintEqualToAnchor:content.topAnchor constant:10],
++ [top.leadingAnchor constraintEqualToAnchor:content.leadingAnchor constant:8],
++ [top.trailingAnchor constraintEqualToAnchor:content.trailingAnchor constant:-8],
++ [_header.trailingAnchor constraintEqualToAnchor:top.trailingAnchor],
++ [tools.trailingAnchor constraintEqualToAnchor:top.trailingAnchor],
++ [_scroll.topAnchor constraintEqualToAnchor:top.bottomAnchor constant:8],
++ [_scroll.leadingAnchor constraintEqualToAnchor:content.leadingAnchor],
++ [_scroll.trailingAnchor constraintEqualToAnchor:content.trailingAnchor],
++ [_scroll.bottomAnchor constraintEqualToAnchor:_details.topAnchor constant:-6],
++ [_details.leadingAnchor constraintEqualToAnchor:content.leadingAnchor constant:8],
++ [_details.trailingAnchor constraintEqualToAnchor:content.trailingAnchor constant:-8],
++ [_details.bottomAnchor constraintEqualToAnchor:bottom.topAnchor constant:-6],
++ [bottom.leadingAnchor constraintEqualToAnchor:content.leadingAnchor constant:8],
++ [bottom.trailingAnchor constraintLessThanOrEqualToAnchor:content.trailingAnchor constant:-8],
++ [bottom.bottomAnchor constraintEqualToAnchor:content.bottomAnchor constant:-8],
++ ]];
++ _checks = [NSMutableDictionary dictionary];
++ _values = [NSMutableDictionary dictionary];
++ _labels = [NSMutableDictionary dictionary];
++ _rows_sig = @"";
++ if (![_panel setFrameUsingName:@"DmCheatsPanel"] && g_win) { // first use: beside the game window, not the screen's corner
++ NSRect g = g_win.frame, f = _panel.frame;
++ [_panel setFrameOrigin:NSMakePoint(NSMaxX(g) + 8, NSMaxY(g) - f.size.height)];
++ }
++}
++
++// The panel became key: keep it only while one of its fields is being edited (a click elsewhere, Full Keyboard Access
++// on a button, the search field's clear button); otherwise the keyboard goes back to the game a main-queue turn later,
++// once the click has settled the first responder
++- (void)windowDidBecomeKey:(NSNotification *)n {
++ (void)n;
++ dispatch_async(dispatch_get_main_queue(), ^{ if (![self editing]) [self giveKeyBack]; });
++}
++
++// Is the search field or a value field being edited (its field editor is the panel's first responder)?
++- (BOOL)editing {
++ if (_search.currentEditor) return YES;
++ for (NSTextField *v in _values.allValues) if (v.currentEditor) return YES;
++ return NO;
++}
++
++// Give the keyboard back to the game: after typing in the search or a value field (Return, Escape, the end of editing)
++- (void)giveKeyBack {
++ if (g_win && _panel.isKeyWindow) [g_win makeKeyWindow];
++}
++
++// ---- the actions ----
++
++// Open Folder: create the cheats folder when missing, reveal it in Finder
++- (void)openFolder:(NSButton *)b { (void)b; cheats_open_folder(); }
++// Reload: re-read the file in place (edits during play need no re-launch)
++- (void)reload:(NSButton *)b { (void)b; dm_cheats_reload(); [self refresh]; }
++// Cheats On: the master switch (off stops every cheat without touching the toggles)
++- (void)toggleMaster:(NSButton *)b { (void)b; dm_cheats_master_set(!dm_cheats_master()); [self refresh]; }
++// Restore (safe mode): the saved toggles and the masters come back
++- (void)restoreSafe:(NSButton *)b { (void)b; dm_cheats_safe_restore(); [self refresh]; }
++// Report: the load report in the details line
++- (void)showReport:(NSButton *)b { (void)b; _detailsFor = -1; [self fillDetails]; }
++
++// Select All / Deselect All: flip every plain cheat (kind 0) that is not already in the wanted state, then one refresh.
++// The loop over dm_cheat_toggle instead of a bulk call keeps the C API small; each toggle rewrites <build ID>.enabled once
++// (a few tiny writes), and a pass between two toggles sees a mix for one frame, which is harmless. Masters, disabled
++// cheats, labels and "set" cheats (Select All must not fire them) are never touched, nor the off half of a pair
++// (hle_cheats.c switches it with its on half)
++- (void)setPlainCheatsOn:(BOOL)on {
++ for (int i = 0, n = dm_cheats_ncheats(); i < n; i++) {
++ if (dm_cheat_kind_at(i) != 0 || (dm_cheat_flags_at(i) & (DM_CHEAT_PAIR_OFF | DM_CHEAT_ONCE))) continue;
++ if (!!dm_cheat_on_at(i) == on) continue;
++ dm_cheat_toggle(i);
++ }
++ [self refresh];
++}
++// The two buttons behind setPlainCheatsOn:
++- (void)selectAllCheats:(NSButton *)b { (void)b; [self setPlainCheatsOn:YES]; }
++- (void)deselectAllCheats:(NSButton *)b { (void)b; [self setPlainCheatsOn:NO]; }
++
++// A checkbox click (or an Apply button: a "set" cheat runs one pass and turns itself off): flip the cheat (hle_cheats.c
++// also rewrites <build ID>.enabled), then refresh — the state comes back from the model
++- (void)cheatClicked:(NSButton *)b {
++ int i = (int)b.tag;
++ BOOL apply = i >= 0 && i < dm_cheats_ncheats() && (dm_cheat_flags_at(i) & DM_CHEAT_ONCE);
++ if (apply && dm_cheat_on_at(i)) return; // Apply only applies: one already waiting for its pass is not cancelled
++ if (i >= 0 && i < dm_cheats_ncheats()) dm_cheat_toggle(i);
++ if (_detailsFor == i) [self fillDetails];
++ [self refresh];
++}
++
++// ⓘ: show the cheat's details below the rows (its dry run now, its note)
++- (void)infoClicked:(NSButton *)b { _detailsFor = (int)b.tag; [self fillDetails]; }
++
++// A field's edit ended. A value field (still the row's own: a rebuild ends edits without applying them) sets its value;
++// a refused one beeps and shows the current value again. The keyboard goes back to the game only for Return (or the
++// search field's Escape), not when the player moved on to another field of the panel (Tab, a click)
++- (void)controlTextDidEndEditing:(NSNotification *)n {
++ NSTextField *f = n.object;
++ NSInteger how = [n.userInfo[@"NSTextMovement"] integerValue];
++ BOOL done = how == NSTextMovementReturn || how == NSTextMovementCancel;
++ if (f != (id)_search && !_rebuilding && _values[@(f.tag)] == f) {
++ int i = (int)f.tag;
++ if (dm_cheat_value_set(i, f.stringValue.UTF8String)) {
++ NSBeep();
++ char v[64]; if (dm_cheat_value_get(i, v, sizeof v)) f.stringValue = @(v);
++ }
++ if (_detailsFor == i) [self fillDetails];
++ }
++ if (done) [self giveKeyBack];
++}
++
++// The search text changed: the rows are filtered again (the signature includes it, so refresh rebuilds)
++- (void)controlTextDidChange:(NSNotification *)n { if (n.object == _search) [self refresh]; }
++
++// Escape: in a value field it abandons the typed text (the current value comes back, nothing is applied); in the search
++// field it clears the search as usual. Either way the keyboard goes back to the game (Return ends editing,
++// controlTextDidEndEditing)
++- (BOOL)control:(NSControl *)c textView:(NSTextView *)tv doCommandBySelector:(SEL)sel {
++ (void)tv;
++ if (sel != @selector(cancelOperation:)) return NO;
++ if (c == (id)_search) { dispatch_async(dispatch_get_main_queue(), ^{ [self giveKeyBack]; }); return NO; }
++ NSTextField *f = (NSTextField *)c;
++ [f abortEditing];
++ char v[64]; if (dm_cheat_value_get((int)f.tag, v, sizeof v)) f.stringValue = @(v);
++ [self giveKeyBack];
++ return YES;
++}
++
++// ---- Find Cheats… and the import ----
++
++// The cheat files of this game the usual places hold, this build's own first:
++// - Ryujinx: mods/contents/<title ID>/cheats/ and its mods' own cheats folders (mods/contents/<title ID>/<mod>/cheats/);
++// - the yuzu family: load/<title ID>/<mod>/cheats/;
++// - the Atmosphère tree of a mounted local volume (an SD card); network volumes are not listed (a stall even off the main thread).
++// Only the .txt files named after a build ID count (not Ryujinx's enabled.txt); each folder is read once whatever case
++// the path came in. build: this build's ID (read from the engine on the main thread by the caller). Runs on a background
++// queue (findCheats:): it touches only the file system and Foundation, never AppKit or the cheats engine
++static NSArray<NSURL *> *found_cheat_files(NSString *build) {
++ NSString *tid = [NSString stringWithFormat:@"%016llX", (unsigned long long)DM_GAME_PROGRAM_ID];
++ NSString *as = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support"];
++ NSMutableArray<NSString *> *dirs = [NSMutableArray array];
++ NSFileManager *fm = NSFileManager.defaultManager;
++ for (NSString *t in @[tid.lowercaseString, tid]) {
++ NSString *mods = [as stringByAppendingFormat:@"/Ryujinx/mods/contents/%@", t];
++ [dirs addObject:[mods stringByAppendingString:@"/cheats"]];
++ for (NSString *m in [fm contentsOfDirectoryAtPath:mods error:nil] ?: @[]) [dirs addObject:[mods stringByAppendingFormat:@"/%@/cheats", m]];
++ }
++ for (NSString *emu in @[@"yuzu", @"citron", @"eden", @"sudachi", @"suyu"]) {
++ NSString *load = [as stringByAppendingFormat:@"/%@/load/%@", emu, tid];
++ for (NSString *m in [fm contentsOfDirectoryAtPath:load error:nil] ?: @[]) [dirs addObject:[load stringByAppendingFormat:@"/%@/cheats", m]];
++ }
++ for (NSURL *vol in [fm mountedVolumeURLsIncludingResourceValuesForKeys:@[NSURLVolumeIsLocalKey] options:NSVolumeEnumerationSkipHiddenVolumes] ?: @[]) {
++ NSNumber *local = nil; [vol getResourceValue:&local forKey:NSURLVolumeIsLocalKey error:nil];
++ if (local.boolValue) [dirs addObject:[vol.path stringByAppendingFormat:@"/atmosphere/contents/%@/cheats", tid]];
++ }
++ NSMutableArray<NSURL *> *mine = [NSMutableArray array], *rest = [NSMutableArray array];
++ NSMutableSet<NSString *> *seen = [NSMutableSet set];
++ NSCharacterSet *nothex = [NSCharacterSet characterSetWithCharactersInString:@"0123456789abcdefABCDEF"].invertedSet;
++ for (NSString *d in dirs) {
++ NSString *real = [d stringByResolvingSymlinksInPath].lowercaseString; // one folder however its path was spelled
++ if ([seen containsObject:real]) continue;
++ [seen addObject:real];
++ for (NSString *f in [fm contentsOfDirectoryAtPath:d error:nil] ?: @[]) {
++ if (f.length != 20 || ![f.lowercaseString hasSuffix:@".txt"] || [[f substringToIndex:16] rangeOfCharacterFromSet:nothex].location != NSNotFound) continue;
++ NSURL *u = [NSURL fileURLWithPath:[d stringByAppendingPathComponent:f]];
++ [([f.uppercaseString hasPrefix:build] ? mine : rest) addObject:u];
++ }
++ }
++ [mine addObjectsFromArray:rest];
++ return mine;
++}
++
++// Find Cheats…: a menu of the files found, under the button; picking one imports it. The folders are read on a background
++// queue, since a sleeping external disk can take seconds to answer and the main thread would beachball the game window
++// meanwhile; the button reads "Looking…" and is disabled until the scan ends, and _finding keeps a second click (or an
++// action sent while disabled) from starting another scan. The menu is built and shown on the main queue, and only while
++// the panel is still on screen (it hides when the app is deactivated): a menu popping up out of nowhere would be worse
++- (void)findCheats:(NSButton *)b {
++ if (_finding) return;
++ _finding = YES;
++ NSString *title = b.title;
++ b.title = @"Looking…"; b.enabled = NO;
++ NSString *build = engine_str(dm_cheats_build()); // the engine's state is read here, on the main thread, not by the scan
++ dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
++ NSArray<NSURL *> *found = found_cheat_files(build);
++ dispatch_async(dispatch_get_main_queue(), ^{
++ self->_finding = NO;
++ b.title = title; b.enabled = YES;
++ if (b.window.visible) [self showFound:found under:b];
++ });
++ });
++}
++// The files a Find Cheats… scan found, as a menu under its button (main thread)
++- (void)showFound:(NSArray<NSURL *> *)found under:(NSButton *)b {
++ NSMenu *m = [NSMenu new];
++ if (!found.count) [m addItemWithTitle:@"No cheat files of this game in Ryujinx, the yuzu family or an SD card" action:nil keyEquivalent:@""].enabled = NO;
++ for (NSURL *u in found) {
++ NSString *parent = u.URLByDeletingLastPathComponent.path.stringByAbbreviatingWithTildeInPath;
++ NSMenuItem *it = [m addItemWithTitle:[NSString stringWithFormat:@"%@ — %@", u.lastPathComponent, parent] action:@selector(importFound:) keyEquivalent:@""];
++ it.target = self; it.representedObject = u;
++ }
++ [m popUpMenuPositioningItem:nil atLocation:NSMakePoint(0, b.bounds.size.height) inView:b];
++}
++// A file picked in Find Cheats…: import it
++- (void)importFound:(NSMenuItem *)it { [self importFiles:@[it.representedObject]]; }
++
++// A yes / no question as a modal alert, answered before returning (the import is the player's own action, so a modal
++// question is fine; the keyboard goes back to the game after it): YES for the first button
++- (BOOL)ask:(NSString *)text info:(NSString *)info yes:(NSString *)yes {
++ NSAlert *a = [NSAlert new];
++ a.messageText = text; a.informativeText = info ?: @"";
++ [a addButtonWithTitle:yes]; [a addButtonWithTitle:@"Cancel"];
++ BOOL r = [a runModal] == NSAlertFirstButtonReturn;
++ [self giveKeyBack];
++ return r;
++}
++
++// Copy cheat files into the cheats folder, then reload: a .cheats.toml (an anchored source) keeps its name; a .txt keeps a
++// build ID name, and a file named otherwise (a Ryujinx list such as "all cheats.txt") becomes this build's after the
++// player confirms it is for this build. A file already there is kept as <name>.bak (asked first). Returns whether
++// something was imported
++- (BOOL)importFiles:(NSArray<NSURL *> *)urls {
++ const char *dirc = dm_cheats_dir_path();
++ if (!dirc || !*dirc || strlen(dm_cheats_build()) != 16) { NSBeep(); return NO; } // no folder, or no build ID to name a file by
++ NSString *dir = engine_str(dirc), *build = engine_str(dm_cheats_build());
++ NSString *tid = [NSString stringWithFormat:@"%016llX", (unsigned long long)DM_GAME_PROGRAM_ID];
++ NSFileManager *fm = NSFileManager.defaultManager;
++ [fm createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
++ BOOL any = NO;
++ for (NSURL *u in urls) {
++ NSString *name = u.lastPathComponent, *dest;
++ if ([name.lowercaseString hasSuffix:@".cheats.toml"]) dest = name;
++ else if (![name.lowercaseString hasSuffix:@".txt"]) continue;
++ else {
++ NSString *stem = name.length >= 16 ? [name substringToIndex:16].uppercaseString : @"";
++ BOOL hex = stem.length == 16 && [stem rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"0123456789ABCDEF"].invertedSet].location == NSNotFound;
++ if (hex && ![stem isEqualToString:tid]) dest = [stem stringByAppendingString:@".txt"]; // a title ID name says no build
++ else {
++ if (![self ask:[NSString stringWithFormat:@"Is “%@” for this version of the game?", name]
++ info:[NSString stringWithFormat:@"Its name does not say which build it is for. It will be used as the cheats of %@.", build_label(dm_cheats_build(), dm_cheats_version())]
++ yes:@"Use for This Build"]) continue;
++ dest = [build stringByAppendingString:@".txt"];
++ }
++ }
++ NSString *path = [dir stringByAppendingPathComponent:dest];
++ if ([u.path.stringByStandardizingPath.lowercaseString isEqualToString:path.stringByStandardizingPath.lowercaseString]) continue; // already the folder's own file
++ if ([fm fileExistsAtPath:path]) {
++ if (![self ask:[NSString stringWithFormat:@"Replace %@?", dest] info:[NSString stringWithFormat:@"The current one is kept as %@.bak (an older %@.bak is replaced).", dest, dest] yes:@"Replace"]) continue;
++ NSString *bak = [path stringByAppendingString:@".bak"];
++ [fm removeItemAtPath:bak error:nil];
++ [fm moveItemAtPath:path toPath:bak error:nil];
++ }
++ NSError *e = nil;
++ if ([fm copyItemAtURL:u toURL:[NSURL fileURLWithPath:path] error:&e]) any = YES;
++ else LOG("[RED] cheats: cannot copy %s into the cheats folder: %s", u.path.UTF8String, e.localizedDescription.UTF8String);
++ }
++ if (any) { dm_cheats_reload(); _detailsFor = -1; [self refresh]; [self fillDetails]; }
++ return any;
++}
++
++// ---- the rows ----
++
++// A row of one cheat: its checkbox (or, for a "set" cheat, its name and an Apply button), its value field for an "ask"
++// cheat, and ⓘ. The title truncates and is whole in the tooltip, so a long one never widens the panel
++- (NSView *)cheatRow:(int)i {
++ int kind = dm_cheat_kind_at(i), f = dm_cheat_flags_at(i);
++ NSString *title = cheat_row_title(i), *tip = cheat_row_tip(i);
++ NSMutableArray<NSView *> *views = [NSMutableArray array];
++ NSButton *b;
++ if (f & DM_CHEAT_ONCE) {
++ NSTextField *l = [NSTextField labelWithString:title];
++ l.lineBreakMode = NSLineBreakByTruncatingTail; l.toolTip = tip;
++ _labels[@(i)] = l;
++ [l setContentCompressionResistancePriority:NSLayoutPriorityDefaultLow forOrientation:NSLayoutConstraintOrientationHorizontal];
++ [views addObject:l];
++ b = panel_button(@"Apply", self, @selector(cheatClicked:));
++ b.controlSize = NSControlSizeSmall;
++ } else {
++ b = [NSButton checkboxWithTitle:title target:self action:@selector(cheatClicked:)];
++ ((NSButtonCell *)b.cell).lineBreakMode = NSLineBreakByTruncatingTail;
++ [b setContentCompressionResistancePriority:NSLayoutPriorityDefaultLow forOrientation:NSLayoutConstraintOrientationHorizontal];
++ b.state = cheat_row_state(i);
++ }
++ b.tag = i; b.enabled = kind == 0; b.toolTip = tip;
++ _checks[@(i)] = b;
++ if (!(f & DM_CHEAT_ONCE)) [views addObject:b];
++ if (f & DM_CHEAT_ASK) {
++ NSTextField *v = [NSTextField textFieldWithString:@""];
++ char cur[64]; if (dm_cheat_value_get(i, cur, sizeof cur)) v.stringValue = @(cur);
++ v.placeholderString = @(dm_cheat_value_bounds(i));
++ v.toolTip = [NSString stringWithFormat:@"Value (%s, %s)", dm_cheat_type_at(i), dm_cheat_value_bounds(i)];
++ v.tag = i; v.delegate = self; v.controlSize = NSControlSizeSmall;
++ [v.widthAnchor constraintEqualToConstant:90].active = YES;
++ _values[@(i)] = v;
++ [views addObject:v];
++ }
++ if (f & DM_CHEAT_ONCE) [views addObject:b];
++ NSButton *info = [NSButton buttonWithImage:[NSImage imageWithSystemSymbolName:@"info.circle" accessibilityDescription:@"Details"] target:self action:@selector(infoClicked:)];
++ info.bordered = NO; info.tag = i; info.toolTip = @"Show what it writes now, and its note";
++ [views addObject:info];
++ return panel_hrow(views);
++}
++
++// A section header: the section's name in bold
++- (NSView *)sectionRow:(const char *)name {
++ NSTextField *l = [NSTextField labelWithString:engine_str(name)];
++ l.font = [NSFont boldSystemFontOfSize:NSFont.systemFontSize];
++ return l;
++}
++
++// Does entry i pass the search text (its name or its section contains it, any case)?
++- (BOOL)matches:(int)i {
++ NSString *q = _search.stringValue;
++ if (!q.length) return YES;
++ return [cheat_display_name(i) rangeOfString:q options:NSCaseInsensitiveSearch].location != NSNotFound
++ || [engine_str(dm_cheat_section_at(i)) rangeOfString:q options:NSCaseInsensitiveSearch].location != NSNotFound;
++}
++
++// What the rows on screen were built from: the signature rebuilt on every refresh, the rows rebuilt when it differs (the
++// list, the flags that choose a row's controls, the search text). States and titles are not in it: they change per cheat
++// and the update path carries them in place
++- (NSString *)rowsSig {
++ NSMutableString *s = [NSMutableString stringWithFormat:@"%d/%d/%@/", dm_cheats_ncheats(), dm_cheats_found(), _search.stringValue];
++ for (int i = 0, n = dm_cheats_ncheats(); i < n; i++) [s appendFormat:@"%@:%d|", engine_str(dm_cheat_name_at(i)), dm_cheat_flags_at(i)];
++ for (int i = 0, n = dm_cheats_nothers(); i < n; i++) [s appendFormat:@"%@:%@|", engine_str(dm_cheats_other(i)), engine_str(dm_cheats_other_version(i))];
++ for (int i = 0, n = dm_cheats_nskipped(); i < n; i++) [s appendFormat:@"%@|", engine_str(dm_cheats_skipped_name(i))];
++ for (int i = 0, n = dm_cheats_nsources(); i < n; i++) [s appendFormat:@"%@|", engine_str(dm_cheats_source(i))];
++ return s;
++}
++
++// Rebuild all rows (a reload, a first fill, a new search), keeping the scroll position as far as possible
++- (void)rebuildRows {
++ NSClipView *clip = _scroll.contentView;
++ CGFloat keepY = clip.bounds.origin.y;
++ _rebuilding = YES; // an edit in progress ends now without being applied (its row may be another cheat after a reload)
++ for (NSTextField *v in _values.allValues) if (v.currentEditor) [v abortEditing];
++ for (NSView *v in [_stack.arrangedSubviews copy]) [v removeFromSuperview];
++ _rebuilding = NO;
++ [_checks removeAllObjects]; [_values removeAllObjects]; [_labels removeAllObjects];
++ const char *sec = "";
++ for (int i = 0, n = dm_cheats_ncheats(); i < n; i++) {
++ if (!cheat_has_row(i) || ![self matches:i]) continue;
++ const char *s = dm_cheat_section_at(i);
++ if (strcmp(s, sec)) { sec = s; if (*s) [_stack addArrangedSubview:[self sectionRow:s]]; }
++ if (dm_cheat_kind_at(i) == 3) [_stack addArrangedSubview:panel_note(cheat_display_name(i))]; // a label: credits and the like
++ else [_stack addArrangedSubview:[self cheatRow:i]];
++ }
++ for (int i = 0, n = dm_cheats_nskipped(); i < n; i++)
++ [_stack addArrangedSubview:panel_note([NSString stringWithFormat:@"Left out of this build: %@ — %@", engine_str(dm_cheats_skipped_name(i)), engine_str(dm_cheats_skipped_why(i))])];
++ for (int i = 0, n = dm_cheats_nothers(); i < n; i++)
++ [_stack addArrangedSubview:panel_note([NSString stringWithFormat:@"Cheats for %@: another version of the game, its addresses do not fit this one",
++ build_label(dm_cheats_other(i), dm_cheats_other_version(i))])];
++ if (!dm_cheats_found())
++ for (int i = 0, n = dm_cheats_nsources(); i < n; i++) {
++ NSButton *copy = panel_button(@"Copy Command", self, @selector(copyCompile:)); copy.tag = i; copy.controlSize = NSControlSizeSmall;
++ [_stack addArrangedSubview:panel_hrow(@[panel_note([NSString stringWithFormat:@"%@: anchored cheats, not compiled for this build yet", engine_str(dm_cheats_source(i))]), copy])];
++ }
++ _rows_sig = [self rowsSig];
++ if (keepY <= 0) return; // at the top already: the new rows start at the top too
++ __weak DmCheatsPanel *wself = self; // one main-queue tick later: the panel may be hidden by then
++ dispatch_async(dispatch_get_main_queue(), ^{
++ DmCheatsPanel *s = wself;
++ if (!s || !s->_panel || !s->_panel.isVisible) return;
++ NSClipView *c = s->_scroll.contentView;
++ CGFloat max = fmax(0, s->_doc.frame.size.height - c.bounds.size.height);
++ [c setBoundsOrigin:NSMakePoint(0, fmin(keepY, max))];
++ });
++}
++
++// Copy Command: the command that compiles an anchored source for this build (scripts/cheat_anchor.py, run from the
++// nxnative repository's folder; the build's ExeFS/main is the one the NSP script extracted), paths quoted for the shell
++- (void)copyCompile:(NSButton *)b {
++ NSString *dir = engine_str(dm_cheats_dir_path());
++ NSString *cmd = [NSString stringWithFormat:@"python3 scripts/cheat_anchor.py compile %@ --nso '<the ExeFS/main of build %@>' -o %@",
++ shell_quote([dir stringByAppendingPathComponent:engine_str(dm_cheats_source((int)b.tag))]), engine_str(dm_cheats_build()), shell_quote(dir)];
++ [NSPasteboard.generalPasteboard clearContents];
++ [NSPasteboard.generalPasteboard setString:cmd forType:NSPasteboardTypeString];
++ _detailsFor = -2; // the timer leaves this text alone
++ _details.stringValue = [@"Copied (run it in the nxnative folder): " stringByAppendingString:cmd];
++}
++
++// Update the rows in place (a click, a timer tick, a menu toggle): each control's state, enabled flag and title; a value
++// field the player is editing is left alone
++- (void)updateRows {
++ [_checks enumerateKeysAndObjectsUsingBlock:^(NSNumber *k, NSButton *b, BOOL *stop) {
++ (void)stop; int i = k.intValue;
++ BOOL once = (dm_cheat_flags_at(i) & DM_CHEAT_ONCE) != 0;
++ b.enabled = dm_cheat_kind_at(i) == 0 && (!once || (dm_cheats_master() && !dm_cheat_on_at(i))); // Apply: not while one waits
++ if (once) {
++ NSTextField *l = self->_labels[k];
++ NSString *full = cheat_row_title(i);
++ if (l && ![l.stringValue isEqualToString:full]) { l.stringValue = full; l.toolTip = cheat_row_tip(i); }
++ } else {
++ b.state = cheat_row_state(i);
++ NSString *full = cheat_row_title(i);
++ if (![b.title isEqualToString:full]) { b.title = full; b.toolTip = cheat_row_tip(i); }
++ }
++ }];
++ [_values enumerateKeysAndObjectsUsingBlock:^(NSNumber *k, NSTextField *v, BOOL *stop) {
++ (void)stop;
++ if (v.currentEditor) return;
++ char cur[64]; if (dm_cheat_value_get(k.intValue, cur, sizeof cur) && ![v.stringValue isEqualToString:@(cur)]) v.stringValue = @(cur);
++ }];
++}
++
++// The details line: the shown cheat's dry run and note, or the load report
++- (void)fillDetails {
++ if (_detailsFor == -1) { _details.stringValue = engine_str(dm_cheats_report()); return; }
++ if (_detailsFor < 0 || _detailsFor >= dm_cheats_ncheats()) { _details.stringValue = @""; return; }
++ char pv[1024]; dm_cheat_preview(_detailsFor, pv, sizeof pv);
++ NSMutableString *t = [NSMutableString stringWithFormat:@"%@\n%@", cheat_display_name(_detailsFor), engine_str(pv)];
++ const char *note = dm_cheat_note_at(_detailsFor);
++ if (note && *note) [t appendString:engine_str(note)];
++ _details.stringValue = [t stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
++}
++
++// The Select All / Deselect All buttons' enable state: Select All while some switchable plain cheat is off, Deselect All
++// while one is on (the same cheats setPlainCheatsOn: flips); both off while Cheats On is off
++- (void)updateSelectButtons {
++ BOOL someOff = NO, someOn = NO;
++ for (int i = 0, n = dm_cheats_ncheats(); i < n; i++) {
++ if (dm_cheat_kind_at(i) != 0 || (dm_cheat_flags_at(i) & (DM_CHEAT_PAIR_OFF | DM_CHEAT_ONCE))) continue;
++ if (dm_cheat_on_at(i)) someOn = YES; else someOff = YES;
++ if (someOn && someOff) break;
++ }
++ _selectAll.enabled = someOff && dm_cheats_master();
++ _deselectAll.enabled = someOn && dm_cheats_master();
++}
++
++// The header's one line (the folder missing, the counts and the build's version, or no file of this build) and the
++// master switch and safe-mode controls
++- (void)fillHeader {
++ const char *dir = dm_cheats_dir_path();
++ int n = 0, on = 0, masters = 0; // switchable cheats and those on; master codes are counted apart (always on)
++ for (int i = 0, c = dm_cheats_ncheats(); i < c; i++) {
++ int kind = dm_cheat_kind_at(i);
++ if (!cheat_has_row(i) || kind == 3) continue;
++ if (kind == 1) { masters++; continue; }
++ n++; on += kind == 0 && dm_cheat_on_at(i);
++ }
++ NSString *build = build_label(dm_cheats_build(), dm_cheats_version());
++ if (!dir || !*dir) _header.stringValue = @"Cheats are off: no cheats folder (DM_CHEATS or DM_ROOT is not set)";
++ else if (dm_cheats_found()) _header.stringValue = [NSString stringWithFormat:@"%@: %d cheats, %d on%@", build, n, on,
++ masters ? [NSString stringWithFormat:@", %d master", masters] : @""];
++ else _header.stringValue = [NSString stringWithFormat:@"No cheats for %@", build];
++ _header.toolTip = engine_str(dm_cheats_report());
++ _master.state = dm_cheats_master() ? NSControlStateValueOn : NSControlStateValueOff;
++ _safeRow.hidden = !dm_cheats_safe();
++}
++
++// The one refresh: the header and the buttons always, the rows rebuilt when what they show changed, only updated when it
++// did not. Nothing happens while the panel is not on screen — it fills itself in show
++- (void)refresh {
++ if (!_panel || !_panel.isVisible) return;
++ [self fillHeader];
++ [self updateSelectButtons];
++ _openFolder.enabled = ({ const char *d = dm_cheats_dir_path(); d && *d; });
++ if (![_rows_sig isEqualToString:[self rowsSig]]) [self rebuildRows];
++ else [self updateRows];
++}
++
++// Arm the ~1 s refresh unless it is already running: called by show and by the app's return to the foreground
++- (void)startTimer {
++ if (_refreshTimer.isValid) return;
++ _refreshTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(tick) userInfo:nil repeats:YES];
++}
++
++// One timer tick: refresh the rows (and the details of a shown cheat, whose dry run changes with the game), and stop for a
++// panel that is no longer on screen
++- (void)tick {
++ if (!_panel.isVisible) { [_refreshTimer invalidate]; _refreshTimer = nil; return; }
++ [self refresh];
++ if (_detailsFor >= 0) [self fillDetails];
++}
++
++// The app was deactivated: the utility panel goes off screen with it, so the refresh timer stops until the app comes back
++- (void)appResignedActive:(NSNotification *)n {
++ (void)n;
++ _upOnDeactivate = _panel.isVisible;
++ [_refreshTimer invalidate];
++ _refreshTimer = nil;
++}
++
++// The app is active again: AppKit brings back a panel that was up, so the timer is armed a main-queue turn later
++- (void)appBecameActive:(NSNotification *)n {
++ (void)n;
++ dispatch_async(dispatch_get_main_queue(), ^{ if (_upOnDeactivate) [self startTimer]; });
++}
++
++// Shown: order the panel front (created first if needed) — orderFront, not makeKeyAndOrderFront, so the game window stays
++// key. While the panel is on screen a ~1 s timer refreshes it
++- (void)show {
++ if (!_panel) [self makePanel];
++ [_panel orderFront:self];
++ [self refresh];
++ [self startTimer];
++}
++
++// The close button: hide instead of close (the panel object and its autosaved frame stay), and stop the refresh timer
++- (BOOL)windowShouldClose:(NSWindow *)w {
++ if (w != _panel) return YES;
++ [_refreshTimer invalidate];
++ _refreshTimer = nil;
++ for (NSTextField *v in _values.allValues) if (v.currentEditor) [v abortEditing]; // an unfinished value is abandoned
++ [self giveKeyBack]; // while the panel is still key
++ [_panel orderOut:nil];
++ return NO;
++}
++@end
++
+ void front_run(void (*guest)(void)) {
+ // A game: tell macOS its work is latency-critical, so the system does not trade its frame time for power while the frame rate is capped
+ static id activity; activity = [[NSProcessInfo processInfo] beginActivityWithOptions:NSActivityUserInitiated | NSActivityLatencyCritical reason:@"game"];
+@@ -277,6 +1125,18 @@ void front_run(void (*guest)(void)) {
+ NSMenu *bar = [NSMenu new], *app = [NSMenu new], *wm = [[NSMenu alloc] initWithTitle:@"Window"];
+ [[bar addItemWithTitle:@"" action:nil keyEquivalent:@""] setSubmenu:app];
+ [app addItemWithTitle:@"Quit " DM_GAME_NAME action:@selector(terminate:) keyEquivalent:@"q"];
++ // Cheats (hle_cheats.c): the rows rebuild on every open through the delegate, the same rows the file reload changes
++ g_cheats_menu = [DmCheatsMenuDelegate new];
++ NSMenu *cm = [[NSMenu alloc] initWithTitle:@"Cheats"];
++ cm.delegate = g_cheats_menu;
++ cm.autoenablesItems = NO; // the delegate sets enabled on every row itself
++ // Fill the rows now: AppKit matches a key equivalent (⌘R, ⌘⇧C) only against items that exist, and it calls the
++ // delegate's menuNeedsUpdate: when the menu is opened, not at launch, so without this neither works until the
++ // Cheats menu has been opened once. Every open rebuilds them through the delegate as before
++ [g_cheats_menu menuNeedsUpdate:cm];
++ [[bar addItemWithTitle:@"Cheats" action:nil keyEquivalent:@""] setSubmenu:cm];
++ if (getenv("DM_CHEATS_WINDOW") && atoi(getenv("DM_CHEATS_WINDOW"))) // the Cheats panel open from the start (beside the game, not key)
++ dispatch_async(dispatch_get_main_queue(), ^{ [g_cheats_menu showPanel:nil]; });
+ [[bar addItemWithTitle:@"Window" action:nil keyEquivalent:@""] setSubmenu:wm];
+ [wm addItemWithTitle:@"Enter Full Screen" action:@selector(toggleFullScreen:) keyEquivalent:@"f"].keyEquivalentModifierMask = NSEventModifierFlagControl | NSEventModifierFlagCommand;
+ NSApp.mainMenu = bar;
diff --git a/patches/series b/patches/series
index ddc5b67e..64c65a1d 100644
--- a/patches/series
+++ b/patches/series
@@ -19,3 +19,5 @@
0025-cloud-saves.patch
0026-lm3-depth-mode.patch
0027-nsp-title-id-from-package.patch
+0028-cheats-engine.patch
+0029-cheats-mac-panel.patch