| 1 |
"""Utilities for querying Windows system handles and their information. |
| 2 |
|
| 3 |
It uses the Windows API through the `ctypes` library. |
| 4 |
""" |
| 5 |
|
| 6 |
from __future__ import annotations |
| 7 |
|
| 8 |
import ctypes |
| 9 |
import os |
| 10 |
import sys |
| 11 |
from ctypes import wintypes |
| 12 |
from typing import ClassVar |
| 13 |
|
| 14 |
from DisplayCAL.win_structs import NTSTATUS, UNICODE_STRING |
| 15 |
|
| 16 |
PVOID = ctypes.c_void_p |
| 17 |
PULONG = ctypes.POINTER(wintypes.ULONG) |
| 18 |
ULONG_PTR = wintypes.WPARAM |
| 19 |
ACCESS_MASK = wintypes.DWORD |
| 20 |
STATUS_INFO_LENGTH_MISMATCH = NTSTATUS(0xC0000004) |
| 21 |
|
| 22 |
|
| 23 |
class SYSTEM_INFORMATION_CLASS(ctypes.c_ulong): # noqa: N801 |
| 24 |
"""Class representing SYSTEM_INFORMATION_CLASS values.""" |
| 25 |
|
| 26 |
def __repr__(self) -> str: |
| 27 |
"""Return a string representation of the SYSTEM_INFORMATION_CLASS. |
| 28 |
|
| 29 |
Returns: |
| 30 |
str: A string representation of the SYSTEM_INFORMATION_CLASS in |
| 31 |
hexadecimal format. |
| 32 |
""" |
| 33 |
return f"{self.__class__.__name__}({self.value})" |
| 34 |
|
| 35 |
|
| 36 |
SystemExtendedHandleInformation = SYSTEM_INFORMATION_CLASS(64) |
| 37 |
|
| 38 |
|
| 39 |
class SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX(ctypes.Structure): # noqa: N801 |
| 40 |
"""Class representing SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX structure.""" |
| 41 |
|
| 42 |
_fields_: ClassVar[list[tuple]] = [ |
| 43 |
("Object", PVOID), |
| 44 |
("UniqueProcessId", wintypes.HANDLE), |
| 45 |
("HandleValue", wintypes.HANDLE), |
| 46 |
("GrantedAccess", ACCESS_MASK), |
| 47 |
("CreatorBackTraceIndex", wintypes.USHORT), |
| 48 |
("ObjectTypeIndex", wintypes.USHORT), |
| 49 |
("HandleAttributes", wintypes.ULONG), |
| 50 |
("Reserved", wintypes.ULONG), |
| 51 |
] |
| 52 |
|
| 53 |
|
| 54 |
class SYSTEM_INFORMATION(ctypes.Structure): # noqa: N801 |
| 55 |
"""Class representing SYSTEM_INFORMATION structure.""" |
| 56 |
|
| 57 |
|
| 58 |
PSYSTEM_INFORMATION = ctypes.POINTER(SYSTEM_INFORMATION) |
| 59 |
|
| 60 |
|
| 61 |
class SYSTEM_HANDLE_INFORMATION_EX(SYSTEM_INFORMATION): # noqa: N801 |
| 62 |
"""Class representing SYSTEM_HANDLE_INFORMATION_EX structure.""" |
| 63 |
|
| 64 |
_fields_: ClassVar[list[tuple]] = [ |
| 65 |
("NumberOfHandles", ULONG_PTR), |
| 66 |
("Reserved", ULONG_PTR), |
| 67 |
("_Handles", SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX * 1), |
| 68 |
] |
| 69 |
|
| 70 |
@property |
| 71 |
def Handles(self): |
| 72 |
"""Return a list of handles. |
| 73 |
|
| 74 |
Returns: |
| 75 |
list[SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX]: A list of handles |
| 76 |
represented by SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX structures. |
| 77 |
""" |
| 78 |
arr_t = SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX * self.NumberOfHandles |
| 79 |
return ctypes.POINTER(arr_t)(self._Handles)[0] |
| 80 |
|
| 81 |
|
| 82 |
try: |
| 83 |
ntdll = ctypes.WinDLL("ntdll") |
| 84 |
ntdll.NtQuerySystemInformation.restype = NTSTATUS |
| 85 |
ntdll.NtQuerySystemInformation.argtypes = ( |
| 86 |
SYSTEM_INFORMATION_CLASS, # SystemInformationClass |
| 87 |
PSYSTEM_INFORMATION, # SystemInformation |
| 88 |
wintypes.ULONG, # SystemInformationLength |
| 89 |
PULONG, |
| 90 |
) # ReturnLength |
| 91 |
except OSError: |
| 92 |
# Just in case |
| 93 |
ntdll = None |
| 94 |
|
| 95 |
|
| 96 |
ObjectBasicInformation = 0 |
| 97 |
ObjectNameInformation = 1 |
| 98 |
ObjectTypeInformation = 2 |
| 99 |
|
| 100 |
|
| 101 |
def _get_handle_info(handle, info_class): |
| 102 |
if hasattr(handle, "HandleValue"): |
| 103 |
handle = handle.HandleValue |
| 104 |
size_needed = wintypes.DWORD() |
| 105 |
buf = ctypes.c_buffer(0x1000) |
| 106 |
ntdll.NtQueryObject( |
| 107 |
handle, |
| 108 |
info_class, |
| 109 |
ctypes.byref(buf), |
| 110 |
ctypes.sizeof(buf), |
| 111 |
ctypes.byref(size_needed), |
| 112 |
) |
| 113 |
return UNICODE_STRING.from_buffer_copy(buf[: size_needed.value]).Buffer |
| 114 |
|
| 115 |
|
| 116 |
def get_handle_name(handle): |
| 117 |
"""Get the name of a handle.""" |
| 118 |
return _get_handle_info(handle, ObjectNameInformation) |
| 119 |
|
| 120 |
|
| 121 |
def get_handle_type(handle): |
| 122 |
"""Get the type of a handle.""" |
| 123 |
return _get_handle_info(handle, ObjectTypeInformation) |
| 124 |
|
| 125 |
|
| 126 |
def get_handles(): |
| 127 |
"""Get all handles in the system.""" |
| 128 |
info = SYSTEM_HANDLE_INFORMATION_EX() |
| 129 |
length = wintypes.ULONG() |
| 130 |
while True: |
| 131 |
status = ntdll.NtQuerySystemInformation( |
| 132 |
SystemExtendedHandleInformation, |
| 133 |
ctypes.byref(info), |
| 134 |
ctypes.sizeof(info), |
| 135 |
ctypes.byref(length), |
| 136 |
) |
| 137 |
if status != STATUS_INFO_LENGTH_MISMATCH: |
| 138 |
break |
| 139 |
ctypes.resize(info, length.value) |
| 140 |
if status < 0: |
| 141 |
raise ctypes.WinError(ntdll.RtlNtStatusToDosError(status)) |
| 142 |
return info.Handles |
| 143 |
|
| 144 |
|
| 145 |
def get_process_handles(pid=None): |
| 146 |
"""Get handles of process <pid> (current process if not specified).""" |
| 147 |
if not pid: |
| 148 |
pid = os.getpid() |
| 149 |
handles = [] |
| 150 |
for handle in get_handles(): |
| 151 |
if handle.UniqueProcessId != pid: |
| 152 |
continue |
| 153 |
handles.append(handle) |
| 154 |
return handles |
| 155 |
|
| 156 |
|
| 157 |
if __name__ == "__main__": |
| 158 |
pid = int(sys.argv[1]) if len(sys.argv) > 1 else None |
| 159 |
for handle in get_process_handles(pid): |
| 160 |
print( |
| 161 |
f"Handle = 0x{handle.HandleValue:04x}, " |
| 162 |
f"Type = 0x{handle.ObjectTypeIndex:02x} {get_handle_type(handle)!r}, " |
| 163 |
f"Access = 0x{handle.GrantedAccess:06x}, " |
| 164 |
f"Name = {get_handle_name(handle)!r}" |
| 165 |
) |