Files
Triforce-Source/tests/test_amiibo.py
ruckus7382sfgsgdf 822ee913bc Triforce v0.9.0
Character tab, faster renderer defaults, HD rumble shipped, and the 11-30 bug pass: ending softlock below 60 fps, adult first-night lock, Intel Arc robust buffers, adult map, randomizer load order.
2026-11-30 20:55:14 -06:00

272 lines
19 KiB
Python

"""An amiibo from a file (host/amiibo.h, host/nn_nfp.c; no game, no figure's data, no key).
The game asks nn::nfp for a reader, a tag on it, the tag's TagInfo and ModelInfo, and waits for the figure to be lifted
off. A player chooses a dump of one of their own figures on the Debug tab's Scan amiibo page; until one is chosen the
game is told what it always was (no reader).
Compiles and runs tests/amiibo_test.c: the dump parser on bytes of the test's own making (a tag's layout and a decrypted
one, the three sizes, every other size and every wrong mark refused with nothing written, and the data ending at a page
that cannot be read, so a read past its end stops the test); the TagInfo and ModelInfo bytes where the game's code reads
them; the file names taken; the readers' states (none before a figure is chosen, the figure found by the reader that
looks, mounted, read, lifted off a second later, one touch a choice, taken away); and the game's own task, as its code
has it, run against them: it waits in the search state with no figure and ends with the figure's data with one.
Also (Triforce): a Flipper Zero NFC file (.nfc) read as the tag's bytes, cut short anywhere; and the application area a
game may keep on a figure: made, opened by its access ID, set, flushed, kept in a file of its own (never the dump),
closed when the figure is lifted off.
Reads the source for what cannot be run without the game: every SDK function answers as the lift's stub did (0, nothing
written) for a handle that is not a listed reader's; the file is opened by a checked name inside the amiibo folder and
its read is bounded; the only file written is the area's, under the amiibo folder's "areas", by the serial number;
nothing names or opens a key; the choice is taken at the pad read; the option ids.
And (Triforce) the System tab's Unlimited amiibo uses row (host/oot_amiibo_uses.c): the same figure read fifty times in a
row through the game's task, each choice right after the last read (the reader side keeps no count); nx2/oot_patches.py's
call at the head of the game's once-a-day check, on a lift of its own making (once, again a no-op, only that function and
only with the calls read there); the host's answer compiled from its source with stubs (Off: 0, nothing of the game read
or written; On: "not used today"); the row Off by default, its option, the renderer's answer and the launcher's copy; the
page sending a figure the game has read again; and the clock's answer that keeps the game's other check (a clock set by
hand) from refusing a figure.
python -I -B tests/test_amiibo.py [--cc gcc]
"""
import argparse
import re
import subprocess
import sys
import tempfile
from pathlib import Path
RUN_ALL_ARGS = ["--cc", "gcc"]
ROOT = Path(__file__).resolve().parents[1]
# the eleven functions the game's own request makes (its task at 0x83b84230 and the NfpMgr around it)
FUNCTIONS = (
"_ZN2nn3nfp10InitializeEv", "_ZN2nn3nfp8FinalizeEv", "_ZN2nn3nfp29AttachAvailabilityChangeEventEPNS_2os15SystemEventTypeE",
"_ZN2nn3nfp11ListDevicesEPNS0_12DeviceHandleEPii", "_ZN2nn3nfp9GetNpadIdEPjRKNS0_12DeviceHandleE",
"_ZN2nn3nfp14GetDeviceStateERKNS0_12DeviceHandleE", "_ZN2nn3nfp14StartDetectionERKNS0_12DeviceHandleE",
"_ZN2nn3nfp13StopDetectionERKNS0_12DeviceHandleE", "_ZN2nn3nfp10GetTagInfoEPNS0_7TagInfoERKNS0_12DeviceHandleE",
"_ZN2nn3nfp5MountERKNS0_12DeviceHandleENS0_9ModelTypeENS0_11MountTargetE",
"_ZN2nn3nfp12GetModelInfoEPNS0_9ModelInfoERKNS0_12DeviceHandleE")
# ((Triforce) the application area's, for a game that keeps data on a figure: answered for a figure of ours only)
AREA_FUNCTIONS = (
"_ZN2nn3nfp19OpenApplicationAreaERKNS0_12DeviceHandleEj", "_ZN2nn3nfp18GetApplicationAreaEPvPmRKNS0_12DeviceHandleEm",
"_ZN2nn3nfp18SetApplicationAreaERKNS0_12DeviceHandleEPKvm",
"_ZN2nn3nfp21CreateApplicationAreaERKNS0_12DeviceHandleERKNS0_25ApplicationAreaCreateInfoE",
"_ZN2nn3nfp23RecreateApplicationAreaERKNS0_12DeviceHandleERKNS0_25ApplicationAreaCreateInfoE",
"_ZN2nn3nfp5FlushERKNS0_12DeviceHandleE")
def check(ok, why):
if not ok:
raise SystemExit("FAIL: " + why)
def body(text, name):
start = text.index("HLE(%s) {" % name)
end = text.index("{", start) + 1
depth = 1
while depth:
depth += (text[end] == "{") - (text[end] == "}")
end += 1
return text[start:end]
def check_source():
nfp = (ROOT / "host/nn_nfp.c").read_text(encoding="utf-8")
header = (ROOT / "host/amiibo.h").read_text(encoding="utf-8")
hid = (ROOT / "host/nn_hid.c").read_text(encoding="utf-8")
api = (ROOT / "gpu/vk/vk_api.h").read_text(encoding="utf-8")
sys.path.insert(0, str(ROOT / "nx2"))
import standalone
have = standalone.implemented()
for name in FUNCTIONS + AREA_FUNCTIONS:
check("imp_" + name in have, "host/ has no " + name)
code = nfp[nfp.index("#include"):]
check(len(re.findall(r"^HLE\(", code, re.M)) == len(FUNCTIONS + AREA_FUNCTIONS),
"host/nn_nfp.c has other SDK functions than the game's request and the application area's")
for name in AREA_FUNCTIONS: # (a figure of ours only: 0 and nothing written for any other handle)
text = body(nfp, name)
check("reader_of(ARG(" in text or "area_create(c, " in text, name + " does not ask whose handle it is")
for write in re.findall(r"^[^\n]*(?:memcpy\(out|G64\(ARG|area_save\()[^\n]*$", text, re.M):
check("reader >= 0" in write or "if (save)" in write, name + " writes for a handle that is not a reader's: " + write.strip())
create = nfp[nfp.index("static uint32_t area_create("):]
create = create[:create.index("\n}\n")]
check("reader >= 0 && info ? nfp_area_create(" in create and "if (save) area_save(&tag, bytes)" in create,
"CreateApplicationArea makes or writes an area for a handle that is not a reader's")
# a handle that is not a listed reader's: 0 and nothing written, as the lift's stub answers
for name in FUNCTIONS[4:]:
text = body(nfp, name)
check("reader_of(ARG(" in text, name + " does not ask whose handle it is")
check(re.search(r"reader >= 0 \? nfp_\w+\(&nfp, reader[^;]*\) : 0;", text) or "if (reader >= 0 && ARG(0)) G32(ARG(0))" in text,
name + " does not answer 0 for a handle that is not a reader's")
for write in re.findall(r"^[^\n]*(?:memcpy\(GP|G32\(ARG|G64\(ARG)[^\n]*$", text, re.M):
check("reader >= 0" in write, name + " writes for a handle that is not a reader's: " + write.strip())
listing = body(nfp, FUNCTIONS[3])
check("nfp_list(&nfp, handles, max < NFP_READERS ? max : NFP_READERS)" in listing and "if (n > 0) G32(ARG(1)) = (uint32_t)n;" in listing
and "for (int i = 0; i < n; i++) G64(ARG(0) + 8ULL * i) = handles[i];" in listing,
"ListDevices writes a count or a handle while no reader is listed, or more than the game has room for")
check("if (!n->listed) return -1;" in header and "n->listed && i < NFP_READERS && count < max" in header,
"host/amiibo.h takes a handle or lists a reader before a figure was chosen")
# the file: a checked name inside the amiibo folder, a bounded read, and no key anywhere
load = nfp[nfp.index("static int load_dump("):nfp.index("void hos_amiibo_poll(")]
check("if (!amiibo_name_ok(name) || !hos_share_game_dir(dir, sizeof dir)) return NFP_SAID_NO_FILE;" in load
and 'snprintf(path, sizeof path, "%s/amiibo/%s", dir, name);' in load, "the dump is not opened by a checked name inside the amiibo folder")
check("static uint8_t data[AMIIBO_NFC_MAX + 1], pages[540];" in load and "fread(data, 1, sizeof data, f)" in load and
"amiibo_parse(data, n, tag)" in load and "n <= AMIIBO_NFC_MAX && amiibo_flipper((const char *)data, n, pages)" in load,
"the dump's read is not bounded")
# ((Triforce) the dump is only read: the one file written is the area's, in the amiibo folder's areas, by its serial number)
area = nfp[nfp.index("static int area_path("):nfp.index("void hos_amiibo_poll(")]
check(nfp.count("fopen(") == 3 and nfp.count('fopen(path, "rb")') == 2 and nfp.count("fwrite(") == 1 and "fopen" not in header,
"host/nn_nfp.c opens other files than the dump and the area's, or writes another")
check('snprintf(path, cap, "%s/amiibo/areas/%s", dir, name);' in area and "amiibo_area_name(tag, name);" in area and
'fopen(path, "wb")' in area and "fwrite(bytes, 1, NFP_AREA_FILE, f)" in area, "the area is written somewhere else than its own file")
for text, where in ((code, "host/nn_nfp.c"), (header[header.index("#pragma once"):], "host/amiibo.h")):
stripped = re.sub(r"/\*.*?\*/", "", text, flags=re.S)
check(not re.search(r"key|retail|hmac|aes|decrypt\w*\(", stripped, re.I), where + " has code that names a key or decrypts")
# the choice is taken at the pad read, the event signalled only when the readers appear
states = hid[hid.index("static void npad_states("):]
check("hos_amiibo_poll();" in states[:states.index("if (connected) {")], "host/nn_hid.c does not take the page's choice at the pad read")
poll = nfp[nfp.index("void hos_amiibo_poll("):]
check("rx_option(HOS_OPT_AMIIBO_ASK, 0)" in poll and "rx_option_set(HOS_OPT_AMIIBO_SAID, told = said)" in poll, "the page's line is not read, or the page not told")
check("if (nfp_choose(&nfp, &tag)) event = availability_event;" in poll and "if (event) hos_system_event_signal(event);" in poll,
"the game is not told that the readers appeared, or is told at every figure")
check("availability_event = 0;" in body(nfp, FUNCTIONS[1]), "the game's event is kept after Finalize")
check("enum { HOS_OPT_DEBUG_ASK = 115, HOS_OPT_DEBUG_TEXT, HOS_OPT_DEBUG_SAID, HOS_OPT_AMIIBO_ASK, HOS_OPT_AMIIBO_SAID };" in api,
"gpu/vk/vk_api.h: the option ids 115 to 119")
# (the System tab's NFC group: the same Scan amiibo page for every player, not only with the Debug tab's tools on)
menu = (ROOT / "gpu/vk/vk_menu.cpp").read_text(encoding="utf-8")
if not re.search(r'MENU_HEADING\(TAB_SYSTEM, "NFC"\),\s*\{TAB_SYSTEM, kNfcTag, nullptr,', menu) or \
"else if (press[7] && r.name == kNfcTag) names_open(kNamesAmiibo)" not in menu:
raise SystemExit("FAIL: vk_menu.cpp: the System tab's NFC tag row does not open the Scan amiibo page")
print("PASS: the SDK's functions answer as before until a figure is chosen, and no key is read")
# ((Triforce) the game's once-a-day check as its lift has it, cut short: its head, today's date, the history's test of a
# figure, its return)
DAY_LIFT = (
'#include "a64.h"\n'
"void f_8328cd20(Ctx *__restrict A64_NOESC c) {\n return;\n}\n"
"void f_8328cd30(Ctx *__restrict A64_NOESC c) {\n"
" uint8_t fn_ = c->n, fz_ = c->z, fc_ = c->c, fv_ = c->v;\n"
"c->x[30] = 0x8328cd74ULL; f_83290a50(c);\n"
" c->x[19]=recomp_load64(c,c->x[8] + 0);\n"
"c->x[30] = 0x8328ce58ULL; f_8328ee40(c);\n"
" return;\n}\n"
"void f_8328ce90(Ctx *__restrict A64_NOESC c) {\n return;\n}\n")
# the host's answer, cut from its file, with stubs: what it asks of the renderer and what it does to the game's registers
DAY_HOST = r"""
#include <stdint.h>
#include <stdio.h>
typedef struct { uint64_t x[32]; } Ctx;
enum { HOS_OPT_AMIIBO_UNLIMITED = %d };
static int row = -1, asked_id = -1, asked_otherwise = -1, logged;
int rx_option(int id, int otherwise) { asked_id = id, asked_otherwise = otherwise; return row < 0 ? otherwise : row; }
void hos_log(const char *fmt, ...) { (void)fmt; logged++; }
%s
int main(void) {
Ctx c;
int bad = 0;
for (int r = -1; r <= 1; r++) { /* (-1: a renderer that does not answer the option: the default) */
for (int i = 0; i < 32; i++) c.x[i] = 0x5500 + i;
row = r, logged = 0;
const int took = hos_oot_amiibo_used_today(&c);
if (asked_id != HOS_OPT_AMIIBO_UNLIMITED || asked_otherwise != 0) bad |= 1;
if (r == 1 && (took != 1 || c.x[0] != 0 || logged != 1)) bad |= 2;
if (r != 1 && (took != 0 || logged)) bad |= 4;
for (int i = r == 1; i < 32; i++) if (c.x[i] != 0x5500ULL + i) bad |= 8;
}
printf(bad ? "bad %%d\n" : "ok\n", bad);
return bad;
}
"""
def menu_row(menu, name):
"""vk_menu.cpp's row of that name: its text from the brace to its end"""
at = menu.index('{TAB_SYSTEM, "%s", ' % name)
return menu[at:menu.index("},\n", at) + 3]
def check_unlimited(cc):
"""(Triforce) The Unlimited amiibo uses row: the patch, the host's answer, the row, its option and the launcher's copy"""
sys.path.insert(0, str(ROOT / "nx2"))
import oot_patches as op
out, n = op.patch_amiibo_uses(DAY_LIFT)
check(n == 1 and out.count(op.AMIIBO_DAY_HEAD + op.AMIIBO_DAY_HOOK) == 1 and out.count(op.AMIIBO_DAY_HOOK) == 1 and
out.count(op.AMIIBO_DAY_DECL) == 1 and out.index(op.AMIIBO_DAY_DECL) < out.index("void f_"),
"the once-a-day check is not called at the head of f_8328cd30, once, declared before the code")
check(op.patch_amiibo_uses(out) == (out, 1), "a second run of the patch changes the lift")
check(out.replace(op.AMIIBO_DAY_HOOK, "").replace(op.AMIIBO_DAY_DECL, "") == DAY_LIFT, "the patch changes more than the call")
other = DAY_LIFT.replace("f_8328cd30", "f_8328cd40")
check(op.patch_amiibo_uses(other) == (other, 0), "another function is patched")
for call in op.AMIIBO_DAY_CALLS: # (another build's function at that address: left as it is)
without = DAY_LIFT.replace(call, " f_80000000(c);\n")
check(op.patch_amiibo_uses(without) == (without, 0), "f_8328cd30 is patched without the call to" + call.strip())
elsewhere = DAY_LIFT.replace(" return;\n}\nvoid f_8328ce90", op.AMIIBO_DAY_HOOK + " return;\n}\nvoid f_8328ce90")
check(op.patch_amiibo_uses(elsewhere) == (elsewhere, 0), "a call away from the function's head is taken as the patch")
patches = (ROOT / "nx2/oot_patches.py").read_text(encoding="utf-8")
apply = patches[patches.index("def apply(gen,"):patches.index("def apply_output_size(")]
check("unlimited, found = patch_amiibo_uses(out)" in apply and "amiibo_sites += found" in apply and
"if protect_hearts and amiibo_sites != 1:" in apply, "the build does not make the call, or does not say when it is not found")
# the host: the row read first; Off, nothing of the game read or written
host = (ROOT / "host/oot_amiibo_uses.c").read_text(encoding="utf-8")
fn = host[host.index("int hos_oot_amiibo_used_today(Ctx *c) {"):]
check(fn.index("if (!rx_option(HOS_OPT_AMIIBO_UNLIMITED, 0)) return 0;") < fn.index("c->x["), "the host reads the game before the row")
check(set(re.findall(r"c->x\[\d+\]", fn)) == {"c->x[0]"} and "recomp_" not in fn and "fopen" not in host and "fwrite" not in host,
"the host touches more of the game than its answer, or writes a file")
api = (ROOT / "gpu/vk/vk_api.h").read_text(encoding="utf-8")
m = re.search(r"enum \{ HOS_OPT_FOV = 200,([^}]*)\};", api)
names = ["HOS_OPT_FOV"] + [w.strip() for w in m.group(1).split(",") if w.strip()]
check("HOS_OPT_AMIIBO_UNLIMITED" in names and api.count("HOS_OPT_AMIIBO_UNLIMITED") == 2, "gpu/vk/vk_api.h: the row's option")
number = 200 + names.index("HOS_OPT_AMIIBO_UNLIMITED")
with tempfile.TemporaryDirectory() as tmp:
src, exe = Path(tmp) / "day.c", Path(tmp) / "day.exe"
src.write_text(DAY_HOST % (number, fn), encoding="utf-8")
subprocess.run([cc, "-std=c11", "-O1", "-Wall", "-Wextra", "-Werror", str(src), "-o", str(exe)], check=True)
run = subprocess.run([str(exe)], capture_output=True, text=True)
check(run.returncode == 0 and run.stdout.strip() == "ok", "the host's answer (Off: the game's own, On: not used today): " + run.stdout)
# the row: the System tab's NFC group, after NFC tag; Off by default; the renderer's answer; the launcher's copy
menu = (ROOT / "gpu/vk/vk_menu.cpp").read_text(encoding="utf-8")
row = menu_row(menu, "Unlimited amiibo uses")
check(row.startswith('{TAB_SYSTEM, "Unlimited amiibo uses", &opts.amiibo_unlimited, 0, 1, 1, tx_onoff,') and row.endswith("nullptr, false, true},\n"),
"vk_menu.cpp: the row is not an Off/On row of opts.amiibo_unlimited")
group = menu[menu.index('MENU_HEADING(TAB_SYSTEM, "NFC")'):menu.index('MENU_HEADING(TAB_SYSTEM, "Online")')]
check(group.index("{TAB_SYSTEM, kNfcTag, ") < group.index(row), "the row is not in the NFC group, after NFC tag")
header = (ROOT / "gpu/vk/vk_menu.h").read_text(encoding="utf-8")
check(re.search(r"^\s*int amiibo_unlimited = 0;", header, re.M), "vk_menu.h: the row is not Off by default")
replay = (ROOT / "gpu/vk/vk_replay.cpp").read_text(encoding="utf-8")
check("if (id == HOS_OPT_AMIIBO_UNLIMITED) return opts.amiibo_unlimited != 0;" in replay, "the renderer does not answer the row's option")
helptext = "".join(re.findall(r'"((?:[^"\\]|\\.)*)"', row[row.index("tx_onoff,"):]))
schema = (ROOT / "launcher/Logic/GameOptions/GameOptionsSchema.cs").read_text(encoding="utf-8")
check('Row(GameOptionTab.System, "NFC", "Unlimited amiibo uses", 0, 1, 1, 0, GameOptionKind.Choice, TxOnoff, false, true,\n'
' "%s"),' % helptext in schema, "the launcher's copy of the row is not the menu's (NFC, Off, the same help)")
# the page sends a figure the game has read again (another touch); a figure's clock check never refuses here
check("const bool away = (said == HOS_AMIIBO_WAITING || said == HOS_AMIIBO_ON_READER) && amiibo_chosen == name;" in menu,
"the Scan amiibo page takes a figure off when it is chosen again after the game read it")
applet = (ROOT / "host/nn_applet.c").read_text(encoding="utf-8")
check("HLE(_ZN2nn4time48CalculateStandardUserSystemClockDifferenceByUserERKNS0_13ClockSnapshotES3_) { RET(0); }" in applet,
"host/nn_applet.c: the clock set by hand is not answered 0 (the game's clock check could refuse a figure)")
print("PASS: Unlimited amiibo uses: the once-a-day check's call, the host's answer, the row Off by default, its launcher copy")
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--cc", default="gcc")
a = p.parse_args()
check_source()
check_unlimited(a.cc)
with tempfile.TemporaryDirectory() as tmp:
exe = Path(tmp) / "amiibo_test.exe"
subprocess.run([a.cc, "-std=c11", "-O1", "-Wall", "-Wextra", "-Werror", str(ROOT / "tests/amiibo_test.c"), "-o", str(exe)], check=True)
run = subprocess.run([str(exe)], capture_output=True, text=True)
if run.returncode or run.stdout.strip() != "ok":
raise SystemExit("FAIL: tests/amiibo_test.c (exit %d)\n%s%s" % (run.returncode, run.stdout, run.stderr))
print("PASS: the dump parser, the infos, the names, the readers' states, the game's task against them and fifty scans in a row")
if __name__ == "__main__":
main()