我正在为 Windows 编写一段 C++ 代码,它需要查询进程及其每个单独线程的计时。
为了执行必要的系统调用,我需要进程及其每个线程的句柄。我正在使用 getCurrentProcess 和 getCurrentThread 函数,它们都返回伪句柄。经过进一步检查,我注意到所有线程的伪句柄共享相同的值。
在互联网上进行简短搜索后,我发现以下文章报告了与我得到的进程和线程伪句柄相同的值:https://weseetips.wordpress.com/2008/03/26/getcurrentthread-returns-pseudo-handle-not-the-real-handle/
我的问题:是否安全和/或定义从一个线程调用一次getCurrentThread
并在所有其他线程中使用返回的伪句柄让它们引用自己?
使用当前的实现,这可以按预期工作。我只是想知道这种行为是否得到保证。换句话说,它是否可以在任何提供 getCurrentThread 函数的 Windows 平台上运行?改变行为会被视为重大改变吗?
documentation for the getCurrentThread
function状态(强调我的):
A pseudo handle is a special constant that is interpreted as the current thread handle. The calling thread can use this handle to specify itself whenever a thread handle is required. [...]
这让我相信这个特殊的伪句柄只是“当前线程”的别名,因此可以在所有线程之间共享以让它们引用自己。另一方面,文档还说返回值可以被调用线程使用,因此我很困惑!
最佳答案
是的,这是安全的 - 这个伪句柄是众所周知的值,并记录在 wdm.h
(来自 Windows wdk)
#define NtCurrentProcess() ( (HANDLE)(LONG_PTR) -1 )
#define ZwCurrentProcess() NtCurrentProcess()
#define NtCurrentThread() ( (HANDLE)(LONG_PTR) -2 )
#define ZwCurrentThread() NtCurrentThread()
#define NtCurrentSession() ( (HANDLE)(LONG_PTR) -3 )
#define ZwCurrentSession() NtCurrentSession()
and can therefore be shared among all threads to let them refer to themselves.
当然不行,它不能“在所有线程之间共享”——只有当前进程/线程可以使用它来引用自己。
当内核模式 api 将线程/进程句柄作为输入参数时 - 他需要将句柄转换为对象指针(ETHREAD
或 EPROCESS
)。首先检查此常量值 - 如果是 - 使用指向当前线程/进程对象的指针。否则句柄是进程句柄表中的索引
关于c++ - 假定 Windows 伪句柄的值是否安全/已定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45631747/