how does procexp close a mutex held by another process? - winapi

I am trying to close a mutex that is being held by a process on Windows using Win32 functions. This can be done using procexp but I need to do it programmatically without using the procexp GUI.
Method1:
I tried injecting a dll into the processs using EasyHook and then tried the following from the injected thread:
- OpenMutex
- ReleaseMutex
It gave me the ERROR_NOT_OWNER error probably because the release was called on a different thread than the one that called AcquireMutex.
Method2:
After injecting the dll, I tried to hook for CreateMutex using mHook. The hooked CreateMutex just called back the original CreateMutex. But this would just crash the application.
I can use procexp to close the mutex but I need to do it programmatically. How does procexp do it? How can it be done programmatically without any kernel mode code?

Use NtQuerySystemInformation() to retrieve an array of open handles, loop through the array until you find the desired mutex handle in the target process, then close it using DuplicateHandle() by specifying the DUPLICATE_CLOSE_SOURCE flag.
The following article explains it in more detail:
HOWTO: Enumerate handles

Just adding a complete answer. I had to add the following the following code to handles.cpp after the mutex is recognized:
HANDLE realHandle;
ret = DuplicateHandle(processHandle, (HANDLE)handle.Handle, GetCurrentProcess(), &realHandle, 0, TRUE, DUPLICATE_CLOSE_SOURCE);
if(!ret)
printf("DuplicateHandle Problem!");
if (!CloseHandle(realHandle))
{
printf("Problem closing the copied handle");
}
printf("", realHandle);
}

Related

Why is WebViewControlProcess.CreateWebViewControlAsync() never completing?

I’m trying to write some Rust code that uses Windows.Web.UI.Interop.WebViewControl (which is a Universal Windows Platform out-of-process wrapper expressly designed so Win32 apps can use EdgeHTML), and it’s all compiling, but not working properly at runtime.
The relevant code boils down to this, using the winit, winapi and winrt crates:
use winit::os::windows::WindowExt;
use winit::{EventsLoop, WindowBuilder};
use winapi::winrt::roapi::{RoInitialize, RO_INIT_SINGLETHREADED};
use winapi::shared::winerror::S_OK;
use winrt::{RtDefaultConstructible, RtAsyncOperation};
use winrt::windows::foundation::Rect;
use winrt::windows::web::ui::interop::WebViewControlProcess;
fn main() {
assert!(unsafe { RoInitialize(RO_INIT_SINGLETHREADED) } == S_OK);
let mut events_loop = EventsLoop::new();
let window = WindowBuilder::new()
.build(&events_loop)
.unwrap();
WebViewControlProcess::new()
.create_web_view_control_async(
window.get_hwnd() as usize as i64,
Rect {
X: 0.0,
Y: 0.0,
Width: 800.0,
Height: 600.0,
},
)
.expect("Creation call failed")
.blocking_get()
.expect("Creation async task failed")
.expect("Creation produced None");
}
The WebViewControlProcess instantiation works, and the CreateWebViewControlAsync function does seem to care about the value it received as host_window_handle (pass it 0, or one off from the actual HWND value, and it complains). Yet the IAsyncOperation stays determinedly at AsyncStatus.Started (0), and so the blocking_get() call hangs indefinitely.
A full, runnable demonstration of the issue (with a bit more instrumentation).
I get the feeling that the WebViewControlProcess is at fault: its ProcessId is stuck at 0, and it doesn’t look to have spawned any subprocess. The ProcessExited event does not seem to be being fired (I attached something to it immediately after instantiation, is there opportunity for it to be fired before that?). Calling Terminate() fails as one might expect in such a situation, E_FAIL.
Have I missed some sort of initialization for using Windows.Web.UI.Interop? Or is there some other reason why it’s not working?
It turned out that the problem was threading-related: the winit crate was doing its event loop in a different thread, and I did not realise this; I had erroneously assumed winit to be a harmless abstraction, which it turned out not quite to be.
I discovered this when I tried minimising and porting a known-functioning C++ example, this time doing all the Win32 API calls manually rather than using winit, so that the translation was correct. I got it to work, and discovered this:
The IAsyncOperation is fulfilled in the event loop, deep inside a DispatchMessageW call. That is when the Completion handler is called. Thus, for the operation to complete, you must run an event loop on the same thread. (An event loop on another thread doesn’t do anything.) Otherwise, it stays in the Started state.
Fortunately, winit is already moving to a new event loop which operates in the same thread, with the Windows implementation having landed a few days ago; when I migrated my code to use the eventloop-2.0 branch of winit, and to using the Completed handler instead of blocking_get(), it all started working.
I shall clarify about the winrt crate’s blocking_get() call which would normally be the obvious solution while prototyping: you can’t use it in this case because it causes deadlock, since it blocks until the IAsyncOperation completes, but the IAsyncOperation will not complete until you process messages in the event loop (DispatchMessageW), which will never happen because you’re blocking the thread.
Try to initialize WebViewProcessControl with winrt::init_apartment(); And it may needs a single-threaded apartment(according to the this answer).
More attention on Microsoft Edge Developer Guide:
Lastly, power users might notice the apppearance of the Desktop App
Web Viewer (previously named Win32WebViewHost), an internal system app
representing the Win32 WebView, in the following places:
● In the Windows 10 Action Center. The source of these notifications
should be understood as from a WebView hosted from a Win32 app.
● In the device access settings UI
(Settings->Privacy->Camera/Location/Microphone). Disabling any of
these settings denies access from all WebViews hosted in Win32 apps.

Windows Kernel Driver: Does the "HANDLE UniqueThread" in "CLIENT_ID CreatingThreadId" is the same during the process loading?

I'm trying to write an APC dll injection driver, I've found this example and thought to modify it to my needs.
After I understood the code, this is how I thought to modify it (and my question come from there).
In the code, the writer used PsLookupThreadByThreadId to receive a referenced pointer to the ETHREAD structure of the targeted process.
PsLookupThreadByThreadId(pSpi->Threads[0].ClientId.UniqueThread,&Thread)
but to get the SYSTEM_THREAD_INFORMATION for the UniqueThread handle, he used ZwQuerySystemInformation
I want to load my dll right after ntdll is loaded, so I want to use PsSetCreateProcessNotifyRoutineEx and save the UniqueThread from the PS_CREATE_NOTIFY_INFO I got when the callback is called for the process I'm targeting.
And after ntdll is loaded, which I'll know thanks to PsSetLoadImageNotifyRoutineEx I could inject my dll using his APC injection logic.
my goal is to inject my dll in the PloadImageNotifyRoutine callback, but don't use ZwQuerySystemInformation as he does to get the UniqueThread, but save it in the PcreateProcessNotifyRoutineEx callback.
So, my question is: Can I trust the UniqueThread I get from PS_CREATE_NOTIFY_INFO is the same during all the process loading time?
I want to use PsSetCreateProcessNotifyRoutineEx and save the
UniqueThread from the PS_CREATE_NOTIFY_INFO I got when the
callback is called for the process I'm targeting.
about CreatingThreadId from PS_CREATE_NOTIFY_INFO
The process ID and thread ID of the process and thread that
created the new process
this id not for new created process/thread, but for creator. if you want inject self dll in the PloadImageNotifyRoutine callback - the PcreateProcessNotifyRoutineEx is useless for you.
the PloadImageNotifyRoutine called when image is mapped to target process - inside ZwMapViewOfSection . you need check that ProcessId (second parameter of PcreateProcessNotifyRoutineEx - The process ID of the process where image is loaded) is equal to PsGetCurrentProcessId(). this mean that image loaded to the current process and you can use KeGetCurrentThread() - you not need PsLookupThreadByThreadId at all
I want to load my dll right after ntdll is loaded
at this moment any user mode structures in process yet not initialized. because it initialized by ntdll. as result - if you inject your apc and force execute it at this moment - you got crash of process. nothing more
i can advice you inject your dll when kernel32.dll is loaded. and here you need check that this is load as dll, not simply image mapping - check ArbitraryUserPointer in thread teb - are it point to L"*\\kernel32.dll": smss.exe map kernel32.dll during create \\KnownDlls (ArbitraryUserPointer == 0 in this case), wow64 process several time map kernel32.dll (32 and 64 bit) with L"WOW64_IMAGE_SECTION" or L"NOT_AN_IMAGE" names in ArbitraryUserPointer

Safe place to put unsafe DLL cleanup code on Windows?

We hit a case where it would be the best solution for us to put a FreeLibrary call into DllMain / DLL_PROCESS_DETACH.
Of course, you must not do that:
It is not safe to call FreeLibrary from DllMain.
The use case is that we have a situation like this:
(unknown client dll or exe) links dynamically or statically to ->
-> DLL_1, loads dynamically -> DLL_x
DLL_1 should load DLL_x transparently wrt. to it's client code, and it should to load DLL_x dynamically. Now, the loading can be done lazily, so that the LoadLibrary call needn't reside in the DLL_PROCESS_ATTACH part of DLL_1.
But once the client is done with DLL_1, when/before DLL_1 is unloaded from the process, it should also unload (== FreeLibrary) DLL_x.
Is there any way to do this without an explicit DLL_1/Uninitialize function that must be called by the client?
I'll note:
DllMain, and thus also any C++ global static destructor cannot be used.
Is there any other callback mechanism in either kernel32/ntdll or maybe in the shared MS CRT to make this happen?
Are there other patterns to make this usecase work?
The correct approach is an explicit Uninitialize function in DLL_1.
However, if you can't do that, you can work around the problem by launching a helper thread to do the unload for you. If you want to play it safe, launch the thread at the same time you load DLL_x and have it wait on an event object. (For the record, though, it is generally considered safe to launch a thread from DllMain so long as you respect the fact that it won't start up until DllMain has exited.)
Obviously, the helper thread's code can't be in DLL_1. If you can modify DLL_x you can put it there. If not, you'll need a helper DLL. In either case, the DLL containing the helper thread's code can safely self-unload using the FreeLibraryAndExitThread function.

Pthread RWLock on MAC Deadlocking but not on Linux?

I've been experimenting with rwlock's on Mac and am experiencing something that seems to me shouldn't be happening. There's some weird combination of using read/write locks with recursive read locks that is deadlocking, but shouldn't be.
I posted the code on pastebin because it's more than just a snippet. The way this code is written shouldn't deadlock, and indeed doesn't when running on linux. Why does this deadlock on a mac?
http://pastebin.com/Ui9iS1ke
Any ideas?
See the bug I reported with apple.
https://bugreport.apple.com/cgi-bin/WebObjects/RadarWeb.woa/7/wo/0blX77DJS8lBTTxVnTsNDM/5.83.28.0.13
Here's the open radar bug.
http://openradar.appspot.com/8588290
Aaron: I just ran into this. I found that one can workaround this by using thread local storage. Create a wrapper around the rwlock that increments a thread local key:
#interface ReadWriteLock : NSObject {
pthread_key_t readKey;
pthread_key_t writeKey;
pthread_rwlock_t rwLock;
}
-(void)lockRead;
-(void)unlockRead;
-(void)lockWrite;
-(void)unlockWrite;
#end
Then increment the readKey using pthread_setspecific when you call lockRead, decrement it when you call unlockRead, only rd_lock when the key goes from 0 to 1 and only rw_unlock when the key goes from 1 to 0. Copy this for the writeLock logic.
Since the pthread_setspecific and pthread_getspecific are thread-local, you don't need to lock around access to these. Make sure to call the appropriate pthread creation / initialization functions in init, and make sure to dispose of all of the pthread_* members in dealloc.
Unfortunately I can't give you the full source to my solution, but the above method works ( I've tested it heavily ).

How to set name to a Win32 Thread?

How do I set a name to a Win32 thread. I did'nt find any Win32 API to achieve the same. Basically I want to add the Thread Name in the Log file. Is TLS (Thread Local Storage) the only way to do it?
Does this help ?
How to: Set a Thread Name in Native Code
In managed code, it is as easy as setting the Name property of the corresponding Thread object.
http://msdn.microsoft.com/en-us/library/xcb2z8hs(VS.90).aspx
//
// Usage: SetThreadName (-1, "MainThread");
//
#include <windows.h>
const DWORD MS_VC_EXCEPTION=0x406D1388;
#pragma pack(push,8)
typedef struct tagTHREADNAME_INFO
{
DWORD dwType; // Must be 0x1000.
LPCSTR szName; // Pointer to name (in user addr space).
DWORD dwThreadID; // Thread ID (-1=caller thread).
DWORD dwFlags; // Reserved for future use, must be zero.
} THREADNAME_INFO;
#pragma pack(pop)
void SetThreadName( DWORD dwThreadID, char* threadName)
{
THREADNAME_INFO info;
info.dwType = 0x1000;
info.szName = threadName;
info.dwThreadID = dwThreadID;
info.dwFlags = 0;
__try
{
RaiseException( MS_VC_EXCEPTION, 0, sizeof(info)/sizeof(ULONG_PTR), (ULONG_PTR*)&info );
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
}
}
According to discussion with the Microsoft debugging team leads (see link below for details) the SetThreadDescription API is the API that will be used going forward by Microsoft to support thread naming officially in native code. By "officially" I mean an MS-supported API for naming threads, as opposed to the current exception-throwing hack that currently only works while a process is running in Visual Studio.
This API became available starting in Windows 10, version 1607.
Currently, however, there is very little tooling support, so the names you set won't be visible in the Visual Studio or WinDbg debuggers. As of April 2017, however, the Microsoft xperf/WPA tools do support it (threads named via this API will have their names show up properly in those tools).
If you would like to see this gain better support, such as in WinDbg, Visual Studio, and crash dump files, please vote for it using this link:
https://visualstudio.uservoice.com/forums/121579-visual-studio-ide/suggestions/17608120-properly-support-native-thread-naming-via-the-sett
Win32 threads do not have names. There is a Microsoft convention whereby applications raise special SEH exceptions containing a thread name. These exceptions can be intercepted by debuggers and used to indicate the thread name. A couple of the answers cover that.
However, that is all handled by the debugger. Threads themselves are nameless objects. So, if you want to associate names with your threads, you'll have to develop your own mechanism. Whilst you could use thread local storage that will only allow you to obtain the name from code executing in that thread. So a global map between thread ID and the name would seem like the most natural and useful approach.
You can use a thread-local storage object to store the name. For example,
__declspec( thread ) char threadName[32];
Then you can write and read this from a thread. This might be useful in a logger application, where you want to print out the name of the thread for every message. You probably want to write this variable as soon as the thread starts, and also throw the Microsoft exception (https://stackoverflow.com/a/10364541/364818) so that the debugger also knows the thread name.
If your application runs on Windows version 1607+, you can use SetThreadDescription()
If you want to see the name of your thread in the debugger (windbg or visual studio):
http://blogs.msdn.com/stevejs/archive/2005/12/19/505815.aspx
I'm not actually sure if there's a reverse method to get the thread name. But TLS sounds like the way to go.
Another way to do this is to store a pointer to the name in the ArbitraryUserPointer field of the TEB of the thread. This can be written to and read from at runtime.
There's a CodeProject article titled "Debugging With The Thread Information Block" that shows you how to do this.
You can always store this information for yourself in a suitable data structure. Use a hash or a map to map GetThreadId() to this name. Since GetThreadId() is always a unique identifier, this works just fine.
Cheers !
Of course, if he's creating many
threads, that hashmap will slowly fill
up and use more and more memory, so
some cleanup procedure is probably a
good thing as well.
You're absolutely right. When a thread dies, it's corresponding entry in the map should naturally be removed.

Resources