From 6d0ee8708a37006138fd4dab5500219e65e1ed92 Mon Sep 17 00:00:00 2001 From: Ratin Gao Date: Sat, 27 Dec 2025 08:37:09 +0800 Subject: [PATCH] Fix and improve thread program counter adjustment - Match `rbCode` field explicitly - Update each thread at most once - Adjust program counter correctly if it's equals to `rbCodeIn` (x64 only, noticed by @hakujitsu7) See also comments on https://github.com/KNSoft/KNSoft.SlimDetours/commit/35aa2ca8a5a3a6bdd087923754a14ba02ccde9aa --- src/detours.cpp | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/detours.cpp b/src/detours.cpp index 91d840d1..e2b286b5 100644 --- a/src/detours.cpp +++ b/src/detours.cpp @@ -1948,9 +1948,9 @@ typedef ULONG_PTR DETOURS_EIP_TYPE; if (GetThreadContext(t->hThread, &cxt)) { for (o = s_pPendingOperations; o != NULL; o = o->pNext) { if (o->fIsRemove) { - if (cxt.DETOURS_EIP >= (DETOURS_EIP_TYPE)(ULONG_PTR)o->pTrampoline && - cxt.DETOURS_EIP < (DETOURS_EIP_TYPE)((ULONG_PTR)o->pTrampoline - + sizeof(*o->pTrampoline)) + if (cxt.DETOURS_EIP >= (DETOURS_EIP_TYPE)(ULONG_PTR)o->pTrampoline->rbCode && + cxt.DETOURS_EIP < (DETOURS_EIP_TYPE)((ULONG_PTR)o->pTrampoline->rbCode + + RTL_FIELD_SIZE(DETOUR_TRAMPOLINE, rbCode)) ) { cxt.DETOURS_EIP = (DETOURS_EIP_TYPE) @@ -1961,7 +1961,16 @@ typedef ULONG_PTR DETOURS_EIP_TYPE; o->pTrampoline))); SetThreadContext(t->hThread, &cxt); + break; } +#ifdef _AMD64_ + else if (cxt.DETOURS_EIP == (DETOURS_EIP_TYPE)o->pTrampoline->rbCodeIn) + { + cxt.DETOURS_EIP = (DETOURS_EIP_TYPE)o->pbTarget; + SetThreadContext(t->hThread, &cxt); + break; + } +#endif } else { if (cxt.DETOURS_EIP >= (DETOURS_EIP_TYPE)(ULONG_PTR)o->pbTarget && @@ -1977,6 +1986,7 @@ typedef ULONG_PTR DETOURS_EIP_TYPE; o->pbTarget))); SetThreadContext(t->hThread, &cxt); + break; } } }