From ecb4d5cc9928feb5066571727a8b072de17f469b Mon Sep 17 00:00:00 2001 From: ruckus7382sfgsgdf <355121112+ruckus7382sfgsgdf@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:54:12 -0600 Subject: [PATCH] Triforce v0.8.3 Fixes from the 0.8 reports: a mod's code patches go in together or not at all and a mod whose code is refused is off whole; nn::crypto random bytes from the host (a crash at start); shader preparation on three quarters of the CPU threads; Evil HD ornaments and shoot leaves kept to 75 m and 70 m (flicker); the RADV lighting flicker fix; 3D BC images through block attachments on AMD RDNA 1/2 Windows (rainbow lights). --- docs/development.md | 1 + gpu/vk/prepare_threads.h | 9 +++++++-- gpu/vk/vk_internal.h | 2 ++ gpu/vk/vk_memory.cpp | 31 ++++++++++++++++++++++++------- gpu/vk/vk_replay.cpp | 1 + gpu/vk/vk_texture.cpp | 14 +++++++++----- host/evil_hd.h | 19 ++++++++++++++++--- host/mods.c | 24 +++++++++++++++++------- host/nn_applet.c | 34 ++++++++++++++++++++++++++++++++++ nx2/code_mods.py | 33 +++++++++++++++++++++++++++++++-- tests/test_code_mods.py | 31 +++++++++++++++++++++++++++++++ tests/test_evil_hd_foliage.py | 7 +++++-- tests/test_prepare_threads.cpp | 13 +++++++------ 13 files changed, 185 insertions(+), 34 deletions(-) diff --git a/docs/development.md b/docs/development.md index 657673f..cdff13f 100644 --- a/docs/development.md +++ b/docs/development.md @@ -198,6 +198,7 @@ case-sensitive, and an unknown one is ignored. | `RX_VK_SETTLE_GATE=1`, `=2` | (Triforce, 11-22, off by default; the performance audit's SYNC-29, after Source A's; `gpu/vk/settle_gate.h`) A CPU read that lets the stopped queues whose waits are met go on (the readback's look, which `RX_VK_RB_SETTLE=1` turns on, and the two looks made for a range a texture may be in) takes the order's lock whenever a queue is stopped, and that lock is held through whole replays and presents. With the gate a site looks only while a queue is stopped **and** the CPU has signalled an event since the last finished look, or a stopped queue waits on an event whose value is read from guest memory; any other met wait was met by a signal in the stream, and the thread that replayed it looked before it let the lock go. `1`: the readback's look; `2`: the texture sites' too (new ground: those looks order the exposure meter's readback, so `2` needs the lab's flicker count). Unset or `0`: every look as before. The `RX_VK_LAB_AB` knobs `settlegate` and `texgate` are `1` and `2` in their phases (`rbsettle+settlegate` is the pair the audit asks for). The 3000-readback line and the texture catch-ups' 300-call line count the looks made and skipped | | `RX_VK_READBACK_LATE=[,]`, `RX_VK_LOG_READBACK_RANGES=1` | (Triforce, 11-22, the performance audit's SYNC-19, after Source A's; `gpu/vk/readback_late.h`) Ranges the CPU reads back **without** the wait for their write-back, from what guest memory holds (the last write-back made): a rule is a size in hex (`3980`: every range of 0x3980 bytes, the culling camera block Source A reads late by default) or `newest` (a range whose writer is the newest submission handed out: the game cannot have waited for it). **Unset: no rule**, every readback waits as before, until the lab has run it where the waits are long (a handheld, an AMD iGPU, a weak discrete card); `=0`: none either. The `RX_VK_LAB_AB` knob `rblate` is `3980` in its phases. A late read hands the game the frame before's values, and when the CPU resets a range read late the pending write-back lands over its reset (the exposure meter's flashes): `newest` can catch that meter, so it is never a default. `RX_VK_LOG_READBACK_RANGES=1`: with every 3000-readback line, the 12 ranges that waited longest (readbacks, waits, ms, how often their writer was the newest submission, how often read late), to find such ranges on other hardware; nothing is noted without it | | `RX_VK_WB_WAIT_REC=1`, `=2` | (Triforce, off by default; the handoff's §12.9, `gpu/vk/wb_rec_wait.h`) A wait for a write-back still on the GPU (a capture's late pages on the game's submitting thread, a read or binding of a page put off) ends once the recording its submission was finished in is done on the GPU, not when the submissions' timeline reaches it: that timeline is held below any submission stopped at an event wait, and the lab's Market had 20-46 ms waits of the game's thread with the GPU 4 submissions behind. Whatever the switch, the wait for the recording comes first and the rest is counted: the stall line's `N of them X ms after their writer's recording was done`, the `late:` line's `ms of the wait after the recording that finished it was done`, the frame trace's `wb_held_ms`. Off: the captures' late-page wait orders something not known yet (`RX_VK_LATE_NEW`), so it is tried with the lab's flicker count first. (Triforce, 11-22, the performance audit's SYNC-122, after Source B's) The reads' side: a readback whose write-back is not recorded yet waited on the submissions' timeline with no bound and no second look; it is counted now (the 3000-readback line's second line), and the stall line names the held part by caller (takes, reads, binds, readbacks). The variable is a mode: `1` as above, and such a readback waits in 1 ms slices, looks its writer's recording up between them and ends with it; `2` is the check, where no wait ends earlier and the readback's slices count the part after the recording was done (what `1` would not have waited); unset, `0` or any other text: off, one wait as before. The check of the pages a later write-back changes (the audit's SYNC-101) is not built. `RX_VK_TL_REC=1` and the lab knob `tlrec` ended a capture's wait at a submission's first part, before its burst's write-backs were recorded: they now end it at the recording the submission was finished in, as `=1` here does; `RX_VK_TL_REC=2` keeps the old lookup | +| `RX_VK_LATE_QUEUE=1` or `0` | (Triforce, 11-20; 11-23) A capture's late pages (pages a submission still on the GPU writes back: OoT's exposure meter and the per-frame pools) waited for at the queue's next submit, not at the capture's take (`gpu/vk/vk_memory.cpp` `late_queue_on`). Unset: at the queue, except while the replay's submits are held (`RX_VK_BATCH`, on by default with Mesa's RADV): there a held submit applies no fix, the fixes wait for the batch's flush and copy guest memory the game has written again for its next frame, and the replay reads those slots live meanwhile: the lighting and exposure flicker on Linux AMD from 50-90 s into play in v0.7.0. `1`: at the queue with held submits too (v0.7.0 as shipped); `0`: at the take on every driver, as before 11-20. The log says `vk: late pages' wait ...` when it is first asked and when the answer changes | | `RX_VK_LATE_INLINE=1` | (Triforce, 11-22, the performance audit's MEM-80, after Source B's; `gpu/vk/late_inline.h`; **off unless set**, not yet run in the game) A late page (one the CPU wrote while a submission still on the GPU writes it back) is waited for and taken again by default (`RX_VK_LATE_QUEUE`: at the queue's next submit). `RX_VK_LATE_NEW=1` (knob `latenew`) turns four no-wait rules on, each of which brought brightness steps back at the Castle Town save. This turns on the partial rule alone (knob `lateinline`): a page only part of which a submission on the GPU writes back has its other parts synced from the capture, no wait; pages of pools with no mirror, texture storage, pages written back whole and pages whose write-backs' ranges are not known are waited for as by default. The partial rule, here and under `RX_VK_LATE_NEW`, now asks which ranges are still on the GPU against the progress the capture read before its copies, not a second read at the take: a write-back done between the two counts as in flight, and its range is not synced from the older copy. `RX_VK_LOG_LATE` shows the pages waited for | | `RX_VK_PASS_TIMING=1` or `2` | GPU time per pass (2: per program too), logged every 600 presents | | `RX_VK_SLOW_LOG=` | The replay's times for each frame that took longer than this | diff --git a/gpu/vk/prepare_threads.h b/gpu/vk/prepare_threads.h index 809bba5..998f730 100644 --- a/gpu/vk/prepare_threads.h +++ b/gpu/vk/prepare_threads.h @@ -8,7 +8,7 @@ // else on the PC, and nothing of the game runs during the preparation: there the other half of the processors stood idle // through a wait of minutes (165 s with 12 workers on a 24-thread PC). NX2navi prepares on every processor it is given. // -// So: every processor, 64 at most, unless the process was started above normal priority (half, as before). Nothing +// So: every processor (three quarters of them since 11-25, below), 64 at most, unless the process was started above normal priority (half, as before). Nothing // bounded the memory a worker takes: each holds one program's translation at a time and the driver's compiler for one // pipeline, and how much the driver's part is has not been measured here (the compute programs go first, so every worker // is in the driver's compiler at once when the preparation begins). So the workers past half are given only what RAM is @@ -45,9 +45,14 @@ inline constexpr unsigned kAmdOlderMost = 8; /// cpus: the logical processors; ram_free: the physical memory free now, 0 when it is not known; above_normal: the process /// was started above normal priority; asked: RX_VK_PREPARE_THREADS, 0 or less when it is not set +/// ((Triforce, 11-25) the most by default: three quarters of the processors, never fewer than half. Two players' PCs in one day +/// with every processor busy for the whole preparation after 0.8's update: one at 100 °C, one switched itself off. The quarter +/// left keeps the PC's own work and its fans ahead; RX_VK_PREPARE_THREADS still asks for any number) +inline unsigned three_quarters(unsigned cpus) { return std::max(half(cpus), std::clamp(cpus - cpus / 4, 1u, 64u)); } + inline unsigned count(unsigned cpus, uint64_t ram_free, bool above_normal, int asked) { if (asked > 0) return (unsigned)std::min(asked, 64); - const unsigned least = half(cpus), most = std::clamp(cpus, 1u, 64u); + const unsigned least = half(cpus), most = three_quarters(cpus); if (above_normal || !ram_free) return least; return (unsigned)std::clamp(ram_free / kRamAWorker, least, most); } diff --git a/gpu/vk/vk_internal.h b/gpu/vk/vk_internal.h index c4ad091..c051084 100644 --- a/gpu/vk/vk_internal.h +++ b/gpu/vk/vk_internal.h @@ -446,6 +446,8 @@ void vk_timeline_wait_from(uint64_t v, int who); // ((Triforce) RX_VK_LATE_QUEUE: the highest timeline value on the queue; a wait for a sent one (no flush; false: not reached in 1 s); // the late pages' fixes applied (dev.present_mu held; queue_flush_locked does it first); vk_memory.cpp's side uint64_t vk_timeline_signal_sent(); +/// ((Triforce, 11-23) whether the replay's submits are held (RX_VK_BATCH: on by default with RADV): vk_memory.cpp late_queue_on +bool vk_batch_holds(); bool vk_timeline_wait_sent(uint64_t v); void late_fix_flush_locked(); void vk_late_queue_stats(int64_t* waits, int64_t* wait_ns, int64_t* timeouts); diff --git a/gpu/vk/vk_memory.cpp b/gpu/vk/vk_memory.cpp index d77fb73..61a9955 100644 --- a/gpu/vk/vk_memory.cpp +++ b/gpu/vk/vk_memory.cpp @@ -4206,15 +4206,32 @@ inline const uint8_t* cap_page_bytes(const Capture& c, uint32_t slot) { // while the GPU finishes the frame before. Not deferred, as before: a value not sent yet, a late page in a texture's storage (its // shadow and uploads read the capture at the take), more than kLateFixMax pending. Triforce's earlier experiments that dropped // the wait (RX_VK_LATE_NEW, the lab's nolatewait) took the bytes WITHOUT waiting and stepped the exposure; this still waits +// ((Triforce, 11-23, the Linux RADV lighting flicker: tickets 451323, 973820, 240338, 474460, 626285, 374015) NOT with held +// submits (RX_VK_BATCH, on by default with Mesa's RADV). A held submit goes into the batch without late_fix_flush_locked (only +// the batch's flush applies the fixes: a poll 2 ms on, a present, a wait), so the fixes stay pending far longer than "until the +// next submit". Meanwhile the replay's reads of those slots read guest memory as it is then (memory_read_as_submitted), and the +// fix itself copies guest memory as it is at the flush: by then the game's CPU has gone on into the next frame and written those +// pages again, so the capture carries another frame's bytes there (OoT's exposure meter and the per-frame pools beside it). In +// every RADV log of the tickets the flicker starts where the late pages stop being texture storage (the take waited until then) +// and are put off to the queue instead: the RX_VK_LATE_QUEUE line goes from "0 put off, 60-100 texture storage, 0 replay reads +// of a pending slot" to "150-230 put off, 0 texture storage, 250-2100 replay reads of a pending slot", 50-90 s into play, and +// stays there until the game ends. NVIDIA on Linux defers as many with 0 such reads (no held submits: the next submit applies +// them); AMD on Windows has none. So while submits are held the take waits, as before 11-20. RX_VK_LATE_QUEUE unset: moved to +// the queue unless submits are held; =1: moved to the queue with held submits too (v0.7.0 as shipped); =0: the take waits, on +// any driver, as before. Asked at each take: whether submits are held is known once the replay has its batch timeline bool late_queue_on() { - static const bool v = [] { - // (on by default since 11-20: 79.8 -> 80.4 fps, three alternating rounds each at the owner's save (every round ahead), - // frame log clean: no cell blinks or whole-frame steps against none. RX_VK_LATE_QUEUE=0: the take waits, as before) - const bool on = !(getenv("RX_VK_LATE_QUEUE") && atoi(getenv("RX_VK_LATE_QUEUE")) == 0); - logf("vk: late pages' wait %s (RX_VK_LATE_QUEUE)", on ? "moved to the queue" : "at the capture's take, as before"); - return on; + static const int env = [] { // (-1 unset, 0 off, 1 on) + const char* e = getenv("RX_VK_LATE_QUEUE"); + return e && *e ? (atoi(e) != 0 ? 1 : 0) : -1; }(); - return v; + const bool on = env == 1 || (env == -1 && !vk_batch_holds()); + static std::atomic said{-1}; // (the last answer logged: a line when it is first asked and when it changes) + if (said.exchange(on ? 1 : 0, std::memory_order_relaxed) != (on ? 1 : 0)) + logf("vk: late pages' wait %s (RX_VK_LATE_QUEUE%s)", + on ? "moved to the queue" : "at the capture's take, as before", + env == -1 ? (on ? "; =0: at the take" : ": submits are held (RX_VK_BATCH), so the take waits; =1: moved to the queue, as v0.7.0") + : env == 1 ? "=1" : "=0"); + return on; } struct LateFix { uint64_t value = 0; // (the late pages' write-back: their slots copied again once it is done) diff --git a/gpu/vk/vk_replay.cpp b/gpu/vk/vk_replay.cpp index 30b2aaa..e9ff28d 100644 --- a/gpu/vk/vk_replay.cpp +++ b/gpu/vk/vk_replay.cpp @@ -536,6 +536,7 @@ void split_part_submitted(VkCommandBuffer cmd, bool uploads) { // again into their captures' buffers, as the take did after its wait. At most 250 ms at a time, 4 times: a submission the event // ordering holds behind a later one cannot hold the queue's lock for ever (the fix goes in as it is, counted) uint64_t vk_timeline_signal_sent() { return stall_ct.queue_top.load(std::memory_order_relaxed); } +bool vk_batch_holds() { return batch_on(); } // ((Triforce, 11-23) vk_memory.cpp late_queue_on: no late pages put off while submits are held) bool vk_timeline_wait_sent(uint64_t v) { if (!timeline) return true; for (int i = 0; i < 4; i++) { diff --git a/gpu/vk/vk_texture.cpp b/gpu/vk/vk_texture.cpp index e646afd..c6638b0 100644 --- a/gpu/vk/vk_texture.cpp +++ b/gpu/vk/vk_texture.cpp @@ -1084,17 +1084,21 @@ VkImageView make_view(Texture* tex, VkImageViewType type, VkFormat f, VkImageAsp /// 0 not at all: the pass is left out, the volumes stay zero and trees are bare at mid distance. /// NVIDIA's Pascal and older (device IDs below 0x1e00: GTX 10 series, GTX 900) take the usage and the per-slice views, then /// lose the device on the first draw or even a clear into one (a GTX 1080 and a GTX 1070, driver 581.80, at the area load -/// after the opening cutscene and at every save load): 2 there, where it was 0. RX_VK_BC3D_TARGET=0, 1 or 2: that way +/// after the opening cutscene and at every save load): 2 there, where it was 0. ((Triforce, 11-25) And AMD's Windows driver for +/// RDNA 1 and 2 (vk_vendor.h amd_older_compiler): its raw views draw wrong values into the volumes, and the effects that read +/// them showed bright rainbow lights on the walls (an RX 6900 XT, driver 26.11.2, Goron City; the player's own +/// RX_VK_BC3D_TARGET=2 fixed it). RX_VK_BC3D_TARGET=0, 1 or 2: that way int bc3d_way() { static const int way = [] { const char* e = getenv("RX_VK_BC3D_TARGET"); const bool old_nvidia = dev.props.vendorID == 0x10de && dev.props.deviceID < 0x1e00; - const int v = e && *e ? std::clamp(atoi(e), 0, 2) : old_nvidia ? 2 : 1; + const bool amd_older = dev.amd_older_compiler; + const int v = e && *e ? std::clamp(atoi(e), 0, 2) : old_nvidia || amd_older ? 2 : 1; if (v != 1) - logf("vk: 3D BC images are drawn into %s (%s; NVIDIA before Turing loses the device on raw views of them; " - "RX_VK_BC3D_TARGET=1: raw views, 2: block attachments, 0: not at all)", + logf("vk: 3D BC images are drawn into %s (%s; NVIDIA before Turing loses the device on raw views of them, AMD's driver " + "for RDNA 1 and 2 draws wrong values through them; RX_VK_BC3D_TARGET=1: raw views, 2: block attachments, 0: not at all)", v ? "through uncompressed block attachments of their own" : "not at all: the noise pass is left out", - e && *e ? "RX_VK_BC3D_TARGET" : "NVIDIA device id below 0x1e00"); + e && *e ? "RX_VK_BC3D_TARGET" : old_nvidia ? "NVIDIA device id below 0x1e00" : "AMD's driver for RDNA 1 and 2"); return v; }(); return way; diff --git a/host/evil_hd.h b/host/evil_hd.h index 8f12c31..9cdcb59 100644 --- a/host/evil_hd.h +++ b/host/evil_hd.h @@ -44,6 +44,19 @@ enum { EVIL_HD_FOLIAGE_COUNT = 8 }; #define EVIL_HD_FOLIAGE_DEFAULTS 0x83f0fd38ULL /* (main+0x3eefd38: the eight defaults, in this order) */ static const float evil_hd_foliage_game[EVIL_HD_FOLIAGE_COUNT] = {40.0f, 60.0f, 35.0f, 30.0f, 40.0f, 135.0f, 10.0f, 45.0f}; +/* ((Triforce, 11-25, a player's report with the measurements: "Evil HD 4x: Kokiri Forest bushes and Lost Woods tree leaves + flicker") The most two of them go to: the ornaments (Kokiri Forest's cuttable bushes and flowers) flickered at 140 m (4x) + and 105 m (3x) and were steady at 70 and 75 m; the low trees' shoot leaves (the Lost Woods' leaves overhead) flickered at + 120 m and were steady at 30 and 70 m. The game's own areas set them no farther than 75 m (Hyrule Castle's ornaments) and + 70 m (Zora's Domain's shoot leaves): the foliage system seems to have room for about that many of them. The other six + showed no flicker at 4x and keep the whole factor. 0: no bound */ +static const float evil_hd_foliage_most[EVIL_HD_FOLIAGE_COUNT] = {0.0f, 0.0f, 75.0f, 70.0f, 0.0f, 0.0f, 0.0f, 0.0f}; +/* One distance at a factor: the game's times it, kept to its most */ +static inline float evil_hd_foliage_one(int i, float factor) { + const float v = factor == 1.0f ? evil_hd_foliage_game[i] : evil_hd_foliage_game[i] * factor; + return evil_hd_foliage_most[i] > 0.0f && v > evil_hd_foliage_most[i] && evil_hd_foliage_game[i] <= evil_hd_foliage_most[i] + ? evil_hd_foliage_most[i] : v; +} /* Whether Evil HD is on: the row's value, or HOS_EVIL_HD's when it is set to 0 or 1 (anything else: the row's) */ static inline int evil_hd_on(int row, const char *asked) { @@ -76,9 +89,9 @@ static inline float evil_hd_factor(int row, const char *mode, const char *dist) return evil_hd_on(row, mode) ? evil_hd_dist_factor(dist) : 1.0f; } -/* The game's eight foliage defaults, each times the factor, into out (the factor 1: the game's own exactly) */ +/* The game's eight foliage defaults, each times the factor (kept to evil_hd_foliage_most), into out (the factor 1: the game's own exactly) */ static inline void evil_hd_foliage(float factor, float out[EVIL_HD_FOLIAGE_COUNT]) { - for (int i = 0; i < EVIL_HD_FOLIAGE_COUNT; i++) out[i] = factor == 1.0f ? evil_hd_foliage_game[i] : evil_hd_foliage_game[i] * factor; + for (int i = 0; i < EVIL_HD_FOLIAGE_COUNT; i++) out[i] = evil_hd_foliage_one(i, factor); } /* Whether the eight floats at the defaults' place are a version of them this rule knows: the game's own, or the game's @@ -87,7 +100,7 @@ static inline int evil_hd_foliage_known(const float have[EVIL_HD_FOLIAGE_COUNT]) const float f = have[0] / evil_hd_foliage_game[0]; if (!(f >= 1.0f && f <= EVIL_HD_DIST_MOST)) return 0; for (int i = 0; i < EVIL_HD_FOLIAGE_COUNT; i++) { - const float want = evil_hd_foliage_game[i] * f, d = have[i] - want; + const float want = evil_hd_foliage_one(i, f), d = have[i] - want; if (d > want * 1e-4f || d < -want * 1e-4f) return 0; } return 1; diff --git a/host/mods.c b/host/mods.c index 4aae486..728d622 100644 --- a/host/mods.c +++ b/host/mods.c @@ -204,8 +204,9 @@ static void code_record_load(void) { if (built) nbuilt = mod_code_parse(text, built, BUILT_MOST); free(text); } -/* (returns how many of this mod's patches wait for a build: new since it, or changed) */ -static int code_patches(const Mod *mod) { +/* (returns how many of this mod's patches wait for a build: new since it, or changed; *refused: how many the build refused) */ +static int code_patches(const Mod *mod, int *refused) { + *refused = 0; char pat[MAX_PATH]; snprintf(pat, sizeof pat, "%s\\exefs\\*", mod->path); WIN32_FIND_DATAA fd; @@ -227,6 +228,8 @@ static int code_patches(const Mod *mod) { else if (state == MOD_CODE_CHANGED) hos_log("mods: %s changed since the game was built: the game has it as it was then", rel); else hos_log("mods: %s is not built into the game", rel); waits += state == MOD_CODE_CHANGED || state == MOD_CODE_WAITS; + /* (one for another build of the game holds nothing back: mods carry a patch per game version, nx2/code_mods.py OtherBuild) */ + *refused += state == MOD_CODE_REFUSED && strncmp(why, "it is for build ", 16) != 0; } while (FindNextFileA(f, &fd)); FindClose(f); code_waits += waits; @@ -289,13 +292,20 @@ static void mods_scan(void) { files waiting too: the game crashed at its start with a mod's new files over its old code (Classic Item Slots put in by the Mods menu, #bug-tracker "Crashing on startup"; a build put them in step). They come with the code, at the next build. HOS_MODS_SPLIT=1: the files now anyway, as before) */ - const int waits = code_patches(&mods[i]); + /* ((Triforce, 11-25) and a mod whose code the build refused (a code cave, another build) is off whole: its RomFS + files were made for its code. A player's "More Tunics" had its two code-cave patches refused and its 172 files + (new tunics in the actor and game data tables) loaded over the game's own code; crashes at every loading screen) */ + int refused = 0; + const int waits = code_patches(&mods[i], &refused); static int split = -1; if (split < 0) split = getenv("HOS_MODS_SPLIT") && atoi(getenv("HOS_MODS_SPLIT")) == 1; - const int hold = waits > 0 && !split; - const int files = hold ? 0 : index_romfs(dir, "", 0); - cheat_files(&mods[i]); /* (and its cheat file) */ - if (hold) + const int hold = waits > 0 && !split, off = refused > 0 && !split; + const int files = hold || off ? 0 : index_romfs(dir, "", 0); + if (!off) cheat_files(&mods[i]); /* (and its cheat file) */ + if (off) + hos_log("mods: %s is off: %d of its code patch(es) could not be built in, and its RomFS files and cheats go with its code " + "(HOS_MODS_SPLIT=1: its files anyway)", mods[i].name, refused); + else if (hold) hos_log("mods: %s: its RomFS files wait for the build too, with its code (%d patch(es) not built in yet)", mods[i].name, waits); else hos_log("mods: %s: %d RomFS files", mods[i].name, files); diff --git a/host/nn_applet.c b/host/nn_applet.c index be767d7..078c17e 100644 --- a/host/nn_applet.c +++ b/host/nn_applet.c @@ -465,6 +465,40 @@ HLE(_ZN2nn5prepo10PlayReport4SaveERKNS_7account3UidE) { RET(0); } /* (hookshot) PlayReport::Send(Uid const&), SDK 22's: kept nowhere, as Save. Left to the SDK it opened the prepo service through sm: and aborted on the empty reply (OoT's PlayReporter thread, ~5 minutes into a game). */ HLE(_ZN2nn5prepo10PlayReport4SendERKNS_7account3UidE) { RET(0); } + +/* ((Triforce, 11-25) nn::crypto::GenerateCryptographicallyRandomBytes(void* out, size_t size): the host's own secure random + bytes. Left to the SDK it opened the csrng service through sm:, got the empty reply and aborted (svcBreak in + nn::diag::detail::Abort): a player's game stopped ~6 s after every start, on OoT's Porter thread (main 0x82507050, the + npln online code), on an RX 6800 PC; never seen here, so its call is on a path our runs do not take. */ +#ifdef _WIN32 +#include /* (RtlGenRandom, as host/hos_report_run.c) */ +#else +#include +#include +#endif +HLE(_ZN2nn6crypto36GenerateCryptographicallyRandomBytesEPvm) { + const uint64_t out = ARG(0), size = ARG(1); + if (!out || !size || !hos_guest_range(out, size)) return; + uint8_t *p = (uint8_t *)GP(out); + uint64_t done = 0; + while (done < size) { + const uint64_t n = size - done < 0x10000 ? size - done : 0x10000; +#ifdef _WIN32 + if (!RtlGenRandom(p + done, (ULONG)n)) break; + done += n; +#else + const ssize_t got = getrandom(p + done, (size_t)n, 0); + if (got < 0 && errno == EINTR) continue; + if (got <= 0) break; + done += (uint64_t)got; +#endif + } + if (done < size) { /* (no host randomness: never seen; the bytes still differ from run to run) */ + uint64_t x = (uint64_t)hos_now_ns() ^ (out << 17) ^ 0x9E3779B97F4A7C15ULL; + for (; done < size; done++) { x ^= x << 13; x ^= x >> 7; x ^= x << 17; p[done] = (uint8_t)x; } + hos_log("crypto: the host gave no random bytes: %llu made from the clock", (unsigned long long)size); + } +} /* (hookshot) prepo::AsyncContext: the report "sent" at once. GetCompletionEvent(SystemEvent* out) gives an event already signaled (the SDK's own aborted on the context the empty IPC reply left), GetResult success. */ void hos_system_event_init(uint64_t key, int autoclear); /* nn_os_sync.c */ diff --git a/nx2/code_mods.py b/nx2/code_mods.py index e2f3ed9..1f1a174 100644 --- a/nx2/code_mods.py +++ b/nx2/code_mods.py @@ -22,7 +22,8 @@ Offsets are as emulators and Atmosphere read them: they count the NSO's 0x100-by .pchtxt offset after its "@flag offset_shift" is added). A file is applied whole or not at all: one that is cut short, that cannot be read, or that writes outside the module's three segments (.text, .rodata, .data) is refused. That leaves out code caves, patches that put new code into the empty space after .text: the translator has not been tried on -them. +them. A mod is applied whole or not at all too: when one of its patch files is refused, so are its others (one of them +may branch into the code the refused one adds). What a build did is kept in the game folder, triforce_code_mods.txt (RECORD, write_record): the next build, an update (--update) among them, reads the mods folder again, builds the same patches in again and says which of the last build's @@ -52,6 +53,10 @@ class Refused(ValueError): """A patch file that is not applied; the text says why""" +class OtherBuild(Refused): + """A patch file for another build of the game: mods carry one per game version, so it does not hold the mod's others back""" + + # ---- the formats: [(offset in the module's image, bytes)] in the file's order def parse_ips(data): @@ -317,6 +322,11 @@ def read_patch(rel, data): return build, writes +def mod_of(rel): + """The mod a patch file is of: its path under the mods folder up to /exefs/ (patch_files)""" + return rel.rsplit("/exefs/", 1)[0] + + def check_writes(module, writes): """Refused when a write is not whole inside one of the module's segments""" for offset, data in writes: @@ -337,6 +347,8 @@ def apply(exefs, mods_root, say=print): modules = load_modules(exefs) game = ", ".join("%s %s" % (m.name, m.build_id.rstrip("0")[:40] or "0") for m in modules.values()) entries, owner = [], {} # (owner: {(module, offset): the entry whose byte is there}) + checked = [] # ((entry, module, writes) of each file that can be applied on its own) + other_build = set() # (the entries refused only for being another build's: they hold no other file back) for rel, path in files: entry = {"state": "refused", "path": rel, "fnv": "0" * 16, "size": 0, "module": "", "changed": 0, "why": ""} entries.append(entry) @@ -350,7 +362,7 @@ def apply(exefs, mods_root, say=print): named, writes = read_patch(rel, data) module = next((m for m in modules.values() if same_build(named, m.build_id)), None) if module is None: - raise Refused("it is for build %s, which is not this game's code (%s)" % (named.lower()[:40], game)) + raise OtherBuild("it is for build %s, which is not this game's code (%s)" % (named.lower()[:40], game)) try: module.load() except (OSError, ValueError) as e: @@ -359,6 +371,23 @@ def apply(exefs, mods_root, say=print): except Refused as e: entry["why"] = str(e) say("code mods: %s is not applied: %s" % (rel, e)) + if isinstance(e, OtherBuild): + other_build.add(id(entry)) + continue + checked.append((entry, module, writes)) + # ((Triforce, 11-25) a mod's patch files go in together or not at all: a player's "Classic Projectile Targeting" had + # one file for main, built in, that branches into the code its other file puts in subsdk0's code cave, refused; the + # game then branched to nothing and crashed at its start, "FATAL: branch to a non-function", at every build) + refused_in, ok = {}, {id(entry) for entry, _, _ in checked} + for entry in entries: + if id(entry) not in ok and id(entry) not in other_build: + refused_in.setdefault(mod_of(entry["path"]), entry["path"]) + for entry, module, writes in checked: + rel = entry["path"] + first = refused_in.get(mod_of(rel)) + if first is not None: + entry["why"] = "another patch of the same mod is not applied (%s): a mod's patches go in together or not at all" % first + say("code mods: %s is not applied: %s" % (rel, entry["why"])) continue entry["state"], entry["module"] = "applied", module.name over = {} diff --git a/tests/test_code_mods.py b/tests/test_code_mods.py index 892e71d..94caba2 100644 --- a/tests/test_code_mods.py +++ b/tests/test_code_mods.py @@ -410,6 +410,37 @@ class Apply(Folder): self.apply() self.assertEqual(self.image()[0x10:0x12], b"\xaa\xbb") + def test_a_mod_goes_in_whole_or_not_at_all(self): + # (11-25: a mod's file built in branched into the code cave its other file was refused for, and the game crashed) + before = (self.exefs / "main").read_bytes() + self.patch("cave/exefs/a.pchtxt", "@nsobid-%s\n@enabled\n00000110 AAAA\n" % MAIN_HEX) + self.patch("cave/exefs/%s.ips" % MAIN_HEX, ips([(0x100 + 0x400, b"\x1f\x20\x03\xd5")])) # (the code cave) + entries = self.apply() + self.assertEqual([e["state"] for e in entries], ["refused", "refused"]) + self.assertEqual((self.exefs / "main").read_bytes(), before) + cave = "cave/exefs/%s.ips" % MAIN_HEX + refused = next(e for e in entries if e["path"] == "cave/exefs/a.pchtxt") + self.assertIn("another patch of the same mod is not applied (%s)" % cave, refused["why"]) + self.assertTrue(any(line.startswith("code mods: cave/exefs/a.pchtxt is not applied: another patch") for line in self.said), + self.said) + # (another mod beside it is applied as before) + self.patch("other/exefs/b.pchtxt", "@nsobid-%s\n@enabled\n00000120 BB\n" % MAIN_HEX) + self.fresh() + entries = self.apply() + self.assertEqual({e["path"]: e["state"] for e in entries}, + {"cave/exefs/a.pchtxt": "refused", cave: "refused", "other/exefs/b.pchtxt": "applied"}) + self.assertNotEqual(self.image()[0x10:0x12], b"\xaa\xaa") # (the refused mod's bytes are not in) + self.assertEqual(self.image()[0x20], 0xBB) + + def test_a_patch_for_another_build_holds_nothing_back(self): + # (mods carry one patch per game version: the others' refusal leaves this build's file applied) + self.patch("multi/exefs/a.pchtxt", "@nsobid-%s\n@enabled\n00000110 AAAA\n" % MAIN_HEX) + self.patch("multi/exefs/0123456789abcdef0123456789abcdef01234567.ips", ips([(0x100 + 0x10, b"\x01")])) + entries = self.apply() + self.assertEqual({e["path"].split("/")[-1]: e["state"] for e in entries}, + {"a.pchtxt": "applied", "0123456789abcdef0123456789abcdef01234567.ips": "refused"}) + self.assertEqual(self.image()[0x10:0x12], b"\xaa\xaa") + def test_a_patch_that_changes_nothing_leaves_the_file(self): before = (self.exefs / "main").read_bytes() self.patch("same/exefs/%s.ips" % MAIN_HEX, ips([(0x100 + 0x40, b"\x11\x11"), (0x100 + 0x1040, (3, 0x12))])) diff --git a/tests/test_evil_hd_foliage.py b/tests/test_evil_hd_foliage.py index 7c952f4..3f7d6be 100644 --- a/tests/test_evil_hd_foliage.py +++ b/tests/test_evil_hd_foliage.py @@ -78,9 +78,12 @@ int main(void) { evil_hd_foliage(1.0f, out); CHECK(same(out, game, 1.0f)); evil_hd_foliage(2.5f, out); - CHECK(same(out, game, 2.5f) && out[0] == 100.0f && out[1] == 150.0f && out[5] == 337.5f); + CHECK(out[0] == 100.0f && out[1] == 150.0f && out[5] == 337.5f && out[4] == 100.0f && out[7] == 112.5f); + CHECK(out[2] == 75.0f && out[3] == 70.0f); /* (the ornaments and shoot leaves kept to 75 and 70 m: 11-25 flicker) */ evil_hd_foliage(4.0f, out); - CHECK(same(out, game, 4.0f)); + CHECK(out[0] == 160.0f && out[1] == 240.0f && out[5] == 540.0f && out[2] == 75.0f && out[3] == 70.0f); + evil_hd_foliage(2.0f, out); + CHECK(out[2] == 70.0f && out[3] == 60.0f); /* (under their most: the factor's own) */ /* which bytes are known: the game's, or what a write of this left (a factor from 1 to 4) */ CHECK(evil_hd_foliage_known(game)); for (float f = 1.0f; f <= 4.0f; f += 0.25f) { diff --git a/tests/test_prepare_threads.cpp b/tests/test_prepare_threads.cpp index 56b41c3..82fe00d 100644 --- a/tests/test_prepare_threads.cpp +++ b/tests/test_prepare_threads.cpp @@ -21,10 +21,11 @@ int main() { // (what it was: half the processors, 1 to 32) expect(half(1) == 1 && half(2) == 1 && half(12) == 6 && half(24) == 12 && half(64) == 32 && half(128) == 32, "half, as before"); // (a player's PC: normal priority, RAM free at the start) - expect(count(12, 24 * GB, false, 0) == 12, "12 processors, 24 GB free: all 12"); - expect(count(24, 26 * GB, false, 0) == 24, "24 processors, 26 GB free: all 24"); + expect(count(12, 24 * GB, false, 0) == 9, "12 processors, 24 GB free: three quarters, 9"); + expect(count(24, 26 * GB, false, 0) == 18, "24 processors, 26 GB free: three quarters, 18"); + expect(count(8, 16 * GB, false, 0) == 6 && count(4, 16 * GB, false, 0) == 3, "8 and 4 processors: 6 and 3"); expect(count(1, 8 * GB, false, 0) == 1 && count(2, 8 * GB, false, 0) == 2, "one and two processors"); - expect(count(128, 256 * GB, false, 0) == 64, "64 at most"); + expect(count(128, 256 * GB, false, 0) == 64 && count(64, 256 * GB, false, 0) == 48, "64 at most; 64 processors: 48"); // (1 GB free a worker past half) expect(count(24, 16 * GB, false, 0) == 16, "24 processors, 16 GB free: 16"); expect(count(32, 11 * GB, false, 0) == 16, "32 processors, 11 GB free: half, 16, not fewer"); @@ -46,16 +47,16 @@ int main() { expect(count(24, 2 * GB, true, 20) == 20, "the switch decides, whatever the RAM and the priority"); expect(count(4, 64 * GB, false, 1) == 1, "the switch: one"); expect(count(8, 64 * GB, false, 1000) == 64, "the switch: 64 at most"); - expect(count(24, 26 * GB, false, -3) == 24 && count(24, 26 * GB, false, 0) == 24, "the switch not set, or not a count: the rule"); + expect(count(24, 26 * GB, false, -3) == 18 && count(24, 26 * GB, false, 0) == 18, "the switch not set, or not a count: the rule"); // (the translation pass on AMD's Windows driver for RDNA 1 and 2: kAmdOlderMost at most, fewer where count gives fewer; // other drivers and the switch: count's number) using prepare_threads::translate; const unsigned most = prepare_threads::kAmdOlderMost; expect(translate(count(24, 26 * GB, false, 0), true, false) == most, "AMD's older driver, 24 processors: the cap"); expect(translate(count(24, 64 * GB, true, 0), true, false) == most, "AMD's older driver, above normal: the cap over half"); - expect(translate(count(4, 64 * GB, false, 0), true, false) == 4 && translate(2, true, false) == 2, "AMD's older driver, few processors: count's"); + expect(translate(count(4, 64 * GB, false, 0), true, false) == count(4, 64 * GB, false, 0) && translate(2, true, false) == 2, "AMD's older driver, few processors: count's"); expect(translate(count(24, 26 * GB, false, 20), true, true) == 20, "AMD's older driver: the switch still decides"); - expect(translate(count(24, 26 * GB, false, 0), false, false) == 24, "other drivers: count's"); + expect(translate(count(24, 26 * GB, false, 0), false, false) == 18, "other drivers: count's"); // ((Triforce) the process heap's signature: the segment heap's, the NT heap's, anything else not known) expect(prepare_threads::segment_heap(0xDDEEDDEEu) && !prepare_threads::segment_heap(0xFFEEFFEEu) && !prepare_threads::segment_heap(0), "segment_heap: the segment heap's signature only");