Load Atmosphere cheat files and switch their cheats from a Cheats tab in the menu

Players bring their own cheats\<build id>.txt next to totk.exe; none ship with the port. The setup turns cheats that
write main's code into patch sets (tools/cheats.py), cheats that write data run in a cheat VM after dmnt's every
presented frame (runtime/cheats.c), and the menu's Cheats tab switches each one, saved under [cheats] in totk.ini.

The patch table now takes several sets per site, first set in file order winning, and replacements that end in a
branch or ret, so cheats that patch the same instruction or end in a jump can be built.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
conongnangandClaude Opus 5.5 committed 2026-10-30 10:28:37 +07:00
1 parent c3b9a4e7f6
commit 3df82b8842
16 files changed
+1241 -74

No files matched your search

+1
View File
@@ -22,6 +22,7 @@ Report problems as issues, following [CONTRIBUTING.md](CONTRIBUTING.md).
- In-game settings menu (F1) and performance overlay (F10)
- Keyboard, mouse and gamepad with remapping, rumble and gyro
- Shaders prepared at install instead of during play
- Atmosphère cheat files: bring your own, switch cheats in the menu ([docs/cheats.md](docs/cheats.md))
## Planned
+62
View File
@@ -0,0 +1,62 @@
# Cheats
The port reads Atmosphère cheat files, the format Switch homebrew and the emulators use. No cheats ship with the port: bring your own file for your game update.
## Adding a cheat file
1. Find the cheat file for your update. It is named after the first 8 bytes of the game's build id:
| Update | File |
|---|---|
| 1.2.1 | `9B4E43650501A4D4.txt` |
| 1.4.3 | `277178B7DBA1B6D4.txt` |
The Cheats tab of the menu names the file the installed game reads, and `logs\totk.log` says `cheats: no cheats\<id>.txt` when it is missing.
2. Put it in a `cheats` folder next to `totk.exe`: `cheats\277178B7DBA1B6D4.txt`.
3. Run `TotK-Setup.exe` again on the same folder. It builds the cheats that change the game's code into the game (about three minutes); saves and settings are kept. A file with only data cheats works without this step.
4. In game, open the menu (F1) and switch cheats on and off on the Cheats tab. The switches are saved under `[cheats]` in `totk.ini`.
## The file format
Standard Atmosphère: a `[name]` line starts a cheat, `{name}` a master cheat that is always on, and the cheat's opcodes follow as 8-digit hex words. A name with no opcodes is shown as a heading. The file's title line (the one with `TID=`) is not shown.
```
[The Legend of Zelda: Tears of the Kingdom v1.4.3 TID=0100F2C0115B6000 BID=277178B7DBA1B6D4]
[Player]
[A code cheat]
040A0000 XXXXXXXX YYYYYYYY
[A data cheat (Hold ZL+X)]
80000104
580F0000 XXXXXXXX
640F0000 00000000 YYYYYYYY
20000000
```
The words above are placeholders: `XXXXXXXX` an offset, `YYYYYYYY` a value.
Each cheat's switch is `cheat_<hash> = 1`, where the hash is FNV-1a 32 of the cheat's name. Two files that use the same names, for example one per update, share their switches.
## How cheats run
The game's code is compiled ahead of time, so a cheat cannot write new instructions into it while the game runs. The port sorts each cheat by what it writes (`tools/cheats.py` at setup, `runtime/cheats.c` in game):
| Kind | What the cheat does | How the port runs it |
|---|---|---|
| code | Opcode 0 writes into main's code | Built into the game at setup as a patch set (`recomp/patches.py`); switches at once. |
| key | Code writes inside a button condition (`8` mask, writes, `21` else, the original words, `20`) | A patch set that is on while the cheat is on and the buttons are held. |
| data | Writes data only: heap, main's data, pointer chains, button conditions | Runs in a cheat VM after dmnt's, opcodes 0 to A, every presented frame while on. |
| master | `{name}` with code writes | A patch set that is always on. |
| restore | Writes back only the game's original instructions | Not needed: switching a cheat off restores them. Greyed out. |
A cheat whose code writes call or jump into a code cave the cheat writes itself (into main's zero padding) gets the cave inlined at the call site. A code cheat added to the file or edited after the setup ran is greyed out until the setup runs again; a data cheat runs at once.
Not supported, and shown greyed out with the reason:
- the 0xC and 0xF opcode extensions;
- opcode 5 with a register offset;
- code writes mixed with other opcodes, except the button pattern above;
- code writes that change the CPU flags differently from the game's instruction, or code caves with branches or pc-relative instructions.
`cheats\<build id>.status`, written by the setup, records which cheats were built and how; the log line `cheats: ...` sums it up at start.
+25 -2
View File
@@ -490,12 +490,24 @@ EMITTED = re.compile(r'^emitted (\d+)/(\d+) chunks')
DISCOVERED = re.compile(r'^(\w+): \d+ functions \(.*discovery')
def cheats_file(ctx):
"""<dest>/cheats/<build id>.txt, the Atmosphere cheat file of the installed main (tools/cheats.py), whether or not
it exists."""
try:
with open(ctx.dest / 'exefs' / 'main', 'rb') as f:
bid = f.read(0x48)[0x40:0x48].hex().upper()
except OSError:
bid = 'unknown'
return ctx.dest / 'cheats' / f'{bid}.txt'
class Lift(Step):
id = 'lift'
transient = True
def key(self, ctx):
return fingerprint('lift-1', ctx.keys['extract'], ctx.layout.recomp, ctx.layout.patches(game_version(ctx)))
return fingerprint('lift-2', ctx.keys['extract'], ctx.layout.recomp, ctx.layout.patches(game_version(ctx)),
ctx.layout.tools / 'cheats.py', cheats_file(ctx))
def current(self, ctx, record):
gen = ctx.temp / 'gen'
@@ -512,8 +524,19 @@ class Lift(Step):
if m:
rep.progress('lift', 'emit', int(m.group(1)), int(m.group(2)), 'chunks')
# The code cheats of the cheat file become patch sets (tools/cheats.py); its status file tells the runtime
# which cheats the build has.
patches, cheats = layout.patches(game_version(ctx)), cheats_file(ctx)
if cheats.is_file():
combined = ctx.temp / 'patches-cheats.txt'
code, log = run_tool(ctx, 'lift', layout.tools / 'cheats.py',
['--exefs', ctx.dest / 'exefs', '--cheats', cheats, '--patches', patches,
'--out', combined, '--status', cheats.with_suffix('.status')])
if code:
raise InstallError('lift.failed', code=code, log=str(log))
patches = combined
code, log = run_tool(ctx, 'lift', layout.recomp / 'gen.py',
['--exefs', ctx.dest / 'exefs', '--out', gen, '--patches', layout.patches(game_version(ctx))], parse)
['--exefs', ctx.dest / 'exefs', '--out', gen, '--patches', patches], parse)
if code:
raise InstallError('lift.failed', code=code, log=str(log))
(gen / STAMP).write_text(ctx.keys['lift'] + '\n')
+75 -40
View File
@@ -210,7 +210,7 @@ class Emitter:
def __init__(self, mod, starts, patched=None, reg_locals=regs.LOCALS, callee_saved=True, spins=None):
self.mod = mod
self.starts = starts
self.patched = patched or {} # {address: (set index, [replacement words])} (recomp/patches.py)
self.patched = patched or {} # {address: [(set index, [replacement words])]} (recomp/patches.py)
self.spins = spins or {} # {spin wait back-edge: its head} (recomp/patches.py `spin`)
self.reg_locals = reg_locals # recomp/regs.py: registers per function in C locals
self.kept = regs.CALLEE_SAVED if callee_saved else frozenset() # not reloaded after a call
@@ -249,33 +249,54 @@ class Emitter:
self.unsupported[re.sub(r'\b[0-9a-f]{8}\b', '', msg).strip()] += 1
elif k == 'asm':
raise ValueError(f'{entry + 4 * i:#x}: asm instruction from the portable lifter')
for a in self.patched: # a replacement's branch into the function needs its label
if entry <= a < end:
for words in self.replacements(a):
r = words[-1]
if r.kind in ('b', 'bcond') and entry <= r.target < end:
labels.add(r.target)
return labels, tables
def replacements(self, a):
"""Lifted replacement words of the patched site a."""
return [self.mod.lifter.lift(w, a) for w in self.patched[a][1]]
"""The lifted words of each alternative of the patched site a, in set order. Only the last word of an
alternative may branch (bl, b, b.cond / cbz / tbz, ret)."""
out = []
for _, words in self.patched[a]:
lifted = [self.mod.lifter.lift(w, a) for w in words]
for j, r in enumerate(lifted):
last = j == len(lifted) - 1
if r.kind != 'op' and not (last and r.kind in ('bl', 'b', 'bcond', 'ret')):
raise patches.PatchError(f'{a:#x}: replacement word {words[j]:08x} is a {r.kind}')
out.append(lifted)
return out
@staticmethod
def flow(insns, entry, end, tables):
def flow(self, insns, entry, end, tables):
"""Successors of each instruction inside the function [entry, end). Index len(insns) stands for falling
through into the next function and has none."""
through into the next function and has none. A patched site has the successors of all its alternatives."""
def idx(t):
return [(t - entry) // 4] if entry <= t < end else []
succ = []
for i, ins in enumerate(insns):
def of(ins, i):
k = ins.kind
if k in ('op', 'bl', 'blr'):
succ.append([i + 1])
elif k == 'b':
succ.append(idx(ins.target))
elif k == 'bcond':
succ.append(idx(ins.target) + [i + 1])
elif k == 'br':
return [i + 1]
if k == 'b':
return idx(ins.target)
if k == 'bcond':
return idx(ins.target) + [i + 1]
if k == 'br':
jt = tables.get(entry + 4 * i)
succ.append([t for x in jt for t in idx(x)] if jt and jt != 'all' else [])
else: # ret, trap
succ.append([])
return [t for x in jt for t in idx(x)] if jt and jt != 'all' else []
return [] # ret, trap
succ = []
for i, ins in enumerate(insns):
s = of(ins, i)
a = entry + 4 * i
if a in self.patched:
for words in self.replacements(a):
s += [t for t in of(words[-1], i) if t not in s]
succ.append(s)
succ.append([])
return succ
@@ -293,27 +314,34 @@ class Emitter:
exits.add(i) # through rt_dispatch, also a table's default
if a in self.patched:
effects.append(self.patched_effect(ins, a))
if any(r.kind == 'bl' for r in self.replacements(a)):
calls.add(i)
for words in self.replacements(a):
r = words[-1]
if r.kind == 'bl':
calls.add(i)
elif r.kind in ('b', 'bcond') and not entry <= r.target < end:
exits.add(i)
else:
effects.append(flags.effect(ins.cond if k == 'bcond' else ins.code or ''))
effects.append((False, None))
return flags.plan(effects, succ, calls, exits)
def patched_effect(self, ins, a):
"""Flag effect of a patched site: both alternatives must have the same one, in at most one word each."""
"""Flag effect of a patched site: every alternative (the original and each replacement) must write the same
flags, in at most one word each; the site reads flags when any alternative does (a b.cond reads them)."""
alts = []
for words in ([ins], self.replacements(a)):
fx = [flags.effect(w.code or '') for w in words if w.kind == 'op']
for words in [[ins]] + self.replacements(a):
fx = [flags.effect(w.code or '') if w.kind == 'op' else flags.effect(w.cond) for w in words
if w.kind in ('op', 'bcond')]
fx = [e for e in fx if e[0] or e[1]]
if len(fx) > 1:
raise patches.PatchError(f'{a:#x}: several flag-using words in one alternative')
alts.append(fx[0] if fx else (False, None))
if alts[0][1] != alts[1][1]:
raise patches.PatchError(f'{a:#x}: the alternatives write different flags ({alts[0][1]}, {alts[1][1]})')
if (alts[0][1] or alts[0][0] or alts[1][0]) and ins.kind == 'bl':
if any(e[1] != alts[0][1] for e in alts):
raise patches.PatchError(f'{a:#x}: the alternatives write different flags ({[e[1] for e in alts]})')
reads = any(e[0] for e in alts)
if (alts[0][1] or reads) and (ins.kind == 'bl' or any(w[-1].kind == 'bl' for w in self.replacements(a))):
raise patches.PatchError(f'{a:#x}: a patched call that uses flags')
return alts[0][0] or alts[1][0], alts[0][1]
return reads, alts[0][1]
def function(self, entry, end):
"""(lines of C, referenced function starts) for the guest function [entry, end)."""
@@ -384,23 +412,30 @@ class Emitter:
code = fx(i, code)
return f'{spill}{code}{reload}' if regs.ESCAPE.search(code) else code
def one(i, r, a):
"""C of one lifted word of a patched site."""
if r.kind == 'op':
return op(i, r.code)
if r.kind == 'bl':
return call(r.target, a)
if r.kind == 'b':
return jump(r.target, i)
if r.kind == 'bcond':
return f'if ({fx(i, r.cond)}) {{ {jump(r.target, i)} }}'
if r.kind == 'ret':
return f'{spill}return;'
raise patches.PatchError(f'{a:#x}: patched instruction is a {r.kind}')
def patch(i, ins, a):
"""if (switch) { replacement } else { original } for a patched site (recomp/patches.py)."""
k, words = self.patched[a]
if ins.kind not in ('op', 'bl'):
"""if (switch) { replacement } else if ... else { original } for a patched site (recomp/patches.py)."""
if ins.kind not in ('op', 'bl', 'b', 'bcond'):
raise patches.PatchError(f'{a:#x}: patched instruction is a {ins.kind}')
repl = []
for j, (w, r) in enumerate(zip(words, self.replacements(a))):
if r.kind == 'op':
repl.append(op(i, r.code))
elif r.kind == 'bl' and j == len(words) - 1:
repl.append(call(r.target, a))
else:
raise patches.PatchError(f'{a:#x}: replacement word {w:08x} is a {r.kind}')
orig = op(i, ins.code) if ins.kind == 'op' else call(ins.target, a)
line = ' '
for (k, _), words in zip(self.patched[a], self.replacements(a)):
line += f' if (rt_patch_on[{k}]) {{ {" ".join(one(i, r, a) for r in words)} }} else'
self.uses_patches = True
self.stats['patched_sites'] += 1
return f' if (rt_patch_on[{k}]) {{ {" ".join(repl)} }} else {{ {orig} }}'
return f'{line} {{ {one(i, ins, a)} }}'
body = [] # (instruction index or None for a label, line); a line belongs to the instruction it lifts
@@ -444,7 +479,7 @@ class Emitter:
else:
raise ValueError(f'{a:#x}: unknown instruction kind {k!r}')
n = len(insns)
if k not in TERMINATORS: # falls through into the next function
if k not in TERMINATORS or end - 4 in self.patched: # falls through into the next function
if end < mod.hi:
emit(n, ' ' + jump(end, n))
else:
+19 -13
View File
@@ -14,10 +14,12 @@ encoded for the site's address. The patch page is the first 4 KiB page after mai
of the 2 MiB-aligned module slot free); the runtime commits it and owns its contents.
The replacement words are lifted at the site's address in place of the original instruction, and the generated C reads
`if (rt_patch_on[<set>]) { replacement } else { original }`: one byte load and a branch per executed site. Replacement
words must not branch except a final `bl` (lifted with the site's return address); the original must not be a branch
other than `bl`. So the function's control flow, labels and jump tables are the original's. The generator writes
patches.h (set names, switches, the page address) next to layout.h for the runtime.
`if (rt_patch_on[<set>]) { replacement } else { original }`: one byte load and a branch per executed site. Several
sets may patch one address (cheats that write different values there): `if (a) {..} else if (b) {..} else {..}`, the
first set in file order wins. The original may be any instruction but br, blr and ret; a replacement's last word may be
a bl (lifted with the site's return address), a b or b.cond / cbz / tbz (its target joins the function's labels when
inside it) or a ret; earlier words must not branch. Every alternative of a site writes the same flags. The generator
writes patches.h (set names, switches, the page address) next to layout.h for the runtime.
A `spin` line names a spin wait found by tools/spin_waits.py: a loop with head <head> that only another thread can end,
and the direct branches back to it (module offsets). Each back-edge (checked: a b, b.cond, cbz / cbnz or tbz / tbnz to
@@ -42,7 +44,8 @@ def adrp(pc, target, rd):
class Table:
"""sets: [(name, env, default)]; sites: {module: {offset: (set index, [word | ('page', reg)], original)}}; page."""
"""sets: [(name, env, default)]; sites: {module: {offset: [(set index, [word | ('page', reg)], original)]}} (the
alternatives of a site in file order); page."""
def __init__(self, sets=(), sites=None, page=0, spins=None):
self.sets = list(sets)
@@ -55,11 +58,12 @@ class Table:
return {base + b: base + h for b, h in self.spins.get(name, {}).items()}
def for_module(self, name, base):
"""{absolute address: (set index, [words])} with @page resolved."""
"""{absolute address: [(set index, [words])]} with @page resolved."""
out = {}
for off, (k, repl, _) in self.sites.get(name, {}).items():
for off, alts in self.sites.get(name, {}).items():
a = base + off
out[a] = (k, [adrp(a, self.page, w[1]) if isinstance(w, tuple) else w for w in repl])
out[a] = [(k, [adrp(a, self.page, w[1]) if isinstance(w, tuple) else w for w in repl])
for k, repl, _ in alts]
return out
@@ -89,10 +93,12 @@ def load(path, mods):
repl.append(('page', int(w[7:])))
else:
repl.append(int(w, 16))
mod = sites.setdefault(f[2], {})
if off in mod:
raise PatchError(f'{where}: {f[2]}+{off:#x} patched twice')
mod[off] = (index[f[1]], repl, orig)
alts = sites.setdefault(f[2], {}).setdefault(off, [])
if any(k == index[f[1]] for k, _, _ in alts):
raise PatchError(f'{where}: {f[2]}+{off:#x} patched twice by set {f[1]}')
if alts and alts[0][2] != orig:
raise PatchError(f'{where}: {f[2]}+{off:#x} expects {orig:08x}, an earlier line {alts[0][2]:08x}')
alts.append((index[f[1]], repl, orig))
elif f[0] == 'spin' and len(f) >= 4:
if f[1] not in bases:
raise PatchError(f'{where}: module {f[1]} not in the layout')
@@ -114,7 +120,7 @@ def load(path, mods):
def check(table, mod, name):
"""Stops on a site whose original word differs from the module's."""
for off, (_, _, want) in table.sites.get(name, {}).items():
for off, [(_, _, want), *_] in table.sites.get(name, {}).items():
a = mod.base + off
if not mod.in_text(a):
raise PatchError(f'{name}+{off:#x}: patch site outside .text')
+2
View File
@@ -15,6 +15,7 @@
#include <string.h>
#include "cfg.h"
#include "cheats.h"
#include "fs.h"
#include "gfx.h"
#include "nvn_api.h"
@@ -341,6 +342,7 @@ void rt_boot(void) {
rt_patches_init();
frame_step_init();
res_init();
cheats_init(); // after the patch sets: a cheat's set follows its setting
cb_addr[0] = hostfn_register("<rtld loader_ready>", cb_loader_ready);
cb_addr[1] = hostfn_register("<rtld module_inits>", cb_module_inits);
cb_addr[2] = hostfn_register("<rtld module_finis>", cb_module_finis);
+2 -1
View File
@@ -132,7 +132,7 @@ static const CfgMeta metas[] = {
static int is_known(const char *key) {
for (size_t i = 0; i < sizeof known / sizeof *known; i++)
if (!strcmp(known[i], key)) return 1;
return 0;
return !strncmp(key, "CHEAT_", 6); // cheats.c and the cheat patch sets (tools/cheats.py)
}
static void clear(void) {
@@ -391,6 +391,7 @@ static void puts_(Out *o, const char *s) { put(o, s, strlen(s)); }
static const char *section_of(const char *key) {
for (size_t i = 0; i < sizeof sections / sizeof *sections; i++)
if (!strcmp(sections[i].key, key)) return sections[i].section;
if (!strncmp(key, "CHEAT_", 6)) return "cheats"; // cheats.c: one key per cheat of the cheat file
return NULL;
}
+516
View File
@@ -0,0 +1,516 @@
// Cheats of an Atmosphere cheat file (cheats.h). The file is cheats\<build id>.txt next to totk.exe, the build id the
// first 8 bytes of main's NSO build id, as Atmosphere and the emulators name it. Each cheat's switch is the setting
// TOTK_CHEAT_<name hash> (cheat_<hash> under [cheats] in totk.ini).
//
// Code cheats (opcode 0 writes into main's code) cannot be applied here: the game's code is lifted C. tools/cheats.py
// turns them into patch sets cheat_<hash> when the game is built and writes cheats\<build id>.status, one line per
// cheat: name hash, content hash, kind, buttons, note (tools/cheats.py has the format). A cheat whose status line is
// missing or has another content hash was added or edited after the build: a data cheat runs anyway, a code cheat waits
// for the setup to run again.
//
// Data cheats run in a VM after Atmosphere's dmnt cheat VM (opcodes 0-A; the 0xC.. and 0xF.. extensions are not
// supported), every presented frame while their switch is on, with registers cleared before each cheat. Memory is the
// guest's, mapped at its own addresses: main's image is written through VirtualProtect (its read-only data included,
// as dmnt writes through the debugger), everything else after mem_query says the guest may read or write it. Buttons
// are input_poll's HidNpadButton bits, the same as the cheat format's key masks; they read 0 while the menu is open.
#include <windows.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cfg.h"
#include "cheats.h"
#include "host.h"
#include "input.h"
#include "platform/platform.h"
enum { STATUS_MAX = 160, OPS_PER_RUN = 1 << 20 };
typedef struct {
CheatInfo info;
uint32_t *words;
int n;
int set; // patch set, -1 none
volatile LONG on;
char note[STATUS_MAX];
} Cheat;
static Cheat *g_cheats;
static int g_n, g_vm; // g_vm: some cheat needs cheats_frame
static char g_file[64];
static uint64_t g_main, g_main_size, g_code_end; // main's image; its code with the padding up to .rodata
static uint32_t fnv(const char *s, size_t n) {
uint32_t h = 0x811C9DC5u;
for (size_t i = 0; i < n; i++) h = (h ^ (uint8_t)s[i]) * 0x01000193u;
return h;
}
// The folder of totk.exe, UTF-8, with a trailing backslash.
static int exe_dir(char *out, int n) {
wchar_t w[MAX_PATH * 2];
DWORD k = GetModuleFileNameW(NULL, w, MAX_PATH * 2);
if (!k || k >= MAX_PATH * 2) return 0;
wchar_t *cut = wcsrchr(w, L'\\');
if (!cut) return 0;
cut[1] = 0;
return WideCharToMultiByte(CP_UTF8, 0, w, -1, out, n, NULL, NULL) > 0;
}
static int build_id(char out[17]) {
char path[1024];
snprintf(path, sizeof path, "%s/main", rt_config()->exefs);
wchar_t w[1024];
if (!MultiByteToWideChar(CP_UTF8, 0, path, -1, w, 1024)) return 0;
HANDLE f = CreateFileW(w, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
if (f == INVALID_HANDLE_VALUE) return 0;
uint8_t head[0x48];
DWORD got = 0;
int ok = ReadFile(f, head, sizeof head, &got, NULL) && got == sizeof head && !memcmp(head, "NSO0", 4);
CloseHandle(f);
for (int i = 0; ok && i < 8; i++) snprintf(out + 2 * i, 3, "%02X", head[0x40 + i]);
return ok;
}
// ---- opcodes
// Words of the opcode at w (left words remain), 0 when it is cut short.
static int op_len(const uint32_t *w, int left) {
uint32_t f = w[0];
int t = f >> 28, width = (f >> 24) & 0xF, n;
switch (t) {
case 0: case 1: n = width == 8 ? 4 : 3; break;
case 2: case 8: n = 1; break;
case 3: n = width == 0 ? 2 : 1; break;
case 4: case 6: n = 3; break;
case 5: case 7: n = 2; break;
case 9: n = 1 + (((f >> 8) & 0xF) ? (width == 8 ? 2 : 1) : 0); break;
case 0xA: n = ((f >> 8) & 0xF) == 2 || ((f >> 8) & 0xF) == 4 || ((f >> 8) & 0xF) == 5 ? 2 : 1; break;
default: n = 1; break;
}
return n <= left ? n : 0;
}
// NULL when the VM runs the opcode, else why not (tools/cheats.py vm_ok).
static const char *vm_unsupported(const uint32_t *w, char *buf, int n) {
uint32_t f = w[0];
int t = f >> 28, width = (f >> 24) & 0xF;
if (t > 0xA || (t == 5 && ((f >> 12) & 0xF) > 1) || (t == 0xA && ((f >> 8) & 0xF) > 5)) {
snprintf(buf, n, "opcode %08X is not supported", f);
return buf;
}
if ((t <= 1 || t == 5 || t == 6 || t == 7 || t == 9 || t == 0xA) && width != 1 && width != 2 && width != 4 &&
width != 8) {
snprintf(buf, n, "opcode %08X has a bad width", f);
return buf;
}
return NULL;
}
// The kind of a cheat the build did not see: heading, data, rebuild (it writes main's code) or unsupported.
static CheatKind classify(Cheat *c) {
int ops = 0, ends = 0;
for (int i = 0; i < c->n;) {
int len = op_len(c->words + i, c->n - i);
if (!len) {
snprintf(c->note, sizeof c->note, "opcode %08X is cut short", c->words[i]);
return CHEAT_UNSUPPORTED;
}
uint32_t f = c->words[i];
ops++;
ends += f >> 28 == 2;
if (f >> 28 == 0 && ((f >> 20) & 0xF) == 0) {
uint64_t off = ((uint64_t)(f & 0xFF) << 32) | c->words[i + 1];
if (off < g_code_end - g_main) return CHEAT_REBUILD;
}
if (vm_unsupported(c->words + i, c->note, sizeof c->note)) return CHEAT_UNSUPPORTED;
i += len;
}
return ops == ends && ops <= 1 ? CHEAT_HEADING : CHEAT_DATA;
}
// ---- guest memory
static uint64_t region(int m) {
const RtGuestLayout *l = mem_layout();
switch (m) {
case 0: return g_main;
case 1: return l->heap.base;
case 2: return l->alias.base;
case 3: return l->aslr.base;
default: return 0;
}
}
static int in_main(uint64_t a, unsigned n) { return a >= g_main && a + n <= g_main + g_main_size; }
static int guest_ok(uint64_t a, unsigned n, uint32_t perm) {
if (in_main(a, n)) return 1;
RtMemoryInfo mi;
if (mem_query(a, &mi) || !mi.state || (mi.perm & perm) != perm) return 0;
return a + n <= mi.base + mi.size;
}
static int rd(uint64_t a, int width, uint64_t *v) {
if (!a || !guest_ok(a, (unsigned)width, 1)) return 0;
uint64_t x = 0;
memcpy(&x, (const void *)(uintptr_t)a, (size_t)width);
*v = x;
return 1;
}
static void wr(uint64_t a, int width, uint64_t v) {
uint64_t now;
if (!rd(a, width, &now) || !memcmp(&now, &v, (size_t)width)) return; // unchanged: no write, no protection change
void *p = (void *)(uintptr_t)a;
if (in_main(a, (unsigned)width)) {
DWORD old, back;
if (!VirtualProtect(p, (SIZE_T)width, PAGE_READWRITE, &old)) return;
memcpy(p, &v, (size_t)width);
VirtualProtect(p, (SIZE_T)width, old, &back);
} else if (guest_ok(a, (unsigned)width, 2)) {
memcpy(p, &v, (size_t)width); // a frozen region thaws on the write (memory.c)
}
}
static uint64_t masked(int width, uint64_t v) { return width >= 8 ? v : v & ((1ull << (8 * width)) - 1); }
static uint64_t arith(int op, uint64_t a, uint64_t b) {
switch (op) {
case 0: return a + b;
case 1: return a - b;
case 2: return a * b;
case 3: return b < 64 ? a << b : 0;
case 4: return b < 64 ? a >> b : 0;
case 5: return a & b;
case 6: return a | b;
case 7: return ~a;
case 8: return a ^ b;
default: return a; // 9: move
}
}
static int compare(int cond, uint64_t a, uint64_t b) {
switch (cond) {
case 1: return a > b;
case 2: return a >= b;
case 3: return a < b;
case 4: return a <= b;
case 5: return a == b;
case 6: return a != b;
default: return 0;
}
}
// From i (after a failed condition, or an else reached while running), the opcode to continue at: after the
// matching else (else_ok) or end.
static int skip(const uint32_t *w, int n, int i, int else_ok) {
int depth = 0;
while (i < n) {
int len = op_len(w + i, n - i);
if (!len) return n;
uint32_t f = w[i];
int t = f >> 28;
i += len;
if (t == 1 || t == 8) depth++;
else if (t == 2 && ((f >> 24) & 0xF) == 0 && depth-- == 0) return i;
else if (t == 2 && depth == 0 && else_ok) return i;
}
return n;
}
static uint64_t imm64(const uint32_t *w) { return (uint64_t)w[0] << 32 | w[1]; }
static void run(const Cheat *c, uint64_t keys) {
uint64_t r[16] = {0};
int loop[16] = {0};
const uint32_t *w = c->words;
int n = c->n, budget = OPS_PER_RUN;
for (int i = 0; i < n && budget-- > 0;) {
int len = op_len(w + i, n - i);
if (!len) return;
uint32_t f = w[i];
int t = f >> 28, width = (f >> 24) & 0xF, x = (f >> 20) & 0xF, y = (f >> 16) & 0xF, z = (f >> 12) & 0xF;
uint64_t rel = ((uint64_t)(f & 0xFF) << 32) | (len > 1 ? w[i + 1] : 0), v;
switch (t) {
case 0: // 0TMR00AA AAAAAAAA V..: store a value at region M + A + register R
wr(region(x) + rel + r[y], width, width == 8 ? imm64(w + i + 2) : w[i + 2]);
break;
case 1: // 1TMC00AA AAAAAAAA V..: if (region M + A) <cond C> V
if (!rd(region(x) + rel, width, &v) || !compare(y, v, width == 8 ? imm64(w + i + 2) : w[i + 2])) {
i = skip(w, n, i + len, 1);
continue;
}
break;
case 2: // 20000000 end, 21000000 else: an else reached while running skips to the end
if (width == 1) {
i = skip(w, n, i + len, 0);
continue;
}
break;
case 3: // 300R0000 VVVVVVVV loop start, 310R0000 loop end
if (width == 0) {
r[y] = w[i + 1];
loop[y] = i + len;
} else if (r[y] && --r[y]) {
i = loop[y];
continue;
}
break;
case 4: // 400R0000 V V: register R = V
r[y] = imm64(w + i + 1);
break;
case 5: // 5TMRI0AA AAAAAAAA: R = (I ? R : region M) + A, read
if (!rd(z ? r[y] + rel : region(x) + rel, width, &v)) return; // a broken pointer chain: nothing more
r[y] = v;
break;
case 6: { // 6T0RIor0 V V: store V at R (+ register r); I: R += width
uint64_t a = r[y] + (((f >> 8) & 0xF) ? r[(f >> 4) & 0xF] : 0);
wr(a, width, imm64(w + i + 1));
if (z) r[y] += (uint64_t)width;
break;
}
case 7: // 7T0RC000 VVVVVVVV: R = R <op C> V
r[y] = masked(width, arith(z, r[y], w[i + 1]));
break;
case 8: // 8kkkkkkk: if the buttons are held
if ((keys & (f & 0x0FFFFFFF)) != (f & 0x0FFFFFFF)) {
i = skip(w, n, i + len, 1);
continue;
}
break;
case 9: { // 9TCRS0s0 / 9TCRS100 V..: R = S <op C> (s or V)
uint64_t b = (f >> 8) & 0xF ? (width == 8 ? imm64(w + i + 1) : w[i + 1]) : r[(f >> 4) & 0xF];
r[y] = masked(width, arith(x, r[z], b));
break;
}
case 0xA: { // ATSRIOxa (aaaaaaaa): store register S at an address of type O
int o = (f >> 8) & 0xF, m = (f >> 4) & 0xF;
uint64_t imm = ((uint64_t)(f & 0xF) << 32) | (len > 1 ? w[i + 1] : 0), a;
switch (o) {
case 0: a = r[y]; break;
case 1: a = r[y] + r[m]; break;
case 2: a = r[y] + imm; break;
case 3: a = region(m) + r[y]; break;
case 4: a = region(m) + imm; break;
default: a = region(m) + r[y] + imm; break;
}
wr(a, width, r[x]);
if (z) r[y] += (uint64_t)width;
break;
}
default:
return;
}
i += len;
}
}
// ---- the file
static char *read_text(const char *path) {
uint64_t n = 0;
char *s = (char *)plat_file_read(path, &n);
if (s && n >= 3 && !memcmp(s, "\xEF\xBB\xBF", 3)) memmove(s, s + 3, (size_t)n - 2); // a UTF-8 BOM
return s;
}
static void add_word(Cheat *c, uint32_t v, int *cap) {
if (c->n == *cap) {
*cap = *cap ? *cap * 2 : 16;
c->words = (uint32_t *)realloc(c->words, sizeof *c->words * (size_t)*cap);
if (!c->words) rt_fatal("cheats: out of memory");
}
c->words[c->n++] = v;
}
static void parse(char *s) {
int cap = 0, wcap = 0;
for (char *line = s; line && *line;) {
char *end = strchr(line, '\n'), *next = end ? end + 1 : NULL;
if (end) *end = 0;
while (*line == ' ' || *line == '\t') line++;
size_t len = strlen(line);
while (len && (line[len - 1] == '\r' || line[len - 1] == ' ' || line[len - 1] == '\t')) line[--len] = 0;
if (len >= 2 && (line[0] == '[' || line[0] == '{') && (line[len - 1] == ']' || line[len - 1] == '}')) {
if (g_n == cap) {
cap = cap ? cap * 2 : 32;
g_cheats = (Cheat *)realloc(g_cheats, sizeof *g_cheats * (size_t)cap);
if (!g_cheats) rt_fatal("cheats: out of memory");
}
Cheat *c = &g_cheats[g_n++];
memset(c, 0, sizeof *c);
line[len - 1] = 0;
char *name = line + 1;
while (*name == ' ' || *name == '\t') name++;
size_t k = strlen(name);
while (k && (name[k - 1] == ' ' || name[k - 1] == '\t')) name[--k] = 0;
c->info.name = _strdup(name);
c->info.kind = line[0] == '{' ? CHEAT_MASTER : CHEAT_HEADING;
c->set = -1;
wcap = 0;
} else if (g_n) {
for (char *tok = strtok(line, " \t"); tok; tok = strtok(NULL, " \t")) {
char *e;
unsigned long v = strtoul(tok, &e, 16);
if (e - tok == 8 && !*e) add_word(&g_cheats[g_n - 1], (uint32_t)v, &wcap);
}
}
line = next;
}
}
// The status line of key, its fields split in place; 0 when none.
static int status_of(char *status, const char *key, char **fields) {
for (char *line = status; line && *line;) {
char *end = strchr(line, '\n'), *next = end ? end + 1 : NULL;
if (!strncmp(line, key, 8) && line[8] == '\t') {
static char copy[512];
size_t n = end ? (size_t)(end - line) : strlen(line);
if (n >= sizeof copy) n = sizeof copy - 1;
memcpy(copy, line, n);
copy[n] = 0;
if (n && copy[n - 1] == '\r') copy[n - 1] = 0;
int k = 0;
fields[k++] = copy;
for (char *p = copy; *p && k < 5; p++)
if (*p == '\t') *p = 0, fields[k++] = p + 1;
while (k < 5) fields[k++] = (char *)"";
return 1;
}
line = next;
}
return 0;
}
void cheats_init(void) {
const RtLoaded *m = ldr_count() ? ldr_module(0) : NULL;
char dir[MAX_PATH * 3], bid[17], path[MAX_PATH * 3 + 64];
if (!m || !exe_dir(dir, sizeof dir) || !build_id(bid)) return;
g_main = m->base;
g_main_size = m->size;
g_code_end = m->base + ((m->text_end + 0xFFF) & ~0xFFFull);
snprintf(g_file, sizeof g_file, "cheats\\%s.txt", bid);
snprintf(path, sizeof path, "%s%s", dir, g_file);
char *text = read_text(path);
if (!text) {
rt_log("cheats: no %s", g_file);
return;
}
parse(text);
free(text);
snprintf(path, sizeof path, "%scheats\\%s.status", dir, bid);
char *status = read_text(path);
int counts[CHEAT_UNSUPPORTED + 1] = {0}, seen_dups = 0;
for (int i = 0; i < g_n; i++) {
Cheat *c = &g_cheats[i];
// the name hash: a repeated name gets "#2", "#3" ... (tools/cheats.py parse)
int dup = 1;
for (int j = 0; j < i; j++) dup += !strcmp(g_cheats[j].info.name, c->info.name);
char named[600];
snprintf(named, sizeof named, dup > 1 ? "%s#%d" : "%s", c->info.name, dup);
seen_dups += dup > 1;
char key[9], content[9];
snprintf(key, sizeof key, "%08X", fnv(named, strlen(named)));
size_t tn = (size_t)c->n * 9 + 1, tl = 0;
char *t = (char *)malloc(tn);
if (!t) rt_fatal("cheats: out of memory");
t[0] = 0;
for (int k = 0; k < c->n; k++) tl += (size_t)snprintf(t + tl, tn - tl, k ? " %08X" : "%08X", c->words[k]);
snprintf(content, sizeof content, "%08X", fnv(t, tl));
free(t);
snprintf(c->info.key, sizeof c->info.key, "TOTK_CHEAT_%s", key);
int master = c->info.kind == CHEAT_MASTER;
char *f[5];
CheatKind kind;
if (status && status_of(status, key, f) && !strcmp(f[1], content)) {
const char *k = f[2];
kind = !strcmp(k, "code") ? CHEAT_CODE : !strcmp(k, "key") ? CHEAT_KEY : !strcmp(k, "master") ? CHEAT_MASTER
: !strcmp(k, "restore") ? CHEAT_RESTORE : !strcmp(k, "heading") ? CHEAT_HEADING
: !strcmp(k, "data") ? CHEAT_DATA : CHEAT_UNSUPPORTED;
c->info.buttons = (uint32_t)strtoul(f[3], NULL, 16);
snprintf(c->note, sizeof c->note, "%s", f[4]);
if (kind == CHEAT_CODE || kind == CHEAT_KEY || kind == CHEAT_MASTER) {
char set[32];
snprintf(set, sizeof set, "cheat_%08x", fnv(named, strlen(named)));
c->set = rt_patch_set(set);
if (c->set < 0 && kind != CHEAT_MASTER) kind = CHEAT_REBUILD;
}
} else {
kind = classify(c);
}
if (master && kind == CHEAT_DATA) kind = CHEAT_MASTER; // a data master code: the VM, always on
c->info.kind = kind;
c->info.note = c->note;
const char *v = cfg_get(c->info.key);
c->on = kind == CHEAT_MASTER || (v && *v && strcmp(v, "0") != 0);
if (kind == CHEAT_KEY && c->set >= 0) rt_patch_switch(c->set, 0); // on while the buttons are held
if (kind == CHEAT_KEY || kind == CHEAT_DATA || (kind == CHEAT_MASTER && c->set < 0)) g_vm = 1;
counts[kind]++;
}
free(status);
int on = 0;
for (int i = 0; i < g_n; i++) on += g_cheats[i].on && g_cheats[i].info.kind != CHEAT_HEADING;
rt_log("cheats: %s: %d cheats, %d on; %d code, %d while buttons are held, %d data, %d master, %d restore, "
"%d headings, %d need the setup again, %d not supported%s",
g_file, g_n, on, counts[CHEAT_CODE], counts[CHEAT_KEY], counts[CHEAT_DATA], counts[CHEAT_MASTER],
counts[CHEAT_RESTORE], counts[CHEAT_HEADING], counts[CHEAT_REBUILD], counts[CHEAT_UNSUPPORTED],
seen_dups ? " (repeated names numbered)" : "");
}
int cheats_count(void) { return g_n; }
const CheatInfo *cheats_info(int i) { return i >= 0 && i < g_n ? &g_cheats[i].info : NULL; }
int cheats_on(int i) { return i >= 0 && i < g_n && g_cheats[i].on; }
const char *cheats_file(void) { return g_file; }
void cheats_set(int i, int on) {
if (i < 0 || i >= g_n) return;
Cheat *c = &g_cheats[i];
if (c->info.kind != CHEAT_CODE && c->info.kind != CHEAT_KEY && c->info.kind != CHEAT_DATA) return;
InterlockedExchange(&c->on, on != 0);
if (c->info.kind == CHEAT_CODE) rt_patch_switch(c->set, on); // CHEAT_KEY: cheats_frame follows the buttons
cfg_set(c->info.key, on ? "1" : "0");
rt_log("cheats: %s %s", c->info.name, on ? "on" : "off");
}
void cheats_frame(uint64_t frame) {
if (!g_vm || frame < 60) return; // the game polls its input (and starts SDL) before this
uint64_t keys = 0;
int32_t lx, ly, rx, ry;
input_poll(&keys, &lx, &ly, &rx, &ry); // 0 while the menu is open
for (int i = 0; i < g_n; i++) {
Cheat *c = &g_cheats[i];
switch (c->info.kind) {
case CHEAT_KEY:
if (c->set >= 0) {
int want = c->on && (keys & c->info.buttons) == c->info.buttons;
if (rt_patch_enabled(c->set) != want) rt_patch_switch(c->set, want);
}
break;
case CHEAT_DATA:
if (c->on) run(c, keys);
break;
case CHEAT_MASTER:
if (c->set < 0) run(c, keys);
break;
default:
break;
}
}
}
const char *cheats_buttons(uint32_t mask, char *buf, int n) {
static const char *const names[] = {"A", "B", "X", "Y", "Left stick press", "Right stick press", "L", "R", "ZL",
"ZR", "+", "-", "D-pad left", "D-pad up", "D-pad right", "D-pad down",
"Left stick left", "Left stick up", "Left stick right", "Left stick down",
"Right stick left", "Right stick up", "Right stick right", "Right stick down"};
int k = 0;
buf[0] = 0;
for (int b = 0; b < 24; b++)
if (mask & (1u << b)) k += snprintf(buf + k, (size_t)(n > k ? n - k : 0), "%s%s", k ? " + " : "", names[b]);
return buf;
}
+43
View File
@@ -0,0 +1,43 @@
// Cheats of an Atmosphere cheat file (cheats.c): cheats\<build id>.txt next to totk.exe, switched from the menu's
// Cheats tab. A cheat that writes the game's instructions is a code patch set that tools/cheats.py built into the game
// (switched with rt_patch_switch); one that writes data runs in the cheat VM every presented frame.
#pragma once
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
CHEAT_HEADING, // no opcodes: a title or a group label
CHEAT_CODE, // a patch set
CHEAT_KEY, // a patch set on while the buttons are held
CHEAT_DATA, // the cheat VM
CHEAT_MASTER, // {master}: always on
CHEAT_RESTORE, // writes the original instructions back: nothing to do
CHEAT_REBUILD, // writes instructions, but the game was built without this version of it
CHEAT_UNSUPPORTED, // note says why
} CheatKind;
typedef struct {
const char *name; // UTF-8, as in the file
const char *note; // why it is unsupported ("" otherwise)
CheatKind kind;
uint32_t buttons; // CHEAT_KEY: HidNpadButton mask
char key[24]; // its setting, TOTK_CHEAT_<name hash>
} CheatInfo;
void cheats_init(void); // after rt_patches_init: reads the file and its build status
int cheats_count(void);
const CheatInfo *cheats_info(int i);
int cheats_on(int i); // the player's switch (1 for a master cheat)
void cheats_set(int i, int on); // switches at once and sets the cheat's setting (the menu saves totk.ini)
const char *cheats_file(void); // "cheats\<build id>.txt"
// Every presented frame (the present path): the data cheats' VM and the button state of CHEAT_KEY cheats.
void cheats_frame(uint64_t frame);
// The button names of a mask ("ZL + Right stick left"), into buf.
const char *cheats_buttons(uint32_t mask, char *buf, int n);
#ifdef __cplusplus
}
#endif
+59 -6
View File
@@ -24,6 +24,7 @@
extern "C" {
#include "cfg.h"
#include "cheats.h"
#include "input.h"
#include "input_map.h"
#include "perfmon.h"
@@ -245,10 +246,11 @@ static int vk_up(const MenuTarget *t) {
return 1;
}
// Roboto Medium (Latin, Cyrillic, dashes and quotes) at 26 px per 1080 lines, with the glyphs of the Japanese, Korean
// and Chinese language names merged in from a system font when there is one (each language is named in its own script).
// Made again when the window height changes; the old texture goes after the queue is idle (CreateFontsTexture).
static const ImWchar kRanges[] = {0x0020, 0x00FF, 0x0400, 0x052F, 0x2010, 0x2027, 0};
// Roboto Medium (Latin, Cyrillic, dashes, quotes and the numero sign of cheat names) at 26 px per 1080 lines, with
// the glyphs of the Japanese, Korean and Chinese language names merged in from a system font when there is one (each
// language is named in its own script). Made again when the window height changes; the old texture goes after the
// queue is idle (CreateFontsTexture).
static const ImWchar kRanges[] = {0x0020, 0x00FF, 0x0400, 0x052F, 0x2010, 0x2027, 0x2116, 0x2116, 0};
static const struct { const char *lang; UiTextId name; } kCjk[] = {
{"ja", UI_MENU_LANGNAME_JA}, {"ko", UI_MENU_LANGNAME_KO}, {"zh-Hans", UI_MENU_LANGNAME_ZH_HANS},
{"zh-Hant", UI_MENU_LANGNAME_ZH_HANT},
@@ -299,7 +301,7 @@ extern "C" void menu_vk_release(void) {
// TOTK_MENU_TEST_SET=<frame>:<key>=<value>[,<key>=<value>...][;<frame>:...]: cfg_set of each key (TOTK_ prefix
// optional) at that presented frame; changes live settings with no input, menu open or not. totk.ini is written only by
// the pseudo-key SAVE=1 (cfg_save, as a row change does; a failed write shows the menu's save note).
enum { TAB_SCREEN, TAB_GAME, TAB_SOUND, TAB_CONTROLS, TAB_MENU, TAB_ADVANCED, TAB_COUNT };
enum { TAB_SCREEN, TAB_GAME, TAB_SOUND, TAB_CONTROLS, TAB_MENU, TAB_CHEATS, TAB_ADVANCED, TAB_COUNT };
enum { TEST_PAGE_FRAMES = 30, TEST_SETS = 16 };
struct TestSet { uint64_t frame; char key[64], value[64]; };
static struct {
@@ -580,6 +582,54 @@ static void tab_menu(float scale) {
opt_end();
}
// ---- Cheats: the cheats of cheats\<build id>.txt (cheats.c), a row per cheat in file order and a heading per group
// label; a cheat that cannot be switched here is greyed out with the reason.
static void tab_cheats(float scale) {
opt_begin("##cheats", scale);
static char line[512], desc[768], buttons[192];
int n = cheats_count();
if (!n) {
snprintf(line, sizeof line, menu_text(UI_MENU_CHEATS_NONE),
cheats_file()[0] ? cheats_file() : "cheats\\<build id>.txt");
opt_text_str(line);
opt_end();
return;
}
int listed = 0;
for (int i = 0; i < n; i++) listed += cheats_info(i)->kind != CHEAT_HEADING;
snprintf(line, sizeof line, menu_text(UI_MENU_CHEATS_FILE), cheats_file(), listed);
opt_text_str(line);
for (int i = 0; i < n; i++) {
const CheatInfo *c = cheats_info(i);
UiTextId text = UI_MENU_CHEAT_CODE_DESC;
switch (c->kind) {
case CHEAT_HEADING:
if (!strstr(c->name, "TID=")) opt_group_text(c->name); // the file's title line only names the game
continue;
case CHEAT_CODE: break;
case CHEAT_KEY: text = UI_MENU_CHEAT_KEY_DESC; break;
case CHEAT_DATA: text = UI_MENU_CHEAT_DATA_DESC; break;
case CHEAT_MASTER: text = UI_MENU_CHEAT_MASTER_DESC, opt_disable_next(UI_MENU_CHEAT_MASTER); break;
case CHEAT_RESTORE: text = UI_MENU_CHEAT_RESTORE_DESC, opt_disable_next(UI_MENU_CHEAT_RESTORE); break;
case CHEAT_REBUILD: text = UI_MENU_CHEAT_REBUILD_DESC, opt_disable_next(UI_MENU_CHEAT_REBUILD); break;
case CHEAT_UNSUPPORTED:
text = UI_MENU_CHEAT_UNSUPPORTED_DESC, opt_disable_next(UI_MENU_CHEAT_UNSUPPORTED);
break;
}
if (c->kind == CHEAT_KEY)
snprintf(desc, sizeof desc, menu_text(text), cheats_buttons(c->buttons, buttons, sizeof buttons));
else if (c->kind == CHEAT_UNSUPPORTED)
snprintf(desc, sizeof desc, "%s %s", menu_text(text), c->note);
else
snprintf(desc, sizeof desc, "%s", menu_text(text));
if (opt_toggle_text(c->key, c->name, desc, cheats_on(i) != 0)) {
cheats_set(i, !cheats_on(i));
opt_save_soon();
}
}
opt_end();
}
// ---- Advanced: the testing and troubleshooting keys, the bug report helpers and the reset of every setting
static bool g_modal; // the reset confirmation is open: B and Esc close it, not the menu; L / R stay on the page
@@ -737,7 +787,8 @@ static void tab_advanced(float scale) {
}
static const UiTextId kTabNames[TAB_COUNT] = {UI_MENU_TAB_SCREEN, UI_MENU_TAB_GAME, UI_MENU_TAB_SOUND,
UI_MENU_TAB_CONTROLS, UI_MENU_TAB_MENU, UI_MENU_TAB_ADVANCED};
UI_MENU_TAB_CONTROLS, UI_MENU_TAB_MENU, UI_MENU_TAB_CHEATS,
UI_MENU_TAB_ADVANCED};
static int g_tab; // the tab shown
static int g_tab_request = -1; // select this tab at the next layout; -1 none
static int g_focus_page = -1; // this tab's first row takes the cursor once it is shown; -1 none
@@ -789,6 +840,7 @@ static void layout_menu(uint32_t w, uint32_t h, float scale) {
case TAB_SOUND: tab_sound(scale); break;
case TAB_CONTROLS: tab_controls(scale); break;
case TAB_MENU: tab_menu(scale); break;
case TAB_CHEATS: tab_cheats(scale); break;
case TAB_ADVANCED: tab_advanced(scale); break;
}
ImGui::EndTabItem();
@@ -1065,6 +1117,7 @@ static void perf_draw(const MenuTarget *t, float scale) {
extern "C" int menu_overlay_frame(uint64_t frame, const MenuTarget *t, const char **shot) {
*shot = NULL;
cheats_frame(frame); // the data cheats and the buttons of the cheats that need them held
if (!g_test.parsed) test_parse();
if (g_test.next_set < g_test.n_sets && frame >= g_test.sets[g_test.next_set].frame) test_apply_sets(frame);
if (g_perf_save.exchange(0)) cfg_save();
+36 -11
View File
@@ -33,15 +33,15 @@ static char g_focus_key[64]; // opt_focus_key: the row that takes th
static bool g_held; // the last row's left / right has been held a while (steppers go faster)
static float g_bottom; // opt_reserve_bottom: kept free under the panes
static bool g_disable_next; // opt_disable_next: the next row is greyed out with g_disable_note
static UiTextId g_disable_note;
static const char *g_disable_note;
// The description pane: this frame's hovered and selected rows, the page's first row, and the last one shown.
struct Desc { char text[512]; };
static Desc g_hover, g_focus, g_first, g_shown;
// disabled: the note of a row opt_disable_next greyed out, else NULL.
static void desc_set(Desc &d, UiTextId desc, const char *key, const CfgMeta *m, const char *disabled) {
int n = snprintf(d.text, sizeof d.text, "%s", menu_text(desc));
static void desc_set(Desc &d, const char *desc, const char *key, const CfgMeta *m, const char *disabled) {
int n = snprintf(d.text, sizeof d.text, "%s", desc);
if (n < 0 || n >= (int)sizeof d.text) return;
if (disabled)
snprintf(d.text + n, sizeof d.text - n, "\n\n%s", disabled);
@@ -57,7 +57,9 @@ void opt_focus_key(const char *key) { snprintf(g_focus_key, sizeof g_focus_key,
void opt_reserve_bottom(float h) { g_bottom = h; }
void opt_disable_next(UiTextId note) {
void opt_disable_next(UiTextId note) { opt_disable_next_text(menu_text(note)); }
void opt_disable_next_text(const char *note) {
g_disable_next = true;
g_disable_note = note;
}
@@ -109,9 +111,9 @@ struct RowView {
// One row: draws it, handles A / click and left / right while selected. Returns 2 (A / click), -1 / +1 (left / right) or
// 0; always 0 for a row the environment fixes (greyed out, still selectable so its description shows).
static int row(const char *key, UiTextId label, UiTextId desc, const RowView &v) {
static int row_text(const char *key, const char *label, const char *desc, const RowView &v) {
const CfgMeta *m = cfg_meta(key);
const char *disabled = g_disable_next ? menu_text(g_disable_note) : NULL;
const char *disabled = g_disable_next ? g_disable_note : NULL;
g_disable_next = false;
bool off = disabled || cfg_from_env(key) != 0;
ImGui::PushID(key);
@@ -187,8 +189,7 @@ static int row(const char *key, UiTextId label, UiTextId desc, const RowView &v)
}
// the label and its note, clipped before the value
ImVec4 clip(p.x, p.y, value_left - fs * 0.6f, p.y + h);
dl->AddText(font, fs, ImVec2(p.x + pad, ty), off ? kGrey : IM_COL32(240, 236, 224, 255), menu_text(label), NULL, 0,
&clip);
dl->AddText(font, fs, ImVec2(p.x + pad, ty), off ? kGrey : IM_COL32(240, 236, 224, 255), label, NULL, 0, &clip);
const char *note = disabled ? disabled
: off ? menu_text(UI_MENU_SET_BY_ENV)
: m && !m->live ? menu_text(UI_MENU_AFTER_RESTART)
@@ -198,6 +199,10 @@ static int row(const char *key, UiTextId label, UiTextId desc, const RowView &v)
return off ? 0 : step;
}
static int row(const char *key, UiTextId label, UiTextId desc, const RowView &v) {
return row_text(key, menu_text(label), menu_text(desc), v);
}
// ---- writing a setting: at once in memory (live settings follow), to totk.ini a moment later (opt_save_tick)
static uint64_t g_save_at; // plat_now_ns deadline of the pending write; 0 none
static bool g_save_logged;
@@ -241,6 +246,26 @@ bool opt_button(const char *id, UiTextId label, UiTextId desc, const char *value
return row(id, label, desc, v) == 2; // A or a click; left and right do nothing
}
bool opt_toggle_text(const char *id, const char *label, const char *desc, bool on, const char *value) {
// off is the plain state: its value drawn dim, without the "default" mark
RowView v = {value ? value : menu_text(on ? UI_MENU_ON : UI_MENU_OFF), !on, false, on ? NULL : ""};
return row_text(id, label, desc, v) != 0; // any step flips it
}
void opt_group_text(const char *title) {
ImGui::Dummy(ImVec2(0, 6 * g_scale));
ImGui::PushTextWrapPos(0);
ImGui::TextColored(ImVec4(0.93f, 0.76f, 0.33f, 1), "%s", title);
ImGui::PopTextWrapPos();
}
void opt_text_str(const char *text, bool warn) {
ImGui::PushTextWrapPos(0);
if (warn) ImGui::TextColored(ImVec4(0.95f, 0.66f, 0.40f, 1), "%s", text);
else ImGui::TextUnformatted(text);
ImGui::PopTextWrapPos();
}
void opt_group(UiTextId title) {
ImGui::Dummy(ImVec2(0, 6 * g_scale));
ImGui::TextColored(ImVec4(0.93f, 0.76f, 0.33f, 1), "%s", menu_text(title));
@@ -400,9 +425,9 @@ int opt_bind_row(const char *key, const char *label, UiTextId desc, const char *
}
char k[64];
snprintf(k, sizeof k, "TOTK_%s", key);
if (row_foc) desc_set(g_focus, desc, k, NULL, NULL);
if (row_hov) desc_set(g_hover, desc, k, NULL, NULL);
if (!g_first.text[0]) desc_set(g_first, desc, k, NULL, NULL);
if (row_foc) desc_set(g_focus, menu_text(desc), k, NULL, NULL);
if (row_hov) desc_set(g_hover, menu_text(desc), k, NULL, NULL);
if (!g_first.text[0]) desc_set(g_first, menu_text(desc), k, NULL, NULL);
if (note && (row_foc || row_hov)) { // e.g. what moved here, after the description
Desc &d = row_hov ? g_hover : g_focus;
size_t n = strlen(d.text);
+7
View File
@@ -25,6 +25,7 @@ void opt_focus_first(void);
void opt_focus_key(const char *key);
// The next row is greyed out like one the environment fixes, with note under its label and in its description.
void opt_disable_next(UiTextId note);
void opt_disable_next_text(const char *note); // note must outlive the frame
// Page text that is not a row: a group heading in the accent colour, a wrapped paragraph (warn: the warning colour).
void opt_group(UiTextId title);
@@ -45,6 +46,12 @@ bool opt_choice_list(const char *key, UiTextId label, const char *const *values,
// A row that runs an action: true on A or a click. id: unique on the page and not a setting ("##copy_info"); value:
// shown on the right ("" none).
bool opt_button(const char *id, UiTextId label, UiTextId desc, const char *value = "");
// Rows and text that are not settings of the cfg table: a label and description of the caller's own (the cheats of
// the cheat file). opt_toggle_text shows on / off (value: shown instead, NULL for On / Off) and returns true on A, a
// click, left or right; the caller changes its state. id: unique on the page, the environment check uses it.
bool opt_toggle_text(const char *id, const char *label, const char *desc, bool on, const char *value = nullptr);
void opt_group_text(const char *title);
void opt_text_str(const char *text, bool warn = false);
// lo..hi in steps of step (left and right held for a second go ten times as fast); fmt formats the value ("%.0f %%").
bool opt_slider(const char *key, UiTextId label, float lo, float hi, UiTextId desc, float step = 1,
const char *fmt = "%g");
+32
View File
@@ -237,6 +237,22 @@ static const char *const text_en[UI_TEXT_COUNT] = {
[UI_MENU_OV_FMT_SIZE] = "%ux%u", [UI_MENU_OV_FMT_SCENE] = "%ux%u, %.0f%%",
[UI_MENU_OV_FMT_FSR] = "AMD FSR 1, sharpness %d%%", [UI_MENU_OV_SCALE_NONE] = "none (1:1)",
[UI_MENU_OV_SCALE_BILINEAR] = "bilinear",
[UI_MENU_TAB_CHEATS] = "Cheats",
[UI_MENU_CHEATS_NONE] = "No cheats for this game version. Put an Atmosphere cheat file in %s next to totk.exe and "
"run the setup again on this folder: it builds the cheats that change the game's code.",
[UI_MENU_CHEATS_FILE] = "%s, %d cheats",
[UI_MENU_CHEAT_CODE_DESC] = "Changes the game's code. Switches at once.",
[UI_MENU_CHEAT_KEY_DESC] = "Changes the game's code while you hold %s. Switches at once.",
[UI_MENU_CHEAT_DATA_DESC] = "Writes the game's memory every frame while it is on.",
[UI_MENU_CHEAT_MASTER] = "always on",
[UI_MENU_CHEAT_MASTER_DESC] = "The file's master code: it is always on.",
[UI_MENU_CHEAT_RESTORE] = "not needed",
[UI_MENU_CHEAT_RESTORE_DESC] = "It only writes the game's own code back. Switching a cheat off already does that.",
[UI_MENU_CHEAT_REBUILD] = "run the setup again",
[UI_MENU_CHEAT_REBUILD_DESC] = "This cheat changes the game's code and is new or edited since the game was built. "
"Run the setup again on this folder to build it (about three minutes).",
[UI_MENU_CHEAT_UNSUPPORTED] = "not supported",
[UI_MENU_CHEAT_UNSUPPORTED_DESC] = "This cheat cannot be used with this version of the game:",
};
static const char *const text_ru[UI_TEXT_COUNT] = {
@@ -459,6 +475,22 @@ static const char *const text_ru[UI_TEXT_COUNT] = {
[UI_MENU_OV_FMT_SIZE] = "%ux%u", [UI_MENU_OV_FMT_SCENE] = "%ux%u, %.0f%%",
[UI_MENU_OV_FMT_FSR] = "AMD FSR 1, резкость %d%%", [UI_MENU_OV_SCALE_NONE] = "нет (1:1)",
[UI_MENU_OV_SCALE_BILINEAR] = "билинейное",
[UI_MENU_TAB_CHEATS] = "Читы",
[UI_MENU_CHEATS_NONE] = "Для этой версии игры читов нет. Положите файл читов Atmosphere в %s рядом с totk.exe и "
"запустите установщик для этой папки ещё раз: он соберёт читы, меняющие код игры.",
[UI_MENU_CHEATS_FILE] = "%s, читов: %d",
[UI_MENU_CHEAT_CODE_DESC] = "Меняет код игры. Включается и выключается сразу.",
[UI_MENU_CHEAT_KEY_DESC] = "Меняет код игры, пока вы держите %s. Включается и выключается сразу.",
[UI_MENU_CHEAT_DATA_DESC] = "Пока включён, записывает память игры каждый кадр.",
[UI_MENU_CHEAT_MASTER] = "всегда вкл.",
[UI_MENU_CHEAT_MASTER_DESC] = "Главный код файла: включён всегда.",
[UI_MENU_CHEAT_RESTORE] = "не нужен",
[UI_MENU_CHEAT_RESTORE_DESC] = "Он только возвращает исходный код игры. Выключение чита уже делает это.",
[UI_MENU_CHEAT_REBUILD] = "запустите установщик",
[UI_MENU_CHEAT_REBUILD_DESC] = "Этот чит меняет код игры и появился или изменился после сборки игры. Запустите "
"установщик для этой папки ещё раз, чтобы собрать его (около трёх минут).",
[UI_MENU_CHEAT_UNSUPPORTED] = "не поддерживается",
[UI_MENU_CHEAT_UNSUPPORTED_DESC] = "Этот чит нельзя использовать с этой версией игры:",
};
#define SWKBD_ONLY(name, ...) static const char *const name[UI_TEXT_COUNT] = {SWKBD(__VA_ARGS__)}
+8 -1
View File
@@ -153,7 +153,14 @@ typedef enum {
UI_MENU_OV_FMT_SCENE, // "%ux%u, %.0f%%": the scene and its share of the game image's width
UI_MENU_OV_FMT_FSR, // "AMD FSR 1, sharpness %d%%"
UI_MENU_OV_SCALE_NONE, UI_MENU_OV_SCALE_BILINEAR,
UI_MENU_LAST_ID = UI_MENU_OV_SCALE_BILINEAR,
// the Cheats tab (cheats.c): the file, the kinds of cheat and why one cannot be switched
UI_MENU_TAB_CHEATS,
UI_MENU_CHEATS_NONE, // "%s": cheats\<build id>.txt
UI_MENU_CHEATS_FILE, // "%s": the file, "%d": its cheats
UI_MENU_CHEAT_CODE_DESC, UI_MENU_CHEAT_KEY_DESC /* "%s": the buttons */, UI_MENU_CHEAT_DATA_DESC,
UI_MENU_CHEAT_MASTER, UI_MENU_CHEAT_MASTER_DESC, UI_MENU_CHEAT_RESTORE, UI_MENU_CHEAT_RESTORE_DESC,
UI_MENU_CHEAT_REBUILD, UI_MENU_CHEAT_REBUILD_DESC, UI_MENU_CHEAT_UNSUPPORTED, UI_MENU_CHEAT_UNSUPPORTED_DESC,
UI_MENU_LAST_ID = UI_MENU_CHEAT_UNSUPPORTED_DESC,
UI_TEXT_COUNT
} UiTextId;
+349
View File
@@ -0,0 +1,349 @@
"""Cheat file to code patch sets: the code cheats of an Atmosphere cheat file become patch sets of the lifted game.
Lifted code cannot be written to while the game runs, so a cheat that writes instructions into main's .text is turned
into `site` lines (recomp/patches.py) when the game is lifted; the runtime (runtime/cheats.c) switches each cheat's set
from the in-game menu. A cheat that only writes data (heap, main's data, pointer chains, button conditions) needs no
patch: runtime/cheats.c runs it in its cheat VM.
python tools/cheats.py --exefs <dir> --cheats <BUILD_ID>.txt --patches <patch file> --out <patch file> --status <file>
--out gets the --patches file followed by one set per convertible cheat (`cheat_<hash>`, switch TOTK_CHEAT_<HASH>,
default off) and its sites. --status gets one line per cheat of the file, in file order, tab separated:
<name hash> <content hash> <kind> <buttons> <note>
name hash: FNV-1a 32 of the UTF-8 name (a repeated name: name + "#2", "#3" ...), 8 upper-case hex digits; content
hash: the same over the cheat's words, so the runtime sees an edited cheat that was not rebuilt. kind:
code instruction writes, a patch set
key instruction writes while buttons are held (8 mask / writes / 21 else / the original words / 20): a patch
set the runtime switches on while the cheat is on and <buttons> (hex HidNpadButton mask) are held
master a {master} cheat with instruction writes: a set that is always on
restore writes only the original instructions (switching a cheat off restores them): nothing to do
heading no opcodes (a title or a group label)
data no instruction writes: the runtime's cheat VM
unsupported <note> says why
A code cheat that calls or jumps into a code cave it writes (words where main has zeros) gets the cave's body inlined
at the call site; a conditional skip of one store in the body (cbz wN, +8; str wN, ...) is dropped.
Standard library and recomp/ only.
"""
import argparse
import struct
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'recomp'))
import flags # noqa: E402
from lifter import Lifter # noqa: E402
from nso import Nso # noqa: E402
BASE = 0x7000000000 # main's base in the layout (recomp/layout.py); only pc-relative decoding sees it
NOP = 0xD503201F
RET = 0xD65F03C0
def fnv(data):
h = 0x811C9DC5
for b in data:
h = ((h ^ b) * 0x01000193) & 0xFFFFFFFF
return f'{h:08X}'
def build_id(main):
"""The first 8 bytes of the NSO build id, as cheat files name themselves."""
return Path(main).read_bytes()[0x40:0x48].hex().upper()
# ---- parsing
class Cheat:
def __init__(self, name, master, line):
self.name, self.master, self.line, self.words = name, master, line, []
self.key = self.kind = self.note = ''
self.buttons = 0
self.sites = {} # {offset: [words]}
def parse(text):
"""Cheats in file order; words that are not 8 hex digits are skipped."""
out = []
for no, raw in enumerate(text.splitlines(), 1):
s = raw.strip()
if len(s) >= 2 and s[0] in '[{' and s[-1] in ']}':
out.append(Cheat(s[1:-1].strip(), s[0] == '{', no))
elif out:
for w in s.split():
if len(w) == 8:
try:
out[-1].words.append(int(w, 16))
except ValueError:
pass
seen = {}
for c in out:
n = seen[c.name] = seen.get(c.name, 0) + 1
c.key = fnv((c.name if n == 1 else f'{c.name}#{n}').encode())
return out
def ops(words):
"""[(type, [words])] of a cheat; type is the opcode nibble, 0xC0.. for the extended ones. ValueError when the last
opcode is cut short."""
out, i = [], 0
while i < len(words):
w = words[i]
t = w >> 28
width = (w >> 24) & 0xF
if t in (0, 1):
n = 4 if width == 8 else 3
elif t in (2, 8):
n = 1
elif t == 3:
n = 2 if (w >> 24) & 0xF == 0 else 1
elif t in (4, 6):
n = 3
elif t in (5, 7):
n = 2
elif t == 9:
n = 1 + ((2 if width == 8 else 1) if (w >> 8) & 0xF else 0)
elif t == 0xA:
n = 2 if (w >> 8) & 0xF in (2, 4, 5) else 1
else:
t = (w >> 24) & 0xFF if t == 0xC else (w >> 20) & 0xFFF
n = 1
if i + n > len(words):
raise ValueError(f'opcode {w:08X} is cut short')
out.append((t, words[i:i + n]))
i += n
return out
VM_TYPES = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xA}
def vm_ok(o):
"""None when runtime/cheats.c runs the opcode, else why not."""
t, w = o
if t not in VM_TYPES:
return f'opcode {w[0]:08X} is not supported'
if t == 5 and (w[0] >> 12) & 0xF > 1:
return f'opcode {w[0]:08X} (load from a register offset) is not supported'
if t == 0xA and (w[0] >> 8) & 0xF > 5:
return f'opcode {w[0]:08X} is not supported'
if t in (0, 1, 5, 6, 7, 9, 0xA) and (w[0] >> 24) & 0xF not in (1, 2, 4, 8):
return f'opcode {w[0]:08X} has a bad width'
return None
# ---- instruction writes
class Main:
def __init__(self, path):
n = Nso(str(path))
self.image = bytes(n.image)
self.text = n.text # (offset, size)
self.code_end = n.rodata[0] # .text and its padding up to .rodata, where code caves go
self.lifter = Lifter(BASE, 'c')
def in_text(self, off):
return self.text[0] <= off < self.text[0] + self.text[1] and off % 4 == 0
def in_code(self, off):
return self.text[0] <= off < self.code_end and off % 4 == 0
def word(self, off):
return struct.unpack_from('<I', self.image, off)[0]
def lift(self, w, off):
return self.lifter.lift(w, BASE + off)
def effect(self, w, off):
ins = self.lift(w, off)
if ins.kind == 'op':
return flags.effect(ins.code or '')
if ins.kind == 'bcond':
return flags.effect(ins.cond)
return (False, None)
def code_writes(main, o):
"""{offset: word} of an opcode 0 into main's code (.text and its padding; 4 or 8 bytes, no offset register in
use), None for any other opcode; ValueError for a write into the code the patch cannot express."""
t, w = o
if t != 0 or (w[0] >> 20) & 0xF != 0:
return None
width = (w[0] >> 24) & 0xF
off = ((w[0] & 0xFF) << 32) | w[1]
if not main.in_code(off - off % 4):
return None
if width == 4 and off % 4 == 0:
return {off: w[2]}
if width == 8 and off % 4 == 0:
return {off: w[3], off + 4: w[2]}
raise ValueError(f'a {width}-byte write into the code at main+{off:X}')
def branch(w, off):
"""(kind, target offset) of a b / bl word at off, else None."""
if w & 0x7C000000 == 0x14000000:
return ('bl' if w >> 31 else 'b', off + ((((w & 0x3FFFFFF) ^ 0x2000000) - 0x2000000) << 2))
return None
def pc_relative(w):
"""adr / adrp, a literal load, or any branch: wrong once moved to another address."""
return (w & 0x1F000000 == 0x10000000 or w & 0x3B000000 == 0x18000000 or w & 0x7C000000 == 0x14000000
or w & 0xFE000000 in (0x54000000, 0x34000000, 0x36000000, 0xB4000000, 0xB6000000)
or w & 0xFE000000 == 0xD6000000)
def skip_store(body, i):
"""body[i] is cbz / cbnz wN / xN, +8 and body[i + 1] a str of that register: the skip can go (the cheat stores
only when the value is non-zero)."""
w = body[i]
if w & 0x7E000000 != 0x34000000 or (w >> 5) & 0x7FFFF != 2 or i + 1 >= len(body):
return False
s = body[i + 1]
return s & 0x3B400000 == 0x39000000 and s & 0x1F == w & 0x1F # str (unsigned offset), same Rt
def cave_body(writes, caves, start, back, call):
"""The cave's words from start up to its ret (call) or its b to back."""
body, a = [], start
while True:
if a not in caves:
raise ValueError(f'the cheat branches to main+{a:X}, which it does not write')
w = writes[a]
if call and w == RET:
return body
b = branch(w, a)
if not call and b and b[0] == 'b' and b[1] == back:
return body
body.append(w)
a += 4
if len(body) > 64:
raise ValueError('a code cave of more than 64 instructions')
def convert(main, writes):
"""{offset: [replacement words]} of a set of instruction writes; ValueError when it cannot."""
caves = {a for a in writes if main.word(a) == 0}
sites = {}
for a, w in sorted(writes.items()):
if a in caves or w == main.word(a):
continue
if not main.in_text(a):
raise ValueError(f'main+{a:X} is past the end of the code')
b = branch(w, a)
if b and b[1] in caves:
body = cave_body(writes, caves, b[1], a + 4, b[0] == 'bl')
out = []
for i, x in enumerate(body):
if skip_store(body, i):
continue
if pc_relative(x):
raise ValueError(f'the code cave at main+{b[1]:X} has a branch or pc-relative instruction')
out.append(x)
repl = out or [NOP]
else:
repl = [w]
orig = main.word(a)
kind = main.lift(orig, a).kind
if kind not in ('op', 'bl', 'b', 'bcond'):
raise ValueError(f'main+{a:X} is a {kind}, which a patch cannot replace')
last = main.lift(repl[-1], a).kind
if last not in ('op', 'bl', 'b', 'bcond', 'ret'):
raise ValueError(f'main+{a:X} gets a {last}')
want = main.effect(orig, a)[1]
got = [e[1] for e in (main.effect(x, a) for x in repl) if e[1]]
if (got[0] if got else None) != want or len(got) > 1:
# a nop over adds / subs Rd, Rd, #imm: subtract 0 instead, the flags still written and Rd unchanged
if repl == [NOP] and orig & 0x1F000000 == 0x11000000 and orig & 0x20000000 and \
orig & 0x1F == (orig >> 5) & 0x1F:
repl = [orig & ~0x003FFC00]
else:
raise ValueError(f'main+{a:X}: the cheat changes the CPU flags differently from the game')
sites[a] = repl
return sites
def classify(main, c):
try:
os_ = ops(c.words)
except ValueError as e:
c.kind, c.note = 'unsupported', str(e)
return
os_ = [o for o in os_ if not (o[0] == 2 and len(os_) == 1)] # [Link] 20000000: a label
if not os_:
c.kind = 'heading'
return
try:
cw = [code_writes(main, o) for o in os_]
except ValueError as e:
c.kind, c.note = 'unsupported', str(e)
return
if not any(x is not None for x in cw):
bad = next((r for r in map(vm_ok, os_) if r), None)
c.kind, c.note = ('unsupported', bad) if bad else ('data', '')
return
try:
if all(x is not None for x in cw):
writes = {k: v for x in cw for k, v in x.items()}
if all(main.word(a) == w for a, w in writes.items()):
c.kind = 'restore'
return
c.sites, c.kind = convert(main, writes), 'master' if c.master else 'code'
return
# 8 mask, writes, 21000000, the original words, 20000000
t = [o[0] for o in os_]
els = next((i for i, o in enumerate(os_) if o[0] == 2 and (o[1][0] >> 24) & 0xF == 1), -1)
if (t[0] == 8 and t[-1] == 2 and (os_[-1][1][0] >> 24) & 0xF == 0 and els > 1
and all(x is not None for x in cw[1:els] + cw[els + 1:-1])):
on = {k: v for x in cw[1:els] for k, v in x.items()}
off = {k: v for x in cw[els + 1:-1] for k, v in x.items()}
if set(off) == set(on) and all(main.word(a) == w for a, w in off.items()):
c.sites, c.kind, c.buttons = convert(main, on), 'key', os_[0][1][0] & 0x0FFFFFFF
return
raise ValueError('it mixes instruction writes with other cheat opcodes')
except ValueError as e:
c.kind, c.note, c.sites = 'unsupported', str(e), {}
def main():
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument('--exefs', type=Path, required=True)
ap.add_argument('--cheats', type=Path, required=True)
ap.add_argument('--patches', type=Path, required=True, help='the game version\'s patch file')
ap.add_argument('--out', type=Path, required=True, help='the patch file with the cheats added')
ap.add_argument('--status', type=Path, required=True)
args = ap.parse_args()
sys.stdout.reconfigure(errors='replace') # cheat names in a console without their characters
m = Main(args.exefs / 'main')
text = args.patches.read_text()
cheats = parse(args.cheats.read_text(encoding='utf-8-sig', errors='replace')) if args.cheats.is_file() else []
sets, sites, status = [], [], []
for c in cheats:
classify(m, c)
if c.sites:
name = f'cheat_{c.key.lower()}'
label = c.name.encode('ascii', 'replace').decode() # recomp/patches.py reads the file as ASCII
sets.append(f'set {name} TOTK_CHEAT_{c.key} {1 if c.kind == "master" else 0} # {label}')
for a, repl in sorted(c.sites.items()):
sites.append(f'site {name} main {a:x} {m.word(a):08x} {" ".join(f"{w:08x}" for w in repl)}')
content = fnv(' '.join(f'{w:08X}' for w in c.words).encode())
note = c.note.replace('\t', ' ')
status.append(f'{c.key}\t{content}\t{c.kind}\t{c.buttons:X}\t{note}')
print(f'cheats: {c.kind:11} {c.name}' + (f' ({note})' if note else ''))
if sets:
text += (f'\n# Cheats of {args.cheats.name} (tools/cheats.py)\n' + '\n'.join(sets) + '\n'
+ '\n'.join(sites) + '\n')
args.out.write_text(text)
args.status.write_text('\n'.join(status) + ('\n' if status else ''), encoding='utf-8')
kinds = {}
for c in cheats:
kinds[c.kind] = kinds.get(c.kind, 0) + 1
print(f'cheats: {len(cheats)} in {args.cheats.name}: '
+ ', '.join(f'{n} {k}' for k, n in sorted(kinds.items())) + f'; {len(sites)} sites')
if __name__ == '__main__':
main()
+5
View File
@@ -172,6 +172,11 @@
# Folder with RomFS mod files that replace or add game files. Default: none.
# romfs_mods =
[cheats]
# One line per cheat of cheats\<build id>.txt next to totk.exe (docs/cheats.md); the Cheats tab of the menu writes
# them. cheat_<hash> = 1 switches a cheat on, the hash being FNV-1a 32 of its name. Default: every cheat off.
# cheat_0123abcd = 1
[diagnostics]
# Extra lines in the log, comma separated: svc, host, ipc, fs, gfx, perf, sched, audio, present or all. The menu's
# Performance log sets perf (frame timings). Default: none.