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

Fix deadlock with Windows Loader during execute_while_frozen #51

Closed
wants to merge 3 commits into from
Closed
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
30 changes: 30 additions & 0 deletions src/thread_freezer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,20 @@ void execute_while_frozen(
int num_threads_frozen;
auto first_run = true;

ULONG_PTR loader_magic = 0;

typedef NTSTATUS (WINAPI* PFN_LdrLockLoaderLock)(ULONG Flags, ULONG *State, ULONG_PTR *Cookie);
typedef NTSTATUS (WINAPI* PFN_LdrUnlockLoaderLock)(ULONG Flags, ULONG_PTR Cookie);

const auto ntdll = GetModuleHandleW(L"ntdll.dll");

auto lock_loader = (PFN_LdrLockLoaderLock)GetProcAddress(ntdll, "LdrLockLoaderLock");
auto unlock_loader = (PFN_LdrUnlockLoaderLock)GetProcAddress(ntdll, "LdrUnlockLoaderLock");

if (lock_loader != nullptr && unlock_loader != nullptr) {
Comment on lines +30 to +38
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would prefer if these were just imported normally. See

extern "C" {
NTSTATUS
NTAPI
NtGetNextThread(HANDLE ProcessHandle, HANDLE ThreadHandle, ACCESS_MASK DesiredAccess, ULONG HandleAttributes,
ULONG Flags, PHANDLE NewThreadHandle);
}

lock_loader(0, nullptr, &loader_magic);
}

do {
num_threads_frozen = 0;
HANDLE thread{};
Expand Down Expand Up @@ -73,7 +87,18 @@ void execute_while_frozen(
}

if (visit_fn) {
// Unlock the loader lock.
if (lock_loader != nullptr && unlock_loader != nullptr) {
unlock_loader(0, loader_magic);
}

visit_fn(thread_id, thread, thread_ctx);

// Lock it again.
if (lock_loader != nullptr && unlock_loader != nullptr) {
loader_magic = 0;
lock_loader(0, nullptr, &loader_magic);
}
}

++num_threads_frozen;
Expand All @@ -82,6 +107,11 @@ void execute_while_frozen(
first_run = false;
} while (num_threads_frozen != 0);

// Unlock the loader lock.
if (lock_loader != nullptr && unlock_loader != nullptr) {
unlock_loader(0, loader_magic);
}

// Run the function.
if (run_fn) {
run_fn();
Expand Down