Skip to content

Commit

Permalink
Thirdparty: fix several bugs in DetourTransactionCommitEx()
Browse files Browse the repository at this point in the history
- Fix incorrect sizeof() usage, see microsoft/Detours#331
- Update thread PC correctly when unhooking, see KNSoft/KNSoft.SlimDetours#2

NOTE: the sizeof() usage has been updated again from the microsoft pull request to the KNSoft one as it was supposed to be used on DETOUR_TRAMPOLINE::rbCode.
  • Loading branch information
Mauler125 committed Feb 19, 2025
1 parent d138c32 commit ebaac90
Showing 1 changed file with 19 additions and 5 deletions.
24 changes: 19 additions & 5 deletions src/thirdparty/detours/src/detours.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1824,6 +1824,7 @@ LONG WINAPI DetourTransactionCommitEx(_Out_opt_ PVOID **pppFailedPointer)
DetourOperation *o;
DetourThread *t;
BOOL freed = FALSE;
BOOL bUpdateContext = FALSE;

// Insert or remove each of the detours.
for (o = s_pPendingOperations; o != NULL; o = o->pNext) {
Expand Down Expand Up @@ -1988,10 +1989,11 @@ typedef ULONG_PTR DETOURS_EIP_TYPE;

if (GetThreadContext(t->hThread, &cxt)) {
for (o = s_pPendingOperations; o != NULL; o = o->pNext) {
bUpdateContext = FALSE;
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)
Expand All @@ -2001,8 +2003,15 @@ typedef ULONG_PTR DETOURS_EIP_TYPE;
- (DETOURS_EIP_TYPE)(ULONG_PTR)
o->pTrampoline)));

SetThreadContext(t->hThread, &cxt);
bUpdateContext = TRUE;
}
#if defined(_AMD64_)
else if (cxt.DETOURS_EIP == (ULONG_PTR)o->pTrampoline->rbCodeIn)
{
cxt.DETOURS_EIP = (ULONG_PTR)o->pbTarget;
bUpdateContext = TRUE;
}
#endif
}
else {
if (cxt.DETOURS_EIP >= (DETOURS_EIP_TYPE)(ULONG_PTR)o->pbTarget &&
Expand All @@ -2017,9 +2026,14 @@ typedef ULONG_PTR DETOURS_EIP_TYPE;
- (DETOURS_EIP_TYPE)(ULONG_PTR)
o->pbTarget)));

SetThreadContext(t->hThread, &cxt);
bUpdateContext = TRUE;
}
}
if (bUpdateContext)
{
SetThreadContext(t->hThread, &cxt);
break;
}
}
}
#undef DETOURS_EIP
Expand Down

0 comments on commit ebaac90

Please sign in to comment.