fix(mods): a hook entered with BL that goes back with B returns, where that is safe #3166
No reviewers
Labels
No labels
area/accessibility
area/audio
area/input
area/install
area/menu
area/mods
area/renderer
area/saves
area/tooling
area/upscaling
beanstalk: approved
beanstalk: failed
beanstalk: needs approval
beanstalk: running
beanstalk: tested
ci: approved
good first issue
gpu/amd
gpu/igpu
gpu/intel
gpu/nvidia
help wanted
kind
bug
kind
chore
kind
docs
kind
feature
kind
performance
kind
question
needs measurements
platform/linux
platform/macos
platform/steam-deck
platform/windows
preview
priority
critical
priority
high
priority
low
regression
risk
high
risk
low
risk
medium
status
blocked
status
confirmed
status
duplicate
status
invalid
status
needs-info
status
wontfix
ci: approved
No milestone
No project
No assignees
3 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
MagicBeanDev/Longshot!3166
Loading…
Reference in a new issue
No description provided.
Delete branch "snaildev99/Longshot:mods/exefs-bl-return"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Summary
Many code mods hook the game by writing
bl my_hookover one of its instructions, and the hook jumps back withb <the instruction after the call>because its own calls have used up the return register. On the console that jumpis a return. In a recompiled build it is not: the lift makes
bla call and the jump a branch inside the hook, so thehook runs the rest of the game's function (its epilogue) inside the call, then returns into it, and the game runs that
rest a second time with its stack frame gone. It crashes a few calls up (Character Select v0.1.2 did, on the old
builder).
With this change the build writes such a jump back as
RETbefore the code is lifted, when that is exactly the samething: when nothing but that one call can reach the hook's code (no other branch or call, no instruction above falling
in, no unwind start, function symbol, relocated pointer or ADR / ADRP+ADD address, in any switch state). Otherwise it
leaves the jump and says why in the build log and the file's note. The pass runs after the switches are planned, over
the files the build takes (a mod that is off and no switch takes no part). The
RETgoes into the writes of eachfile that writes the branch, in the image and in the switch table: two mods with the same hook, each behind its own
switch, both get it, so the hook returns with either on. A hook that only jumps on through a register (a trampoline
into a code module's hook, or a tail call) has no way back and stays quiet.
How to see it on
main:the_lifted_hook_leaves_the_callers_epilogue_in_the_caller(build-driver'sdrivertest)lifts a synthetic game with such a hook; on
mainthe hook's lifted function holds the caller's epilogue.This is the Rust port of #960. It is stacked on #3165 (the overlap pass runs first and hands this pass the
final writes), so its diff holds that PR's commit (
d30a27407) until it merges. Review the last two commits: the test,then the fix.
Read first:
builder/crates/game-files/src/returns.rs(make_returns,Hook::walk,Code::writers), then wherepatches::collectcalls it.Testing
Tested: Windows 11 Pro, RTX 3090, NVIDIA 610.88, in the game, built by
longshot-builder play --profilewiththis PR and the other mod compatibility ports merged, adult Link in Kakariko, with four code mods (HUD of Time, Rupee
Counter, Ragdoll Button, Edge-to-Edge). Their hooks are trampolines (
blinto a stub that jumps on withbr). Thefirst build said each "has an indirect jump: left as it is, it may not run as on the console"; that was wrong, a
trampoline has no way back, and the fix's last change keeps them quiet (test
a_trampoline_that_jumps_on_through_a_register_stays_quiet). After it the build says nothing about returns and themods work in the game. None of these mods has a hook that goes back with
b, so no return was made in the game.After the rebase and the review's fixes, here @
ad9338505, built with the other ports merged (929bf025a), the sameprofile again: the build says nothing about returns, and the mods work in Kakariko.
Game-free: the 20 tests of
returns_tests.rsand the two driver tests, below. After the review two cases were addedand fixed: a later mod that is off and built out over the hook's call (
a_later_mod_left_out_of_the_build_hides_no_call:the analysis took it in, missed the call and left the B), and two mods with the same hook
(
two_mods_with_the_same_hook_each_return, and the driver'stwo_mods_with_the_same_hook_return_in_every_switch_state, which lifts each switch state: with only the earliermod on, its hook still ran the caller's RET at +18). Each fails on the test commit and passes now, and each fails
again with its fix's key lines undone (the pass back before the switch plan, over every file that applies; only
the last writer as owner, the earlier head's rule).
Rebased onto #3165 @
d30a27407(main@3a0f7d8f7), here @ad9338505:cargo test -p game-files93 passed (89 in the library, 4 in its other targets);cargo test -p build-driver --test driver11 passed;clippy -p game-files -p build-driver --no-deps --all-targets -- -D warningsclean (without--no-depsit stops onmain's own errors:host-sys's "large array defined asconst" and an unused import in
build-core'ssandbox_windows.rs); rustfmt clean;tests/test_doc_anchors.pypasses.
mise run test, run locally while CI's run waits for approval (Windows 11,tests/run_all.py --strict, 12 checks atonce), here @
ad9338505and onmain@3a0f7d8f7: 847 passed, 12 failed, 52 skipped here; 845 passed, 14 failed, 52skipped on
main. All 12 also fail onmain: test_dlssg, test_fsr4_tune, test_lifter, test_no_game_title,test_no_map_reload, test_present_acquire_ahead, test_present_geometry_trace, test_present_held_image,
test_present_image_free, test_sync_watch_event, test_turf_budget, test_ui_renderer.
Still to test:
b(Character Select v0.1.2's patch), expecting the log tosay the branch was made a return and the mod's menu to work without a crash (by hand)
main(measurement, the review's L4)Measurements
Verdict: Fixed in the lift: the tests that fail without the fix pass, and the other cases keep their branch with a
note. Nothing changes per frame; the pass runs in the build only when a patch writes a
blinto code it also writes.Setup:
cargo testofgame-filesandbuild-driveron Windows 11; the before side is the test commit(
5df5a805e), which is #3165's code (d30a27407, onmain@3a0f7d8f7) with the tests.Baseline: the test commit, not
main, because this PR stacks on #3165 (its overlap pass makes the final writes thefix reads); the test commit is that code with this PR's tests and without the fix.
5df5a805ead9338505cargo test -p game-files returns_testscargo test -p build-driver --test driver the_lifted_hook_leaves_the_callers_epilogue_in_the_callercargo test -p build-driver --test driver two_mods_with_the_same_hook_return_in_every_switch_statecargo test -p game-filesRisks
mainknows. An indirect jump table the analysis doesn'tsee, or an entry only the lift adds, could still reach a routine made a return. Then the mod's hook would return
early where the console would have run on.
writer; another file that could change one of them in some switch state still keeps the B.
Checklist
Ready for review
main; the title is a Conventional Commit.mise run testpasses (any failure that also fails onmainis named). (run locally, Testing names them; CI's run waits for approval)main, or Measurements says why there is nothing to measure.third_party/untouched; nothing GPL-incompatible.When it applies
mainand passes here.tests/that reads changed source is updated, not weakened. (tests/test_parity_gates.pyreadsloader/mod.rs's log lines, which this keeps: it passes unchanged)Assisted-by:/Co-Authored-By:trailers.Ready to merge
main, measured again or a comment says why the numbers still hold.🤖 Generated with Claude Code
Tested in game: Windows 11 Pro, RTX 3090, NVIDIA 610.88, adult Link in Kakariko, built by longshot-builder play --profile with the mod compatibility ports merged, with four code mods (HUD of Time, Rupee Counter, Ragdoll Button, Edge-to-Edge) whose hooks are trampolines (bl into a stub that jumps on with br). The first build wrongly noted each as having an indirect jump; with this head the build says nothing about returns and the mods work in the game. None of these mods has a hook that goes back with b, so no return was made in the game: that case is the driver test.
mise run test, run locally while CI's run waits for approval: 824 passed, 21 failed, 51 skipped here @
07621fa32; 18 of the 21 also fail on main @f577a1aea(named in Testing), the other three timed out under load and pass here run alone (--exact). tests/test_parity_gates.py, which reads loader/mod.rs, passes unchanged. Boxes ticked.WIP: fix(mods): a hook entered with BL that goes back with B returns, where that is safeto fix(mods): a hook entered with BL that goes back with B returns, where that is safeRecommendation: Request changes. The return pass can miss an active hook when an overlapping mod is off, and it can leave an identical hook unfixed when only one of two switches is enabled. Both cases retain the crash this change is intended to prevent.
The builder detects some BL hooks that branch back to their callers and replaces safe branches with returns. It also reports overlapping patch writes and changes which overlapping mods require a rebuild to switch.
Blocking (3): must change before merging.
builder/crates/game-files/src/returns.rs:43: The analysis includes off files that the overlap pass will later make build-time-only, so it can analyze an image different from the one actually built. (more on the line) Do: Plan or otherwise identify build-time-only off files before constructing the analysis image, and analyze the actual built image plus the switch states that can really occur. Add a test with an enabled hook and a later disabled conflicting patch.builder/crates/game-files/src/returns.rs:400: Only the last writer receives the return even when another independently switched file supplies the same hook. (more on the line) Do: Handle every reachable switch state that supplies the branch, for example by safely rewriting each eligible writer or making the overlapping hooks switch together. Add a test that lifts the earlier-only state of two identical hooks.@​fixor@​rebasetry first). (for the author)Testing before merging (2) (runs on the systems it can change; it doesn't hold the recommendation)
builder/crates/game-files/src/returns.rs:328: The target behavior has not yet been exercised with a real hook that branches back. (more on the line) Do: Build and play with a mod containing a BL hook that returns with B, checking the conversion note and the affected feature on Windows and Linux.builder/crates/game-files/src/patches.rs:553: The build cost of scanning code and patch alternatives has not been measured. (more on the line) Do: Measure clean and incremental build time and output size against the base with representative code mods, as the builder standards require.@fixcan do L1 and L2.Checks: Still running: 11 checks.
More: does it help, other systems, switches, what was read
Does it help: Unproven in the game for the target hook: the reported synthetic driver test failed before and passed after, but the in-game run used only trampolines and made no returns. Build-time cost has not been measured.
Other systems: The pass affects patched code and switch variants on Windows and Linux, regardless of GPU. The reported Windows game run covers trampoline mods, but not an actual rewritten return; Linux and the stated target mod have not been run. The overlap pass also changes restart-versus-rebuild behavior for conflicting mods.
Switches: No environment variables or developer switches added. Mods that write different values to a shared byte now require a rebuild to switch; nonconflicting mods retain restart switches. Identical overlapping hooks need additional handling for independent switch states.
Reviewed:
07621fa328againstf577a1aeab: Read the repository rules, PR template, commit log, return analysis, return tests, switch planning, patch collection and application paths, and changed diffs. Skimmed the larger loader and driver files, documentation changes, lockfile, and related lift discovery references; did not read every changed code file in full. docs/review-checklist.md was absent.; nothing run (a code review).Checked and fine:
Testing: Read-only review; no builds, tests, scripts, or game runs were executed. The author reports 18 return tests and the driver test passing on Windows, and CI is still running.
Overlaps and merge order: Stacked on Longshot#3165; that overlap pass should merge first.
Automated code review by BeanBot (gpt-6.1-terra), asked for by BeanBot, as snaildev99 took it out of WIP. Nothing was run; a maintainer decides.
@ -513,0 +550,4 @@refuse(&mut out)?;let diagnostics: Vec<_> = out.iter().map(|f| f.note.clone()).collect();let fixed = overlaps(&m, &mut out, written, log);// (the return pass reads the final writes: after the overlaps put the lower files' bytes back, which can make a fileL4 (should fix): The build cost of scanning code and patch alternatives has not been measured.
When: A build with code patches now scans the code range and analyzes alternate writes; players wait for this work during the build.
Do: Measure clean and incremental build time and output size against the base with representative code mods, as the builder standards require.
@ -0,0 +40,4 @@let end = main.segments[1].offset.min(main.image.len() as u64) & !3;let range = main.segments[0].offset..end;let mut edits = BTreeMap::<u64, Vec<Edit>>::new();for (i, file) in files.iter().enumerate().filter(|(_, f)| f.kind.applies()) {L1 (blocking): The analysis includes off files that the overlap pass will later make build-time-only, so it can analyze an image different from the one actually built.
When: An enabled mod supplies a BL hook and its branch back, while a later disabled mod writes a different instruction over the BL. The overlap pass fixes both mods at build time, but Code::new still overlays the disabled file; the call is not discovered, then switch planning drops that file. The enabled hook is built with its original branch and can execute the caller's epilogue twice.
Do: Plan or otherwise identify build-time-only off files before constructing the analysis image, and analyze the actual built image plus the switch states that can really occur. Add a test with an enabled hook and a later disabled conflicting patch.
@ -0,0 +325,4 @@}/// Write each safe return into its last writer, before the image, switch table and lift take those bytes.pub(crate) fn make_returns(main: &Nso, files: &mut [PatchFile], log: &mut dyn FnMut(String)) -> Result<()> {L3 (should fix): The target behavior has not yet been exercised with a real hook that branches back.
When: The reported game run used trampoline hooks, so it never executed a return produced by this pass.
Do: Build and play with a mod containing a BL hook that returns with B, checking the conversion note and the affected feature on Windows and Linux.
@ -0,0 +397,4 @@} else {let start = file.writes.partition_point(|&(o, _)| o < at);let end = file.writes.partition_point(|&(o, _)| o < at + 4);file.writes.splice(start..end, (at..at + 4).zip(RET.to_le_bytes()));L2 (blocking): Only the last writer receives the return even when another independently switched file supplies the same hook.
When: Two mods write identical copies of a BL hook and its branch back. Their bytes do not conflict, so both retain switches; the all-on analysis assigns the exit to the later mod and rewrites only that file. With the earlier mod on and the later one off, the earlier file still supplies the original branch, so its hook can run the caller's continuation twice.
Do: Handle every reachable switch state that supplies the branch, for example by safely rewriting each eligible writer or making the overlapping hooks switch together. Add a test that lifts the earlier-only state of two identical hooks.
07621fa328ad93385051Rebased onto #3165's rebased commit (main @
3a0f7d8f7) for the base conflict; here @ad9338505. Tested (the game again on this head),mise run test(against main @3a0f7d8f7: every failure also fails on main) and Measurements are updated. Answers to the review below.L1 (the analysis sees off files the overlap pass builds out): fixed in
ad9338505.collectnow plans the switches first and runs the return pass after, over the files the build takes (PatchFile::takes: on, or behind a switch). A mod that is off and no switch, such as one the overlap pass builds in or out, is left out of the analysis as it is left out of the image, so it can no longer hide the hook's call. The RETs still reach the switch table, which is made from the files' final writes aftercollect. New testa_later_mod_left_out_of_the_build_hides_no_call(in5df5a805e): the hook's mod on, a later mod off that writes another instruction over the call. Before the fix the image kept the B; now it gets the RET and the hook file's note says so.L2 (only the last writer gets the return): fixed in
ad9338505. Every file that writes the branch by itself now gets the RET where the proof holds with that file present (Code::writers): the last writer as before, and each earlier one whose RET no later file's partial bytes could mix with. The proof's same-mod check now asks that the RET file's mod writes the call and the routine, rather than being their last writer; the check of the other files' alternatives is unchanged and still refuses any state in which another file changes them. New tests (in5df5a805e):two_mods_with_the_same_hook_each_return(each mod alone and both: RET in the image and in both switches' table rows, both notes) and build-driver'stwo_mods_with_the_same_hook_return_in_every_switch_state, which lifts the two identical hooks and checks that the version with only the earlier switch on, as well as the later-only version and the all-on function, ends at the hook's RET. Both fail on the test commit, and again with the owner put back to the last writer alone (the earlier head's rule): the unit test at "first on", the driver test at "first on alone", whose lifted hook still runs on to the caller's RET at +18.L3 (a real hook that branches back, in the game): still to run: none of the mods on this PC has such a hook. It stays in Still to test (Character Select v0.1.2's patch, by hand). On this head, built with the other ports merged, the four code mods' trampolines still build with no word about returns, and the mods work in the game.
L4 (build cost): still to measure: the build time and size against
main(Still to test).L5 (conflicts with
main): rebased onto #3165's rebased commit (onmain@3a0f7d8f7). One conflict, indocs/dev/reference/mods.md: #3165's sentence on overlap notes (now with its note bound) and this PR's paragraph on returns, both kept.Merge note for #3166 and #3216: each passes alone on
main, but whichever merges second needs a two-line test fix. #3216 giveswrite_imageinbuilder/crates/build-driver/tests/driver.rsa second argument (the writes), and #3166's two return tests call it with one:write_image(&d, &[]). With all the mod compatibility ports merged together, that is the only change it needed there.@review
Recommendation: Approve. The code is ready: only testing is left. The two reported code defects are fixed, but the target behavior still needs a real in-game hook test and the build cost remains unmeasured. The PR is also stacked on #3165. Recommend approval; not approved on the forge.
The builder turns a safe branch back from a mod hook into a return, preventing the lifted caller’s continuation from running twice. The pass adds build-time analysis and can increase switch-table writes.
Testing before merging (2) (runs on the systems it can change; it doesn't hold the recommendation)
builder/crates/game-files/src/returns.rs:328: The target behavior has not yet been exercised with a real hook that branches back. When: The reported game run used trampoline hooks, so it never executed a return produced by this pass. Do: Build and play with a mod containing a BL hook that returns with B, checking the conversion note and the affected feature on Windows and Linux.builder/crates/game-files/src/patches.rs:553: The build cost of scanning code and patch alternatives has not been measured. When: A build with code patches now scans the code range and analyzes alternate writes; players wait for this work during the build. Do: Measure clean and incremental build time and output size against the base with representative code mods, as the builder standards require.Since the last review (on
07621fa328)Resolved: L1 (The analysis includes off files that the overlap pass will later make build-time-only, so…); L2 (Only the last writer receives the return even when another independently switched file sup…); L5 (It conflicts with its base branch: bring it up to date (
@​fixor@​rebasetry first).)Still open: L3 (The target behavior has not yet been exercised with a real hook that branches back.); L4 (The build cost of scanning code and patch alternatives has not been measured.)
Checks: Still running: 11 checks.
More: does it help, other systems, switches, what was read
Does it help: Unproven in the game for the target hook: the recorded synthetic tests pass after the fix, while the tested in-game mods use trampolines and did not trigger a return. Build time and size have not been measured.
Other systems: The pass affects patch collection, switch states and lifted game code on Windows and Linux. The recorded game run covers Windows and trampoline hooks; a real branch-back hook remains untested.
Switches: No player-facing switch added, changed or removed. Existing mod switches now receive the return in each qualifying file.
Reviewed:
ad93385051against3a0f7d8f7f: Read AGENTS.md, CONTRIBUTING.md, the pull request template, returns.rs and switches.rs; inspected the supplied range-diff and review context. The full base diff and all changed files were not read in full; docs/review-checklist.md was absent.; nothing run (a code review).Checked and fine:
Testing: No commands that build or run tests were executed. The author reports 20 return tests and both driver tests passing, plus an in-game Windows run with trampoline mods; CI is still running.
Overlaps and merge order: Stacked on #3165, which should merge first. #3216 also changes the driver test helper; whichever merges second needs its return-test calls updated.
Automated code review by BeanBot (gpt-6.1-terra), asked for by HumanBean. Nothing was run; a maintainer decides.
@rebase
I rebased this pull request onto
main(3145d9d48f): the new head isbdcac619bf.Nothing was built or run: read the resolution before merging.
Automated rebase by BeanBot (gpt-6.1-terra), asked for by HumanBean. Nothing was run; a maintainer decides.
ad93385051bdcac619bfRecommendation: Approve. The code is ready: only testing is left. The synthetic tests show the hook return is corrected, but the target behavior has not yet been exercised with a real mod in the game, and build cost remains unmeasured. Recommend approval; not approved on the forge.
The builder converts a safe branch back from a mod hook into a return, preventing the caller’s epilogue from running twice. It adds build-time code and patch-alternative analysis.
Testing before merging (2) (runs on the systems it can change; it doesn't hold the recommendation)
builder/crates/game-files/src/returns.rs:328: The target behavior has not yet been exercised with a real hook that branches back. When: The reported game run used trampoline hooks, so it never executed a return produced by this pass. Do: Build and play with a mod containing a BL hook that returns with B, checking the conversion note and the affected feature on Windows and Linux.builder/crates/game-files/src/patches.rs:553: The build cost of scanning code and patch alternatives has not been measured. When: A build with code patches now scans the code range and analyzes alternate writes; players wait for this work during the build. Do: Measure clean and incremental build time and output size against the base with representative code mods, as the builder standards require.Since the last review (on
ad93385051)Still open: L3 (The target behavior has not yet been exercised with a real hook that branches back.); L4 (The build cost of scanning code and patch alternatives has not been measured.)
Checks: they run again on this head; a failure shows on the pull request.
More: does it help, other systems, switches, what was read
Does it help: Unproven in a real game hook. The reported synthetic tests changed from 18 failures to 20 passes in game-files, and both relevant driver tests passed after failing before the fix; no tested game mod used the branch-back pattern.
Other systems: The pass affects builds on Windows and Linux and switch-dependent patch states. The reported Windows game run exercised trampoline mods, while the target branch-back hook and build cost remain untested.
Switches: No switches added, changed or removed. Existing mod switch states are considered by the analysis.
Reviewed:
bdcac619bfagainst3145d9d48f: Read the repository rules and PR template, the commit list and diff summary, and the return pass and patch integration diff. The remaining changed files, tests and supporting callers were not read in full in this re-check.; nothing run (a code review).Checked and fine:
Testing: No commands that build or run tests were executed. The author reports 93 game-files tests and 11 driver tests passing, plus a Windows game run with trampoline mods; CI has not run on this head.
Overlaps and merge order: #3216 changes the driver test helper signature; whichever PR merges second needs the reported two-line test adjustment. The PR was stacked on #3165, whose commit is no longer in this diff.
Automated code review by BeanBot (gpt-6.1-terra), asked for by BeanBot, after its rebase. Nothing was run; a maintainer decides.