diff --git a/README.md b/README.md index 21ee2fcb..8f330b0c 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,7 @@ Report problems as issues, following [CONTRIBUTING.md](CONTRIBUTING.md). - Keyboard, mouse and gamepad with remapping, rumble and gyro - Xbox button prompts: LB, RB, LT, RT, Menu and View, and A, B, X and Y as labelled on the button to press, with either button layout - Shaders prepared at install instead of during play +- Atmosphère cheats: files for 1.2.1 and 1.4.3 included, switch them in the menu, or bring your own ([docs/cheats.md](docs/cheats.md)) ## Planned diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 2d890f97..3c744541 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -103,3 +103,4 @@ folder's `licenses/` and in each component's own folder. | `totk_xlate` (NativeAOT linux-x64 build of `tools/xlate/`, linked with the folder's clang, lld and sysroot) | built by `tools/build_xlate.py --llvm --sysroot` | MIT | `bin/totk_xlate` | | AppImage type-2 runtime (static; includes libfuse and squashfuse), the AppImage's first part; appimagetool packs the folder and is not distributed | https://github.com/AppImage/type2-runtime | MIT; libfuse LGPL-2.1; squashfuse BSD-2-Clause | the AppImage header | | MacNativeGames shader variant list | as in the installer release row above | MIT | `data/shader_list.tsv` | +| MyNXCheats cheat files for TotK 1.2.1 and 1.4.3 (data, unchanged below an added credit comment) | https://github.com/Arch9SK7/MyNXCheats @ `6066c82322d4668dd71ff94354fe9e0653a6a4f1` (`The Legend Of Zelda Tears Of The Kingdom/0100F2C0115B6000/cheats/`), by Skyla Kikari (Arch9SK7) and the people that repository credits | None stated: the repository has no licence file, so reuse rests on the author's permission, which is not recorded here | `tools/data/cheats/` | diff --git a/docs/cheats.md b/docs/cheats.md new file mode 100644 index 00000000..2fc271f4 --- /dev/null +++ b/docs/cheats.md @@ -0,0 +1,66 @@ +# Cheats + +The port reads Atmosphère cheat files, the format Switch homebrew and the emulators use. The setup installs a cheat file for 1.2.1 and for 1.4.3, all cheats off: open the menu (F1) and switch them on the Cheats tab. The switches are saved under `[cheats]` in `totk.ini`. + +The two files are from [MyNXCheats](https://github.com/Arch9SK7/MyNXCheats) by Skyla Kikari (Arch9SK7) and stay in `tools/data/cheats/` with that credit at the top. The 1.2.1 file has not been tried in game. + +## Adding your own cheat file + +A file of your own replaces the one the setup installed. The setup never overwrites a file you changed. + +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\.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. Switch the cheats on the Cheats tab of the menu. + +## 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_ = 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\.status`, written by the setup, records which cheats were built and how; the log line `cheats: ...` sums it up at start. diff --git a/installer/steps.py b/installer/steps.py index 1ac63909..23ba1688 100644 --- a/installer/steps.py +++ b/installer/steps.py @@ -711,12 +711,40 @@ EMITTED = re.compile(r'^emitted (\d+)/(\d+) chunks') DISCOVERED = re.compile(r'^(\w+): \d+ functions \(.*discovery') +def bundled_cheats(ctx): + """The folder of cheat files the release carries, one per update, tools/data/cheats/.txt.""" + return ctx.layout.tools / 'data' / 'cheats' + + +def cheat_files(ctx): + """The Atmosphere cheat files in /cheats, for the lift key. All of them: the one the build reads goes by the + build id of the installed main, and the keys are computed before Extract runs (runner plan), when a fresh install + has no main and an update may still have another version's. The .status files beside them are lift's own output. + A file the same as the bundled one of its name is left out, or installing it would change the key of the next run: + the key covers the bundled folder anyway.""" + bundled = bundled_cheats(ctx) + return [f for f in sorted((ctx.dest / 'cheats').glob('*.txt')) + if not (bundled / f.name).is_file() or f.read_bytes() != (bundled / f.name).read_bytes()] + + +def cheats_file(ctx): + """/cheats/.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', bundled_cheats(ctx), *cheat_files(ctx)) def current(self, ctx, record): gen = ctx.temp / 'gen' @@ -733,10 +761,33 @@ class Lift(Step): if m: rep.progress('lift', 'emit', int(m.group(1)), int(m.group(2)), 'chunks') - code, log = run_tool(ctx, 'lift', layout.recomp / 'gen.py', - ['--exefs', ctx.dest / 'exefs', '--out', gen, '--patches', layout.patches(game_version(ctx))], parse) + # The code cheats of the cheat file become patch sets (tools/cheats.py); its status file tells the runtime + # which cheats the build has. A player's own file wins over the bundled one, which is installed when there is + # none. The player did not choose a bundled file, so one the tools refuse costs its cheats, not the install. + plain, cheats = layout.patches(game_version(ctx)), cheats_file(ctx) + patches, skipped, bundled = plain, None, bundled_cheats(ctx) / cheats.name + ours = bundled.is_file() and (not cheats.is_file() or cheats.read_bytes() == bundled.read_bytes()) + if ours and not cheats.is_file(): + cheats.parent.mkdir(exist_ok=True) + shutil.copyfile(bundled, cheats) + 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 and not ours: + raise InstallError('lift.failed', code=code, log=str(log)) + patches, skipped = (plain, log) if code else (combined, None) + args = ['--exefs', ctx.dest / 'exefs', '--out', gen] + code, log = run_tool(ctx, 'lift', layout.recomp / 'gen.py', args + ['--patches', patches], parse) + if code and ours and patches != plain: + skipped = log + remove(gen) + code, log = run_tool(ctx, 'lift', layout.recomp / 'gen.py', args + ['--patches', plain], parse) if code: raise InstallError('lift.failed', code=code, log=str(log)) + if skipped: + rep.warning('warn.cheats_skipped', log=str(skipped)) (gen / STAMP).write_text(ctx.keys['lift'] + '\n') return {} diff --git a/installer/text/en.json b/installer/text/en.json index 6f06ab4e..3e9f76cb 100644 --- a/installer/text/en.json +++ b/installer/text/en.json @@ -94,6 +94,7 @@ "warn.lang_needs_fonts": "Text in {lang} needs the Switch system fonts. Choose the firmware folder (Contents/registered) to install them; without it some text may not show.", "warn.npdm_differs": "main.npdm differs from the reference {version} dump; only the code modules are used.", + "warn.cheats_skipped": "The bundled cheats that change the game's code could not be built; the game installs without them. Details: {log}", "warn.xbox_prompts_failed": "The Xbox button prompts could not be prepared (exit code {code}); the game keeps the Switch prompts. Details: {log}", "warn.shaders_skipped": "The graphics driver crashed while building some shaders, so {count} were left out of the preparation. The game builds them when it first needs them, and the driver may crash there too; a driver update may fix it. Details: {log}", "warn.kernel_old": "Linux {version} lacks the write tracking the game relies on (6.7 or later); the game may run very slowly. Updating the system fixes this.", diff --git a/installer/text/ru.json b/installer/text/ru.json index 72db03d2..32caa0ca 100644 --- a/installer/text/ru.json +++ b/installer/text/ru.json @@ -94,6 +94,7 @@ "warn.lang_needs_fonts": "Для языка «{lang}» нужны системные шрифты Switch. Выберите папку прошивки (Contents/registered), чтобы установить их; без неё часть текста может не отображаться.", "warn.npdm_differs": "main.npdm отличается от эталонного дампа {version}; используются только модули с кодом.", + "warn.cheats_skipped": "Не удалось собрать встроенные читы, меняющие код игры; игра установится без них. Подробности: {log}", "warn.xbox_prompts_failed": "Не удалось подготовить подсказки кнопок Xbox (код выхода {code}); игра оставит подсказки Switch. Подробности: {log}", "warn.shaders_skipped": "Графический драйвер аварийно завершился при сборке части шейдеров, поэтому {count} из них пропущены при подготовке. Игра соберёт их, когда они впервые понадобятся, и драйвер может упасть и там; обновление драйвера может это исправить. Подробности: {log}", "warn.kernel_old": "В Linux {version} нет отслеживания записи, на которое опирается игра (нужна версия 6.7 или новее); игра может работать очень медленно. Обновление системы это исправит.", diff --git a/recomp/gen.py b/recomp/gen.py index 1eaa00f2..c43a6d8c 100644 --- a/recomp/gen.py +++ b/recomp/gen.py @@ -211,7 +211,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 @@ -250,33 +250,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 @@ -294,27 +315,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).""" @@ -385,23 +413,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 @@ -445,7 +480,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: diff --git a/recomp/patches.py b/recomp/patches.py index 72ef2f74..544e5086 100644 --- a/recomp/patches.py +++ b/recomp/patches.py @@ -18,10 +18,12 @@ the field-of-view factor (runtime/resolution.c res_fov_live, set fov), +92..95 t (runtime/resolution.c shadow_init, set shadow). A new set takes words outside these. 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[]) { 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[]) { 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 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 @@ -46,7 +48,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) @@ -59,11 +62,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 @@ -93,10 +97,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') @@ -118,7 +124,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') diff --git a/runtime/boot.c b/runtime/boot.c index a92830db..4c168896 100644 --- a/runtime/boot.c +++ b/runtime/boot.c @@ -15,6 +15,7 @@ #include #include "cfg.h" +#include "cheats.h" #include "fs.h" #include "gfx.h" #include "nvn_api.h" @@ -344,6 +345,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("", cb_loader_ready); cb_addr[1] = hostfn_register("", cb_module_inits); cb_addr[2] = hostfn_register("", cb_module_finis); diff --git a/runtime/cfg.c b/runtime/cfg.c index 720e254d..d40c2cfa 100644 --- a/runtime/cfg.c +++ b/runtime/cfg.c @@ -172,7 +172,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) { @@ -510,6 +510,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; } diff --git a/runtime/cheats.c b/runtime/cheats.c new file mode 100644 index 00000000..132b3ebf --- /dev/null +++ b/runtime/cheats.c @@ -0,0 +1,540 @@ +// Cheats of an Atmosphere cheat file (cheats.h). The file is cheats\.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_ (cheat_ 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_ when the game is built and writes cheats\.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 with its pages made writable for the write (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 +#include +#include +#include + +#include "cfg.h" +#include "cheats.h" +#include "host.h" +#include "input.h" +#include "platform/platform.h" + +#ifdef _WIN32 +#define SEP "\\" +#else +#define SEP "/" +#endif + +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 int32_t 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 the executable, with a trailing separator. +static int exe_dir(char *out, size_t n) { + if (!plat_exe_path(out, n)) return 0; + char *cut = plat_last_sep(out); + if (!cut) return 0; + cut[1] = 0; + return 1; +} + +static int build_id(char out[17]) { + char path[PLAT_PATH_MAX]; + snprintf(path, sizeof path, "%s/main", rt_config()->exefs); + PlatFile *f = plat_file_open(path); + if (!f) return 0; + uint8_t head[0x48]; + int ok = plat_file_pread(f, head, sizeof head, 0) == sizeof head && !memcmp(head, "NSO0", 4); + plat_file_close(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; +} + +// Writes n bytes into main's image a page at a time: a read-only page is writable for its part of the copy only. +static void wr_main(uint64_t a, const uint8_t *from, int n) { + while (n > 0) { + uint64_t page = a & ~0xFFFull, end; + int k = (int)(page + 0x1000 - a); + if (k > n) k = n; + int prot = plat_mem_state(page, page + 0x1000, &end); + if (prot != PLAT_PROT_READ && prot != PLAT_PROT_RW) return; + if (prot == PLAT_PROT_READ && !plat_mem_protect(page, 0x1000, PLAT_PROT_RW)) return; + memcpy((void *)(uintptr_t)a, from, (size_t)k); + if (prot == PLAT_PROT_READ) plat_mem_protect(page, 0x1000, PLAT_PROT_READ); + a += (uint64_t)k; + from += k; + n -= k; + } +} + +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)) { + wr_main(a, (const uint8_t *)&v, width); + } 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) 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 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 (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; +} + +// The menu's font has no numero sign (U+2116), which cheat names often start with: they show "No" instead. +static void plain_name(char *s) { + for (char *p; (p = strstr(s, "\xE2\x84\x96")) != NULL;) { + p[0] = 'N', p[1] = 'o'; + memmove(p + 2, p + 3, strlen(p + 3) + 1); + } +} + +void cheats_init(void) { + const RtLoaded *m = ldr_count() ? ldr_module(0) : NULL; + char dir[PLAT_PATH_MAX], bid[17], path[PLAT_PATH_MAX + 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" SEP "%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" SEP "%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); + for (int i = 0; i < g_n; i++) plain_name((char *)g_cheats[i].info.name); // the hashes above read the file's bytes + 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; + plat_xchg32(&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; +} diff --git a/runtime/cheats.h b/runtime/cheats.h new file mode 100644 index 00000000..a6746890 --- /dev/null +++ b/runtime/cheats.h @@ -0,0 +1,43 @@ +// Cheats of an Atmosphere cheat file (cheats.c): cheats\.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 + +#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_ +} 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\.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 diff --git a/runtime/ui/cheats_tab.cpp b/runtime/ui/cheats_tab.cpp new file mode 100644 index 00000000..cd1967ba --- /dev/null +++ b/runtime/ui/cheats_tab.cpp @@ -0,0 +1,58 @@ +// The Cheats tab of the in-game menu: the cheats of cheats\.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. +#include +#include + +#include "imgui.h" +#include "ui/option_rows.h" + +extern "C" { +#include "cheats.h" +#include "ui_text.h" +} + +extern "C" 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\\.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(); +} diff --git a/runtime/ui/menu.cpp b/runtime/ui/menu.cpp index 228abf75..d3f100d4 100644 --- a/runtime/ui/menu.cpp +++ b/runtime/ui/menu.cpp @@ -54,6 +54,8 @@ void res_sizes(unsigned out[2], unsigned scene[2]); double frame_step_limit_hz(void); extern const int rt_game_version; extern const char rt_port_version[]; +void cheats_frame(uint64_t frame); // cheats.c +void tab_cheats(float scale); // ui/cheats_tab.cpp } // Roboto Medium (Apache-2.0, ui/fonts/LICENSE-Roboto.txt) with Latin and Cyrillic glyphs. @@ -371,7 +373,7 @@ extern "C" void menu_vk_release(void) { // TOTK_MENU_TEST_SET=:=[,=...][;:...]: 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_MODS, TAB_SOUND, TAB_CONTROLS, TAB_AMIIBO, TAB_MENU, TAB_ADVANCED, TAB_COUNT }; +enum { TAB_SCREEN, TAB_GAME, TAB_MODS, TAB_CHEATS, TAB_SOUND, TAB_CONTROLS, TAB_AMIIBO, TAB_MENU, TAB_ADVANCED, TAB_COUNT }; enum { TEST_PAGE_FRAMES = 30, TEST_SETS = 16 }; struct TestSet { uint64_t frame; char key[64], value[64]; }; static struct { @@ -1000,7 +1002,7 @@ static void tab_advanced(float scale) { } } -static const UiTextId kTabNames[TAB_COUNT] = {UI_MENU_TAB_SCREEN, UI_MENU_TAB_GAME, UI_MENU_TAB_MODS, UI_MENU_TAB_SOUND, +static const UiTextId kTabNames[TAB_COUNT] = {UI_MENU_TAB_SCREEN, UI_MENU_TAB_GAME, UI_MENU_TAB_MODS, UI_MENU_TAB_CHEATS, UI_MENU_TAB_SOUND, UI_MENU_TAB_CONTROLS, UI_MENU_TAB_AMIIBO, UI_MENU_TAB_MENU, UI_MENU_TAB_ADVANCED}; static int g_tab; // the tab shown @@ -1130,6 +1132,7 @@ static void layout_menu(uint32_t w, uint32_t h, float scale) { case TAB_CONTROLS: tab_controls(scale); break; case TAB_AMIIBO: tab_amiibo(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(); @@ -1410,6 +1413,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(); diff --git a/runtime/ui/option_rows.cpp b/runtime/ui/option_rows.cpp index 0a15506e..78725fd3 100644 --- a/runtime/ui/option_rows.cpp +++ b/runtime/ui/option_rows.cpp @@ -33,7 +33,7 @@ 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[UI_DESC_BYTES]; }; @@ -58,7 +58,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; } float opt_bottom(void) { return g_bottom; } -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; } @@ -113,7 +115,7 @@ struct RowView { // so its description shows). movable: the top / left face buttons, Ctrl+Up / Ctrl+Down and two drawn arrows move it. static int row_text(const char *key, const char *label, const char *desc, const RowView &v, bool movable) { 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); @@ -273,6 +275,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, false) != 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)); diff --git a/runtime/ui/option_rows.h b/runtime/ui/option_rows.h index 8e939c67..83cf4f87 100644 --- a/runtime/ui/option_rows.h +++ b/runtime/ui/option_rows.h @@ -27,6 +27,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); @@ -52,6 +53,12 @@ bool opt_button(const char *id, UiTextId label, UiTextId desc, const char *value // Ctrl+Down, the drawn arrows; movable rows only) or 0. int opt_text_row(const char *id, const char *label, const char *value, const char *note, const char *desc, bool movable); +// 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 files). 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 %%"). // note: a short line under the value in place of the "default" mark (NULL: none). fallback: the setting that applies // while key is unset; the row shows its value then, and a change sets key. diff --git a/runtime/ui_text.h b/runtime/ui_text.h index 4af70c95..7c254a6b 100644 --- a/runtime/ui_text.h +++ b/runtime/ui_text.h @@ -209,7 +209,14 @@ typedef enum { UI_MENU_OV_FMT_FSR, // "AMD FSR 1, sharpness %d%%" UI_MENU_OV_SCALE_NONE, UI_MENU_OV_SCALE_BILINEAR, UI_MENU_OV_SCALE_DOWN, // FSR is selected but the image is larger than the window: FSR only enlarges - UI_MENU_LAST_ID = UI_MENU_OV_SCALE_DOWN, + // 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\.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; diff --git a/tests/installer_test.py b/tests/installer_test.py index bbb75c26..e3ebb588 100644 --- a/tests/installer_test.py +++ b/tests/installer_test.py @@ -197,6 +197,64 @@ class RunnerTest(unittest.TestCase): self.assertEqual(e.exception.id, 'state.newer_format') +class ReleaseFilesTest(unittest.TestCase): + def test_release_ships_every_tool_the_steps_run(self): + sys.path.insert(0, str(ROOT / 'tools')) + import make_release + text = (ROOT / 'installer' / 'steps.py').read_text(encoding='utf-8') + used = set(re.findall(r"layout\.tools / '(\w+\.py)'", text)) + for names in re.findall(r"layout\.tools / n for n in \((.*?)\)", text, re.S): + used |= set(re.findall(r"'(\w+\.py)'", names)) + self.assertIn('cheats.py', used) + self.assertEqual(used - set(make_release.TOOLS_FILES), set()) + + +class LiftKeyTest(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.dest = Path(tmp.name) + layout = SimpleNamespace(recomp=self.dest / 'no-recomp', tools=self.dest / 'no-tools', + patches=lambda version: self.dest / 'no-patches') + self.ctx = SimpleNamespace(dest=self.dest, layout=layout, keys={'extract': 'x'}, state={'version': '1.4.3'}) + + def key(self): + return steps.Lift().key(self.ctx) + + def add_cheats(self, name, text): + (self.dest / 'cheats').mkdir(exist_ok=True) + (self.dest / 'cheats' / name).write_text(text) + + def test_extracting_main_keeps_the_key(self): + before = self.key() + (self.dest / 'exefs').mkdir() + (self.dest / 'exefs' / 'main').write_bytes(bytes(0x48)) + self.assertEqual(self.key(), before) + + def test_cheat_files_change_the_key(self): + before = self.key() + self.add_cheats('277178B7DBA1B6D4.txt', '[a]') + added = self.key() + self.assertNotEqual(added, before) + self.add_cheats('277178B7DBA1B6D4.txt', '[b]') + self.assertNotEqual(self.key(), added) + + def test_installed_bundled_file_keeps_the_key(self): + (self.dest / 'no-tools' / 'data' / 'cheats').mkdir(parents=True) + (self.dest / 'no-tools' / 'data' / 'cheats' / '277178B7DBA1B6D4.txt').write_text('[a]') + before = self.key() + self.add_cheats('277178B7DBA1B6D4.txt', '[a]') + self.assertEqual(self.key(), before) + self.add_cheats('277178B7DBA1B6D4.txt', '[edited by the player]') + self.assertNotEqual(self.key(), before) + + def test_status_file_keeps_the_key(self): + self.add_cheats('277178B7DBA1B6D4.txt', '[a]') + before = self.key() + self.add_cheats('277178B7DBA1B6D4.status', 'written by lift') + self.assertEqual(self.key(), before) + + class IniTest(unittest.TestCase): EXAMPLE = '[display]\n# vk_present = mailbox\n\n[language]\n# locale = en-US\n# lang = en-US\n# x = 1\n' diff --git a/tools/cheats.py b/tools/cheats.py new file mode 100644 index 00000000..eb718a3e --- /dev/null +++ b/tools/cheats.py @@ -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 --cheats .txt --patches --out --status + +--out gets the --patches file followed by one set per convertible cheat (`cheat_`, switch TOTK_CHEAT_, +default off) and its sites. --status gets one line per cheat of the file, in file order, tab separated: + + + +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 (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 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('> 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() diff --git a/tools/data/cheats/277178B7DBA1B6D4.txt b/tools/data/cheats/277178B7DBA1B6D4.txt new file mode 100644 index 00000000..2e306fd6 --- /dev/null +++ b/tools/data/cheats/277178B7DBA1B6D4.txt @@ -0,0 +1,444 @@ +# TotK 1.4.3 cheats from MyNXCheats by Skyla Kikari (Arch9SK7) and the people that repository credits. +# https://github.com/Arch9SK7/MyNXCheats, commit 6066c82322d4668dd71ff94354fe9e0653a6a4f1 +# The Legend Of Zelda Tears Of The Kingdom/0100F2C0115B6000/cheats/277178B7DBA1B6D4.txt +# Everything below this comment is that file, unchanged. Readers skip the lines before the first [. + +[The Legend of Zelda: Tears of the Kingdom v720896 TID=0100F2C0115B6000 BID=277178B7DBA1B6D4] + +[Restore Code (Use after unchecking any cheats below)] +040A0000 004407D0 F9400008 +040A0000 0031D398 1F080800 +080A0000 006E0838 BD401D00 9B292908 +040A0000 006E0840 BD000260 +040A0000 0078251C BD004668 +040A0000 00782568 BD004668 +040A0000 0233765C 71000508 +040A0000 004C4D14 1E204100 +040A0000 004CB9BC 1E200C20 +040A0000 00324C14 B9400008 +040A0000 0072AE28 1A9F57E0 +040A0000 0072B124 BD400009 +040A0000 004414FC 1A89C115 +040A0000 00441520 52800095 +040A0000 001AE99C 1E212000 +040A0000 001B5B2C 1E280400 +040A0000 006343D0 1E212000 +040A0000 01B7A460 1E201C20 +040A0000 023BBE00 1E204100 +040A0000 023BCD2C 2D1F8260 +040A0000 00335C40 1E2E1008 +040A0000 00335CA0 BD400008 +040A0000 0047E09C 52A7F008 +040A0000 023F0864 97DD371F +040A0000 00BD3788 1E211C41 +040A0000 023F6448 396B6288 +040A0000 00A77B40 0B0300C3 +040A0000 0250767C 5A980715 +040A0000 021ECA9C 1B09A148 +040A0000 00282E58 B9400901 +040A0000 002829F4 B9400901 +040A0000 01B78CD0 12800001 +040A0000 020B2A1C 12800001 +040A0000 01CCC718 1E201C42 +040A0000 020B3ABC 12800001 +040A0000 020B3B98 54FFFE2C +040A0000 003067F4 BD415E80 +040A0000 01F87E08 370001E0 +040A0000 020F6F10 D10183FF +040A0000 020F6F14 FD0013EA +040A0000 007362D0 D101C3FF +040A0000 007362D4 FD001BEA +040A0000 020FC7A4 39407688 +040A0000 020F6FF0 34000248 +040A0000 00736614 340002C8 +040A0000 020FD158 34FFFBE8 +040A0000 020FEDD4 34FFFBE8 +040A0000 00736CE0 394073A8 +040A0000 020F9F9C 340000E8 +040A0000 00736488 34FFFE4D +040A0000 007364F8 394063E8 +040A0000 020FE2BC 34FFFBA8 +040A0000 020FE2BC 34FFFBA8 +040A0000 020FDC68 34FFFB48 +040A0000 020F8068 34000988 +040A0000 020FCCE4 34FFFA88 +040A0000 00ECCDBC 34FFF7E8 +040A0000 01C0BA70 B9401268 +040A0000 0068C15C BD403E69 +040A0000 0068C15C BD403E69 +040A0000 0068C15C BD403E69 +040A0000 0067FCC4 1E2E1003 +040A0000 01FD39CC 1E2E1001 + +[Link] +20000000 + +[№ 1. Inf. Health] +080A0000 02BB9FF8 176219F6 F9400008 +080A0000 02BB9FF0 B9000808 34000048 +040A0000 02BB9FEC B9401808 +040A0000 004407D0 149DE607 + +[№ 2. Inf. Stamina] +040A0000 0031D398 1E204040 + +[№ 3. Inf. Stamina (Use Only For Master Sword Quest)] +080A0000 006E0838 F2B0000F D2A8B76F +040A0000 006E0840 B900026F + +[№ 4. Inf. Battery] +040A0000 0078251C BD004662 +040A0000 00782568 BD004662 + +[№ 5. Inf. Horse Stamina] +040A0000 0233765C D503201F + +[№ 6. Stealth Mode] +040A0000 004C4D14 1E2703E0 +040A0000 004CB9BC 1E2703E0 + +[№ 7. Perfect Thermometer (No Fire, Heat, Cold)] +040A0000 00324C14 52800068 +040A0000 0072AE28 2A1F03E0 +040A0000 0072B124 BD400809 + +[№ 8. Ignore Gloom Effects] +040A0000 004414FC 1A89C135 +040A0000 00441520 2A1F03F5 + +[Link] +20000001 + +[Combat] +20000000 + +[№ 9. Instant Companion Skills (No CDs)] +040A0000 001AE99C 1E212020 +040A0000 001B5B2C 1E282100 +040A0000 006343D0 1E212020 + +[№10. Faster Weapon Charge] +040A0000 01B7A460 1E211000 + +[№11. Faster Bow Charge] +040A0000 023BBE00 1E209000 + +[№12. Quickfire Bow] +040A0000 023BCD2C 291FA268 + +[№13. Damage Multiplier (2x)] +040A0000 00335C40 1E201008 +040A0000 00335CA0 1E201008 + +[№14. Damage Multiplier (4x)] +040A0000 00335C40 1E221008 +040A0000 00335CA0 1E221008 + +[№15. Damage Multiplier (10x)] +040A0000 00335C40 1E249008 +040A0000 00335CA0 1E249008 + +[№16. Damage Multiplier (30x)] +040A0000 00335C40 1E27D008 +040A0000 00335CA0 1E27D008 + +[Combat] +20000001 + +[Movement] +20000000 + +[№17. Hold (X) Moon Jump] +80000004 +580F0000 03AD99B8 +580F1000 00000070 +580F1000 00000040 +580F1000 000000D0 +580F1000 000000C0 +580F1000 00000198 +580F1000 00000038 +780F0000 000000F4 +640F0000 00000000 41200000 +20000000 + +[№18. Glider Speed (1.5x) (Hold A)] +80000001 +040A0000 02D01D70 3F000000 +21000000 +040A0000 02D01D70 3D088889 +20000000 + +[№19. Glider Speed (2.0x) (Hold A)] +80000001 +040A0000 02D01D70 3F28F5C3 +21000000 +040A0000 02D01D70 3D088889 +20000000 + +[№20. Glider Speed (3.0x) (Hold A)] +80000001 +040A0000 02D01D70 3F7D70A4 +21000000 +040A0000 02D01D70 3D088889 +20000000 + +[№21. Glider Speed (3.8x) (Hold A)] +80000001 +040A0000 02D01D70 3FA08312 +21000000 +040A0000 02D01D70 3D088889 +20000000 + +[№22. Movement Speed (2x)] +80000002 +040A0000 0047E09C 52A80008 +21000000 +040A0000 0047E09C 52A7F008 +20000000 + +[№23. Movement Speed (3x)] +80000002 +040A0000 0047E09C 52A80808 +21000000 +040A0000 0047E09C 52A7F008 +20000000 + +[№24. Movement Speed (10x)] +80000002 +040A0000 0047E09C 52A82408 +21000000 +040A0000 0047E09C 52A7F008 +20000000 + +[№25. Dive Boost] +040A0000 023F0864 1E211000 + +[№26. Jump Higher] +040A0000 00BD3788 1E209001 + +[№27. Default Movement is Running] +040A0000 023F6448 52800028 + +[№28. Default Movement is Walking] +040A0000 023F6448 396B6288 + +[Movement] +20000001 + +[Inventory] +20000000 + +[№29. Items x999] +040A0000 00A77B40 52807CE3 + +[№30. Free Shopping] +040A0000 0250767C 1A9813F5 + +[№31. Inf. Equipment Durability] +040A0000 021ECA9C 1B09A3E8 +080A0000 02BB9FE4 D65F03C0 B9000901 +040A0000 02BB9FE0 B9401901 +040A0000 00282E58 94A4DC62 +040A0000 002829F4 94A4DD7B + +[№32. Inf. Arrow(s)] +040A0000 01B78CD0 2A1F03E1 + +[№33. Inf. Zonai Devices] +040A0000 020B2A1C 2A1F03E1 + +[№34. Inf. Zonai Device Duration (No Blink + Despawn)] +040A0000 01CCC718 1E2703E2 + +[№35. Inf. Food Items] +040A0000 020B3ABC 2A1F03E1 +040A0000 020B3B98 17FFFFF2 + +[№36. Inf. Food Buff Timer] +080A0000 02BB9FD8 D65F03C0 BD015E80 +040A0000 02BB9FD4 BD416280 +040A0000 003067F4 94A2CDF8 + +[№37. Inf. Amiibo Usage] +040A0000 01F87E08 D503201F + +[Inventory] +20000001 + +[Map] +20000000 + +[№38. Show All Shrine and Cave Locations] +040A0000 020F6F10 52800020 +040A0000 020F6F14 D65F03C0 +040A0000 007362D0 52800020 +040A0000 007362D4 D65F03C0 + +[№39. Show All Korok Seed Locations (Must Zoom In)] +040A0000 020FC7A4 1400002E + +[№40. Show all All Shrine And Roots] +040A0000 020F6FF0 D503201F + +[№41. Show all All Skyview Towers] +040A0000 00736614 D503201F + +[№42. Show all Tears of the Dragon] +040A0000 020FD158 D503201F + +[№43. Show all Devil Statue] +040A0000 020FEDD4 D503201F + +[№44. Show all village and Stable] +040A0000 00736CE0 52800028 + +[№45. Show all venue not visited] +040A0000 020F9F9C D503201F + +[№46. Show all caves, Wells And Chasm] +040A0000 00736488 D503201F +040A0000 007364F8 52800028 + +[№47. Show all Great Fairy] +040A0000 020FE2BC D503201F + +[№48. Show all Miskos treasure] +040A0000 020FE2BC D503201F + +[№49. Show all old map] +040A0000 020FDC68 D503201F + +[№50. Show all Five Great Temples] +040A0000 020F8068 D503201F + +[№51. Show all All Zonai Device Dispenser] +040A0000 020FCCE4 D503201F + +[№52. Show all game field and restaurant] +040A0000 00ECCDBC D503201F + +[Map] +20000001 + +[Misc] +20000000 + +[№53. Remove 21 Zonai Device Spawn Limit] +040A0000 01C0BA70 52800028 + +[№54. Time Stop] +040A0000 0068C15C D503201F + +[№55. Time Resume] +040A0000 0068C15C BD403E69 + +[№56. Time RW (ZL+R3Left)] +80100100 +040A0000 0068C15C 1E37D009 +21000000 +040A0000 0068C15C BD403E69 +20000000 + +[№57. Time FF (ZL+R3Right)] +80400100 +040A0000 0068C15C 1E27D009 +21000000 +040A0000 0068C15C BD403E69 +20000000 + +[№58. 2x Longer Days] +040A0000 0068C15C 1E2E1009 + +[№59. 3x Longer Days] +040A0000 0068C15C 1E2C1009 + +[№60. 4x Longer Days] +040A0000 0068C15C 1E2A1009 + +[№61. Add 60 Seconds To Mission Timer (L3+R3)] +040A0000 02AA1034 BD401D00 +80000030 +080A0000 02BB9FCC 17FB9C1A BD001D00 +080A0000 02BB9FC4 1E2A2800 1E2B094A +080A0000 02BB9FBC 1E20100B 1E2A094A +080A0000 02BB9FB4 1E27D00A 340000F5 +080A0000 02BB9FAC B9401115 54000120 +080A0000 02BB9FA4 1E202008 BD401D00 +040A0000 02AA1034 140463DC +20000000 + +[№62. Handheld 480p] +580F0000 03ACDF90 +580F1000 000000D8 +580F1000 00000578 +780F0000 00000010 +680F01D0 000001E0 00000356 + +[№63. Handheld 540p] +580F0000 03ACDF90 +580F1000 000000D8 +580F1000 00000578 +780F0000 00000010 +680F01D0 0000021C 000003C0 + +[№64. Handheld 612p] +580F0000 03ACDF90 +580F1000 000000D8 +580F1000 00000578 +780F0000 00000010 +680F01D0 00000264 00000440 + +[№65. Handheld 648p] +580F0000 03ACDF90 +580F1000 000000D8 +580F1000 00000578 +780F0000 00000010 +680F01D0 00000288 00000480 + +[№66. Default Handheld 720p] +580F0000 03ACDF90 +580F1000 000000D8 +580F1000 00000578 +780F0000 00000010 +680F01D0 000002D0 00000500 + +[№67. Docked 720p] +580F0000 03ACDF90 +580F1000 000000D8 +580F1000 00000578 +780F0000 00000010 +680F01D0 00000360 00000600 + +[№68. Docked 810p] +580F0000 03ACDF90 +580F1000 000000D8 +580F1000 00000578 +780F0000 00000010 +680F01D0 000003CC 000006C0 + +[№69. Default Docked 1080p] +580F0000 03ACDF90 +580F1000 000000D8 +580F1000 00000578 +780F0000 00000010 +680F01D0 00000438 00000780 + +[Misc] +20000001 + +[Environment] +20000000 + +[№70. Disable Fog] +040A0000 0067FCC4 1E2703E3 + +[№71. ReEnable Fog] +040A0000 0067FCC4 1E2E1003 + +[№72. Instant Bloodmoon] +040A0000 01FD39CC 1E3E1001 + +[Environment] +20000001 + +[This set of cheats is created by All Credited, enjoy!] diff --git a/tools/data/cheats/9B4E43650501A4D4.txt b/tools/data/cheats/9B4E43650501A4D4.txt new file mode 100644 index 00000000..9fb7f810 --- /dev/null +++ b/tools/data/cheats/9B4E43650501A4D4.txt @@ -0,0 +1,496 @@ +# TotK 1.2.1 cheats from MyNXCheats by Skyla Kikari (Arch9SK7) and the people that repository credits. +# https://github.com/Arch9SK7/MyNXCheats, commit 6066c82322d4668dd71ff94354fe9e0653a6a4f1 +# The Legend Of Zelda Tears Of The Kingdom/0100F2C0115B6000/cheats/9B4E43650501A4D4.txt +# Everything below this comment is that file, unchanged. Readers skip the lines before the first [. + +[The Legend of Zelda Tears of the Kingdom (US) v393216 TID=0100F2C0115B6000 BID=9B4E43650501A4D4] + +[Restore Code (Use after unchecking any cheats below)] +040A0000 0083E86C 6B09011F +040A0000 0064C008 F9400008 +040A0000 009F1DC4 1E212841 +080A0000 00A5DD98 BD401D00 9B292908 +040A0000 00A5DDA0 BD000260 +040A0000 00B96074 BD004668 +040A0000 00B960EC BD004668 +040A0000 01CADA90 71000508 +040A0000 00695E28 4EA81D00 +040A0000 00699360 1E200D00 +040A0000 009E442C 35FFED88 +040A0000 00B7D13C 1A9F57E0 +040A0000 00B7D208 1A9FD7E0 +040A0000 0064C7A8 52800088 +040A0000 0064C92C 1A89C108 +040A0000 009E33BC 3949CA69 +040A0000 009E6874 B9402668 +040A0000 009F5750 3946D289 +040A0000 00BAA738 1E212000 +040A0000 00DAB18C 1E212000 +040A0000 015D79E0 1E201C20 +040A0000 015D7A0C 1E201C20 +040A0000 01D2F89C 4EA81D00 +040A0000 01D2FE5C 2D1F8260 +040A0000 009FA138 1E2E1008 +040A0000 009FA174 BD400000 +040A0000 01E36238 BD400000 +040A0000 01D57248 52800034 +080A0000 01D6EDEC 396C1AA8 37080128 +040A0000 01D6EE0C 1E20CC20 +040A0000 0065B1C8 1E200D28 +040A0000 0065B1E8 1E200908 +040A0000 0171E90C 1E281C08 +040A0000 01D64AA8 940000C0 +040A0000 0107EA8C 1E281C21 +040A0000 01D6AEF0 396B6288 +040A0000 02416324 0B01014A +040A0000 01E8B2A0 5A980716 +040A0000 01B73A14 1B09A148 +040A0000 00836440 B9400901 +040A0000 00835F58 B9400901 +040A0000 015D66C0 12800001 +040A0000 01A6949C 12800001 +040A0000 0118E5CC 1E211C41 +040A0000 01A6D2C0 12800001 +040A0000 01A6D3D0 54FFFCCC +040A0000 009E3B7C BD415E80 +040A0000 00882A54 F9401508 +040A0000 0162A408 52800021 +040A0000 0194C8EC 36000280 +040A0000 01B0433C 2A2003E8 +040A0000 0204BFC8 12000281 +040A0000 02050788 37000339 +040A0000 012E42C8 6B09011F +040A0000 01A5AF78 54FFF26B +040A0000 01FC757C 360000A0 +040A0000 02122D08 360000E0 +080A0000 00EC206C FD0013EA D10183FF +080A0000 00D23F60 FD001BEA D101C3FF +040A0000 00D25670 39407688 +040A0000 00C6A3CC B9401268 +040A0000 00B3920C BD403E68 +040A0000 00D7D69C BD401D00 +040A0000 0280A5D8 1E2E1001 +040A0000 0062E868 1E210800 + +[--SectionStart:Link--] +20000000 + +[♯ 1. Invincible (Ignore Hits)] +080A0000 02B19FF8 D65F03C0 6B09011F +080A0000 02B19FF0 2A0903E8 34000042 +080A0000 02B19FE8 B940EEC2 35000083 +080A0000 02B19FE0 B9406043 F9403842 +080A0000 02B19FD8 F9400442 F94007E2 +080A0000 02B19FD0 37300121 B94032C1 +040A0000 0083E86C 948B6DD9 + +[♯ 2. Inf. Health] +080A0000 02B19FC8 176CC810 F9400008 +080A0000 02B19FC0 B9000808 34000048 +040A0000 02B19FBC B9401808 +040A0000 0064C008 149337ED + +[♯ 3. Inf. Stamina] +040A0000 009F1DC4 1E204041 + +[♯ 4. Inf. Stamina (Use Only For Master Sword Quest)] +080A0000 00A5DD98 F290000F D2A8B76F +040A0000 00A5DDA0 B900026F + +[♯ 5. Inf. Battery] +040A0000 00B96074 BD004669 +040A0000 00B960EC BD004669 + +[♯ 6. Inf. Horse Stamina] +040A0000 01CADA90 D503201F + +[♯ 7. Stealth Mode] +040A0000 00695E28 1E2703E0 +040A0000 00699360 1E2703E0 + +[♯ 8. Ignore Fall Damage & Reaction] +040A0000 009E442C 17FFFF6C + +[♯ 9. Perfect Goldilocks Thermometer (No Hot or Cold)] +040A0000 00B7D13C 2A1F03E0 +040A0000 00B7D208 2A1F03E0 + +[♯10. Ignore Gloom Effects] +040A0000 0064C7A8 2A1F03E8 +040A0000 0064C92C 1A89C128 + +[♯11. Ignore Paralysis & Slow Effects] +080A0000 02B19FB4 D65F03C0 52800169 +080A0000 02B19FAC 54000041 6B02003F +080A0000 02B19FA4 72AF2C22 528D8A02 +080A0000 02B19F9C B845D021 F9400E81 +040A0000 02B19F98 3949CA69 +040A0000 009E33BC 9484DAF7 + +[♯12. Ignore Cold & Freeze Effects] +080A0000 02B19F90 177B3239 177B323A +080A0000 02B19F88 54000041 6B02003F +080A0000 02B19F80 72AF2C22 528D8A02 +080A0000 02B19F78 B845D021 F9400E61 +040A0000 02B19F74 B9402668 +040A0000 009E6874 1484CDC0 + +[♯13. Ignore Fire & Flame Effects] +080A0000 02B19F6C 177B6DF9 177B6DFA +080A0000 02B19F64 54000041 6B02003F +080A0000 02B19F5C 72AF2C22 528D8A02 +080A0000 02B19F54 B845D021 F9400E61 +040A0000 02B19F50 3946D289 +040A0000 009F5750 14849200 + +[--SectionEnd:Link--] +20000001 + +[--SectionStart:Combat--] +20000000 + +[♯14. Instant Companion Skills (No CDs)] +040A0000 00BAA738 1E212020 +040A0000 00DAB18C 1E212020 + +[♯15. No Stamina Cost For Weapon Charge] +080A0000 02B19F48 17AAF6A6 1E2703E0 +080A0000 02B19F40 54000040 7100041F +040A0000 02B19F3C 1E201C20 +040A0000 015D79E0 14550957 + +[♯16. Faster Weapon Charge] +040A0000 015D7A0C 1E211000 + +[♯17. Faster Bow Charge] +040A0000 01D2F89C 1E209000 + +[♯18. Quickfire Bow] +040A0000 01D2FE5C 291FA268 + +[♯19a Damage Multiplier (2x)] +040A0000 009FA138 1E201008 +040A0000 009FA174 1E201000 + +[♯19b Damage Multiplier (4x) ★] +040A0000 009FA138 1E221008 +040A0000 009FA174 1E221000 + +[♯19c Damage Multiplier (10x)] +040A0000 009FA138 1E249008 +040A0000 009FA174 1E249000 + +[♯19d Damage Multiplier (30x)] +040A0000 009FA138 1E27D008 +040A0000 009FA174 1E27D000 + +[♯20. Master Sword Beam Upgrade] +040A0000 01E36238 1E201000 + +[--SectionEnd:Combat--] +20000001 + +[--SectionStart:Movement--] +20000000 + +[♯21. Spider-Man Mode (No Falling While Climbing)] +040A0000 01D57248 2A1F03F4 + +[♯22. Hold (X) Moon Jump] +580F0000 0471DCB0 +580F1000 000000C8 +580F1000 00000178 +580F1000 00000030 +780F0000 000000FC +80000004 +640F01D0 00000000 41200000 +20000000 + +[#8. Character Speed x3 (Hold B)] +040A0000 03877F34 3F800000 +80000002 +040A0000 03877F34 40400000 +20000000 + +[♯23. Glider Speed (3x) (Hold A)] +040A0000 03811EAC 3D088889 +80000001 +040A0000 03811EAC 3E000000 +20000000 + +[♯24a Glider Speed (1.5x)] +080A0000 01D6EDEC 1E2F1002 D503201F +040A0000 01D6EE0C 1E220820 + +[♯25a Glider Speed (2.0x)] +080A0000 01D6EDEC 1E201002 D503201F +040A0000 01D6EE0C 1E220820 + +[♯26a Glider Speed (3.0x)] +080A0000 01D6EDEC 1E211002 D503201F +040A0000 01D6EE0C 1E220820 + +[♯27. Climbing Speed (2x)] +040A0000 0065B1C8 1E209008 + +[♯28. Swimming Speed (3x)] +040A0000 0065B1E8 1E211008 +040A0000 0171E90C 1E221008 + +[♯29a Movement Speed (1x)] +040A0000 03877F34 3F800000 + +[♯29b Movement Speed (1.5x)] +040A0000 03877F34 3FC00000 + +[♯29c Movement Speed (2x) ★] +040A0000 03877F34 40000000 + +[♯29d Movement Speed (3x)] +040A0000 03877F34 40400000 + +[♯30. Dive Boost] +040A0000 01D64AA8 1E211000 + +[♯31. Jump Higher] +040A0000 0107EA8C 1E209001 + +[#12a Attack Speed (1x)] +040A0000 0062E868 1E2E1000 + +[#12b Attack Speed (1.5x) ★] +040A0000 0062E868 1E2F1000 + +[#12c Attack Speed (2x)] +040A0000 0062E868 1E201000 + +[♯32. Default Movement is Running] +040A0000 01D6AEF0 52800028 + +[♯33. Default Movement is Walking] +040A0000 01D6AEF0 396B6288 + +[walk through gate] +040A0000 0020804C FD400678 +040A0000 0020804C 14A447B7 +040A0000 02B19F28 5C000078 +080A0000 02B19F2C 175BB848 FD000678 +040A0000 02B19F34 3F800000 +040A0000 02B19F38 3F800000 +80000101 +040A0000 02B19F38 C2C80000 +040A0000 02B19F34 C2C80000 +20000000 + +[--SectionEnd:Movement--] +20000001 + +[--SectionStart:Inventory--] +20000000 + +[Items x999] +040A0000 02416324 52807CEA + +[♯34. Free Shopping] +040A0000 01E8B2A0 1A9813F6 + +[♯35. Inf. Equipment Durability (Fire will still break it.)] +040A0000 01B73A14 1B09A3E8 +080A0000 02B19E54 D65F03C0 B9000901 +040A0000 02B19E50 B9401901 +040A0000 00836440 948B8E84 +040A0000 00835F58 948B8FBE + +[♯36. Inf. Arrow(s)] +040A0000 015D66C0 2A1F03E1 + +[♯37. Inf. Zonai Devices] +040A0000 01A6949C 2A1F03E1 + +[♯38. Inf. Zonai Device Duration (No Blink + Despawn)] +040A0000 0118E5CC 1E2703E1 + +[♯39. Inf. Food Items] +040A0000 01A6D2C0 2A1F03E1 +040A0000 01A6D3D0 17FFFFE6 + +[♯40. Inf. Food Buff Timer] +080A0000 02B19F20 D65F03C0 BD015E80 +040A0000 02B19F1C BD416280 +040A0000 009E3B7C 9484D8E8 + +[♯41. Inf. Materials & Zonai Devices (Set To Minimum Qty.500)] +080A0000 02B19F14 1775A2D0 F9401508 +080A0000 02B19F0C 1775A2D5 B8695908 +080A0000 02B19F04 B8295904 5400004C +080A0000 02B19EFC 6B0400BF 52803E84 +080A0000 02B19EF4 B8695905 F9401508 +080A0000 02B19EEC 1A9F82E9 6B17013F +080A0000 02B19EE4 54000161 7100F09F +080A0000 02B19EDC 54000060 7107F89F +040A0000 02B19ED8 B9403104 +040A0000 00882A54 148A5D21 + +[♯42a Item Pickup Multiplier (2x)] +040A0000 0162A408 52800041 + +[♯42b Item Pickup Multiplier (4x)] +040A0000 0162A408 52800081 + +[♯42c Item Pickup Multiplier (8x)] +040A0000 0162A408 52800101 + +[♯43. Inf. Amiibo Usage] +040A0000 0194C8EC 14000014 + +[♯44. Ignore Material Requirements for Upgrades (Horse and Armor)] +040A0000 01B0433C 2A1F03E8 +040A0000 0204BFC8 32000281 +040A0000 02050788 14000019 +040A0000 012E42C8 6B09013F +040A0000 01A5AF78 D503201F +040A0000 01FC757C D503201F +040A0000 02122D08 D503201F + +[--SectionEnd:Inventory--] +20000001 + +[--SectionStart:Map--] +20000000 + +[♯45. Show All Shrine and Cave Locations] +080A0000 00EC206C D65F03C0 52800020 +080A0000 00D23F60 D65F03C0 52800020 + +[♯46. Show All Korok Seed Locations (Must Zoom In)] +040A0000 00D25670 14000019 + +[--SectionEnd:Map--] +20000001 + +[--SectionStart:Misc--] +20000000 + +[♯47. Remove 21 Zonai Device Spawn Limit] +040A0000 00C6A3CC 52800028 + +[♯48. Time Stop (ZL+R3Down)] +80800100 +040A0000 00B3920C D503201F +20000000 + +[♯49. Time Resume (ZL+R3Up)] +80200100 +040A0000 00B3920C 1E212901 +20000000 + +[♯50. Time RW (ZL+R3Left)] +040A0000 00B3920C BD403E68 +80100100 +040A0000 00B3920C 1E37D008 +20000000 + +[♯51. Time FF (ZL+R3Left)] +040A0000 00B3920C BD403E68 +80400100 +040A0000 00B3920C 1E27D008 +20000000 + +[♯52. 2x Longer Days] +040A0000 00B3920C 1E2E1008 + +[♯53. 3x Longer Days] +040A0000 00B3920C 1E2C1008 + +[♯54. 4x Longer Days] +040A0000 00B3920C 1E2A1008 + +[#55. Add 60 Seconds To Mission Timer (L3+R3)] +080A0000 02B19E28 17898E1D BD001D00 +080A0000 02B19E20 1E2A2800 1E2B094A +080A0000 02B19E18 1E20100B 1E2A094A +080A0000 02B19E10 1E27D00A 340000F5 +080A0000 02B19E08 B9401115 54000120 +080A0000 02B19E00 1E202008 BD401D00 +040A0000 00D7D69C BD401D00 +80000030 +040A0000 00D7D69C 147671D9 +20000000 + +[♯56a Handheld 480p] +580F0000 04716F50 +580F1000 00000090 +780F0000 000000F0 +680F01D0 000001E0 00000356 + +[♯56b Handheld 540p] +580F0000 04716F50 +580F1000 00000090 +780F0000 000000F0 +680F01D0 0000021C 000003C0 + +[♯56c Handheld 612p] +580F0000 04716F50 +580F1000 00000090 +780F0000 000000F0 +680F01D0 00000264 00000440 + +[♯56d Handheld 648p] +580F0000 04716F50 +580F1000 00000090 +780F0000 000000F0 +680F01D0 00000288 00000480 + +[♯56e Default Handheld 720p] +580F0000 04716F50 +580F1000 00000090 +780F0000 000000F0 +680F01D0 000002D0 00000500 + +[♯56f Docked 720p] +580F0000 04716F50 +580F1000 00000090 +780F0000 000000F0 +680F01D0 00000360 00000600 + +[♯56g Docked 810p] +580F0000 04716F50 +580F1000 00000090 +780F0000 000000F0 +680F01D0 000003CC 000006C0 + +[♯56h Default Docked 900p] +580F0000 04716F50 +580F1000 00000090 +780F0000 000000F0 +680F01D0 00000438 00000780 + +[--SectionEnd:Misc--] +20000001 + +[--SectionStart:Environment--] +20000000 + +[Brighten World (ON)] +040A0000 0126C374 1E251001 + +[Brighten World (OFF)] +040A0000 0126C374 1E2E1001 + +[Disable Particles] +040A0000 0080B074 1E2703E0 + +[ReEnable Particles] +040A0000 0080B074 1E2E1000 + +[Disable Fog] +040A0000 009ADB48 1E2703E4 + +[ReEnable Fog] +040A0000 009ADB48 1E2E1004 + +[Instant Bloodmoon] +040A0000 0280A5D8 1E3E1001 + +[--SectionEnd:Environment--] +20000001 \ No newline at end of file diff --git a/tools/make_release.py b/tools/make_release.py index 4b9bf12f..da0e1666 100644 --- a/tools/make_release.py +++ b/tools/make_release.py @@ -104,7 +104,7 @@ LLVM_SKIP_SUFFIXES = {'.idl', '.tlb'} # tools/ files the installer steps run (and what they import), copied from the repo. TOOLS_FILES = ['build_game.py', 'build_shaders.py', 'button_icons.py', 'check_content.py', 'extract.py', 'hostmem.py', 'make_romfs_patches.py', 'pack_shader_cache.py', 'prepare_shaders.py', 'romfs_index.py', 'shader_census.py', - 'shader_list.py', 'ultrawide_layout.py'] + 'shader_list.py', 'ultrawide_layout.py', 'cheats.py'] TOOLS_DIRS = ['vendor/macnativegames', 'data'] # data/: expected hashes RUNTIME_SUFFIXES = {'.h', '.inc', '.ico'} # .ico: the installer window icon diff --git a/totk.ini.example b/totk.ini.example index bb0065ed..a04650ca 100644 --- a/totk.ini.example +++ b/totk.ini.example @@ -295,6 +295,11 @@ # Default: shared-fonts next to totk.exe. TOTK_SHARED_FONTS overrides it. # shared_fonts = +[cheats] +# One line per cheat of cheats\.txt next to totk.exe (docs/cheats.md); the Cheats tab of the menu writes +# them. cheat_ = 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.