handle usage after using KeStackAttach

I just recently fixed a bug in my code where I would cause a BSOD when attempting to create a handle while being attached to a process that died.

As far as I can tell from the crash dump, the target process died, the handle table got set to NULL, and my attempt to create the handle resulted in ntos trying to add a new handle to a NULL handle table of my process, thus causing a BSOD.

In this case, my fix was to specify OBJ_KERNEL_HANDLE, but there are obviously also cases where I want to actually create a user-handle and pass it back to my user app.

Obviously, I could create a system thread in that process or queue and APC, but I think some people like to use KeStackAttach since it also puts handles into the target process context. Is there a legitimate way to make this safe? Should I just avoid creating handles unless I’m in a thread that’s actually owned by the appropriate process?