Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

don't break stack walking #308

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions src/detours.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2023,6 +2023,33 @@ LONG WINAPI DetourAttachEx(_Inout_ PVOID *ppPointer,
return ERROR_INVALID_PARAMETER;
}

#ifdef DETOURS_X64
// Detouring a function should not break our ability to walk the call stack.
// On X64 stack unwinding relies on RUNTIME_FUNCTION structures - except for
// the first frame which can be a leaf function with no stack allocations.
// See https://learn.microsoft.com/en-us/cpp/build/exception-handling-x64

// These structure are typically found in the .pdata section of PE32+ images.
// Allow all MEM_IMAGE detours.
MEMORY_BASIC_INFORMATION mbi;
if (!VirtualQuery(pDetour, &mbi, sizeof(mbi))) {
DETOUR_TRACE(("invalid detour\n"));
DETOUR_BREAK();
return ERROR_INVALID_PARAMETER;
}

// Alternatively dynamic code should use RtlAddGrowableFunctionTable
// to register this information. This supports kernel stack walks.
// Require this for dynamic code - even though simple leaf functions
// don't strictly require it.
DWORD64 imageBase;
if (mbi.Type != MEM_IMAGE && NULL == RtlLookupFunctionEntry((DWORD64)pDetour, &imageBase, NULL)) {
DETOUR_TRACE(("dynamic detours must have function table entries\n"));
DETOUR_BREAK();
return ERROR_INVALID_PARAMETER;
}
#endif // DETOURS_X64

if (s_nPendingThreadId != (LONG)GetCurrentThreadId()) {
DETOUR_TRACE(("transaction conflict with thread id=%ld\n", s_nPendingThreadId));
return ERROR_INVALID_OPERATION;
Expand Down