fix(loader,victory): non-atomic Clwb patching without FlushInstructionCache, LoaderLock unwind deadlock, and profiler handle/underflow bugs #321

Closed
opened 2026-12-02 09:15:39 +00:00 by github-bot · 0 comments
Owner

@⁠RUIZ-Enrique-25002136 on GitHub · 2026-12-02 09:14 UTC · original

Summary

Three concurrency, resource-lifetime, and live-patching issues exist in crates/victory-loader and apps/victory:

  1. Non-atomic live code patching without FlushInstructionCache (victory-loader): ConsoleOnly::Clwb overwrites live executable bytes byte-by-byte with .fill(0x90) and omits FlushInstructionCache.
  2. Deadlock on unwind & partial-failure leak (apps/victory): LoaderLock::hold leaves the re-entrant lock held forever if f() panics, and LateDlls::load leaks mapped DLLs / stale registry entries if bind_imports fails mid-loop.
  3. Thread handle leak & u64 underflow in profiler (victory-loader): profile::Thread lacks Drop (leaking handles on I/O errors in write()), and cpu() ignores GetThreadTimes failure, risking u64 underflow in choose() and write().

Evidence (file:line & Code Proof)

1. Non-Atomic ConsoleOnly::Clwb Patching Without FlushInstructionCache

  • crates/victory-loader/src/console_insn.rs:425-438 (emulate):
    Unlike Monitorx/Mwaitx and ClzeroLoop (which use patch(), executing atomic cmpxchg16b + FlushInstructionCache), ConsoleOnly::Clwb executes:
    if VirtualProtect(rip as *const _, len, PAGE_EXECUTE_READWRITE, &mut old) != 0 {
        std::slice::from_raw_parts_mut(rip as *mut u8, len).fill(0x90);
        VirtualProtect(rip as *const _, len, old, &mut old);
        patches.insert(rip, vec![0x90; len]);
    }
    
    Other threads executing rip concurrently can fetch a torn instruction (partial 0x90 prefix + tail bytes of the multi-byte clwb instruction) or stale I-cache bytes.

2. LoaderLock::hold Unwind Deadlock & LateDlls::load Partial-Failure Leak

  • apps/victory/src/run.rs:769-787 (LoaderLock::hold):
    owner.1 += 1 is incremented before let result = f(); and decremented/notified only after f() returns normally (no RAII drop guard). If f() unwinds, every subsequent dynamic LoadLibrary deadlocks forever waiting on self.free.
  • apps/victory/src/run.rs:715-726 (LateDlls::load):
    If dll.bind_imports(&resolver, self.policy)? fails on any DLL in new, ? returns early before mapped.extend(...) and bypasses the rollback loop (744-752), leaking Windows LoadLibraryExW modules, threads::IMAGES registrations, and IMAGE_PATHS entries.

3. Profiler Win32 Handle Leak & u64 Underflow

  • crates/victory-loader/src/profile.rs:51-59 (cpu), 134-138 (choose), 150-162 (write):
    Thread has no Drop impl; CloseHandle(t.handle) only runs inside write() after File::create(file)? and earlier writeln! calls, so any I/O error leaks remaining open thread handles. Furthermore, cpu() ignores the BOOL return value of GetThreadTimes (returning 0 on failure), and t.now - t.last (136) / t.now - t.first (157) use unchecked subtraction (panicking in debug or wrapping in release).

AI-Ready Fix Specification

  1. crates/victory-loader/src/console_insn.rs: Route ConsoleOnly::Clwb through patch() (atomic cmpxchg16b + FlushInstructionCache), falling back to emulation without patching if the instruction crosses a 16-byte boundary or cmpxchg16b is unsupported.
  2. apps/victory/src/run.rs:
    • Replace manual unlock in LoaderLock::hold with an RAII drop guard that decrements owner.1, clears owner.0 at 0, and calls self.free.notify_one().
    • In LateDlls::load, roll back every already-loaded DLL in new (forget_image + dll.unload(), and clean up IMAGE_PATHS if needed) when bind_imports fails.
  3. crates/victory-loader/src/profile.rs:
    • Implement Drop for Thread to call CloseHandle(self.handle) when non-null (and remove manual CloseHandle from write()).
    • Check GetThreadTimes(...) != 0 in cpu() (returning Option<u64>) and use saturating_sub for t.now.saturating_sub(t.last) and t.now.saturating_sub(t.first).
  4. Verify with cargo clippy --workspace --all-targets --locked -- -D warnings and cargo test --workspace --exclude victory-gpu --exclude victory-shader --locked on Windows CI.
**@⁠RUIZ-Enrique-25002136** on GitHub · 2026-12-02 09:14 UTC · [original](https://github.com/Androtim/MiniVI/issues/321) ## Summary Three concurrency, resource-lifetime, and live-patching issues exist in `crates/victory-loader` and `apps/victory`: 1. **Non-atomic live code patching without `FlushInstructionCache` (`victory-loader`):** `ConsoleOnly::Clwb` overwrites live executable bytes byte-by-byte with `.fill(0x90)` and omits `FlushInstructionCache`. 2. **Deadlock on unwind & partial-failure leak (`apps/victory`):** `LoaderLock::hold` leaves the re-entrant lock held forever if `f()` panics, and `LateDlls::load` leaks mapped DLLs / stale registry entries if `bind_imports` fails mid-loop. 3. **Thread handle leak & `u64` underflow in profiler (`victory-loader`):** `profile::Thread` lacks `Drop` (leaking handles on I/O errors in `write()`), and `cpu()` ignores `GetThreadTimes` failure, risking `u64` underflow in `choose()` and `write()`. ## Evidence (`file:line` & Code Proof) ### 1. Non-Atomic `ConsoleOnly::Clwb` Patching Without `FlushInstructionCache` - **`crates/victory-loader/src/console_insn.rs:425-438` (`emulate`):** Unlike `Monitorx`/`Mwaitx` and `ClzeroLoop` (which use `patch()`, executing atomic `cmpxchg16b` + `FlushInstructionCache`), `ConsoleOnly::Clwb` executes: ```rust if VirtualProtect(rip as *const _, len, PAGE_EXECUTE_READWRITE, &mut old) != 0 { std::slice::from_raw_parts_mut(rip as *mut u8, len).fill(0x90); VirtualProtect(rip as *const _, len, old, &mut old); patches.insert(rip, vec![0x90; len]); } ``` Other threads executing `rip` concurrently can fetch a torn instruction (partial `0x90` prefix + tail bytes of the multi-byte `clwb` instruction) or stale I-cache bytes. ### 2. `LoaderLock::hold` Unwind Deadlock & `LateDlls::load` Partial-Failure Leak - **`apps/victory/src/run.rs:769-787` (`LoaderLock::hold`):** `owner.1 += 1` is incremented before `let result = f();` and decremented/notified only after `f()` returns normally (no RAII drop guard). If `f()` unwinds, every subsequent dynamic `LoadLibrary` deadlocks forever waiting on `self.free`. - **`apps/victory/src/run.rs:715-726` (`LateDlls::load`):** If `dll.bind_imports(&resolver, self.policy)?` fails on any DLL in `new`, `?` returns early before `mapped.extend(...)` and bypasses the rollback loop (`744-752`), leaking Windows `LoadLibraryExW` modules, `threads::IMAGES` registrations, and `IMAGE_PATHS` entries. ### 3. Profiler Win32 Handle Leak & `u64` Underflow - **`crates/victory-loader/src/profile.rs:51-59` (`cpu`), `134-138` (`choose`), `150-162` (`write`):** `Thread` has no `Drop` impl; `CloseHandle(t.handle)` only runs inside `write()` after `File::create(file)?` and earlier `writeln!` calls, so any I/O error leaks remaining open thread handles. Furthermore, `cpu()` ignores the `BOOL` return value of `GetThreadTimes` (returning `0` on failure), and `t.now - t.last` (`136`) / `t.now - t.first` (`157`) use unchecked subtraction (panicking in debug or wrapping in release). ## AI-Ready Fix Specification 1. **`crates/victory-loader/src/console_insn.rs`:** Route `ConsoleOnly::Clwb` through `patch()` (atomic `cmpxchg16b` + `FlushInstructionCache`), falling back to emulation without patching if the instruction crosses a 16-byte boundary or `cmpxchg16b` is unsupported. 2. **`apps/victory/src/run.rs`:** - Replace manual unlock in `LoaderLock::hold` with an RAII drop guard that decrements `owner.1`, clears `owner.0` at 0, and calls `self.free.notify_one()`. - In `LateDlls::load`, roll back every already-loaded DLL in `new` (`forget_image` + `dll.unload()`, and clean up `IMAGE_PATHS` if needed) when `bind_imports` fails. 3. **`crates/victory-loader/src/profile.rs`:** - Implement `Drop for Thread` to call `CloseHandle(self.handle)` when non-null (and remove manual `CloseHandle` from `write()`). - Check `GetThreadTimes(...) != 0` in `cpu()` (returning `Option<u64>`) and use `saturating_sub` for `t.now.saturating_sub(t.last)` and `t.now.saturating_sub(t.first)`. 4. Verify with `cargo clippy --workspace --all-targets --locked -- -D warnings` and `cargo test --workspace --exclude victory-gpu --exclude victory-shader --locked` on Windows CI.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-12-02 09:15:39 +00:00
This discussion has been locked. Commenting is limited to contributors.
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
github/Androtim--MiniVI#321
No description provided.