Debian Codegraph @

psutil/arch/windows/proc.c

raw
1 /*
2 * Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
3 * Use of this source code is governed by a BSD-style license that can be
4 * found in the LICENSE file.
5 */
6
7 /*
8 * Process related functions. Original code was moved in here from
9 * psutil/_psutil_windows.c in 2023. For reference, here's the GIT blame
10 * history before the move:
11 * https://github.com/giampaolo/psutil/blame/59504a5/psutil/_psutil_windows.c
12 */
13
14 // Fixes clash between winsock2.h and windows.h
15 #define WIN32_LEAN_AND_MEAN
16
17 #include <Python.h>
18 #include <windows.h>
19 #include <Psapi.h> // memory_info(), memory_maps()
20 #include <signal.h>
21 #include <tlhelp32.h> // threads(), PROCESSENTRY32
22
23 // Link with Iphlpapi.lib
24 #pragma comment(lib, "IPHLPAPI.lib")
25
26 #include "../../arch/all/init.h"
27
28
29 // Raised by Process.wait().
30 PyObject *TimeoutExpired;
31 PyObject *TimeoutAbandoned;
32
33
34 /*
35 * Return 1 if PID exists in the current process list, else 0.
36 */
37 PyObject *
38 psutil_pid_exists(PyObject *self, PyObject *args) {
39 DWORD pid;
40 int status;
41
42 if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
43 return NULL;
44
45 status = psutil_pid_is_running(pid);
46 if (-1 == status)
47 return NULL; // exception raised in psutil_pid_is_running()
48 return PyBool_FromLong(status);
49 }
50
51
52 /*
53 * Return a Python list of all the PIDs running on the system.
54 */
55 PyObject *
56 psutil_pids(PyObject *self, PyObject *args) {
57 DWORD *proclist = NULL;
58 DWORD numberOfReturnedPIDs;
59 DWORD i;
60 PyObject *py_pid = NULL;
61 PyObject *py_retlist = PyList_New(0);
62
63 if (py_retlist == NULL)
64 return NULL;
65 proclist = psutil_get_pids(&numberOfReturnedPIDs);
66 if (proclist == NULL)
67 goto error;
68
69 for (i = 0; i < numberOfReturnedPIDs; i++) {
70 py_pid = PyLong_FromPid(proclist[i]);
71 if (!py_pid)
72 goto error;
73 if (PyList_Append(py_retlist, py_pid))
74 goto error;
75 Py_CLEAR(py_pid);
76 }
77
78 // free C array allocated for PIDs
79 free(proclist);
80 return py_retlist;
81
82 error:
83 Py_XDECREF(py_pid);
84 Py_DECREF(py_retlist);
85 if (proclist != NULL)
86 free(proclist);
87 return NULL;
88 }
89
90
91 /*
92 * Kill a process given its PID.
93 */
94 PyObject *
95 psutil_proc_kill(PyObject *self, PyObject *args) {
96 HANDLE hProcess;
97 DWORD pid;
98 DWORD access = PROCESS_TERMINATE | PROCESS_QUERY_LIMITED_INFORMATION;
99
100 if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
101 return NULL;
102 if (pid == 0)
103 return AccessDenied("automatically set for PID 0");
104
105 hProcess = psutil_handle_from_pid(pid, access);
106 if (hProcess == NULL) {
107 return NULL;
108 }
109
110 if (! TerminateProcess(hProcess, SIGTERM)) {
111 // ERROR_ACCESS_DENIED may happen if the process already died. See:
112 // https://github.com/giampaolo/psutil/issues/1099
113 // http://bugs.python.org/issue14252
114 if (GetLastError() != ERROR_ACCESS_DENIED) {
115 psutil_PyErr_SetFromOSErrnoWithSyscall("TerminateProcess");
116 return NULL;
117 }
118 }
119
120 CloseHandle(hProcess);
121 Py_RETURN_NONE;
122 }
123
124
125 /*
126 * Wait for process to terminate and return its exit code.
127 */
128 PyObject *
129 psutil_proc_wait(PyObject *self, PyObject *args) {
130 HANDLE hProcess;
131 DWORD ExitCode;
132 DWORD retVal;
133 DWORD pid;
134 long timeout;
135
136 if (! PyArg_ParseTuple(args, _Py_PARSE_PID "l", &pid, &timeout))
137 return NULL;
138 if (pid == 0)
139 return AccessDenied("automatically set for PID 0");
140
141 hProcess = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
142 FALSE, pid);
143 if (hProcess == NULL) {
144 if (GetLastError() == ERROR_INVALID_PARAMETER) {
145 // no such process; we do not want to raise NSP but
146 // return None instead.
147 Py_RETURN_NONE;
148 }
149 else {
150 psutil_PyErr_SetFromOSErrnoWithSyscall("OpenProcess");
151 return NULL;
152 }
153 }
154
155 // wait until the process has terminated
156 Py_BEGIN_ALLOW_THREADS
157 retVal = WaitForSingleObject(hProcess, timeout);
158 Py_END_ALLOW_THREADS
159
160 // handle return code
161 if (retVal == WAIT_FAILED) {
162 psutil_PyErr_SetFromOSErrnoWithSyscall("WaitForSingleObject");
163 CloseHandle(hProcess);
164 return NULL;
165 }
166 if (retVal == WAIT_TIMEOUT) {
167 PyErr_SetString(TimeoutExpired,
168 "WaitForSingleObject() returned WAIT_TIMEOUT");
169 CloseHandle(hProcess);
170 return NULL;
171 }
172 if (retVal == WAIT_ABANDONED) {
173 psutil_debug("WaitForSingleObject() -> WAIT_ABANDONED");
174 PyErr_SetString(TimeoutAbandoned,
175 "WaitForSingleObject() returned WAIT_ABANDONED");
176 CloseHandle(hProcess);
177 return NULL;
178 }
179
180 // WaitForSingleObject() returned WAIT_OBJECT_0. It means the
181 // process is gone so we can get its process exit code. The PID
182 // may still stick around though but we'll handle that from Python.
183 if (GetExitCodeProcess(hProcess, &ExitCode) == 0) {
184 psutil_PyErr_SetFromOSErrnoWithSyscall("GetExitCodeProcess");
185 CloseHandle(hProcess);
186 return NULL;
187 }
188
189 CloseHandle(hProcess);
190
191 return PyLong_FromLong((long) ExitCode);
192 }
193
194
195 /*
196 * Return a Python tuple (user_time, kernel_time)
197 */
198 PyObject *
199 psutil_proc_times(PyObject *self, PyObject *args) {
200 DWORD pid;
201 HANDLE hProcess;
202 FILETIME ftCreate, ftExit, ftKernel, ftUser;
203
204 if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
205 return NULL;
206
207 hProcess = psutil_handle_from_pid(pid, PROCESS_QUERY_LIMITED_INFORMATION);
208
209 if (hProcess == NULL)
210 return NULL;
211 if (! GetProcessTimes(hProcess, &ftCreate, &ftExit, &ftKernel, &ftUser)) {
212 if (GetLastError() == ERROR_ACCESS_DENIED) {
213 // usually means the process has died so we throw a NoSuchProcess
214 // here
215 NoSuchProcess("GetProcessTimes -> ERROR_ACCESS_DENIED");
216 }
217 else {
218 PyErr_SetFromWindowsErr(0);
219 }
220 CloseHandle(hProcess);
221 return NULL;
222 }
223
224 CloseHandle(hProcess);
225
226 /*
227 * User and kernel times are represented as a FILETIME structure
228 * which contains a 64-bit value representing the number of
229 * 100-nanosecond intervals since January 1, 1601 (UTC):
230 * http://msdn.microsoft.com/en-us/library/ms724284(VS.85).aspx
231 * To convert it into a float representing the seconds that the
232 * process has executed in user/kernel mode I borrowed the code
233 * below from Python's Modules/posixmodule.c
234 */
235 return Py_BuildValue(
236 "(ddd)",
237 (double)(ftUser.dwHighDateTime * HI_T + \
238 ftUser.dwLowDateTime * LO_T),
239 (double)(ftKernel.dwHighDateTime * HI_T + \
240 ftKernel.dwLowDateTime * LO_T),
241 psutil_FiletimeToUnixTime(ftCreate)
242 );
243 }
244
245
246 /*
247 * Return process executable path. Works for all processes regardless of
248 * privilege. NtQuerySystemInformation has some sort of internal cache,
249 * since it succeeds even when a process is gone (but not if a PID never
250 * existed).
251 */
252 PyObject *
253 psutil_proc_exe(PyObject *self, PyObject *args) {
254 DWORD pid;
255 NTSTATUS status;
256 PVOID buffer = NULL;
257 ULONG bufferSize = 0x104 * 2; // WIN_MAX_PATH * sizeof(wchar_t)
258 SYSTEM_PROCESS_ID_INFORMATION processIdInfo;
259 PyObject *py_exe;
260
261 if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
262 return NULL;
263
264 if (pid == 0)
265 return AccessDenied("automatically set for PID 0");
266
267 // ...because NtQuerySystemInformation can succeed for terminated
268 // processes.
269 if (psutil_pid_is_running(pid) == 0)
270 return NoSuchProcess("psutil_pid_is_running -> 0");
271
272 buffer = MALLOC_ZERO(bufferSize);
273 if (! buffer) {
274 PyErr_NoMemory();
275 return NULL;
276 }
277
278 processIdInfo.ProcessId = (HANDLE)(ULONG_PTR)pid;
279 processIdInfo.ImageName.Length = 0;
280 processIdInfo.ImageName.MaximumLength = (USHORT)bufferSize;
281 processIdInfo.ImageName.Buffer = buffer;
282
283 status = NtQuerySystemInformation(
284 SystemProcessIdInformation,
285 &processIdInfo,
286 sizeof(SYSTEM_PROCESS_ID_INFORMATION),
287 NULL);
288
289 if ((status == STATUS_INFO_LENGTH_MISMATCH) &&
290 (processIdInfo.ImageName.MaximumLength <= bufferSize))
291 {
292 // Required length was NOT stored in MaximumLength (WOW64 issue).
293 ULONG maxBufferSize = 0x7FFF * 2; // NTFS_MAX_PATH * sizeof(wchar_t)
294 do {
295 // Iteratively double the size of the buffer up to maxBufferSize
296 bufferSize *= 2;
297 FREE(buffer);
298 buffer = MALLOC_ZERO(bufferSize);
299 if (! buffer) {
300 PyErr_NoMemory();
301 return NULL;
302 }
303
304 processIdInfo.ImageName.MaximumLength = (USHORT)bufferSize;
305 processIdInfo.ImageName.Buffer = buffer;
306
307 status = NtQuerySystemInformation(
308 SystemProcessIdInformation,
309 &processIdInfo,
310 sizeof(SYSTEM_PROCESS_ID_INFORMATION),
311 NULL);
312 } while ((status == STATUS_INFO_LENGTH_MISMATCH) &&
313 (bufferSize <= maxBufferSize));
314 }
315 else if (status == STATUS_INFO_LENGTH_MISMATCH) {
316 // Required length is stored in MaximumLength.
317 FREE(buffer);
318 buffer = MALLOC_ZERO(processIdInfo.ImageName.MaximumLength);
319 if (! buffer) {
320 PyErr_NoMemory();
321 return NULL;
322 }
323
324 processIdInfo.ImageName.Buffer = buffer;
325
326 status = NtQuerySystemInformation(
327 SystemProcessIdInformation,
328 &processIdInfo,
329 sizeof(SYSTEM_PROCESS_ID_INFORMATION),
330 NULL);
331 }
332
333 if (! NT_SUCCESS(status)) {
334 FREE(buffer);
335 if (psutil_pid_is_running(pid) == 0)
336 NoSuchProcess("psutil_pid_is_running -> 0");
337 else
338 psutil_SetFromNTStatusErr(status, "NtQuerySystemInformation");
339 return NULL;
340 }
341
342 if (processIdInfo.ImageName.Buffer == NULL) {
343 // Happens for PID 4.
344 py_exe = Py_BuildValue("s", "");
345 }
346 else {
347 py_exe = PyUnicode_FromWideChar(processIdInfo.ImageName.Buffer,
348 processIdInfo.ImageName.Length / 2);
349 }
350 FREE(buffer);
351 return py_exe;
352 }
353
354
355 /*
356 * Return process memory information as a Python tuple.
357 */
358 PyObject *
359 psutil_proc_memory_info(PyObject *self, PyObject *args) {
360 HANDLE hProcess;
361 DWORD pid;
362 PROCESS_MEMORY_COUNTERS_EX cnt;
363
364 if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
365 return NULL;
366
367 hProcess = psutil_handle_from_pid(pid, PROCESS_QUERY_LIMITED_INFORMATION);
368 if (NULL == hProcess)
369 return NULL;
370
371 if (! GetProcessMemoryInfo(hProcess, (PPROCESS_MEMORY_COUNTERS)&cnt,
372 sizeof(cnt))) {
373 PyErr_SetFromWindowsErr(0);
374 CloseHandle(hProcess);
375 return NULL;
376 }
377 CloseHandle(hProcess);
378
379 // PROCESS_MEMORY_COUNTERS values are defined as SIZE_T which on 64bits
380 // is an (unsigned long long) and on 32bits is an (unsigned int).
381 // "_WIN64" is defined if we're running a 64bit Python interpreter not
382 // exclusively if the *system* is 64bit.
383 #if defined(_WIN64)
384 return Py_BuildValue(
385 "(kKKKKKKKKK)",
386 cnt.PageFaultCount, // unsigned long
387 (unsigned long long)cnt.PeakWorkingSetSize,
388 (unsigned long long)cnt.WorkingSetSize,
389 (unsigned long long)cnt.QuotaPeakPagedPoolUsage,
390 (unsigned long long)cnt.QuotaPagedPoolUsage,
391 (unsigned long long)cnt.QuotaPeakNonPagedPoolUsage,
392 (unsigned long long)cnt.QuotaNonPagedPoolUsage,
393 (unsigned long long)cnt.PagefileUsage,
394 (unsigned long long)cnt.PeakPagefileUsage,
395 (unsigned long long)cnt.PrivateUsage);
396 #else
397 return Py_BuildValue(
398 "(kIIIIIIIII)",
399 cnt.PageFaultCount, // unsigned long
400 (unsigned int)cnt.PeakWorkingSetSize,
401 (unsigned int)cnt.WorkingSetSize,
402 (unsigned int)cnt.QuotaPeakPagedPoolUsage,
403 (unsigned int)cnt.QuotaPagedPoolUsage,
404 (unsigned int)cnt.QuotaPeakNonPagedPoolUsage,
405 (unsigned int)cnt.QuotaNonPagedPoolUsage,
406 (unsigned int)cnt.PagefileUsage,
407 (unsigned int)cnt.PeakPagefileUsage,
408 (unsigned int)cnt.PrivateUsage);
409 #endif
410 }
411
412
413 static int
414 psutil_GetProcWsetInformation(
415 DWORD pid,
416 HANDLE hProcess,
417 PMEMORY_WORKING_SET_INFORMATION *wSetInfo)
418 {
419 NTSTATUS status;
420 PVOID buffer;
421 SIZE_T bufferSize;
422
423 bufferSize = 0x8000;
424 buffer = MALLOC_ZERO(bufferSize);
425 if (! buffer) {
426 PyErr_NoMemory();
427 return 1;
428 }
429
430 while ((status = NtQueryVirtualMemory(
431 hProcess,
432 NULL,
433 MemoryWorkingSetInformation,
434 buffer,
435 bufferSize,
436 NULL)) == STATUS_INFO_LENGTH_MISMATCH)
437 {
438 FREE(buffer);
439 bufferSize *= 2;
440 // Fail if we're resizing the buffer to something very large.
441 if (bufferSize > 256 * 1024 * 1024) {
442 PyErr_SetString(PyExc_RuntimeError,
443 "NtQueryVirtualMemory bufsize is too large");
444 return 1;
445 }
446 buffer = MALLOC_ZERO(bufferSize);
447 if (! buffer) {
448 PyErr_NoMemory();
449 return 1;
450 }
451 }
452
453 if (!NT_SUCCESS(status)) {
454 if (status == STATUS_ACCESS_DENIED) {
455 AccessDenied("NtQueryVirtualMemory -> STATUS_ACCESS_DENIED");
456 }
457 else if (psutil_pid_is_running(pid) == 0) {
458 NoSuchProcess("psutil_pid_is_running -> 0");
459 }
460 else {
461 PyErr_Clear();
462 psutil_SetFromNTStatusErr(
463 status, "NtQueryVirtualMemory(MemoryWorkingSetInformation)");
464 }
465 HeapFree(GetProcessHeap(), 0, buffer);
466 return 1;
467 }
468
469 *wSetInfo = (PMEMORY_WORKING_SET_INFORMATION)buffer;
470 return 0;
471 }
472
473
474 /*
475 * Returns the USS of the process.
476 * Reference:
477 * https://dxr.mozilla.org/mozilla-central/source/xpcom/base/
478 * nsMemoryReporterManager.cpp
479 */
480 PyObject *
481 psutil_proc_memory_uss(PyObject *self, PyObject *args) {
482 DWORD pid;
483 HANDLE hProcess;
484 PSUTIL_PROCESS_WS_COUNTERS wsCounters;
485 PMEMORY_WORKING_SET_INFORMATION wsInfo;
486 ULONG_PTR i;
487
488 if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
489 return NULL;
490 hProcess = psutil_handle_from_pid(pid, PROCESS_QUERY_INFORMATION);
491 if (hProcess == NULL)
492 return NULL;
493
494 if (psutil_GetProcWsetInformation(pid, hProcess, &wsInfo) != 0) {
495 CloseHandle(hProcess);
496 return NULL;
497 }
498 memset(&wsCounters, 0, sizeof(PSUTIL_PROCESS_WS_COUNTERS));
499
500 for (i = 0; i < wsInfo->NumberOfEntries; i++) {
501 // This is what ProcessHacker does.
502 /*
503 wsCounters.NumberOfPages++;
504 if (wsInfo->WorkingSetInfo[i].ShareCount > 1)
505 wsCounters.NumberOfSharedPages++;
506 if (wsInfo->WorkingSetInfo[i].ShareCount == 0)
507 wsCounters.NumberOfPrivatePages++;
508 if (wsInfo->WorkingSetInfo[i].Shared)
509 wsCounters.NumberOfShareablePages++;
510 */
511
512 // This is what we do: count shared pages that only one process
513 // is using as private (USS).
514 if (!wsInfo->WorkingSetInfo[i].Shared ||
515 wsInfo->WorkingSetInfo[i].ShareCount <= 1) {
516 wsCounters.NumberOfPrivatePages++;
517 }
518 }
519
520 HeapFree(GetProcessHeap(), 0, wsInfo);
521 CloseHandle(hProcess);
522
523 return Py_BuildValue("I", wsCounters.NumberOfPrivatePages);
524 }
525
526
527 /*
528 * Resume or suspends a process
529 */
530 PyObject *
531 psutil_proc_suspend_or_resume(PyObject *self, PyObject *args) {
532 DWORD pid;
533 NTSTATUS status;
534 HANDLE hProcess;
535 DWORD access = PROCESS_SUSPEND_RESUME | PROCESS_QUERY_LIMITED_INFORMATION;
536 PyObject* suspend;
537
538 if (! PyArg_ParseTuple(args, _Py_PARSE_PID "O", &pid, &suspend))
539 return NULL;
540
541 hProcess = psutil_handle_from_pid(pid, access);
542 if (hProcess == NULL)
543 return NULL;
544
545 if (PyObject_IsTrue(suspend))
546 status = NtSuspendProcess(hProcess);
547 else
548 status = NtResumeProcess(hProcess);
549
550 if (! NT_SUCCESS(status)) {
551 CloseHandle(hProcess);
552 return psutil_SetFromNTStatusErr(status, "NtSuspend|ResumeProcess");
553 }
554
555 CloseHandle(hProcess);
556 Py_RETURN_NONE;
557 }
558
559
560 PyObject *
561 psutil_proc_threads(PyObject *self, PyObject *args) {
562 HANDLE hThread = NULL;
563 THREADENTRY32 te32 = {0};
564 DWORD pid;
565 int pid_return;
566 int rc;
567 FILETIME ftDummy, ftKernel, ftUser;
568 HANDLE hThreadSnap = NULL;
569 PyObject *py_tuple = NULL;
570 PyObject *py_retlist = PyList_New(0);
571
572 if (py_retlist == NULL)
573 return NULL;
574 if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
575 goto error;
576 if (pid == 0) {
577 // raise AD instead of returning 0 as procexp is able to
578 // retrieve useful information somehow
579 AccessDenied("forced for PID 0");
580 goto error;
581 }
582
583 pid_return = psutil_pid_is_running(pid);
584 if (pid_return == 0) {
585 NoSuchProcess("psutil_pid_is_running -> 0");
586 goto error;
587 }
588 if (pid_return == -1)
589 goto error;
590
591 hThreadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
592 if (hThreadSnap == INVALID_HANDLE_VALUE) {
593 psutil_PyErr_SetFromOSErrnoWithSyscall("CreateToolhelp32Snapshot");
594 goto error;
595 }
596
597 // Fill in the size of the structure before using it
598 te32.dwSize = sizeof(THREADENTRY32);
599
600 if (! Thread32First(hThreadSnap, &te32)) {
601 psutil_PyErr_SetFromOSErrnoWithSyscall("Thread32First");
602 goto error;
603 }
604
605 // Walk the thread snapshot to find all threads of the process.
606 // If the thread belongs to the process, increase the counter.
607 do {
608 if (te32.th32OwnerProcessID == pid) {
609 py_tuple = NULL;
610 hThread = NULL;
611 hThread = OpenThread(THREAD_QUERY_INFORMATION,
612 FALSE, te32.th32ThreadID);
613 if (hThread == NULL) {
614 // thread has disappeared on us
615 continue;
616 }
617
618 rc = GetThreadTimes(hThread, &ftDummy, &ftDummy, &ftKernel,
619 &ftUser);
620 if (rc == 0) {
621 psutil_PyErr_SetFromOSErrnoWithSyscall("GetThreadTimes");
622 goto error;
623 }
624
625 /*
626 * User and kernel times are represented as a FILETIME structure
627 * which contains a 64-bit value representing the number of
628 * 100-nanosecond intervals since January 1, 1601 (UTC):
629 * http://msdn.microsoft.com/en-us/library/ms724284(VS.85).aspx
630 * To convert it into a float representing the seconds that the
631 * process has executed in user/kernel mode I borrowed the code
632 * below from Python's Modules/posixmodule.c
633 */
634 py_tuple = Py_BuildValue(
635 "kdd",
636 te32.th32ThreadID,
637 (double)(ftUser.dwHighDateTime * HI_T + \
638 ftUser.dwLowDateTime * LO_T),
639 (double)(ftKernel.dwHighDateTime * HI_T + \
640 ftKernel.dwLowDateTime * LO_T));
641 if (!py_tuple)
642 goto error;
643 if (PyList_Append(py_retlist, py_tuple))
644 goto error;
645 Py_CLEAR(py_tuple);
646
647 CloseHandle(hThread);
648 }
649 } while (Thread32Next(hThreadSnap, &te32));
650
651 CloseHandle(hThreadSnap);
652 return py_retlist;
653
654 error:
655 Py_XDECREF(py_tuple);
656 Py_DECREF(py_retlist);
657 if (hThread != NULL)
658 CloseHandle(hThread);
659 if (hThreadSnap != NULL)
660 CloseHandle(hThreadSnap);
661 return NULL;
662 }
663
664
665 PyObject *
666 psutil_proc_open_files(PyObject *self, PyObject *args) {
667 DWORD pid;
668 HANDLE processHandle;
669 DWORD access = PROCESS_DUP_HANDLE | PROCESS_QUERY_INFORMATION;
670 PyObject *py_retlist;
671
672 if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
673 return NULL;
674
675 processHandle = psutil_handle_from_pid(pid, access);
676 if (processHandle == NULL)
677 return NULL;
678
679 py_retlist = psutil_get_open_files(pid, processHandle);
680 CloseHandle(processHandle);
681 return py_retlist;
682 }
683
684
685 static PTOKEN_USER
686 _psutil_user_token_from_pid(DWORD pid) {
687 HANDLE hProcess = NULL;
688 HANDLE hToken = NULL;
689 PTOKEN_USER userToken = NULL;
690 ULONG bufferSize = 0x100;
691
692 hProcess = psutil_handle_from_pid(pid, PROCESS_QUERY_LIMITED_INFORMATION);
693 if (hProcess == NULL)
694 return NULL;
695
696 if (!OpenProcessToken(hProcess, TOKEN_QUERY, &hToken)) {
697 psutil_PyErr_SetFromOSErrnoWithSyscall("OpenProcessToken");
698 goto error;
699 }
700
701 // Get the user SID.
702 while (1) {
703 userToken = malloc(bufferSize);
704 if (userToken == NULL) {
705 PyErr_NoMemory();
706 goto error;
707 }
708 if (!GetTokenInformation(hToken, TokenUser, userToken, bufferSize,
709 &bufferSize))
710 {
711 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
712 free(userToken);
713 continue;
714 }
715 else {
716 psutil_PyErr_SetFromOSErrnoWithSyscall("GetTokenInformation");
717 goto error;
718 }
719 }
720 break;
721 }
722
723 CloseHandle(hProcess);
724 CloseHandle(hToken);
725 return userToken;
726
727 error:
728 if (hProcess != NULL)
729 CloseHandle(hProcess);
730 if (hToken != NULL)
731 CloseHandle(hToken);
732 return NULL;
733 }
734
735
736 /*
737 * Return process username as a "DOMAIN//USERNAME" string.
738 */
739 PyObject *
740 psutil_proc_username(PyObject *self, PyObject *args) {
741 DWORD pid;
742 PTOKEN_USER userToken = NULL;
743 WCHAR *userName = NULL;
744 WCHAR *domainName = NULL;
745 ULONG nameSize = 0x100;
746 ULONG domainNameSize = 0x100;
747 SID_NAME_USE nameUse;
748 PyObject *py_username = NULL;
749 PyObject *py_domain = NULL;
750 PyObject *py_tuple = NULL;
751
752 if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
753 return NULL;
754 userToken = _psutil_user_token_from_pid(pid);
755 if (userToken == NULL)
756 return NULL;
757
758 // resolve the SID to a name
759 while (1) {
760 userName = malloc(nameSize * sizeof(WCHAR));
761 if (userName == NULL) {
762 PyErr_NoMemory();
763 goto error;
764 }
765 domainName = malloc(domainNameSize * sizeof(WCHAR));
766 if (domainName == NULL) {
767 PyErr_NoMemory();
768 goto error;
769 }
770 if (!LookupAccountSidW(NULL, userToken->User.Sid, userName, &nameSize,
771 domainName, &domainNameSize, &nameUse))
772 {
773 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
774 free(userName);
775 free(domainName);
776 continue;
777 }
778 else if (GetLastError() == ERROR_NONE_MAPPED) {
779 // From MS doc:
780 // https://docs.microsoft.com/en-us/windows/win32/api/winbase/
781 // nf-winbase-lookupaccountsida
782 // If the function cannot find an account name for the SID,
783 // GetLastError returns ERROR_NONE_MAPPED. This can occur if
784 // a network time-out prevents the function from finding the
785 // name. It also occurs for SIDs that have no corresponding
786 // account name, such as a logon SID that identifies a logon
787 // session.
788 AccessDenied("LookupAccountSidW -> ERROR_NONE_MAPPED");
789 goto error;
790 }
791 else {
792 psutil_PyErr_SetFromOSErrnoWithSyscall("LookupAccountSidW");
793 goto error;
794 }
795 }
796 break;
797 }
798
799 py_domain = PyUnicode_FromWideChar(domainName, wcslen(domainName));
800 if (! py_domain)
801 goto error;
802 py_username = PyUnicode_FromWideChar(userName, wcslen(userName));
803 if (! py_username)
804 goto error;
805 py_tuple = Py_BuildValue("OO", py_domain, py_username);
806 if (! py_tuple)
807 goto error;
808 Py_DECREF(py_domain);
809 Py_DECREF(py_username);
810
811 free(userName);
812 free(domainName);
813 free(userToken);
814 return py_tuple;
815
816 error:
817 if (userName != NULL)
818 free(userName);
819 if (domainName != NULL)
820 free(domainName);
821 if (userToken != NULL)
822 free(userToken);
823 Py_XDECREF(py_domain);
824 Py_XDECREF(py_username);
825 Py_XDECREF(py_tuple);
826 return NULL;
827 }
828
829
830 /*
831 * Get process priority as a Python integer.
832 */
833 PyObject *
834 psutil_proc_priority_get(PyObject *self, PyObject *args) {
835 DWORD pid;
836 DWORD priority;
837 HANDLE hProcess;
838
839 if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
840 return NULL;
841
842 hProcess = psutil_handle_from_pid(pid, PROCESS_QUERY_LIMITED_INFORMATION);
843 if (hProcess == NULL)
844 return NULL;
845
846 priority = GetPriorityClass(hProcess);
847 if (priority == 0) {
848 PyErr_SetFromWindowsErr(0);
849 CloseHandle(hProcess);
850 return NULL;
851 }
852 CloseHandle(hProcess);
853 return Py_BuildValue("i", priority);
854 }
855
856
857 /*
858 * Set process priority.
859 */
860 PyObject *
861 psutil_proc_priority_set(PyObject *self, PyObject *args) {
862 DWORD pid;
863 int priority;
864 int retval;
865 HANDLE hProcess;
866 DWORD access = PROCESS_QUERY_INFORMATION | PROCESS_SET_INFORMATION;
867
868 if (! PyArg_ParseTuple(args, _Py_PARSE_PID "i", &pid, &priority))
869 return NULL;
870 hProcess = psutil_handle_from_pid(pid, access);
871 if (hProcess == NULL)
872 return NULL;
873
874 retval = SetPriorityClass(hProcess, priority);
875 if (retval == 0) {
876 PyErr_SetFromWindowsErr(0);
877 CloseHandle(hProcess);
878 return NULL;
879 }
880
881 CloseHandle(hProcess);
882 Py_RETURN_NONE;
883 }
884
885
886 /*
887 * Get process IO priority as a Python integer.
888 */
889 PyObject *
890 psutil_proc_io_priority_get(PyObject *self, PyObject *args) {
891 DWORD pid;
892 HANDLE hProcess;
893 DWORD IoPriority;
894 NTSTATUS status;
895
896 if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
897 return NULL;
898
899 hProcess = psutil_handle_from_pid(pid, PROCESS_QUERY_LIMITED_INFORMATION);
900 if (hProcess == NULL)
901 return NULL;
902
903 status = NtQueryInformationProcess(
904 hProcess,
905 ProcessIoPriority,
906 &IoPriority,
907 sizeof(DWORD),
908 NULL
909 );
910
911 CloseHandle(hProcess);
912 if (! NT_SUCCESS(status))
913 return psutil_SetFromNTStatusErr(status, "NtQueryInformationProcess");
914 return Py_BuildValue("i", IoPriority);
915 }
916
917
918 /*
919 * Set process IO priority.
920 */
921 PyObject *
922 psutil_proc_io_priority_set(PyObject *self, PyObject *args) {
923 DWORD pid;
924 DWORD prio;
925 HANDLE hProcess;
926 NTSTATUS status;
927 DWORD access = PROCESS_QUERY_INFORMATION | PROCESS_SET_INFORMATION;
928
929 if (! PyArg_ParseTuple(args, _Py_PARSE_PID "i", &pid, &prio))
930 return NULL;
931
932 hProcess = psutil_handle_from_pid(pid, access);
933 if (hProcess == NULL)
934 return NULL;
935
936 status = NtSetInformationProcess(
937 hProcess,
938 ProcessIoPriority,
939 (PVOID)&prio,
940 sizeof(DWORD)
941 );
942
943 CloseHandle(hProcess);
944 if (! NT_SUCCESS(status))
945 return psutil_SetFromNTStatusErr(status, "NtSetInformationProcess");
946 Py_RETURN_NONE;
947 }
948
949
950 /*
951 * Return a Python tuple referencing process I/O counters.
952 */
953 PyObject *
954 psutil_proc_io_counters(PyObject *self, PyObject *args) {
955 DWORD pid;
956 HANDLE hProcess;
957 IO_COUNTERS IoCounters;
958
959 if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
960 return NULL;
961 hProcess = psutil_handle_from_pid(pid, PROCESS_QUERY_LIMITED_INFORMATION);
962 if (NULL == hProcess)
963 return NULL;
964
965 if (! GetProcessIoCounters(hProcess, &IoCounters)) {
966 PyErr_SetFromWindowsErr(0);
967 CloseHandle(hProcess);
968 return NULL;
969 }
970
971 CloseHandle(hProcess);
972 return Py_BuildValue("(KKKKKK)",
973 IoCounters.ReadOperationCount,
974 IoCounters.WriteOperationCount,
975 IoCounters.ReadTransferCount,
976 IoCounters.WriteTransferCount,
977 IoCounters.OtherOperationCount,
978 IoCounters.OtherTransferCount);
979 }
980
981
982 /*
983 * Return process CPU affinity as a bitmask
984 */
985 PyObject *
986 psutil_proc_cpu_affinity_get(PyObject *self, PyObject *args) {
987 DWORD pid;
988 HANDLE hProcess;
989 DWORD_PTR proc_mask;
990 DWORD_PTR system_mask;
991
992 if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
993 return NULL;
994 hProcess = psutil_handle_from_pid(pid, PROCESS_QUERY_LIMITED_INFORMATION);
995 if (hProcess == NULL) {
996 return NULL;
997 }
998 if (GetProcessAffinityMask(hProcess, &proc_mask, &system_mask) == 0) {
999 PyErr_SetFromWindowsErr(0);
1000 CloseHandle(hProcess);
1001 return NULL;
1002 }
1003
1004 CloseHandle(hProcess);
1005 #ifdef _WIN64
1006 return Py_BuildValue("K", (unsigned long long)proc_mask);
1007 #else
1008 return Py_BuildValue("k", (unsigned long)proc_mask);
1009 #endif
1010 }
1011
1012
1013 /*
1014 * Set process CPU affinity
1015 */
1016 PyObject *
1017 psutil_proc_cpu_affinity_set(PyObject *self, PyObject *args) {
1018 DWORD pid;
1019 HANDLE hProcess;
1020 DWORD access = PROCESS_QUERY_INFORMATION | PROCESS_SET_INFORMATION;
1021 DWORD_PTR mask;
1022
1023 #ifdef _WIN64
1024 if (! PyArg_ParseTuple(args, _Py_PARSE_PID "K", &pid, &mask))
1025 #else
1026 if (! PyArg_ParseTuple(args, _Py_PARSE_PID "k", &pid, &mask))
1027 #endif
1028 {
1029 return NULL;
1030 }
1031 hProcess = psutil_handle_from_pid(pid, access);
1032 if (hProcess == NULL)
1033 return NULL;
1034
1035 if (SetProcessAffinityMask(hProcess, mask) == 0) {
1036 PyErr_SetFromWindowsErr(0);
1037 CloseHandle(hProcess);
1038 return NULL;
1039 }
1040
1041 CloseHandle(hProcess);
1042 Py_RETURN_NONE;
1043 }
1044
1045
1046 /*
1047 * Return True if all process threads are in waiting/suspended state.
1048 */
1049 PyObject *
1050 psutil_proc_is_suspended(PyObject *self, PyObject *args) {
1051 DWORD pid;
1052 ULONG i;
1053 PSYSTEM_PROCESS_INFORMATION process;
1054 PVOID buffer;
1055
1056 if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
1057 return NULL;
1058 if (! psutil_get_proc_info(pid, &process, &buffer))
1059 return NULL;
1060 for (i = 0; i < process->NumberOfThreads; i++) {
1061 if (process->Threads[i].ThreadState != Waiting ||
1062 process->Threads[i].WaitReason != Suspended)
1063 {
1064 free(buffer);
1065 Py_RETURN_FALSE;
1066 }
1067 }
1068 free(buffer);
1069 Py_RETURN_TRUE;
1070 }
1071
1072
1073 /*
1074 * Return the number of handles opened by process.
1075 */
1076 PyObject *
1077 psutil_proc_num_handles(PyObject *self, PyObject *args) {
1078 DWORD pid;
1079 HANDLE hProcess;
1080 DWORD handleCount;
1081
1082 if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
1083 return NULL;
1084 hProcess = psutil_handle_from_pid(pid, PROCESS_QUERY_LIMITED_INFORMATION);
1085 if (NULL == hProcess)
1086 return NULL;
1087 if (! GetProcessHandleCount(hProcess, &handleCount)) {
1088 PyErr_SetFromWindowsErr(0);
1089 CloseHandle(hProcess);
1090 return NULL;
1091 }
1092 CloseHandle(hProcess);
1093 return Py_BuildValue("k", handleCount);
1094 }
1095
1096
1097 static char *get_region_protection_string(ULONG protection) {
1098 switch (protection & 0xff) {
1099 case PAGE_NOACCESS:
1100 return "";
1101 case PAGE_READONLY:
1102 return "r";
1103 case PAGE_READWRITE:
1104 return "rw";
1105 case PAGE_WRITECOPY:
1106 return "wc";
1107 case PAGE_EXECUTE:
1108 return "x";
1109 case PAGE_EXECUTE_READ:
1110 return "xr";
1111 case PAGE_EXECUTE_READWRITE:
1112 return "xrw";
1113 case PAGE_EXECUTE_WRITECOPY:
1114 return "xwc";
1115 default:
1116 return "?";
1117 }
1118 }
1119
1120
1121 /*
1122 * Return a list of process's memory mappings.
1123 */
1124 PyObject *
1125 psutil_proc_memory_maps(PyObject *self, PyObject *args) {
1126 MEMORY_BASIC_INFORMATION basicInfo;
1127 DWORD pid;
1128 HANDLE hProcess = NULL;
1129 PVOID baseAddress;
1130 WCHAR mappedFileName[MAX_PATH];
1131 LPVOID maxAddr;
1132 // required by GetMappedFileNameW
1133 DWORD access = PROCESS_QUERY_INFORMATION | PROCESS_VM_READ;
1134 PyObject *py_retlist = PyList_New(0);
1135 PyObject *py_tuple = NULL;
1136 PyObject *py_str = NULL;
1137
1138 if (py_retlist == NULL)
1139 return NULL;
1140 if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
1141 goto error;
1142 hProcess = psutil_handle_from_pid(pid, access);
1143 if (NULL == hProcess)
1144 goto error;
1145
1146 maxAddr = PSUTIL_SYSTEM_INFO.lpMaximumApplicationAddress;
1147 baseAddress = NULL;
1148
1149 while (VirtualQueryEx(hProcess, baseAddress, &basicInfo,
1150 sizeof(MEMORY_BASIC_INFORMATION)))
1151 {
1152 py_tuple = NULL;
1153 if (baseAddress > maxAddr)
1154 break;
1155 if (GetMappedFileNameW(hProcess, baseAddress, mappedFileName,
1156 sizeof(mappedFileName)))
1157 {
1158 py_str = PyUnicode_FromWideChar(mappedFileName,
1159 wcslen(mappedFileName));
1160 if (py_str == NULL)
1161 goto error;
1162 #ifdef _WIN64
1163 py_tuple = Py_BuildValue(
1164 "(KsOI)",
1165 (unsigned long long)baseAddress,
1166 #else
1167 py_tuple = Py_BuildValue(
1168 "(ksOI)",
1169 (unsigned long)baseAddress,
1170 #endif
1171 get_region_protection_string(basicInfo.Protect),
1172 py_str,
1173 basicInfo.RegionSize);
1174
1175 if (!py_tuple)
1176 goto error;
1177 if (PyList_Append(py_retlist, py_tuple))
1178 goto error;
1179 Py_CLEAR(py_tuple);
1180 Py_CLEAR(py_str);
1181 }
1182 baseAddress = (PCHAR)baseAddress + basicInfo.RegionSize;
1183 }
1184
1185 CloseHandle(hProcess);
1186 return py_retlist;
1187
1188 error:
1189 Py_XDECREF(py_tuple);
1190 Py_XDECREF(py_str);
1191 Py_DECREF(py_retlist);
1192 if (hProcess != NULL)
1193 CloseHandle(hProcess);
1194 return NULL;
1195 }
1196
1197
1198 /*
1199 * Return a {pid:ppid, ...} dict for all running processes.
1200 */
1201 PyObject *
1202 psutil_ppid_map(PyObject *self, PyObject *args) {
1203 PyObject *py_pid = NULL;
1204 PyObject *py_ppid = NULL;
1205 PyObject *py_retdict = PyDict_New();
1206 HANDLE handle = NULL;
1207 PROCESSENTRY32 pe = {0};
1208 pe.dwSize = sizeof(PROCESSENTRY32);
1209
1210 if (py_retdict == NULL)
1211 return NULL;
1212 handle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
1213 if (handle == INVALID_HANDLE_VALUE) {
1214 PyErr_SetFromWindowsErr(0);
1215 Py_DECREF(py_retdict);
1216 return NULL;
1217 }
1218
1219 if (Process32First(handle, &pe)) {
1220 do {
1221 py_pid = PyLong_FromPid(pe.th32ProcessID);
1222 if (py_pid == NULL)
1223 goto error;
1224 py_ppid = PyLong_FromPid(pe.th32ParentProcessID);
1225 if (py_ppid == NULL)
1226 goto error;
1227 if (PyDict_SetItem(py_retdict, py_pid, py_ppid))
1228 goto error;
1229 Py_CLEAR(py_pid);
1230 Py_CLEAR(py_ppid);
1231 } while (Process32Next(handle, &pe));
1232 }
1233
1234 CloseHandle(handle);
1235 return py_retdict;
1236
1237 error:
1238 Py_XDECREF(py_pid);
1239 Py_XDECREF(py_ppid);
1240 Py_DECREF(py_retdict);
1241 CloseHandle(handle);
1242 return NULL;
1243 }