Win32 Mutex, HANDLEs and WinDbg !handle extension.
A mutex is like a lock that is shared between processes. So if we run two instances of the following program at the same time, the second instance will hang/wait 10 seconds before acquiring the mutex.
In Win32, once you get the mutex, you can distinguish between two different cases. The first case is WAIT_OBJECT_0 and it means the previous owner released the mutex properly by calling ReleaseMutex() and the second case is WAIT_ABANDONED and it means the previous owner terminated without calling ReleaseMutex().
To reproduce the WAIT_ABANDONED case with the sample program, press CTRL + C in the first instance before the countdown hits zero.
When using WinDbg, during live debugging or during dump analysis, the !handle extension comes very handy.
Just get the handle value:
And print all the handle info:
Now we know 11ac.1628 is the owner of the mutex:
If we print the call stack for each thread in the second instance of the program:
We do not see any 11ac.1628 thread.
But if we print the call stacks of the first process intance:
Then we see the 11ac.1628 thread.
In fact 0x11ac and 0x29f8 match the PID of the processes: