Skip to content

Commit 1fb3ff4

Browse files
authored
Add process heap locking to DetourTransaction (#128)
I realized based on cyb3rpsych0s1s/audioware#81, that Detours use `new`/`delete` operators while the threads are suspended. which cause deadlocks when a thread has the lock on the process' heap. This PR gets the heap lock when the transactions starts.
1 parent 12d22f8 commit 1fb3ff4

2 files changed

Lines changed: 17 additions & 0 deletions

File tree

src/dll/DetourTransaction.cpp

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,21 @@ extern "C" NTSYSCALLAPI NTSTATUS NTAPI NtGetNextThread(_In_ HANDLE ProcessHandle
1919
DetourTransaction::DetourTransaction(const std::source_location aSource)
2020
: m_source(aSource)
2121
, m_state(State::Invalid)
22+
, m_hasHeapLock(false)
2223
{
2324
spdlog::trace("Trying to start a detour transaction in '{}' ({}:{})", m_source.function_name(),
2425
m_source.file_name(), m_source.line());
2526

27+
auto hasLock = HeapLock(GetProcessHeap());
28+
if (!hasLock)
29+
{
30+
spdlog::error("Could not lock the process heap in '{}' ({}:{}). Last error: {}", m_source.function_name(),
31+
m_source.file_name(), m_source.line(), GetLastError());
32+
return;
33+
}
34+
35+
m_hasHeapLock = true;
36+
2637
auto result = DetourTransactionBegin();
2738
if (result == NO_ERROR)
2839
{
@@ -45,6 +56,11 @@ DetourTransaction::~DetourTransaction()
4556
{
4657
Abort();
4758
}
59+
60+
if (m_hasHeapLock)
61+
{
62+
HeapUnlock(GetProcessHeap());
63+
}
4864
}
4965

5066
const bool DetourTransaction::IsValid() const

src/dll/DetourTransaction.hpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,4 +33,5 @@ class DetourTransaction
3333
const std::source_location m_source;
3434
State m_state;
3535
std::vector<wil::unique_handle> m_handles;
36+
bool m_hasHeapLock;
3637
};

0 commit comments

Comments
 (0)