HandleDbg.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. #ifndef UNICODE
  2. #define UNICODE
  3. #endif
  4. #include <windows.h>
  5. #include <stdio.h>
  6. #include <map>
  7. #define NT_SUCCESS(x) ((x) >= 0)
  8. #define STATUS_INFO_LENGTH_MISMATCH 0xc0000004
  9. #define SystemHandleInformation 16
  10. #define ObjectBasicInformation 0f
  11. #define ObjectNameInformation 1
  12. #define ObjectTypeInformation 2
  13. typedef NTSTATUS (NTAPI *_NtQuerySystemInformation)(
  14. ULONG SystemInformationClass,
  15. PVOID SystemInformation,
  16. ULONG SystemInformationLength,
  17. PULONG ReturnLength
  18. );
  19. typedef NTSTATUS (NTAPI *_NtDuplicateObject)(
  20. HANDLE SourceProcessHandle,
  21. HANDLE SourceHandle,
  22. HANDLE TargetProcessHandle,
  23. PHANDLE TargetHandle,
  24. ACCESS_MASK DesiredAccess,
  25. ULONG Attributes,
  26. ULONG Options
  27. );
  28. typedef NTSTATUS (NTAPI *_NtQueryObject)(
  29. HANDLE ObjectHandle,
  30. ULONG ObjectInformationClass,
  31. PVOID ObjectInformation,
  32. ULONG ObjectInformationLength,
  33. PULONG ReturnLength
  34. );
  35. typedef struct _UNICODE_STRING
  36. {
  37. USHORT Length;
  38. USHORT MaximumLength;
  39. PWSTR Buffer;
  40. } UNICODE_STRING, *PUNICODE_STRING;
  41. typedef struct _SYSTEM_HANDLE
  42. {
  43. ULONG ProcessId;
  44. BYTE ObjectTypeNumber;
  45. BYTE Flags;
  46. USHORT Handle;
  47. PVOID Object;
  48. ACCESS_MASK GrantedAccess;
  49. } SYSTEM_HANDLE, *PSYSTEM_HANDLE;
  50. typedef struct _SYSTEM_HANDLE_INFORMATION
  51. {
  52. ULONG HandleCount;
  53. SYSTEM_HANDLE Handles[1];
  54. } SYSTEM_HANDLE_INFORMATION, *PSYSTEM_HANDLE_INFORMATION;
  55. typedef enum _POOL_TYPE
  56. {
  57. NonPagedPool,
  58. PagedPool,
  59. NonPagedPoolMustSucceed,
  60. DontUseThisType,
  61. NonPagedPoolCacheAligned,
  62. PagedPoolCacheAligned,
  63. NonPagedPoolCacheAlignedMustS
  64. } POOL_TYPE, *PPOOL_TYPE;
  65. typedef struct _OBJECT_TYPE_INFORMATION
  66. {
  67. UNICODE_STRING Name;
  68. ULONG TotalNumberOfObjects;
  69. ULONG TotalNumberOfHandles;
  70. ULONG TotalPagedPoolUsage;
  71. ULONG TotalNonPagedPoolUsage;
  72. ULONG TotalNamePoolUsage;
  73. ULONG TotalHandleTableUsage;
  74. ULONG HighWaterNumberOfObjects;
  75. ULONG HighWaterNumberOfHandles;
  76. ULONG HighWaterPagedPoolUsage;
  77. ULONG HighWaterNonPagedPoolUsage;
  78. ULONG HighWaterNamePoolUsage;
  79. ULONG HighWaterHandleTableUsage;
  80. ULONG InvalidAttributes;
  81. GENERIC_MAPPING GenericMapping;
  82. ULONG ValidAccess;
  83. BOOLEAN SecurityRequired;
  84. BOOLEAN MaintainHandleCount;
  85. USHORT MaintainTypeList;
  86. POOL_TYPE PoolType;
  87. ULONG PagedPoolUsage;
  88. ULONG NonPagedPoolUsage;
  89. } OBJECT_TYPE_INFORMATION, *POBJECT_TYPE_INFORMATION;
  90. void* GetLibraryProcAddress(const char* LibraryName, const char* procName)
  91. {
  92. return (void*)GetProcAddress(GetModuleHandleA(LibraryName), procName);
  93. }
  94. #include "HandleDbg.h"
  95. #include "BeefySysLib/util/CritSect.h"
  96. USING_NS_BF;
  97. struct HandleEntry
  98. {
  99. std::string mTraceStr;
  100. SYSTEM_HANDLE mHandle;
  101. };
  102. typedef std::map<USHORT, HandleEntry> HandleMap;
  103. static _NtQuerySystemInformation gNtQuerySystemInformation;
  104. static _NtDuplicateObject gNtDuplicateObject;
  105. static _NtQueryObject gNtQueryObject;
  106. static bool gHDInitialized = false;
  107. static HandleMap gHDHandleMap;
  108. static CritSect gHDCritSect;
  109. static void CheckInit()
  110. {
  111. if (gHDInitialized)
  112. return;
  113. gNtQuerySystemInformation = (_NtQuerySystemInformation) GetLibraryProcAddress("ntdll.dll", "NtQuerySystemInformation");
  114. gNtDuplicateObject = (_NtDuplicateObject) GetLibraryProcAddress("ntdll.dll", "NtDuplicateObject");
  115. gNtQueryObject = (_NtQueryObject) GetLibraryProcAddress("ntdll.dll", "NtQueryObject");
  116. gHDInitialized = true;
  117. }
  118. void HDCheckHandles(const std::string& traceStr)
  119. {
  120. AutoCrit autoCrit(gHDCritSect);
  121. CheckInit();
  122. /*if (!(processHandle = OpenProcess(PROCESS_DUP_HANDLE, FALSE, pid)))
  123. {
  124. printf("Could not open PID %d! (Don't try to open a system process.)\n", pid);
  125. return 1;
  126. }*/
  127. PSYSTEM_HANDLE_INFORMATION handleInfo;
  128. ULONG handleInfoSize = 0x100000;
  129. handleInfo = (PSYSTEM_HANDLE_INFORMATION)malloc(handleInfoSize);
  130. NTSTATUS status;
  131. /* NtQuerySystemInformation won't give us the correct buffer size,
  132. so we guess by doubling the buffer size. */
  133. while ((status = gNtQuerySystemInformation(
  134. SystemHandleInformation,
  135. handleInfo,
  136. handleInfoSize,
  137. NULL
  138. )) == STATUS_INFO_LENGTH_MISMATCH)
  139. handleInfo = (PSYSTEM_HANDLE_INFORMATION)realloc(handleInfo, handleInfoSize *= 2);
  140. /* NtQuerySystemInformation stopped giving us STATUS_INFO_LENGTH_MISMATCH. */
  141. if (!NT_SUCCESS(status))
  142. {
  143. //printf("NtQuerySystemInformation failed!\n");
  144. return;
  145. }
  146. HandleMap oldHandleMap = gHDHandleMap;
  147. gHDHandleMap.clear();
  148. for (int i = 0; i < (int)handleInfo->HandleCount; i++)
  149. {
  150. SYSTEM_HANDLE& handle = handleInfo->Handles[i];
  151. /*HANDLE dupHandle = NULL;
  152. POBJECT_TYPE_INFORMATION objectTypeInfo;
  153. PVOID objectNameInfo;
  154. UNICODE_STRING objectName;
  155. ULONG returnLength;*/
  156. /* Check if this handle belongs to the PID the user specified. */
  157. if (handle.ProcessId != GetCurrentProcessId())
  158. continue;
  159. auto itr = oldHandleMap.find(handle.Handle);
  160. if (itr != oldHandleMap.end())
  161. gHDHandleMap.insert(*itr);
  162. else
  163. {
  164. HandleEntry handleEntry;
  165. handleEntry.mTraceStr = traceStr;
  166. handleEntry.mHandle = handle;
  167. gHDHandleMap.insert(HandleMap::value_type(handle.Handle, handleEntry));
  168. }
  169. }
  170. free(handleInfo);
  171. }
  172. void HDStart()
  173. {
  174. AutoCrit autoCrit(gHDCritSect);
  175. gHDHandleMap.clear();
  176. HDCheckHandles("");
  177. }
  178. void HDDump()
  179. {
  180. AutoCrit autoCrit(gHDCritSect);
  181. HANDLE processHandle = GetCurrentProcess();
  182. for (auto pair : gHDHandleMap)
  183. {
  184. USHORT handle = pair.first;
  185. HandleEntry handleEntry = pair.second;
  186. if (!handleEntry.mTraceStr.empty())
  187. {
  188. OutputDebugStrF("New Handle: %X %s\n", handle, handleEntry.mTraceStr.c_str());
  189. SYSTEM_HANDLE handle = handleEntry.mHandle;
  190. HANDLE dupHandle = NULL;
  191. POBJECT_TYPE_INFORMATION objectTypeInfo;
  192. PVOID objectNameInfo;
  193. UNICODE_STRING objectName;
  194. ULONG returnLength;
  195. /* Check if this handle belongs to the PID the user specified. */
  196. /*if (handle.ProcessId != pid)
  197. continue;*/
  198. /* Duplicate the handle so we can query it. */
  199. if (!NT_SUCCESS(gNtDuplicateObject(
  200. processHandle,
  201. (HANDLE)handle.Handle,
  202. GetCurrentProcess(),
  203. &dupHandle,
  204. 0,
  205. 0,
  206. 0
  207. )))
  208. {
  209. OutputDebugStrF("[%#x] Error!\n", handle.Handle);
  210. continue;
  211. }
  212. /* Query the object type. */
  213. objectTypeInfo = (POBJECT_TYPE_INFORMATION)malloc(0x1000);
  214. if (!NT_SUCCESS(gNtQueryObject(
  215. dupHandle,
  216. ObjectTypeInformation,
  217. objectTypeInfo,
  218. 0x1000,
  219. NULL
  220. )))
  221. {
  222. OutputDebugStrF("[%#x] Error!\n", handle.Handle);
  223. CloseHandle(dupHandle);
  224. continue;
  225. }
  226. /* Query the object name (unless it has an access of
  227. 0x0012019f, on which NtQueryObject could hang. */
  228. if (handle.GrantedAccess == 0x0012019f)
  229. {
  230. /* We have the type, so display that. */
  231. OutputDebugStrF(
  232. "[%#x] %.*S: (did not get name)\n",
  233. handle.Handle,
  234. objectTypeInfo->Name.Length / 2,
  235. objectTypeInfo->Name.Buffer
  236. );
  237. free(objectTypeInfo);
  238. CloseHandle(dupHandle);
  239. continue;
  240. }
  241. objectNameInfo = malloc(0x1000);
  242. if (!NT_SUCCESS(gNtQueryObject(
  243. dupHandle,
  244. ObjectNameInformation,
  245. objectNameInfo,
  246. 0x1000,
  247. &returnLength
  248. )))
  249. {
  250. /* Reallocate the buffer and try again. */
  251. objectNameInfo = realloc(objectNameInfo, returnLength);
  252. if (!NT_SUCCESS(gNtQueryObject(
  253. dupHandle,
  254. ObjectNameInformation,
  255. objectNameInfo,
  256. returnLength,
  257. NULL
  258. )))
  259. {
  260. /* We have the type name, so just display that. */
  261. OutputDebugStrF(
  262. "[%#x] %.*S: (could not get name)\n",
  263. handle.Handle,
  264. objectTypeInfo->Name.Length / 2,
  265. objectTypeInfo->Name.Buffer
  266. );
  267. free(objectTypeInfo);
  268. free(objectNameInfo);
  269. CloseHandle(dupHandle);
  270. continue;
  271. }
  272. }
  273. /* Cast our buffer into an UNICODE_STRING. */
  274. objectName = *(PUNICODE_STRING)objectNameInfo;
  275. /* Print the information! */
  276. if (objectName.Length)
  277. {
  278. /* The object has a name. */
  279. OutputDebugStrF(
  280. "[%#x] %.*S: %.*S\n",
  281. handle.Handle,
  282. objectTypeInfo->Name.Length / 2,
  283. objectTypeInfo->Name.Buffer,
  284. objectName.Length / 2,
  285. objectName.Buffer
  286. );
  287. }
  288. else
  289. {
  290. /* Print something else. */
  291. OutputDebugStrF(
  292. "[%#x] %.*S: (unnamed)\n",
  293. handle.Handle,
  294. objectTypeInfo->Name.Length / 2,
  295. objectTypeInfo->Name.Buffer
  296. );
  297. }
  298. free(objectTypeInfo);
  299. free(objectNameInfo);
  300. CloseHandle(dupHandle);
  301. }
  302. }
  303. }
  304. int ZZwmain(int argc, WCHAR *argv[])
  305. {
  306. _NtQuerySystemInformation NtQuerySystemInformation = (_NtQuerySystemInformation)
  307. GetLibraryProcAddress("ntdll.dll", "NtQuerySystemInformation");
  308. _NtDuplicateObject NtDuplicateObject = (_NtDuplicateObject)
  309. GetLibraryProcAddress("ntdll.dll", "NtDuplicateObject");
  310. _NtQueryObject NtQueryObject = (_NtQueryObject)
  311. GetLibraryProcAddress("ntdll.dll", "NtQueryObject");
  312. NTSTATUS status;
  313. PSYSTEM_HANDLE_INFORMATION handleInfo;
  314. ULONG handleInfoSize = 0x10000;
  315. ULONG pid;
  316. HANDLE processHandle;
  317. ULONG i;
  318. if (argc < 2)
  319. {
  320. printf("Usage: handles [pid]\n");
  321. return 1;
  322. }
  323. pid = _wtoi(argv[1]);
  324. if (!(processHandle = OpenProcess(PROCESS_DUP_HANDLE, FALSE, pid)))
  325. {
  326. printf("Could not open PID %d! (Don't try to open a system process.)\n", pid);
  327. return 1;
  328. }
  329. handleInfo = (PSYSTEM_HANDLE_INFORMATION)malloc(handleInfoSize);
  330. /* NtQuerySystemInformation won't give us the correct buffer size,
  331. so we guess by doubling the buffer size. */
  332. while ((status = NtQuerySystemInformation(
  333. SystemHandleInformation,
  334. handleInfo,
  335. handleInfoSize,
  336. NULL
  337. )) == STATUS_INFO_LENGTH_MISMATCH)
  338. handleInfo = (PSYSTEM_HANDLE_INFORMATION)realloc(handleInfo, handleInfoSize *= 2);
  339. /* NtQuerySystemInformation stopped giving us STATUS_INFO_LENGTH_MISMATCH. */
  340. if (!NT_SUCCESS(status))
  341. {
  342. printf("NtQuerySystemInformation failed!\n");
  343. return 1;
  344. }
  345. for (i = 0; i < handleInfo->HandleCount; i++)
  346. {
  347. SYSTEM_HANDLE handle = handleInfo->Handles[i];
  348. HANDLE dupHandle = NULL;
  349. POBJECT_TYPE_INFORMATION objectTypeInfo;
  350. PVOID objectNameInfo;
  351. UNICODE_STRING objectName;
  352. ULONG returnLength;
  353. /* Check if this handle belongs to the PID the user specified. */
  354. if (handle.ProcessId != pid)
  355. continue;
  356. /* Duplicate the handle so we can query it. */
  357. if (!NT_SUCCESS(NtDuplicateObject(
  358. processHandle,
  359. (HANDLE)(uintptr)handle.Handle,
  360. GetCurrentProcess(),
  361. &dupHandle,
  362. 0,
  363. 0,
  364. 0
  365. )))
  366. {
  367. printf("[%#x] Error!\n", handle.Handle);
  368. continue;
  369. }
  370. /* Query the object type. */
  371. objectTypeInfo = (POBJECT_TYPE_INFORMATION)malloc(0x1000);
  372. if (!NT_SUCCESS(NtQueryObject(
  373. dupHandle,
  374. ObjectTypeInformation,
  375. objectTypeInfo,
  376. 0x1000,
  377. NULL
  378. )))
  379. {
  380. printf("[%#x] Error!\n", handle.Handle);
  381. CloseHandle(dupHandle);
  382. continue;
  383. }
  384. /* Query the object name (unless it has an access of
  385. 0x0012019f, on which NtQueryObject could hang. */
  386. if (handle.GrantedAccess == 0x0012019f)
  387. {
  388. /* We have the type, so display that. */
  389. printf(
  390. "[%#x] %.*S: (did not get name)\n",
  391. handle.Handle,
  392. objectTypeInfo->Name.Length / 2,
  393. objectTypeInfo->Name.Buffer
  394. );
  395. free(objectTypeInfo);
  396. CloseHandle(dupHandle);
  397. continue;
  398. }
  399. objectNameInfo = malloc(0x1000);
  400. if (!NT_SUCCESS(NtQueryObject(
  401. dupHandle,
  402. ObjectNameInformation,
  403. objectNameInfo,
  404. 0x1000,
  405. &returnLength
  406. )))
  407. {
  408. /* Reallocate the buffer and try again. */
  409. objectNameInfo = realloc(objectNameInfo, returnLength);
  410. if (!NT_SUCCESS(NtQueryObject(
  411. dupHandle,
  412. ObjectNameInformation,
  413. objectNameInfo,
  414. returnLength,
  415. NULL
  416. )))
  417. {
  418. /* We have the type name, so just display that. */
  419. printf(
  420. "[%#x] %.*S: (could not get name)\n",
  421. handle.Handle,
  422. objectTypeInfo->Name.Length / 2,
  423. objectTypeInfo->Name.Buffer
  424. );
  425. free(objectTypeInfo);
  426. free(objectNameInfo);
  427. CloseHandle(dupHandle);
  428. continue;
  429. }
  430. }
  431. /* Cast our buffer into an UNICODE_STRING. */
  432. objectName = *(PUNICODE_STRING)objectNameInfo;
  433. /* Print the information! */
  434. if (objectName.Length)
  435. {
  436. /* The object has a name. */
  437. printf(
  438. "[%#x] %.*S: %.*S\n",
  439. handle.Handle,
  440. objectTypeInfo->Name.Length / 2,
  441. objectTypeInfo->Name.Buffer,
  442. objectName.Length / 2,
  443. objectName.Buffer
  444. );
  445. }
  446. else
  447. {
  448. /* Print something else. */
  449. printf(
  450. "[%#x] %.*S: (unnamed)\n",
  451. handle.Handle,
  452. objectTypeInfo->Name.Length / 2,
  453. objectTypeInfo->Name.Buffer
  454. );
  455. }
  456. free(objectTypeInfo);
  457. free(objectNameInfo);
  458. CloseHandle(dupHandle);
  459. }
  460. free(handleInfo);
  461. CloseHandle(processHandle);
  462. return 0;
  463. }