Debian Codegraph @

psutil/arch/windows/proc_info.c

raw
1 /*
2 * Copyright (c) 2009, Jay Loden, 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 * Helper functions related to fetching process information. Used by
7 * _psutil_windows module methods.
8 */
9
10 #include <Python.h>
11 #include <windows.h>
12
13 #include "../../arch/all/init.h"
14
15
16 #ifndef _WIN64
17 typedef NTSTATUS (NTAPI *__NtQueryInformationProcess)(
18 HANDLE ProcessHandle,
19 DWORD ProcessInformationClass,
20 PVOID ProcessInformation,
21 DWORD ProcessInformationLength,
22 PDWORD ReturnLength);
23 #endif
24
25 #define PSUTIL_FIRST_PROCESS(Processes) ( \
26 (PSYSTEM_PROCESS_INFORMATION)(Processes))
27 #define PSUTIL_NEXT_PROCESS(Process) ( \
28 ((PSYSTEM_PROCESS_INFORMATION)(Process))->NextEntryOffset ? \
29 (PSYSTEM_PROCESS_INFORMATION)((PCHAR)(Process) + \
30 ((PSYSTEM_PROCESS_INFORMATION)(Process))->NextEntryOffset) : NULL)
31
32
33 /*
34 * Given a pointer into a process's memory, figure out how much
35 * data can be read from it.
36 */
37 static int
38 psutil_get_process_region_size(HANDLE hProcess, LPCVOID src, SIZE_T *psize) {
39 MEMORY_BASIC_INFORMATION info;
40
41 if (!VirtualQueryEx(hProcess, src, &info, sizeof(info))) {
42 psutil_PyErr_SetFromOSErrnoWithSyscall("VirtualQueryEx");
43 return -1;
44 }
45
46 *psize = info.RegionSize - ((char*)src - (char*)info.BaseAddress);
47 return 0;
48 }
49
50
51 enum psutil_process_data_kind {
52 KIND_CMDLINE,
53 KIND_CWD,
54 KIND_ENVIRON,
55 };
56
57
58 static void
59 psutil_convert_winerr(ULONG err, char* syscall) {
60 char fullmsg[8192];
61
62 if (err == ERROR_NOACCESS) {
63 sprintf(fullmsg, "%s -> ERROR_NOACCESS", syscall);
64 psutil_debug(fullmsg);
65 AccessDenied(fullmsg);
66 }
67 else {
68 psutil_PyErr_SetFromOSErrnoWithSyscall(syscall);
69 }
70 }
71
72
73 static void
74 psutil_convert_ntstatus_err(NTSTATUS status, char* syscall) {
75 ULONG err;
76
77 if (NT_NTWIN32(status))
78 err = WIN32_FROM_NTSTATUS(status);
79 else
80 err = RtlNtStatusToDosErrorNoTeb(status);
81 psutil_convert_winerr(err, syscall);
82 }
83
84
85 static void
86 psutil_giveup_with_ad(NTSTATUS status, char* syscall) {
87 ULONG err;
88 char fullmsg[8192];
89
90 if (NT_NTWIN32(status))
91 err = WIN32_FROM_NTSTATUS(status);
92 else
93 err = RtlNtStatusToDosErrorNoTeb(status);
94 sprintf(fullmsg, "%s -> %lu (%s)", syscall, err, strerror(err));
95 psutil_debug(fullmsg);
96 AccessDenied(fullmsg);
97 }
98
99
100 /*
101 * Get data from the process with the given pid. The data is returned
102 * in the pdata output member as a nul terminated string which must be
103 * freed on success.
104 * On success 0 is returned. On error the output parameter is not touched,
105 * -1 is returned, and an appropriate Python exception is set.
106 */
107 static int
108 psutil_get_process_data(DWORD pid,
109 enum psutil_process_data_kind kind,
110 WCHAR **pdata,
111 SIZE_T *psize) {
112 /* This function is quite complex because there are several cases to be
113 considered:
114
115 Two cases are really simple: we (i.e. the python interpreter) and the
116 target process are both 32 bit or both 64 bit. In that case the memory
117 layout of the structures matches up and all is well.
118
119 When we are 64 bit and the target process is 32 bit we need to use
120 custom 32 bit versions of the structures.
121
122 When we are 32 bit and the target process is 64 bit we need to use
123 custom 64 bit version of the structures. Also we need to use separate
124 Wow64 functions to get the information.
125
126 A few helper structs are defined above so that the compiler can handle
127 calculating the correct offsets.
128
129 Additional help also came from the following sources:
130
131 https://github.com/kohsuke/winp and
132 http://wj32.org/wp/2009/01/24/howto-get-the-command-line-of-processes/
133 http://stackoverflow.com/a/14012919
134 http://www.drdobbs.com/embracing-64-bit-windows/184401966
135 */
136 SIZE_T size = 0;
137 HANDLE hProcess = NULL;
138 LPCVOID src;
139 WCHAR *buffer = NULL;
140 #ifdef _WIN64
141 LPVOID ppeb32 = NULL;
142 #else
143 static __NtQueryInformationProcess NtWow64QueryInformationProcess64 = NULL;
144 static _NtWow64ReadVirtualMemory64 NtWow64ReadVirtualMemory64 = NULL;
145 PVOID64 src64;
146 BOOL weAreWow64;
147 BOOL theyAreWow64;
148 #endif
149 DWORD access = PROCESS_QUERY_INFORMATION | PROCESS_VM_READ;
150 NTSTATUS status;
151
152 hProcess = psutil_handle_from_pid(pid, access);
153 if (hProcess == NULL)
154 return -1;
155
156 #ifdef _WIN64
157 /* 64 bit case. Check if the target is a 32 bit process running in WoW64
158 * mode. */
159 status = NtQueryInformationProcess(
160 hProcess,
161 ProcessWow64Information,
162 &ppeb32,
163 sizeof(LPVOID),
164 NULL);
165
166 if (!NT_SUCCESS(status)) {
167 psutil_SetFromNTStatusErr(
168 status, "NtQueryInformationProcess(ProcessWow64Information)");
169 goto error;
170 }
171
172 if (ppeb32 != NULL) {
173 /* We are 64 bit. Target process is 32 bit running in WoW64 mode. */
174 PEB32 peb32;
175 RTL_USER_PROCESS_PARAMETERS32 procParameters32;
176
177 // read PEB
178 if (!ReadProcessMemory(hProcess, ppeb32, &peb32, sizeof(peb32), NULL)) {
179 // May fail with ERROR_PARTIAL_COPY, see:
180 // https://github.com/giampaolo/psutil/issues/875
181 psutil_convert_winerr(GetLastError(), "ReadProcessMemory");
182 goto error;
183 }
184
185 // read process parameters
186 if (!ReadProcessMemory(hProcess,
187 UlongToPtr(peb32.ProcessParameters),
188 &procParameters32,
189 sizeof(procParameters32),
190 NULL))
191 {
192 // May fail with ERROR_PARTIAL_COPY, see:
193 // https://github.com/giampaolo/psutil/issues/875
194 psutil_convert_winerr(GetLastError(), "ReadProcessMemory");
195 goto error;
196 }
197
198 switch (kind) {
199 case KIND_CMDLINE:
200 src = UlongToPtr(procParameters32.CommandLine.Buffer),
201 size = procParameters32.CommandLine.Length;
202 break;
203 case KIND_CWD:
204 src = UlongToPtr(procParameters32.CurrentDirectoryPath.Buffer);
205 size = procParameters32.CurrentDirectoryPath.Length;
206 break;
207 case KIND_ENVIRON:
208 src = UlongToPtr(procParameters32.env);
209 break;
210 }
211 } else
212 #else // #ifdef _WIN64
213 // 32 bit process. In here we may run into a lot of errors, e.g.:
214 // * [Error 0] The operation completed successfully
215 // (originated from NtWow64ReadVirtualMemory64)
216 // * [Error 998] Invalid access to memory location:
217 // (originated from NtWow64ReadVirtualMemory64)
218 // Refs:
219 // * https://github.com/giampaolo/psutil/issues/1839
220 // * https://github.com/giampaolo/psutil/pull/1866
221 // Since the following code is quite hackish and fails unpredictably,
222 // in case of any error from NtWow64* APIs we raise AccessDenied.
223
224 // 32 bit case. Check if the target is also 32 bit.
225 if (!IsWow64Process(GetCurrentProcess(), &weAreWow64) ||
226 !IsWow64Process(hProcess, &theyAreWow64)) {
227 psutil_PyErr_SetFromOSErrnoWithSyscall("IsWow64Process");
228 goto error;
229 }
230
231 if (weAreWow64 && !theyAreWow64) {
232 /* We are 32 bit running in WoW64 mode. Target process is 64 bit. */
233 PROCESS_BASIC_INFORMATION64 pbi64;
234 PEB64 peb64;
235 RTL_USER_PROCESS_PARAMETERS64 procParameters64;
236
237 if (NtWow64QueryInformationProcess64 == NULL) {
238 NtWow64QueryInformationProcess64 = \
239 psutil_GetProcAddressFromLib(
240 "ntdll.dll", "NtWow64QueryInformationProcess64");
241 if (NtWow64QueryInformationProcess64 == NULL) {
242 PyErr_Clear();
243 AccessDenied("can't query 64-bit process in 32-bit-WoW mode");
244 goto error;
245 }
246 }
247 if (NtWow64ReadVirtualMemory64 == NULL) {
248 NtWow64ReadVirtualMemory64 = \
249 psutil_GetProcAddressFromLib(
250 "ntdll.dll", "NtWow64ReadVirtualMemory64");
251 if (NtWow64ReadVirtualMemory64 == NULL) {
252 PyErr_Clear();
253 AccessDenied("can't query 64-bit process in 32-bit-WoW mode");
254 goto error;
255 }
256 }
257
258 status = NtWow64QueryInformationProcess64(
259 hProcess,
260 ProcessBasicInformation,
261 &pbi64,
262 sizeof(pbi64),
263 NULL);
264 if (!NT_SUCCESS(status)) {
265 /*
266 psutil_convert_ntstatus_err(
267 status,
268 "NtWow64QueryInformationProcess64(ProcessBasicInformation)");
269 */
270 psutil_giveup_with_ad(
271 status,
272 "NtWow64QueryInformationProcess64(ProcessBasicInformation)");
273 goto error;
274 }
275
276 // read peb
277 status = NtWow64ReadVirtualMemory64(
278 hProcess,
279 pbi64.PebBaseAddress,
280 &peb64,
281 sizeof(peb64),
282 NULL);
283 if (!NT_SUCCESS(status)) {
284 /*
285 psutil_convert_ntstatus_err(
286 status, "NtWow64ReadVirtualMemory64(pbi64.PebBaseAddress)");
287 */
288 psutil_giveup_with_ad(
289 status,
290 "NtWow64ReadVirtualMemory64(pbi64.PebBaseAddress)");
291 goto error;
292 }
293
294 // read process parameters
295 status = NtWow64ReadVirtualMemory64(
296 hProcess,
297 peb64.ProcessParameters,
298 &procParameters64,
299 sizeof(procParameters64),
300 NULL);
301 if (!NT_SUCCESS(status)) {
302 /*
303 psutil_convert_ntstatus_err(
304 status, "NtWow64ReadVirtualMemory64(peb64.ProcessParameters)");
305 */
306 psutil_giveup_with_ad(
307 status,
308 "NtWow64ReadVirtualMemory64(peb64.ProcessParameters)");
309 goto error;
310 }
311
312 switch (kind) {
313 case KIND_CMDLINE:
314 src64 = procParameters64.CommandLine.Buffer;
315 size = procParameters64.CommandLine.Length;
316 break;
317 case KIND_CWD:
318 src64 = procParameters64.CurrentDirectoryPath.Buffer,
319 size = procParameters64.CurrentDirectoryPath.Length;
320 break;
321 case KIND_ENVIRON:
322 src64 = procParameters64.env;
323 break;
324 }
325 } else
326 #endif
327 /* Target process is of the same bitness as us. */
328 {
329 PROCESS_BASIC_INFORMATION pbi;
330 PEB_ peb;
331 RTL_USER_PROCESS_PARAMETERS_ procParameters;
332
333 status = NtQueryInformationProcess(
334 hProcess,
335 ProcessBasicInformation,
336 &pbi,
337 sizeof(pbi),
338 NULL);
339
340 if (!NT_SUCCESS(status)) {
341 psutil_SetFromNTStatusErr(
342 status, "NtQueryInformationProcess(ProcessBasicInformation)");
343 goto error;
344 }
345
346
347 // read peb
348 if (!ReadProcessMemory(hProcess,
349 pbi.PebBaseAddress,
350 &peb,
351 sizeof(peb),
352 NULL))
353 {
354 // May fail with ERROR_PARTIAL_COPY, see:
355 // https://github.com/giampaolo/psutil/issues/875
356 psutil_convert_winerr(GetLastError(), "ReadProcessMemory");
357 goto error;
358 }
359
360 // read process parameters
361 if (!ReadProcessMemory(hProcess,
362 peb.ProcessParameters,
363 &procParameters,
364 sizeof(procParameters),
365 NULL))
366 {
367 // May fail with ERROR_PARTIAL_COPY, see:
368 // https://github.com/giampaolo/psutil/issues/875
369 psutil_convert_winerr(GetLastError(), "ReadProcessMemory");
370 goto error;
371 }
372
373 switch (kind) {
374 case KIND_CMDLINE:
375 src = procParameters.CommandLine.Buffer;
376 size = procParameters.CommandLine.Length;
377 break;
378 case KIND_CWD:
379 src = procParameters.CurrentDirectoryPath.Buffer;
380 size = procParameters.CurrentDirectoryPath.Length;
381 break;
382 case KIND_ENVIRON:
383 src = procParameters.env;
384 break;
385 }
386 }
387
388 if (kind == KIND_ENVIRON) {
389 #ifndef _WIN64
390 if (weAreWow64 && !theyAreWow64) {
391 AccessDenied("can't query 64-bit process in 32-bit-WoW mode");
392 goto error;
393 }
394 else
395 #endif
396 if (psutil_get_process_region_size(hProcess, src, &size) != 0)
397 goto error;
398 }
399
400 buffer = calloc(size + 2, 1);
401 if (buffer == NULL) {
402 PyErr_NoMemory();
403 goto error;
404 }
405
406 #ifndef _WIN64
407 if (weAreWow64 && !theyAreWow64) {
408 status = NtWow64ReadVirtualMemory64(
409 hProcess,
410 src64,
411 buffer,
412 size,
413 NULL);
414 if (!NT_SUCCESS(status)) {
415 // psutil_convert_ntstatus_err(status, "NtWow64ReadVirtualMemory64");
416 psutil_giveup_with_ad(status, "NtWow64ReadVirtualMemory64");
417 goto error;
418 }
419 } else
420 #endif
421 if (!ReadProcessMemory(hProcess, src, buffer, size, NULL)) {
422 // May fail with ERROR_PARTIAL_COPY, see:
423 // https://github.com/giampaolo/psutil/issues/875
424 psutil_convert_winerr(GetLastError(), "ReadProcessMemory");
425 goto error;
426 }
427
428 CloseHandle(hProcess);
429
430 *pdata = buffer;
431 *psize = size;
432
433 return 0;
434
435 error:
436 if (hProcess != NULL)
437 CloseHandle(hProcess);
438 if (buffer != NULL)
439 free(buffer);
440 return -1;
441 }
442
443
444 /*
445 * Get process cmdline by using NtQueryInformationProcess. This is a
446 * method alternative to PEB which is less likely to result in
447 * AccessDenied. Requires Windows 8.1+.
448 */
449 static int
450 psutil_cmdline_query_proc(DWORD pid, WCHAR **pdata, SIZE_T *psize) {
451 HANDLE hProcess = NULL;
452 ULONG bufLen = 0;
453 NTSTATUS status;
454 char * buffer = NULL;
455 WCHAR * bufWchar = NULL;
456 PUNICODE_STRING tmp = NULL;
457 size_t size;
458 int ProcessCommandLineInformation = 60;
459
460 if (PSUTIL_WINVER < PSUTIL_WINDOWS_8_1) {
461 PyErr_SetString(
462 PyExc_RuntimeError, "requires Windows 8.1+");
463 goto error;
464 }
465
466 hProcess = psutil_handle_from_pid(pid, PROCESS_QUERY_LIMITED_INFORMATION);
467 if (hProcess == NULL)
468 goto error;
469
470 // get the right buf size
471 status = NtQueryInformationProcess(
472 hProcess,
473 ProcessCommandLineInformation,
474 NULL,
475 0,
476 &bufLen);
477
478 // https://github.com/giampaolo/psutil/issues/1501
479 if (status == STATUS_NOT_FOUND) {
480 AccessDenied("NtQueryInformationProcess(ProcessBasicInformation) -> "
481 "STATUS_NOT_FOUND");
482 goto error;
483 }
484
485 if (status != STATUS_BUFFER_OVERFLOW && \
486 status != STATUS_BUFFER_TOO_SMALL && \
487 status != STATUS_INFO_LENGTH_MISMATCH) {
488 psutil_SetFromNTStatusErr(
489 status, "NtQueryInformationProcess(ProcessBasicInformation)");
490 goto error;
491 }
492
493 // allocate memory
494 buffer = calloc(bufLen, 1);
495 if (buffer == NULL) {
496 PyErr_NoMemory();
497 goto error;
498 }
499
500 // get the cmdline
501 status = NtQueryInformationProcess(
502 hProcess,
503 ProcessCommandLineInformation,
504 buffer,
505 bufLen,
506 &bufLen
507 );
508 if (!NT_SUCCESS(status)) {
509 psutil_SetFromNTStatusErr(
510 status, "NtQueryInformationProcess(ProcessCommandLineInformation)");
511 goto error;
512 }
513
514 // build the string
515 tmp = (PUNICODE_STRING)buffer;
516 size = wcslen(tmp->Buffer) + 1;
517 bufWchar = (WCHAR *)calloc(size, sizeof(WCHAR));
518 if (bufWchar == NULL) {
519 PyErr_NoMemory();
520 goto error;
521 }
522 wcscpy_s(bufWchar, size, tmp->Buffer);
523 *pdata = bufWchar;
524 *psize = size * sizeof(WCHAR);
525 free(buffer);
526 CloseHandle(hProcess);
527 return 0;
528
529 error:
530 if (buffer != NULL)
531 free(buffer);
532 if (hProcess != NULL)
533 CloseHandle(hProcess);
534 return -1;
535 }
536
537
538 /*
539 * Return a Python list representing the arguments for the process
540 * with given pid or NULL on error.
541 */
542 PyObject *
543 psutil_proc_cmdline(PyObject *self, PyObject *args, PyObject *kwdict) {
544 WCHAR *data = NULL;
545 LPWSTR *szArglist = NULL;
546 SIZE_T size;
547 int nArgs;
548 int i;
549 int func_ret;
550 DWORD pid;
551 int pid_return;
552 int use_peb;
553 // TODO: shouldn't this be decref-ed in case of error on
554 // PyArg_ParseTuple?
555 PyObject *py_usepeb = Py_True;
556 PyObject *py_retlist = NULL;
557 PyObject *py_unicode = NULL;
558 static char *keywords[] = {"pid", "use_peb", NULL};
559
560 if (! PyArg_ParseTupleAndKeywords(args, kwdict, _Py_PARSE_PID "|O",
561 keywords, &pid, &py_usepeb))
562 {
563 return NULL;
564 }
565 if ((pid == 0) || (pid == 4))
566 return Py_BuildValue("[]");
567
568 pid_return = psutil_pid_is_running(pid);
569 if (pid_return == 0)
570 return NoSuchProcess("psutil_pid_is_running -> 0");
571 if (pid_return == -1)
572 return NULL;
573
574 use_peb = (py_usepeb == Py_True) ? 1 : 0;
575
576 /*
577 Reading the PEB to get the cmdline seem to be the best method if
578 somebody has tampered with the parameters after creating the process.
579 For instance, create a process as suspended, patch the command line
580 in its PEB and unfreeze it. It requires more privileges than
581 NtQueryInformationProcess though (the fallback):
582 - https://github.com/giampaolo/psutil/pull/1398
583 - https://blog.xpnsec.com/how-to-argue-like-cobalt-strike/
584 */
585 if (use_peb == 1)
586 func_ret = psutil_get_process_data(pid, KIND_CMDLINE, &data, &size);
587 else
588 func_ret = psutil_cmdline_query_proc(pid, &data, &size);
589 if (func_ret != 0)
590 goto error;
591
592 // attempt to parse the command line using Win32 API
593 szArglist = CommandLineToArgvW(data, &nArgs);
594 if (szArglist == NULL) {
595 psutil_PyErr_SetFromOSErrnoWithSyscall("CommandLineToArgvW");
596 goto error;
597 }
598
599 // arglist parsed as array of UNICODE_STRING, so convert each to
600 // Python string object and add to arg list
601 py_retlist = PyList_New(nArgs);
602 if (py_retlist == NULL)
603 goto error;
604 for (i = 0; i < nArgs; i++) {
605 py_unicode = PyUnicode_FromWideChar(szArglist[i],
606 wcslen(szArglist[i]));
607 if (py_unicode == NULL)
608 goto error;
609 PyList_SetItem(py_retlist, i, py_unicode);
610 py_unicode = NULL;
611 }
612
613 LocalFree(szArglist);
614 free(data);
615 return py_retlist;
616
617 error:
618 if (szArglist != NULL)
619 LocalFree(szArglist);
620 if (data != NULL)
621 free(data);
622 Py_XDECREF(py_unicode);
623 Py_XDECREF(py_retlist);
624 return NULL;
625 }
626
627
628 PyObject *
629 psutil_proc_cwd(PyObject *self, PyObject *args) {
630 DWORD pid;
631 PyObject *ret = NULL;
632 WCHAR *data = NULL;
633 SIZE_T size;
634 int pid_return;
635
636 if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
637 return NULL;
638
639 pid_return = psutil_pid_is_running(pid);
640 if (pid_return == 0)
641 return NoSuchProcess("psutil_pid_is_running -> 0");
642 if (pid_return == -1)
643 return NULL;
644
645 if (psutil_get_process_data(pid, KIND_CWD, &data, &size) != 0)
646 goto out;
647
648 // convert wchar array to a Python unicode string
649 ret = PyUnicode_FromWideChar(data, wcslen(data));
650
651 out:
652 if (data != NULL)
653 free(data);
654
655 return ret;
656 }
657
658
659 /*
660 * returns a Python string containing the environment variable data for the
661 * process with given pid or NULL on error.
662 */
663 PyObject *
664 psutil_proc_environ(PyObject *self, PyObject *args) {
665 DWORD pid;
666 WCHAR *data = NULL;
667 SIZE_T size;
668 int pid_return;
669 PyObject *ret = NULL;
670
671 if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
672 return NULL;
673 if ((pid == 0) || (pid == 4))
674 return Py_BuildValue("s", "");
675
676 pid_return = psutil_pid_is_running(pid);
677 if (pid_return == 0)
678 return NoSuchProcess("psutil_pid_is_running -> 0");
679 if (pid_return == -1)
680 return NULL;
681
682 if (psutil_get_process_data(pid, KIND_ENVIRON, &data, &size) != 0)
683 goto out;
684
685 // convert wchar array to a Python unicode string
686 ret = PyUnicode_FromWideChar(data, size / 2);
687
688 out:
689 if (data != NULL)
690 free(data);
691 return ret;
692 }
693
694
695 /*
696 * Given a process PID and a PSYSTEM_PROCESS_INFORMATION structure
697 * fills the structure with various process information in one shot
698 * by using NtQuerySystemInformation.
699 * We use this as a fallback when faster functions fail with access
700 * denied. This is slower because it iterates over all processes
701 * but it doesn't require any privilege (also work for PID 0).
702 * On success return 1, else 0 with Python exception already set.
703 */
704 int
705 psutil_get_proc_info(DWORD pid, PSYSTEM_PROCESS_INFORMATION *retProcess,
706 PVOID *retBuffer) {
707 static ULONG initialBufferSize = 0x4000;
708 NTSTATUS status;
709 PVOID buffer;
710 ULONG bufferSize;
711 PSYSTEM_PROCESS_INFORMATION process;
712
713 bufferSize = initialBufferSize;
714 buffer = malloc(bufferSize);
715 if (buffer == NULL) {
716 PyErr_NoMemory();
717 goto error;
718 }
719
720 while (TRUE) {
721 status = NtQuerySystemInformation(
722 SystemProcessInformation,
723 buffer,
724 bufferSize,
725 &bufferSize);
726 if (status == STATUS_BUFFER_TOO_SMALL ||
727 status == STATUS_INFO_LENGTH_MISMATCH)
728 {
729 free(buffer);
730 buffer = malloc(bufferSize);
731 if (buffer == NULL) {
732 PyErr_NoMemory();
733 goto error;
734 }
735 }
736 else {
737 break;
738 }
739 }
740
741 if (! NT_SUCCESS(status)) {
742 psutil_SetFromNTStatusErr(
743 status, "NtQuerySystemInformation(SystemProcessInformation)");
744 goto error;
745 }
746
747 if (bufferSize <= 0x20000)
748 initialBufferSize = bufferSize;
749
750 process = PSUTIL_FIRST_PROCESS(buffer);
751 do {
752 if ((ULONG_PTR)process->UniqueProcessId == pid) {
753 *retProcess = process;
754 *retBuffer = buffer;
755 return 1;
756 }
757 } while ((process = PSUTIL_NEXT_PROCESS(process)));
758
759 NoSuchProcess("NtQuerySystemInformation (no PID found)");
760 goto error;
761
762 error:
763 if (buffer != NULL)
764 free(buffer);
765 return 0;
766 }
767
768
769 /*
770 * Get various process information by using NtQuerySystemInformation.
771 * We use this as a fallback when faster functions fail with access
772 * denied. This is slower because it iterates over all processes.
773 * Returned tuple includes the following process info:
774 *
775 * - num_threads()
776 * - ctx_switches()
777 * - num_handles() (fallback)
778 * - cpu_times() (fallback)
779 * - create_time() (fallback)
780 * - io_counters() (fallback)
781 * - memory_info() (fallback)
782 */
783 PyObject *
784 psutil_proc_info(PyObject *self, PyObject *args) {
785 DWORD pid;
786 PSYSTEM_PROCESS_INFORMATION process;
787 PVOID buffer;
788 ULONG i;
789 ULONG ctx_switches = 0;
790 double user_time;
791 double kernel_time;
792 double create_time;
793 PyObject *py_retlist;
794
795 if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
796 return NULL;
797 if (! psutil_get_proc_info(pid, &process, &buffer))
798 return NULL;
799
800 for (i = 0; i < process->NumberOfThreads; i++)
801 ctx_switches += process->Threads[i].ContextSwitches;
802 user_time = (double)process->UserTime.HighPart * HI_T + \
803 (double)process->UserTime.LowPart * LO_T;
804 kernel_time = (double)process->KernelTime.HighPart * HI_T + \
805 (double)process->KernelTime.LowPart * LO_T;
806
807 // Convert the LARGE_INTEGER union to a Unix time.
808 // It's the best I could find by googling and borrowing code here
809 // and there. The time returned has a precision of 1 second.
810 if (0 == pid || 4 == pid) {
811 // the python module will translate this into BOOT_TIME later
812 create_time = 0;
813 }
814 else {
815 create_time = psutil_LargeIntegerToUnixTime(process->CreateTime);
816 }
817
818 py_retlist = Py_BuildValue(
819 #if defined(_WIN64)
820 "kkdddkKKKKKK" "kKKKKKKKKK",
821 #else
822 "kkdddkKKKKKK" "kIIIIIIIII",
823 #endif
824 process->HandleCount, // num handles
825 ctx_switches, // num ctx switches
826 user_time, // cpu user time
827 kernel_time, // cpu kernel time
828 create_time, // create time
829 process->NumberOfThreads, // num threads
830 // IO counters
831 process->ReadOperationCount.QuadPart, // io rcount
832 process->WriteOperationCount.QuadPart, // io wcount
833 process->ReadTransferCount.QuadPart, // io rbytes
834 process->WriteTransferCount.QuadPart, // io wbytes
835 process->OtherOperationCount.QuadPart, // io others count
836 process->OtherTransferCount.QuadPart, // io others bytes
837 // memory
838 process->PageFaultCount, // num page faults
839 process->PeakWorkingSetSize, // peak wset
840 process->WorkingSetSize, // wset
841 process->QuotaPeakPagedPoolUsage, // peak paged pool
842 process->QuotaPagedPoolUsage, // paged pool
843 process->QuotaPeakNonPagedPoolUsage, // peak non paged pool
844 process->QuotaNonPagedPoolUsage, // non paged pool
845 process->PagefileUsage, // pagefile
846 process->PeakPagefileUsage, // peak pagefile
847 process->PrivatePageCount // private
848 );
849
850 free(buffer);
851 return py_retlist;
852 }