From f0e5f820288d33542dc222eb94f4b0221420dd4b Mon Sep 17 00:00:00 2001 From: Matt Bilker Date: Mon, 18 Oct 2021 20:49:59 +0000 Subject: [PATCH] hook/iohook.c: Fix race condition at during iohook initialization - If another DLL being loaded spawns a thread that begins doing I/O, then there is a race condition where `hook_table_apply` is still applying the hooks and has not returned yet but the hooked functions are called by those other threads. This causes the assert on `iohook_initted` to trigger. - The easy fix is to always enter the mutex to ensure the hooks have been applied and function addresses for `CreateFileW` and `SetFilePointerEx` have been resolved. --- hook/iohook.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/hook/iohook.c b/hook/iohook.c index f28f52d..6c26072 100644 --- a/hook/iohook.c +++ b/hook/iohook.c @@ -224,6 +224,9 @@ static void iohook_init(void) return; } + InitializeCriticalSection(&iohook_lock); + EnterCriticalSection(&iohook_lock); + /* Splice iohook into IAT entries referencing Win32 I/O APIs */ hook_table_apply( @@ -273,8 +276,9 @@ static void iohook_init(void) "SetFilePointerEx"); } - InitializeCriticalSection(&iohook_lock); iohook_initted = true; + + LeaveCriticalSection(&iohook_lock); } // Deprecated @@ -378,10 +382,10 @@ HRESULT iohook_invoke_next(struct irp *irp) HRESULT hr; assert(irp != NULL); - assert(iohook_initted); EnterCriticalSection(&iohook_lock); + assert(iohook_initted); assert(irp->next_handler <= iohook_nhandlers); if (irp->next_handler < iohook_nhandlers) {