diff options
| author | robot-piglet <[email protected]> | 2025-11-18 12:31:46 +0300 |
|---|---|---|
| committer | robot-piglet <[email protected]> | 2025-11-18 14:57:42 +0300 |
| commit | 0ba04189b98031e49f49f039cd5fcdc298cbe1b6 (patch) | |
| tree | 3f5e0c02732bb585be2c172f25e064ecfa15e08c /contrib/python/psutil/py3 | |
| parent | 8a80252b57977e0e668c38f7b113d717187c776f (diff) | |
Intermediate changes
commit_hash:0584d4b0827c151dc50a4d785718890a021760e5
Diffstat (limited to 'contrib/python/psutil/py3')
62 files changed, 2614 insertions, 2061 deletions
diff --git a/contrib/python/psutil/py3/.dist-info/METADATA b/contrib/python/psutil/py3/.dist-info/METADATA index df3c87860ee..0c7c91f55fb 100644 --- a/contrib/python/psutil/py3/.dist-info/METADATA +++ b/contrib/python/psutil/py3/.dist-info/METADATA @@ -1,6 +1,6 @@ Metadata-Version: 2.1 Name: psutil -Version: 7.1.2 +Version: 7.1.3 Summary: Cross-platform lib for process and system monitoring. Home-page: https://github.com/giampaolo/psutil Author: Giampaolo Rodola @@ -78,6 +78,7 @@ Requires-Dist: validate-pyproject[all] ; extra == 'dev' Requires-Dist: virtualenv ; extra == 'dev' Requires-Dist: vulture ; extra == 'dev' Requires-Dist: wheel ; extra == 'dev' +Requires-Dist: colorama ; (os_name == "nt") and extra == 'dev' Requires-Dist: pyreadline ; (os_name == "nt") and extra == 'dev' Requires-Dist: pywin32 ; (os_name == "nt" and platform_python_implementation != "PyPy") and extra == 'dev' Requires-Dist: wheel ; (os_name == "nt" and platform_python_implementation != "PyPy") and extra == 'dev' diff --git a/contrib/python/psutil/py3/patches/99-fix-ya.make.patch b/contrib/python/psutil/py3/patches/99-fix-ya.make.patch index a9aee73f4e0..017a1ff55bc 100644 --- a/contrib/python/psutil/py3/patches/99-fix-ya.make.patch +++ b/contrib/python/psutil/py3/patches/99-fix-ya.make.patch @@ -8,12 +8,14 @@ - -DPSUTIL_WINDOWS=1 - -DPSUTIL_SIZEOF_PID_T=4 - -DPSUTIL_MAYBE_EXTERN=extern -@@ -42,46 +33,2 @@ SRCS( +@@ -42,50 +33,4 @@ SRCS( - psutil/_psutil_linux.c - psutil/_psutil_osx.c - psutil/_psutil_windows.c + psutil/arch/all/errors.c psutil/arch/all/init.c psutil/arch/all/pids.c + psutil/arch/all/str.c - psutil/arch/linux/disk.c - psutil/arch/linux/mem.c - psutil/arch/linux/net.c @@ -25,10 +27,12 @@ - psutil/arch/osx/net.c - psutil/arch/osx/pids.c - psutil/arch/osx/proc.c +- psutil/arch/osx/proc_utils.c - psutil/arch/osx/sensors.c - psutil/arch/osx/sys.c - psutil/arch/posix/init.c - psutil/arch/posix/net.c +- psutil/arch/posix/pids.c - psutil/arch/posix/proc.c - psutil/arch/posix/sysctl.c - psutil/arch/posix/users.c @@ -55,7 +59,7 @@ - psutil/arch/windows/socks.c - psutil/arch/windows/sys.c - psutil/arch/windows/wmi.c -@@ -74,5 +36,96 @@ SRCS( +@@ -74,5 +36,99 @@ SRCS( -PY_REGISTER( - psutil._psutil_linux - psutil._psutil_osx @@ -75,6 +79,7 @@ + psutil/arch/linux/proc.c + psutil/arch/posix/init.c + psutil/arch/posix/net.c ++ psutil/arch/posix/pids.c + psutil/arch/posix/proc.c + psutil/arch/posix/sysctl.c + psutil/arch/posix/users.c @@ -105,10 +110,12 @@ + psutil/arch/osx/net.c + psutil/arch/osx/pids.c + psutil/arch/osx/proc.c ++ psutil/arch/osx/proc_utils.c + psutil/arch/osx/sensors.c + psutil/arch/osx/sys.c + psutil/arch/posix/init.c + psutil/arch/posix/net.c ++ psutil/arch/posix/pids.c + psutil/arch/posix/proc.c + psutil/arch/posix/sysctl.c + psutil/arch/posix/users.c diff --git a/contrib/python/psutil/py3/psutil/__init__.py b/contrib/python/psutil/py3/psutil/__init__.py index b289c161703..92517709113 100644 --- a/contrib/python/psutil/py3/psutil/__init__.py +++ b/contrib/python/psutil/py3/psutil/__init__.py @@ -203,7 +203,7 @@ if hasattr(_psplatform.Process, "rlimit"): AF_LINK = _psplatform.AF_LINK __author__ = "Giampaolo Rodola'" -__version__ = "7.1.2" +__version__ = "7.1.3" version_info = tuple(int(num) for num in __version__.split('.')) _timer = getattr(time, 'monotonic', time.time) diff --git a/contrib/python/psutil/py3/psutil/_psbsd.py b/contrib/python/psutil/py3/psutil/_psbsd.py index e96a29914e0..ea58c76cad8 100644 --- a/contrib/python/psutil/py3/psutil/_psbsd.py +++ b/contrib/python/psutil/py3/psutil/_psbsd.py @@ -569,14 +569,6 @@ else: # FreeBSD pid_exists = _psposix.pid_exists -def is_zombie(pid): - try: - st = cext.proc_oneshot_info(pid)[kinfo_proc_map['status']] - return PROC_STATUSES.get(st) == _common.STATUS_ZOMBIE - except OSError: - return False - - def wrap_exceptions(fun): """Decorator which translates bare OSError exceptions into NoSuchProcess and AccessDenied. @@ -588,15 +580,17 @@ def wrap_exceptions(fun): try: return fun(self, *args, **kwargs) except ProcessLookupError as err: - if is_zombie(pid): + if cext.proc_is_zombie(pid): raise ZombieProcess(pid, name, ppid) from err raise NoSuchProcess(pid, name) from err except PermissionError as err: raise AccessDenied(pid, name) from err + except cext.ZombieProcessError as err: + raise ZombieProcess(pid, name, ppid) from err except OSError as err: if pid == 0 and 0 in pids(): raise AccessDenied(pid, name) from err - raise + raise err from None return wrapper @@ -611,7 +605,7 @@ def wrap_exceptions_procfs(inst): # ENOENT (no such file or directory) gets raised on open(). # ESRCH (no such process) can get raised on read() if # process is gone in meantime. - if is_zombie(inst.pid): + if cext.proc_is_zombie(inst.pid): raise ZombieProcess(pid, name, ppid) from err else: raise NoSuchProcess(pid, name) from err @@ -694,7 +688,7 @@ class Process: except OSError as err: if err.errno == errno.EINVAL: pid, name, ppid = self.pid, self._name, self._ppid - if is_zombie(self.pid): + if cext.proc_is_zombie(self.pid): raise ZombieProcess(pid, name, ppid) from err if not pid_exists(self.pid): raise NoSuchProcess(pid, name, ppid) from err diff --git a/contrib/python/psutil/py3/psutil/_psutil_linux.c b/contrib/python/psutil/py3/psutil/_psutil_linux.c index 2cfb4e47c42..2b6589c2cfb 100644 --- a/contrib/python/psutil/py3/psutil/_psutil_linux.c +++ b/contrib/python/psutil/py3/psutil/_psutil_linux.c @@ -7,7 +7,7 @@ */ #ifndef _GNU_SOURCE - #define _GNU_SOURCE 1 +#define _GNU_SOURCE 1 #endif #include <Python.h> #include <linux/ethtool.h> // DUPLEX_* @@ -17,11 +17,11 @@ // May happen on old RedHat versions, see: // https://github.com/giampaolo/psutil/issues/607 #ifndef DUPLEX_UNKNOWN - #define DUPLEX_UNKNOWN 0xff +#define DUPLEX_UNKNOWN 0xff #endif static PyMethodDef mod_methods[] = { - // --- per-process functions +// --- per-process functions #ifdef PSUTIL_HAS_IOPRIO {"proc_ioprio_get", psutil_proc_ioprio_get, METH_VARARGS}, {"proc_ioprio_set", psutil_proc_ioprio_set, METH_VARARGS}, diff --git a/contrib/python/psutil/py3/psutil/_psutil_osx.c b/contrib/python/psutil/py3/psutil/_psutil_osx.c index dbb33efc0b0..7e345010be5 100644 --- a/contrib/python/psutil/py3/psutil/_psutil_osx.c +++ b/contrib/python/psutil/py3/psutil/_psutil_osx.c @@ -28,7 +28,8 @@ static PyMethodDef mod_methods[] = { {"proc_net_connections", psutil_proc_net_connections, METH_VARARGS}, {"proc_num_fds", psutil_proc_num_fds, METH_VARARGS}, {"proc_open_files", psutil_proc_open_files, METH_VARARGS}, - {"proc_pidtaskinfo_oneshot", psutil_proc_pidtaskinfo_oneshot, METH_VARARGS}, + {"proc_pidtaskinfo_oneshot", psutil_proc_pidtaskinfo_oneshot, METH_VARARGS + }, {"proc_threads", psutil_proc_threads, METH_VARARGS}, // --- system-related functions diff --git a/contrib/python/psutil/py3/psutil/_psutil_windows.c b/contrib/python/psutil/py3/psutil/_psutil_windows.c index 88bd5e0131c..9711cf9246d 100644 --- a/contrib/python/psutil/py3/psutil/_psutil_windows.c +++ b/contrib/python/psutil/py3/psutil/_psutil_windows.c @@ -24,15 +24,15 @@ #include "arch/windows/init.h" -#define GETSTATE(m) ((struct module_state*)PyModule_GetState(m)) +#define GETSTATE(m) ((struct module_state *)PyModule_GetState(m)) // ------------------------ Python init --------------------------- -static PyMethodDef -PsutilMethods[] = { +static PyMethodDef PsutilMethods[] = { // --- per-process functions - {"proc_cmdline", (PyCFunction)(void(*)(void))psutil_proc_cmdline, + {"proc_cmdline", + (PyCFunction)(void (*)(void))psutil_proc_cmdline, METH_VARARGS | METH_KEYWORDS}, {"proc_cpu_affinity_get", psutil_proc_cpu_affinity_get, METH_VARARGS}, {"proc_cpu_affinity_set", psutil_proc_cpu_affinity_set, METH_VARARGS}, @@ -73,7 +73,9 @@ PsutilMethods[] = { {"getloadavg", (PyCFunction)psutil_get_loadavg, METH_VARARGS}, {"getpagesize", psutil_getpagesize, METH_VARARGS}, {"swap_percent", psutil_swap_percent, METH_VARARGS}, - {"init_loadavg_counter", (PyCFunction)psutil_init_loadavg_counter, METH_VARARGS}, + {"init_loadavg_counter", + (PyCFunction)psutil_init_loadavg_counter, + METH_VARARGS}, {"net_connections", psutil_net_connections, METH_VARARGS}, {"net_if_addrs", psutil_net_if_addrs, METH_VARARGS}, {"net_if_stats", psutil_net_if_stats, METH_VARARGS}, @@ -155,14 +157,16 @@ PyInit__psutil_windows(void) { // Exceptions TimeoutExpired = PyErr_NewException( - "_psutil_windows.TimeoutExpired", NULL, NULL); + "_psutil_windows.TimeoutExpired", NULL, NULL + ); if (TimeoutExpired == NULL) return NULL; if (PyModule_AddObject(mod, "TimeoutExpired", TimeoutExpired)) return NULL; TimeoutAbandoned = PyErr_NewException( - "_psutil_windows.TimeoutAbandoned", NULL, NULL); + "_psutil_windows.TimeoutAbandoned", NULL, NULL + ); if (TimeoutAbandoned == NULL) return NULL; if (PyModule_AddObject(mod, "TimeoutAbandoned", TimeoutAbandoned)) @@ -174,46 +178,84 @@ PyInit__psutil_windows(void) { // process status constants // http://msdn.microsoft.com/en-us/library/ms683211(v=vs.85).aspx - if (PyModule_AddIntConstant(mod, "ABOVE_NORMAL_PRIORITY_CLASS", ABOVE_NORMAL_PRIORITY_CLASS)) + if (PyModule_AddIntConstant( + mod, "ABOVE_NORMAL_PRIORITY_CLASS", ABOVE_NORMAL_PRIORITY_CLASS + )) return NULL; - if (PyModule_AddIntConstant(mod, "BELOW_NORMAL_PRIORITY_CLASS", BELOW_NORMAL_PRIORITY_CLASS)) + if (PyModule_AddIntConstant( + mod, "BELOW_NORMAL_PRIORITY_CLASS", BELOW_NORMAL_PRIORITY_CLASS + )) return NULL; - if (PyModule_AddIntConstant(mod, "HIGH_PRIORITY_CLASS", HIGH_PRIORITY_CLASS)) + if (PyModule_AddIntConstant( + mod, "HIGH_PRIORITY_CLASS", HIGH_PRIORITY_CLASS + )) return NULL; - if (PyModule_AddIntConstant(mod, "IDLE_PRIORITY_CLASS", IDLE_PRIORITY_CLASS)) + if (PyModule_AddIntConstant( + mod, "IDLE_PRIORITY_CLASS", IDLE_PRIORITY_CLASS + )) return NULL; - if (PyModule_AddIntConstant(mod, "NORMAL_PRIORITY_CLASS", NORMAL_PRIORITY_CLASS)) + if (PyModule_AddIntConstant( + mod, "NORMAL_PRIORITY_CLASS", NORMAL_PRIORITY_CLASS + )) return NULL; - if (PyModule_AddIntConstant(mod, "REALTIME_PRIORITY_CLASS", REALTIME_PRIORITY_CLASS)) + if (PyModule_AddIntConstant( + mod, "REALTIME_PRIORITY_CLASS", REALTIME_PRIORITY_CLASS + )) return NULL; // connection status constants // http://msdn.microsoft.com/en-us/library/cc669305.aspx - if (PyModule_AddIntConstant(mod, "MIB_TCP_STATE_CLOSED", MIB_TCP_STATE_CLOSED)) + if (PyModule_AddIntConstant( + mod, "MIB_TCP_STATE_CLOSED", MIB_TCP_STATE_CLOSED + )) return NULL; - if (PyModule_AddIntConstant(mod, "MIB_TCP_STATE_CLOSING", MIB_TCP_STATE_CLOSING)) + if (PyModule_AddIntConstant( + mod, "MIB_TCP_STATE_CLOSING", MIB_TCP_STATE_CLOSING + )) return NULL; - if (PyModule_AddIntConstant(mod, "MIB_TCP_STATE_CLOSE_WAIT", MIB_TCP_STATE_CLOSE_WAIT)) + if (PyModule_AddIntConstant( + mod, "MIB_TCP_STATE_CLOSE_WAIT", MIB_TCP_STATE_CLOSE_WAIT + )) return NULL; - if (PyModule_AddIntConstant(mod, "MIB_TCP_STATE_LISTEN", MIB_TCP_STATE_LISTEN)) + if (PyModule_AddIntConstant( + mod, "MIB_TCP_STATE_LISTEN", MIB_TCP_STATE_LISTEN + )) return NULL; - if (PyModule_AddIntConstant(mod, "MIB_TCP_STATE_ESTAB", MIB_TCP_STATE_ESTAB)) + if (PyModule_AddIntConstant( + mod, "MIB_TCP_STATE_ESTAB", MIB_TCP_STATE_ESTAB + )) return NULL; - if (PyModule_AddIntConstant(mod, "MIB_TCP_STATE_SYN_SENT", MIB_TCP_STATE_SYN_SENT)) + if (PyModule_AddIntConstant( + mod, "MIB_TCP_STATE_SYN_SENT", MIB_TCP_STATE_SYN_SENT + )) return NULL; - if (PyModule_AddIntConstant(mod, "MIB_TCP_STATE_SYN_RCVD", MIB_TCP_STATE_SYN_RCVD)) + if (PyModule_AddIntConstant( + mod, "MIB_TCP_STATE_SYN_RCVD", MIB_TCP_STATE_SYN_RCVD + )) return NULL; - if (PyModule_AddIntConstant(mod, "MIB_TCP_STATE_FIN_WAIT1", MIB_TCP_STATE_FIN_WAIT1)) + if (PyModule_AddIntConstant( + mod, "MIB_TCP_STATE_FIN_WAIT1", MIB_TCP_STATE_FIN_WAIT1 + )) return NULL; - if (PyModule_AddIntConstant(mod, "MIB_TCP_STATE_FIN_WAIT2", MIB_TCP_STATE_FIN_WAIT2)) + if (PyModule_AddIntConstant( + mod, "MIB_TCP_STATE_FIN_WAIT2", MIB_TCP_STATE_FIN_WAIT2 + )) return NULL; - if (PyModule_AddIntConstant(mod, "MIB_TCP_STATE_LAST_ACK", MIB_TCP_STATE_LAST_ACK)) + if (PyModule_AddIntConstant( + mod, "MIB_TCP_STATE_LAST_ACK", MIB_TCP_STATE_LAST_ACK + )) return NULL; - if (PyModule_AddIntConstant(mod, "MIB_TCP_STATE_TIME_WAIT", MIB_TCP_STATE_TIME_WAIT)) + if (PyModule_AddIntConstant( + mod, "MIB_TCP_STATE_TIME_WAIT", MIB_TCP_STATE_TIME_WAIT + )) return NULL; - if (PyModule_AddIntConstant(mod, "MIB_TCP_STATE_TIME_WAIT", MIB_TCP_STATE_TIME_WAIT)) + if (PyModule_AddIntConstant( + mod, "MIB_TCP_STATE_TIME_WAIT", MIB_TCP_STATE_TIME_WAIT + )) return NULL; - if (PyModule_AddIntConstant(mod, "MIB_TCP_STATE_DELETE_TCB", MIB_TCP_STATE_DELETE_TCB)) + if (PyModule_AddIntConstant( + mod, "MIB_TCP_STATE_DELETE_TCB", MIB_TCP_STATE_DELETE_TCB + )) return NULL; if (PyModule_AddIntConstant(mod, "PSUTIL_CONN_NONE", PSUTIL_CONN_NONE)) return NULL; @@ -221,13 +263,19 @@ PyInit__psutil_windows(void) { // ...for internal use in _psutil_windows.py if (PyModule_AddIntConstant(mod, "INFINITE", INFINITE)) return NULL; - if (PyModule_AddIntConstant(mod, "ERROR_ACCESS_DENIED", ERROR_ACCESS_DENIED)) + if (PyModule_AddIntConstant( + mod, "ERROR_ACCESS_DENIED", ERROR_ACCESS_DENIED + )) return NULL; if (PyModule_AddIntConstant(mod, "ERROR_INVALID_NAME", ERROR_INVALID_NAME)) return NULL; - if (PyModule_AddIntConstant(mod, "ERROR_SERVICE_DOES_NOT_EXIST", ERROR_SERVICE_DOES_NOT_EXIST)) + if (PyModule_AddIntConstant( + mod, "ERROR_SERVICE_DOES_NOT_EXIST", ERROR_SERVICE_DOES_NOT_EXIST + )) return NULL; - if (PyModule_AddIntConstant(mod, "ERROR_PRIVILEGE_NOT_HELD", ERROR_PRIVILEGE_NOT_HELD)) + if (PyModule_AddIntConstant( + mod, "ERROR_PRIVILEGE_NOT_HELD", ERROR_PRIVILEGE_NOT_HELD + )) return NULL; if (PyModule_AddIntConstant(mod, "WINVER", PSUTIL_WINVER)) return NULL; diff --git a/contrib/python/psutil/py3/psutil/_pswindows.py b/contrib/python/psutil/py3/psutil/_pswindows.py index c6c8fffa4b0..7d343f26bbb 100644 --- a/contrib/python/psutil/py3/psutil/_pswindows.py +++ b/contrib/python/psutil/py3/psutil/_pswindows.py @@ -265,8 +265,7 @@ def disk_usage(path): # XXX: do we want to use "strict"? Probably yes, in order # to fail immediately. After all we are accepting input here... path = path.decode(ENCODING, errors="strict") - total, free = cext.disk_usage(path) - used = total - free + total, used, free = cext.disk_usage(path) percent = usage_percent(used, total, round_=1) return _common.sdiskusage(total, used, free, percent) diff --git a/contrib/python/psutil/py3/psutil/arch/all/errors.c b/contrib/python/psutil/py3/psutil/arch/all/errors.c new file mode 100644 index 00000000000..039b8f98a22 --- /dev/null +++ b/contrib/python/psutil/py3/psutil/arch/all/errors.c @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + +#include <Python.h> +#include <errno.h> +#include <string.h> +#if defined(PSUTIL_WINDOWS) +#include <windows.h> +#endif + +#include "init.h" + +#define MSG_SIZE 512 + + +// Set OSError() based on errno (UNIX) or GetLastError() (Windows). +PyObject * +psutil_oserror(void) { +#ifdef PSUTIL_WINDOWS + PyErr_SetFromWindowsErr(GetLastError()); +#else + PyErr_SetFromErrno(PyExc_OSError); +#endif + return NULL; +} + + +// Same as above, but adds the syscall to the exception message. On +// Windows this is achieved by setting the `filename` attribute of the +// OSError object. +PyObject * +psutil_oserror_wsyscall(const char *syscall) { + char msg[MSG_SIZE]; + +#ifdef PSUTIL_WINDOWS + DWORD err = GetLastError(); + str_format(msg, sizeof(msg), "(originated from %s)", syscall); + PyErr_SetFromWindowsErrWithFilename(err, msg); +#else + PyObject *exc; + str_format( + msg, sizeof(msg), "%s (originated from %s)", strerror(errno), syscall + ); + exc = PyObject_CallFunction(PyExc_OSError, "(is)", errno, msg); + PyErr_SetObject(PyExc_OSError, exc); + Py_XDECREF(exc); +#endif + return NULL; +} + + +// Set OSError(errno=ESRCH) ("No such process"). +PyObject * +psutil_oserror_nsp(const char *syscall) { + PyObject *exc; + char msg[MSG_SIZE]; + + str_format( + msg, sizeof(msg), "force no such process (originated from %s)", syscall + ); + exc = PyObject_CallFunction(PyExc_OSError, "(is)", ESRCH, msg); + PyErr_SetObject(PyExc_OSError, exc); + Py_XDECREF(exc); + return NULL; +} + + +// Set OSError(errno=EACCES) ("Permission denied"). +PyObject * +psutil_oserror_ad(const char *syscall) { + PyObject *exc; + char msg[MSG_SIZE]; + + str_format( + msg, + sizeof(msg), + "force permission denied (originated from %s)", + syscall + ); + exc = PyObject_CallFunction(PyExc_OSError, "(is)", EACCES, msg); + PyErr_SetObject(PyExc_OSError, exc); + Py_XDECREF(exc); + return NULL; +} + + +// Set RuntimeError with formatted `msg` and optional arguments. +PyObject * +psutil_runtime_error(const char *msg, ...) { + va_list args; + + va_start(args, msg); + PyErr_FormatV(PyExc_RuntimeError, msg, args); + va_end(args); + return NULL; +} + + +// Use it when invalid args are passed to a C function. +int +psutil_badargs(const char *funcname) { + PyErr_Format( + PyExc_RuntimeError, "%s() invalid args passed to function", funcname + ); + return -1; +} diff --git a/contrib/python/psutil/py3/psutil/arch/all/init.c b/contrib/python/psutil/py3/psutil/arch/all/init.c index 82e7c4b6541..67c446b2b6f 100644 --- a/contrib/python/psutil/py3/psutil/arch/all/init.c +++ b/contrib/python/psutil/py3/psutil/arch/all/init.c @@ -7,13 +7,11 @@ // Global names shared by all platforms. #include <Python.h> -#ifdef PSUTIL_WINDOWS -#include <windows.h> -#endif #include "init.h" int PSUTIL_DEBUG = 0; +int PSUTIL_TESTING = 0; int PSUTIL_CONN_NONE = 128; #ifdef Py_GIL_DISABLED @@ -21,57 +19,6 @@ PyMutex utxent_lock = {0}; #endif -// Set OSError(errno=ESRCH, strerror="No such process (originated from") -// Python exception. -PyObject * -NoSuchProcess(const char *syscall) { - PyObject *exc; - char msg[1024]; - - sprintf(msg, "assume no such process (originated from %s)", syscall); - exc = PyObject_CallFunction(PyExc_OSError, "(is)", ESRCH, msg); - PyErr_SetObject(PyExc_OSError, exc); - Py_XDECREF(exc); - return NULL; -} - - -// Set OSError(errno=EACCES, strerror="Permission denied" (originated from ...) -// Python exception. -PyObject * -AccessDenied(const char *syscall) { - PyObject *exc; - char msg[1024]; - - sprintf(msg, "assume access denied (originated from %s)", syscall); - exc = PyObject_CallFunction(PyExc_OSError, "(is)", EACCES, msg); - PyErr_SetObject(PyExc_OSError, exc); - Py_XDECREF(exc); - return NULL; -} - - -// Same as PyErr_SetFromErrno(0) but adds the syscall to the exception -// message. -PyObject * -psutil_PyErr_SetFromOSErrnoWithSyscall(const char *syscall) { - char fullmsg[1024]; - -#ifdef PSUTIL_WINDOWS - DWORD dwLastError = GetLastError(); - sprintf(fullmsg, "(originated from %s)", syscall); - PyErr_SetFromWindowsErrWithFilename(dwLastError, fullmsg); -#else - PyObject *exc; - sprintf(fullmsg, "%s (originated from %s)", strerror(errno), syscall); - exc = PyObject_CallFunction(PyExc_OSError, "(is)", errno, fullmsg); - PyErr_SetObject(PyExc_OSError, exc); - Py_XDECREF(exc); -#endif - return NULL; -} - - // Enable or disable PSUTIL_DEBUG messages. PyObject * psutil_set_debug(PyObject *self, PyObject *args) { @@ -94,41 +41,12 @@ psutil_set_debug(PyObject *self, PyObject *args) { } -// Raise OverflowError if Python int value overflowed when converting -// to pid_t. Raise ValueError if Python int value is negative. -// Otherwise, return None. -PyObject * -psutil_check_pid_range(PyObject *self, PyObject *args) { -#ifdef PSUTIL_WINDOWS - DWORD pid; -#else - pid_t pid; -#endif - - if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) - return NULL; - if (pid < 0) { - PyErr_SetString(PyExc_ValueError, "pid must be a positive integer"); - return NULL; - } - Py_RETURN_NONE; -} - - -// Use it when invalid args are passed to a C function. -int -psutil_badargs(const char *funcname) { - PyErr_Format( - PyExc_RuntimeError, "%s() invalid args passed to function", funcname - ); - return -1; -} - - // Called on module import on all platforms. int psutil_setup(void) { if (getenv("PSUTIL_DEBUG") != NULL) PSUTIL_DEBUG = 1; + if (getenv("PSUTIL_TESTING") != NULL) + PSUTIL_TESTING = 1; return 0; } diff --git a/contrib/python/psutil/py3/psutil/arch/all/init.h b/contrib/python/psutil/py3/psutil/arch/all/init.h index 2b3e20ff81c..27273e895ab 100644 --- a/contrib/python/psutil/py3/psutil/arch/all/init.h +++ b/contrib/python/psutil/py3/psutil/arch/all/init.h @@ -11,6 +11,7 @@ // We do this so that all .c files have to include only one header // (ourselves, init.h). +// clang-format off #if defined(PSUTIL_POSIX) #include "../../arch/posix/init.h" #endif @@ -38,6 +39,7 @@ extern int PSUTIL_DEBUG; // a signaler for connections without an actual status extern int PSUTIL_CONN_NONE; +extern int PSUTIL_TESTING; #ifdef Py_GIL_DISABLED extern PyMutex utxent_lock; @@ -47,28 +49,8 @@ extern int PSUTIL_CONN_NONE; #define UTXENT_MUTEX_LOCK() #define UTXENT_MUTEX_UNLOCK() #endif +// clang-format on -// Print a debug message on stderr. -#define psutil_debug(...) do { \ - if (! PSUTIL_DEBUG) \ - break; \ - fprintf(stderr, "psutil-debug [%s:%d]> ", __FILE__, __LINE__); \ - fprintf(stderr, __VA_ARGS__); \ - fprintf(stderr, "\n");} while(0) - - -// strncpy() variant which appends a null terminator. -#define PSUTIL_STRNCPY(dst, src, n) \ - strncpy(dst, src, n - 1); \ - dst[n - 1] = '\0' - -// ==================================================================== -// --- Custom exceptions -// ==================================================================== - -PyObject *AccessDenied(const char *msg); -PyObject *NoSuchProcess(const char *msg); -PyObject *psutil_PyErr_SetFromOSErrnoWithSyscall(const char *syscall); // ==================================================================== // --- Backward compatibility with missing Python.h APIs @@ -76,6 +58,7 @@ PyObject *psutil_PyErr_SetFromOSErrnoWithSyscall(const char *syscall); // --- _Py_PARSE_PID +// clang-format off // SIZEOF_INT|LONG is missing on Linux + PyPy (only?). // In this case we guess it from setup.py. It's not 100% bullet proof, // If wrong we'll probably get compiler warnings. @@ -117,10 +100,41 @@ PyObject *psutil_PyErr_SetFromOSErrnoWithSyscall(const char *syscall); "sizeof(long) or sizeof(long long)" #endif #endif +// clang-format on + +// ==================================================================== +// --- Internal utils +// ==================================================================== + +// Print a debug message to stderr, including where it originated from +// within the C code (file path + lineno). +#define psutil_debug(...) \ + do { \ + if (!PSUTIL_DEBUG) \ + break; \ + fprintf(stderr, "psutil-debug [%s:%d]> ", __FILE__, __LINE__); \ + fprintf(stderr, __VA_ARGS__); \ + fprintf(stderr, "\n"); \ + } while (0) + + +PyObject *psutil_oserror(void); +PyObject *psutil_oserror_ad(const char *msg); +PyObject *psutil_oserror_nsp(const char *msg); +PyObject *psutil_oserror_wsyscall(const char *syscall); +PyObject *psutil_runtime_error(const char *msg, ...); + +int str_append(char *dst, size_t dst_size, const char *src); +int str_copy(char *dst, size_t dst_size, const char *src); +int str_format(char *buf, size_t size, const char *fmt, ...); int psutil_badargs(const char *funcname); int psutil_setup(void); +// ==================================================================== +// --- Exposed to Python +// ==================================================================== + #if defined(PSUTIL_WINDOWS) || defined(PSUTIL_BSD) || defined(PSUTIL_OSX) PyObject *psutil_pids(PyObject *self, PyObject *args); #endif diff --git a/contrib/python/psutil/py3/psutil/arch/all/pids.c b/contrib/python/psutil/py3/psutil/arch/all/pids.c index d88c10dd6b1..74b1f309d08 100644 --- a/contrib/python/psutil/py3/psutil/arch/all/pids.c +++ b/contrib/python/psutil/py3/psutil/arch/all/pids.c @@ -4,12 +4,33 @@ * found in the LICENSE file. */ -#if defined(PSUTIL_WINDOWS) || defined(PSUTIL_BSD) || defined(PSUTIL_OSX) #include <Python.h> #include "init.h" +// Raise OverflowError if Python int value overflowed when converting +// to pid_t. Raise ValueError if Python int value is negative. +// Otherwise, return None. +PyObject * +psutil_check_pid_range(PyObject *self, PyObject *args) { +#ifdef PSUTIL_WINDOWS + DWORD pid; +#else + pid_t pid; +#endif + + if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) + return NULL; + if (pid < 0) { + PyErr_SetString(PyExc_ValueError, "pid must be a positive integer"); + return NULL; + } + Py_RETURN_NONE; +} + + +#if defined(PSUTIL_WINDOWS) || defined(PSUTIL_BSD) || defined(PSUTIL_OSX) PyObject * psutil_pids(PyObject *self, PyObject *args) { #ifdef PSUTIL_WINDOWS @@ -29,7 +50,7 @@ psutil_pids(PyObject *self, PyObject *args) { goto error; if (pids_count == 0) { - PyErr_Format(PyExc_RuntimeError, "no PIDs found"); + psutil_runtime_error("no PIDs found"); goto error; } diff --git a/contrib/python/psutil/py3/psutil/arch/all/str.c b/contrib/python/psutil/py3/psutil/arch/all/str.c new file mode 100644 index 00000000000..c4b90962dae --- /dev/null +++ b/contrib/python/psutil/py3/psutil/arch/all/str.c @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2009, Giampaolo Rodola. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + +// String utilities. + +#include <stdarg.h> +#include <stddef.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include "init.h" + + +static int +_error(const char *msg) { + if (PSUTIL_TESTING) { + fprintf(stderr, "CRITICAL: %s\n", msg); + fflush(stderr); + exit(EXIT_FAILURE); // terminate execution + } + else { + // Print debug msg because we never check str_*() return value. + psutil_debug("%s", msg); + } + return -1; +} + + +// Safely formats a string into a buffer. Writes a printf-style +// formatted string into `buf` of size `size`, always null-terminating +// if size > 0. Returns the number of characters written (excluding the +// null terminator) on success, or -1 if the buffer is too small or an +// error occurs. +int +str_format(char *buf, size_t size, const char *fmt, ...) { + va_list args; + int ret; + + if (size == 0) + return _error("str_format: invalid arg 'size' = 0"); + + va_start(args, fmt); +#if defined(PSUTIL_WINDOWS) + ret = _vsnprintf_s(buf, size, _TRUNCATE, fmt, args); +#else + ret = vsnprintf(buf, size, fmt, args); +#endif + va_end(args); + + if (ret < 0 || (size_t)ret >= size) { + psutil_debug("str_format: error in format '%s'", fmt); + buf[size - 1] = '\0'; + return -1; + } + return ret; +} + + +// Safely copy `src` to `dst`, always null-terminating. Replaces unsafe +// strcpy/strncpy. +int +str_copy(char *dst, size_t dst_size, const char *src) { + if (dst_size == 0) + return _error("str_copy: invalid arg 'dst_size' = 0"); + +#if defined(PSUTIL_WINDOWS) + if (strcpy_s(dst, dst_size, src) != 0) + return _error("str_copy: strcpy_s failed"); +#else + strncpy(dst, src, dst_size - 1); + dst[dst_size - 1] = '\0'; +#endif + return 0; +} + + +// Safely append `src` to `dst`, always null-terminating. Returns 0 on +// success, -1 on truncation. +int +str_append(char *dst, size_t dst_size, const char *src) { + size_t dst_len; + + if (!dst || !src || dst_size == 0) + return _error("str_append: invalid arg"); + +#if defined(PSUTIL_WINDOWS) + dst_len = strnlen_s(dst, dst_size); + if (dst_len >= dst_size - 1) + return _error("str_append: destination full or truncated"); + if (strcat_s(dst, dst_size, src) != 0) + return _error("str_append: strcat_s failed"); +#elif defined(PSUTIL_MACOS) || defined(PSUTIL_BSD) + dst_len = strlcat(dst, src, dst_size); + if (dst_len >= dst_size) + return _error("str_append: truncated"); +#else + dst_len = strnlen(dst, dst_size); + if (dst_len >= dst_size - 1) + return _error("str_append: destination full or truncated"); + strncat(dst, src, dst_size - dst_len - 1); + dst[dst_size - 1] = '\0'; +#endif + + return 0; +} diff --git a/contrib/python/psutil/py3/psutil/arch/linux/disk.c b/contrib/python/psutil/py3/psutil/arch/linux/disk.c index fb6726af989..81a608cd10b 100644 --- a/contrib/python/psutil/py3/psutil/arch/linux/disk.c +++ b/contrib/python/psutil/py3/psutil/arch/linux/disk.c @@ -39,21 +39,23 @@ psutil_disk_partitions(PyObject *self, PyObject *args) { while ((entry = getmntent(file))) { if (entry == NULL) { - PyErr_Format(PyExc_RuntimeError, "getmntent() syscall failed"); + psutil_runtime_error("getmntent() syscall failed"); goto error; } py_dev = PyUnicode_DecodeFSDefault(entry->mnt_fsname); - if (! py_dev) + if (!py_dev) goto error; py_mountp = PyUnicode_DecodeFSDefault(entry->mnt_dir); - if (! py_mountp) + if (!py_mountp) goto error; - py_tuple = Py_BuildValue("(OOss)", - py_dev, // device - py_mountp, // mount point - entry->mnt_type, // fs type - entry->mnt_opts); // options - if (! py_tuple) + py_tuple = Py_BuildValue( + "(OOss)", + py_dev, // device + py_mountp, // mount point + entry->mnt_type, // fs type + entry->mnt_opts // options + ); + if (!py_tuple) goto error; if (PyList_Append(py_retlist, py_tuple)) goto error; diff --git a/contrib/python/psutil/py3/psutil/arch/linux/init.h b/contrib/python/psutil/py3/psutil/arch/linux/init.h index 77c83c6b355..19a909125b1 100644 --- a/contrib/python/psutil/py3/psutil/arch/linux/init.h +++ b/contrib/python/psutil/py3/psutil/arch/linux/init.h @@ -6,7 +6,7 @@ #include <Python.h> #include <sys/syscall.h> // __NR_* -#include <sched.h> // CPU_ALLOC +#include <sched.h> // CPU_ALLOC PyObject *psutil_disk_partitions(PyObject *self, PyObject *args); PyObject *psutil_linux_sysinfo(PyObject *self, PyObject *args); @@ -14,16 +14,14 @@ PyObject *psutil_net_if_duplex_speed(PyObject *self, PyObject *args); // Linux >= 2.6.13 #if defined(__NR_ioprio_get) && defined(__NR_ioprio_set) - #define PSUTIL_HAS_IOPRIO - - PyObject *psutil_proc_ioprio_get(PyObject *self, PyObject *args); - PyObject *psutil_proc_ioprio_set(PyObject *self, PyObject *args); +#define PSUTIL_HAS_IOPRIO +PyObject *psutil_proc_ioprio_get(PyObject *self, PyObject *args); +PyObject *psutil_proc_ioprio_set(PyObject *self, PyObject *args); #endif // Should exist starting from CentOS 6 (year 2011). #ifdef CPU_ALLOC - #define PSUTIL_HAS_CPU_AFFINITY - - PyObject *psutil_proc_cpu_affinity_get(PyObject *self, PyObject *args); - PyObject *psutil_proc_cpu_affinity_set(PyObject *self, PyObject *args); +#define PSUTIL_HAS_CPU_AFFINITY +PyObject *psutil_proc_cpu_affinity_get(PyObject *self, PyObject *args); +PyObject *psutil_proc_cpu_affinity_set(PyObject *self, PyObject *args); #endif diff --git a/contrib/python/psutil/py3/psutil/arch/linux/mem.c b/contrib/python/psutil/py3/psutil/arch/linux/mem.c index cacf1e7766c..044e6042d44 100644 --- a/contrib/python/psutil/py3/psutil/arch/linux/mem.c +++ b/contrib/python/psutil/py3/psutil/arch/linux/mem.c @@ -15,15 +15,15 @@ psutil_linux_sysinfo(PyObject *self, PyObject *args) { struct sysinfo info; if (sysinfo(&info) != 0) - return PyErr_SetFromErrno(PyExc_OSError); + return psutil_oserror(); // note: boot time might also be determined from here return Py_BuildValue( "(kkkkkkI)", info.totalram, // total info.freeram, // free - info.bufferram, // buffer - info.sharedram, // shared - info.totalswap, // swap tot + info.bufferram, // buffer + info.sharedram, // shared + info.totalswap, // swap tot info.freeswap, // swap free info.mem_unit // multiplier ); diff --git a/contrib/python/psutil/py3/psutil/arch/linux/net.c b/contrib/python/psutil/py3/psutil/arch/linux/net.c index 2488d9ab278..6daaa431383 100644 --- a/contrib/python/psutil/py3/psutil/arch/linux/net.c +++ b/contrib/python/psutil/py3/psutil/arch/linux/net.c @@ -16,18 +16,17 @@ // see: https://github.com/giampaolo/psutil/issues/659 #ifdef PSUTIL_ETHTOOL_MISSING_TYPES - #include <linux/types.h> - typedef __u64 u64; - typedef __u32 u32; - typedef __u16 u16; - typedef __u8 u8; +#include <linux/types.h> +typedef __u64 u64; +typedef __u32 u32; +typedef __u16 u16; +typedef __u8 u8; #endif // Avoid redefinition of struct sysinfo with musl libc. #define _LINUX_SYSINFO_H #include <linux/ethtool.h> - // * defined in linux/ethtool.h but not always available (e.g. Android) // * #ifdef check needed for old kernels, see: // https://github.com/giampaolo/psutil/issues/2164 @@ -43,19 +42,19 @@ psutil_ethtool_cmd_speed(const struct ethtool_cmd *ecmd) { // May happen on old RedHat versions, see: // https://github.com/giampaolo/psutil/issues/607 #ifndef DUPLEX_UNKNOWN - #define DUPLEX_UNKNOWN 0xff +#define DUPLEX_UNKNOWN 0xff #endif + // https://github.com/giampaolo/psutil/pull/2156 #ifndef SPEED_UNKNOWN - #define SPEED_UNKNOWN -1 +#define SPEED_UNKNOWN -1 #endif - // References: // * https://github.com/dpaleino/wicd/blob/master/wicd/backends/be-ioctl.py // * http://www.i-scream.org/libstatgrab/ -PyObject* -psutil_net_if_duplex_speed(PyObject* self, PyObject* args) { +PyObject * +psutil_net_if_duplex_speed(PyObject *self, PyObject *args) { char *nic_name; int sock = 0; int ret; @@ -66,13 +65,14 @@ psutil_net_if_duplex_speed(PyObject* self, PyObject* args) { struct ethtool_cmd ethcmd; PyObject *py_retlist = NULL; - if (! PyArg_ParseTuple(args, "s", &nic_name)) + if (!PyArg_ParseTuple(args, "s", &nic_name)) return NULL; sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock == -1) - return psutil_PyErr_SetFromOSErrnoWithSyscall("socket()"); - PSUTIL_STRNCPY(ifr.ifr_name, nic_name, sizeof(ifr.ifr_name)); + return psutil_oserror_wsyscall("socket()"); + str_copy(ifr.ifr_name, sizeof(ifr.ifr_name), nic_name); + // duplex and speed memset(ðcmd, 0, sizeof ethcmd); @@ -102,7 +102,7 @@ psutil_net_if_duplex_speed(PyObject* self, PyObject* args) { speed = 0; } else { - psutil_PyErr_SetFromOSErrnoWithSyscall("ioctl(SIOCETHTOOL)"); + psutil_oserror_wsyscall("ioctl(SIOCETHTOOL)"); goto error; } } diff --git a/contrib/python/psutil/py3/psutil/arch/linux/proc.c b/contrib/python/psutil/py3/psutil/arch/linux/proc.c index 9024c818424..f608bffdc5b 100644 --- a/contrib/python/psutil/py3/psutil/arch/linux/proc.c +++ b/contrib/python/psutil/py3/psutil/arch/linux/proc.c @@ -11,6 +11,12 @@ #include <sched.h> #include <unistd.h> + +// ==================================================================== +// --- process priority (niceness) +// ==================================================================== + + #ifdef PSUTIL_HAS_IOPRIO enum { IOPRIO_WHO_PROCESS = 1, @@ -33,18 +39,17 @@ ioprio_set(int which, int who, int ioprio) { #define IOPRIO_PRIO_DATA(mask) ((mask) & IOPRIO_PRIO_MASK) #define IOPRIO_PRIO_VALUE(class, data) (((class) << IOPRIO_CLASS_SHIFT) | data) - // Return a (ioclass, iodata) Python tuple representing process I/O // priority. PyObject * psutil_proc_ioprio_get(PyObject *self, PyObject *args) { pid_t pid; int ioprio, ioclass, iodata; - if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) + if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) return NULL; ioprio = ioprio_get(IOPRIO_WHO_PROCESS, pid); if (ioprio == -1) - return PyErr_SetFromErrno(PyExc_OSError); + return psutil_oserror(); ioclass = IOPRIO_PRIO_CLASS(ioprio); iodata = IOPRIO_PRIO_DATA(ioprio); return Py_BuildValue("ii", ioclass, iodata); @@ -60,22 +65,25 @@ psutil_proc_ioprio_set(PyObject *self, PyObject *args) { int ioprio, ioclass, iodata; int retval; - if (! PyArg_ParseTuple( - args, _Py_PARSE_PID "ii", &pid, &ioclass, &iodata)) { + if (!PyArg_ParseTuple(args, _Py_PARSE_PID "ii", &pid, &ioclass, &iodata)) { return NULL; } ioprio = IOPRIO_PRIO_VALUE(ioclass, iodata); retval = ioprio_set(IOPRIO_WHO_PROCESS, pid, ioprio); if (retval == -1) - return PyErr_SetFromErrno(PyExc_OSError); + return psutil_oserror(); Py_RETURN_NONE; } #endif // PSUTIL_HAS_IOPRIO -#ifdef PSUTIL_HAS_CPU_AFFINITY +// ==================================================================== +// --- process CPU affinity +// ==================================================================== -// Return process CPU affinity as a Python list. + +#ifdef PSUTIL_HAS_CPU_AFFINITY +// Return process CPU affinity as a list of integers. PyObject * psutil_proc_cpu_affinity_get(PyObject *self, PyObject *args) { int cpu, ncpus, count, cpucount_s; @@ -100,10 +108,13 @@ psutil_proc_cpu_affinity_get(PyObject *self, PyObject *args) { break; CPU_FREE(mask); if (errno != EINVAL) - return PyErr_SetFromErrno(PyExc_OSError); + return psutil_oserror(); if (ncpus > INT_MAX / 2) { - PyErr_SetString(PyExc_OverflowError, "could not allocate " - "a large enough CPU set"); + PyErr_SetString( + PyExc_OverflowError, + "could not allocate " + "a large enough CPU set" + ); return NULL; } ncpus = ncpus * 2; @@ -153,7 +164,8 @@ psutil_proc_cpu_affinity_set(PyObject *self, PyObject *args) { if (!PySequence_Check(py_cpu_set)) { return PyErr_Format( PyExc_TypeError, - "sequence argument expected, got %R", Py_TYPE(py_cpu_set) + "sequence argument expected, got %R", + Py_TYPE(py_cpu_set) ); } @@ -179,7 +191,7 @@ psutil_proc_cpu_affinity_set(PyObject *self, PyObject *args) { len = sizeof(cpu_set); if (sched_setaffinity(pid, len, &cpu_set)) { - return PyErr_SetFromErrno(PyExc_OSError); + return psutil_oserror(); } Py_RETURN_NONE; diff --git a/contrib/python/psutil/py3/psutil/arch/osx/cpu.c b/contrib/python/psutil/py3/psutil/arch/osx/cpu.c index e556037d57b..56accf167c2 100644 --- a/contrib/python/psutil/py3/psutil/arch/osx/cpu.c +++ b/contrib/python/psutil/py3/psutil/arch/osx/cpu.c @@ -27,15 +27,15 @@ For reference, here's the git history with original implementations: #include <sys/vmmeter.h> #include <mach/mach.h> #if defined(__arm64__) || defined(__aarch64__) - #include <CoreFoundation/CoreFoundation.h> - #include <IOKit/IOKitLib.h> +#include <CoreFoundation/CoreFoundation.h> +#include <IOKit/IOKitLib.h> #endif #include "../../arch/all/init.h" // added in macOS 12 #ifndef kIOMainPortDefault - #define kIOMainPortDefault 0 +#define kIOMainPortDefault 0 #endif PyObject * @@ -66,18 +66,17 @@ psutil_cpu_times(PyObject *self, PyObject *args) { mach_port_t mport = mach_host_self(); if (mport == MACH_PORT_NULL) { - PyErr_SetString(PyExc_RuntimeError, - "mach_host_self() returned MACH_PORT_NULL"); + psutil_runtime_error("mach_host_self() returned MACH_PORT_NULL"); return NULL; } - error = host_statistics(mport, HOST_CPU_LOAD_INFO, - (host_info_t)&r_load, &count); + error = host_statistics( + mport, HOST_CPU_LOAD_INFO, (host_info_t)&r_load, &count + ); mach_port_deallocate(mach_task_self(), mport); if (error != KERN_SUCCESS) { - return PyErr_Format( - PyExc_RuntimeError, + return psutil_runtime_error( "host_statistics(HOST_CPU_LOAD_INFO) syscall failed: %s", mach_error_string(error) ); @@ -101,8 +100,7 @@ psutil_cpu_stats(PyObject *self, PyObject *args) { struct vmmeter vmstat; if (mport == MACH_PORT_NULL) { - PyErr_SetString(PyExc_RuntimeError, - "mach_host_self() returned MACH_PORT_NULL"); + psutil_runtime_error("mach_host_self() returned MACH_PORT_NULL"); return NULL; } @@ -110,10 +108,8 @@ psutil_cpu_stats(PyObject *self, PyObject *args) { mach_port_deallocate(mach_task_self(), mport); if (ret != KERN_SUCCESS) { - PyErr_Format( - PyExc_RuntimeError, - "host_statistics(HOST_VM_INFO) failed: %s", - mach_error_string(ret) + psutil_runtime_error( + "host_statistics(HOST_VM_INFO) failed: %s", mach_error_string(ret) ); return NULL; } @@ -158,8 +154,9 @@ psutil_find_pmgr_entry(io_registry_entry_t *out_entry) { while ((entry = IOIteratorNext(iter)) != IO_OBJECT_NULL) { io_name_t name; - if (IORegistryEntryGetName(entry, name) == KERN_SUCCESS && - strcmp(name, "pmgr") == 0) { + if (IORegistryEntryGetName(entry, name) == KERN_SUCCESS + && strcmp(name, "pmgr") == 0) + { found = 1; break; } @@ -197,10 +194,7 @@ psutil_cpu_freq(PyObject *self, PyObject *args) { uint32_t pMin = 0, eMin = 0, min = 0, max = 0, curr = 0; if (!psutil_find_pmgr_entry(&entry)) { - PyErr_SetString( - PyExc_RuntimeError, - "'pmgr' entry not found in AppleARMIODevice" - ); + psutil_runtime_error("'pmgr' entry not found in AppleARMIODevice"); return NULL; } @@ -211,14 +205,11 @@ psutil_cpu_freq(PyObject *self, PyObject *args) { entry, CFSTR("voltage-states1-sram"), kCFAllocatorDefault, 0 ); - if (!pCoreRef || - !eCoreRef || - CFGetTypeID(pCoreRef) != CFDataGetTypeID() || - CFGetTypeID(eCoreRef) != CFDataGetTypeID() || - CFDataGetLength(pCoreRef) < 8 || - CFDataGetLength(eCoreRef) < 4) + if (!pCoreRef || !eCoreRef || CFGetTypeID(pCoreRef) != CFDataGetTypeID() + || CFGetTypeID(eCoreRef) != CFDataGetTypeID() + || CFDataGetLength(pCoreRef) < 8 || CFDataGetLength(eCoreRef) < 4) { - PyErr_SetString(PyExc_RuntimeError, "invalid CPU frequency data"); + psutil_runtime_error("invalid CPU frequency data"); goto cleanup; } @@ -260,7 +251,7 @@ psutil_cpu_freq(PyObject *self, PyObject *args) { int mib[2] = {CTL_HW, HW_CPU_FREQ}; if (psutil_sysctl(mib, 2, &curr, sizeof(curr)) < 0) - return psutil_PyErr_SetFromOSErrnoWithSyscall("sysctl(HW_CPU_FREQ)"); + return psutil_oserror_wsyscall("sysctl(HW_CPU_FREQ)"); if (psutil_sysctlbyname("hw.cpufrequency_min", &min, sizeof(min)) != 0) { min = 0; @@ -296,7 +287,7 @@ psutil_per_cpu_times(PyObject *self, PyObject *args) { return NULL; if (mport == MACH_PORT_NULL) { - PyErr_SetString(PyExc_RuntimeError, "mach_host_self() returned NULL"); + psutil_runtime_error("mach_host_self() returned NULL"); goto error; } @@ -306,10 +297,8 @@ psutil_per_cpu_times(PyObject *self, PyObject *args) { mach_port_deallocate(mach_task_self(), mport); if (error != KERN_SUCCESS || !info_array) { - PyErr_Format( - PyExc_RuntimeError, - "host_processor_info failed: %s", - mach_error_string(error) + psutil_runtime_error( + "host_processor_info failed: %s", mach_error_string(error) ); goto error; } diff --git a/contrib/python/psutil/py3/psutil/arch/osx/disk.c b/contrib/python/psutil/py3/psutil/arch/osx/disk.c index 052d19996b3..c08ef24c7cc 100644 --- a/contrib/python/psutil/py3/psutil/arch/osx/disk.c +++ b/contrib/python/psutil/py3/psutil/arch/osx/disk.c @@ -46,7 +46,7 @@ psutil_disk_partitions(PyObject *self, PyObject *args) { num = getfsstat(NULL, 0, MNT_NOWAIT); Py_END_ALLOW_THREADS if (num == -1) { - PyErr_SetFromErrno(PyExc_OSError); + psutil_oserror(); goto error; } @@ -61,7 +61,7 @@ psutil_disk_partitions(PyObject *self, PyObject *args) { num = getfsstat(fs, len, MNT_NOWAIT); Py_END_ALLOW_THREADS if (num == -1) { - PyErr_SetFromErrno(PyExc_OSError); + psutil_oserror(); goto error; } @@ -71,74 +71,75 @@ psutil_disk_partitions(PyObject *self, PyObject *args) { // see sys/mount.h if (flags & MNT_RDONLY) - strlcat(opts, "ro", sizeof(opts)); + str_append(opts, sizeof(opts), "ro"); else - strlcat(opts, "rw", sizeof(opts)); + str_append(opts, sizeof(opts), "rw"); if (flags & MNT_SYNCHRONOUS) - strlcat(opts, ",sync", sizeof(opts)); + str_append(opts, sizeof(opts), ",sync"); if (flags & MNT_NOEXEC) - strlcat(opts, ",noexec", sizeof(opts)); + str_append(opts, sizeof(opts), ",noexec"); if (flags & MNT_NOSUID) - strlcat(opts, ",nosuid", sizeof(opts)); + str_append(opts, sizeof(opts), ",nosuid"); if (flags & MNT_UNION) - strlcat(opts, ",union", sizeof(opts)); + str_append(opts, sizeof(opts), ",union"); if (flags & MNT_ASYNC) - strlcat(opts, ",async", sizeof(opts)); + str_append(opts, sizeof(opts), ",async"); if (flags & MNT_EXPORTED) - strlcat(opts, ",exported", sizeof(opts)); + str_append(opts, sizeof(opts), ",exported"); if (flags & MNT_LOCAL) - strlcat(opts, ",local", sizeof(opts)); + str_append(opts, sizeof(opts), ",local"); if (flags & MNT_QUOTA) - strlcat(opts, ",quota", sizeof(opts)); + str_append(opts, sizeof(opts), ",quota"); if (flags & MNT_ROOTFS) - strlcat(opts, ",rootfs", sizeof(opts)); + str_append(opts, sizeof(opts), ",rootfs"); if (flags & MNT_DOVOLFS) - strlcat(opts, ",dovolfs", sizeof(opts)); + str_append(opts, sizeof(opts), ",dovolfs"); if (flags & MNT_DONTBROWSE) - strlcat(opts, ",dontbrowse", sizeof(opts)); + str_append(opts, sizeof(opts), ",dontbrowse"); if (flags & MNT_IGNORE_OWNERSHIP) - strlcat(opts, ",ignore-ownership", sizeof(opts)); + str_append(opts, sizeof(opts), ",ignore-ownership"); if (flags & MNT_AUTOMOUNTED) - strlcat(opts, ",automounted", sizeof(opts)); + str_append(opts, sizeof(opts), ",automounted"); if (flags & MNT_JOURNALED) - strlcat(opts, ",journaled", sizeof(opts)); + str_append(opts, sizeof(opts), ",journaled"); if (flags & MNT_NOUSERXATTR) - strlcat(opts, ",nouserxattr", sizeof(opts)); + str_append(opts, sizeof(opts), ",nouserxattr"); if (flags & MNT_DEFWRITE) - strlcat(opts, ",defwrite", sizeof(opts)); + str_append(opts, sizeof(opts), ",defwrite"); if (flags & MNT_UPDATE) - strlcat(opts, ",update", sizeof(opts)); + str_append(opts, sizeof(opts), ",update"); if (flags & MNT_RELOAD) - strlcat(opts, ",reload", sizeof(opts)); + str_append(opts, sizeof(opts), ",reload"); if (flags & MNT_FORCE) - strlcat(opts, ",force", sizeof(opts)); + str_append(opts, sizeof(opts), ",force"); if (flags & MNT_CMDFLAGS) - strlcat(opts, ",cmdflags", sizeof(opts)); - // requires macOS >= 10.5 + str_append(opts, sizeof(opts), ",cmdflags"); + // requires macOS >= 10.5 #ifdef MNT_QUARANTINE if (flags & MNT_QUARANTINE) - strlcat(opts, ",quarantine", sizeof(opts)); + str_append(opts, sizeof(opts), ",quarantine"); #endif #ifdef MNT_MULTILABEL if (flags & MNT_MULTILABEL) - strlcat(opts, ",multilabel", sizeof(opts)); + str_append(opts, sizeof(opts), ",multilabel"); #endif #ifdef MNT_NOATIME if (flags & MNT_NOATIME) - strlcat(opts, ",noatime", sizeof(opts)); + str_append(opts, sizeof(opts), ",noatime"); #endif py_dev = PyUnicode_DecodeFSDefault(fs[i].f_mntfromname); - if (! py_dev) + if (!py_dev) goto error; py_mountp = PyUnicode_DecodeFSDefault(fs[i].f_mntonname); - if (! py_mountp) + if (!py_mountp) goto error; py_tuple = Py_BuildValue( "(OOss)", - py_dev, // device - py_mountp, // mount point - fs[i].f_fstypename, // fs type - opts); // options + py_dev, // device + py_mountp, // mount point + fs[i].f_fstypename, // fs type + opts // options + ); if (!py_tuple) goto error; if (PyList_Append(py_retlist, py_tuple)) @@ -166,9 +167,16 @@ PyObject * psutil_disk_usage_used(PyObject *self, PyObject *args) { PyObject *py_default_value; PyObject *py_mount_point_bytes = NULL; - char* mount_point; + char *mount_point; - if (!PyArg_ParseTuple(args, "O&O", PyUnicode_FSConverter, &py_mount_point_bytes, &py_default_value)) { + if (!PyArg_ParseTuple( + args, + "O&O", + PyUnicode_FSConverter, + &py_mount_point_bytes, + &py_default_value + )) + { return NULL; } mount_point = PyBytes_AsString(py_mount_point_bytes); @@ -197,7 +205,9 @@ psutil_disk_usage_used(PyObject *self, PyObject *args) { Py_XDECREF(py_mount_point_bytes); return PyLong_FromUnsignedLongLong(attrbuf.spaceused); } - psutil_debug("getattrlist(ATTR_VOL_SPACEUSED) failed, fall-back to default value"); + psutil_debug( + "getattrlist(ATTR_VOL_SPACEUSED) failed, fall-back to default value" + ); #endif Py_XDECREF(py_mount_point_bytes); Py_INCREF(py_default_value); @@ -223,11 +233,11 @@ psutil_disk_io_counters(PyObject *self, PyObject *args) { return NULL; if (IOServiceGetMatchingServices( - kIOMasterPortDefault, - IOServiceMatching(kIOMediaClass), - &disk_list) != kIOReturnSuccess) + kIOMasterPortDefault, IOServiceMatching(kIOMediaClass), &disk_list + ) + != kIOReturnSuccess) { - PyErr_SetString(PyExc_RuntimeError, "unable to get the list of disks"); + psutil_runtime_error("unable to get the list of disks"); goto error; } @@ -238,8 +248,10 @@ psutil_disk_io_counters(PyObject *self, PyObject *args) { stats_dict = NULL; parent = IO_OBJECT_NULL; - if (IORegistryEntryGetParentEntry(disk, kIOServicePlane, &parent) != kIOReturnSuccess) { - PyErr_SetString(PyExc_RuntimeError, "unable to get the disk's parent"); + if (IORegistryEntryGetParentEntry(disk, kIOServicePlane, &parent) + != kIOReturnSuccess) + { + psutil_runtime_error("unable to get the disk's parent"); goto error; } @@ -249,41 +261,47 @@ psutil_disk_io_counters(PyObject *self, PyObject *args) { continue; } - if (IORegistryEntryCreateCFProperties(disk, + if (IORegistryEntryCreateCFProperties( + disk, (CFMutableDictionaryRef *)&parent_dict, - kCFAllocatorDefault, kNilOptions) != kIOReturnSuccess) + kCFAllocatorDefault, + kNilOptions + ) + != kIOReturnSuccess) { - PyErr_SetString( - PyExc_RuntimeError, "unable to get the parent's properties" - ); + psutil_runtime_error("unable to get the parent's properties"); goto error; } - if (IORegistryEntryCreateCFProperties(parent, + if (IORegistryEntryCreateCFProperties( + parent, (CFMutableDictionaryRef *)&props_dict, - kCFAllocatorDefault, kNilOptions) != kIOReturnSuccess) + kCFAllocatorDefault, + kNilOptions + ) + != kIOReturnSuccess) { - PyErr_SetString( - PyExc_RuntimeError, "unable to get the disk properties" - ); + psutil_runtime_error("unable to get the disk properties"); goto error; } - CFStringRef disk_name_ref = (CFStringRef)CFDictionaryGetValue( - parent_dict, CFSTR(kIOBSDNameKey) - ); + CFStringRef disk_name_ref = (CFStringRef + )CFDictionaryGetValue(parent_dict, CFSTR(kIOBSDNameKey)); if (disk_name_ref == NULL) { - PyErr_SetString(PyExc_RuntimeError, "unable to get disk name"); + psutil_runtime_error("unable to get disk name"); goto error; } const int kMaxDiskNameSize = 64; char disk_name[kMaxDiskNameSize]; - if (!CFStringGetCString(disk_name_ref, disk_name, kMaxDiskNameSize, - CFStringGetSystemEncoding())) { - PyErr_SetString( - PyExc_RuntimeError, "unable to convert disk name to C string" - ); + if (!CFStringGetCString( + disk_name_ref, + disk_name, + kMaxDiskNameSize, + CFStringGetSystemEncoding() + )) + { + psutil_runtime_error("unable to convert disk name to C string"); goto error; } @@ -291,7 +309,7 @@ psutil_disk_io_counters(PyObject *self, PyObject *args) { props_dict, CFSTR(kIOBlockStorageDriverStatisticsKey) ); if (stats_dict == NULL) { - PyErr_SetString(PyExc_RuntimeError, "unable to get disk stats"); + psutil_runtime_error("unable to get disk stats"); goto error; } @@ -300,27 +318,36 @@ psutil_disk_io_counters(PyObject *self, PyObject *args) { int64_t read_time = 0, write_time = 0; if ((number = (CFNumberRef)CFDictionaryGetValue( - stats_dict, CFSTR(kIOBlockStorageDriverStatisticsReadsKey)))) + stats_dict, CFSTR(kIOBlockStorageDriverStatisticsReadsKey) + ))) CFNumberGetValue(number, kCFNumberSInt64Type, &reads); if ((number = (CFNumberRef)CFDictionaryGetValue( - stats_dict, CFSTR(kIOBlockStorageDriverStatisticsWritesKey)))) + stats_dict, CFSTR(kIOBlockStorageDriverStatisticsWritesKey) + ))) CFNumberGetValue(number, kCFNumberSInt64Type, &writes); if ((number = (CFNumberRef)CFDictionaryGetValue( - stats_dict, CFSTR(kIOBlockStorageDriverStatisticsBytesReadKey)))) + stats_dict, CFSTR(kIOBlockStorageDriverStatisticsBytesReadKey) + ))) CFNumberGetValue(number, kCFNumberSInt64Type, &read_bytes); if ((number = (CFNumberRef)CFDictionaryGetValue( - stats_dict, CFSTR(kIOBlockStorageDriverStatisticsBytesWrittenKey)))) + stats_dict, + CFSTR(kIOBlockStorageDriverStatisticsBytesWrittenKey) + ))) CFNumberGetValue(number, kCFNumberSInt64Type, &write_bytes); if ((number = (CFNumberRef)CFDictionaryGetValue( - stats_dict, CFSTR(kIOBlockStorageDriverStatisticsTotalReadTimeKey)))) + stats_dict, + CFSTR(kIOBlockStorageDriverStatisticsTotalReadTimeKey) + ))) CFNumberGetValue(number, kCFNumberSInt64Type, &read_time); if ((number = (CFNumberRef)CFDictionaryGetValue( - stats_dict, CFSTR(kIOBlockStorageDriverStatisticsTotalWriteTimeKey)))) + stats_dict, + CFSTR(kIOBlockStorageDriverStatisticsTotalWriteTimeKey) + ))) CFNumberGetValue(number, kCFNumberSInt64Type, &write_time); py_disk_info = Py_BuildValue( diff --git a/contrib/python/psutil/py3/psutil/arch/osx/init.c b/contrib/python/psutil/py3/psutil/arch/osx/init.c index 7120e8ab0e5..1f4aab463f6 100644 --- a/contrib/python/psutil/py3/psutil/arch/osx/init.c +++ b/contrib/python/psutil/py3/psutil/arch/osx/init.c @@ -20,7 +20,7 @@ psutil_setup_osx(void) { ret = mach_timebase_info(&PSUTIL_MACH_TIMEBASE_INFO); if (ret != KERN_SUCCESS) { - psutil_PyErr_SetFromOSErrnoWithSyscall("mach_timebase_info"); + psutil_oserror_wsyscall("mach_timebase_info"); return -1; } return 0; diff --git a/contrib/python/psutil/py3/psutil/arch/osx/init.h b/contrib/python/psutil/py3/psutil/arch/osx/init.h index 4a13f73e0da..d36e26f2caa 100644 --- a/contrib/python/psutil/py3/psutil/arch/osx/init.h +++ b/contrib/python/psutil/py3/psutil/arch/osx/init.h @@ -5,12 +5,24 @@ */ #include <Python.h> +#include <sys/user.h> +#include <sys/types.h> +#include <libproc.h> #include <mach/mach_time.h> extern struct mach_timebase_info PSUTIL_MACH_TIMEBASE_INFO; int psutil_setup_osx(void); int _psutil_pids(pid_t **pids_array, int *pids_count); +int is_zombie(size_t pid); + +int psutil_get_kinfo_proc(pid_t pid, struct kinfo_proc *kp); +int psutil_sysctl_procargs(pid_t pid, char *procargs, size_t *argmax); +int psutil_proc_pidinfo( + pid_t pid, int flavor, uint64_t arg, void *pti, int size +); +int psutil_task_for_pid(pid_t pid, mach_port_t *task); +struct proc_fdinfo *psutil_proc_list_fds(pid_t pid, int *num_fds); PyObject *psutil_boot_time(PyObject *self, PyObject *args); PyObject *psutil_cpu_count_cores(PyObject *self, PyObject *args); @@ -28,7 +40,6 @@ PyObject *psutil_proc_cmdline(PyObject *self, PyObject *args); PyObject *psutil_proc_cwd(PyObject *self, PyObject *args); PyObject *psutil_proc_environ(PyObject *self, PyObject *args); PyObject *psutil_proc_exe(PyObject *self, PyObject *args); -PyObject *psutil_proc_is_zombie(PyObject *self, PyObject *args); PyObject *psutil_proc_kinfo_oneshot(PyObject *self, PyObject *args); PyObject *psutil_proc_memory_uss(PyObject *self, PyObject *args); PyObject *psutil_proc_name(PyObject *self, PyObject *args); diff --git a/contrib/python/psutil/py3/psutil/arch/osx/mem.c b/contrib/python/psutil/py3/psutil/arch/osx/mem.c index cbac711a9b0..b222b566a67 100644 --- a/contrib/python/psutil/py3/psutil/arch/osx/mem.c +++ b/contrib/python/psutil/py3/psutil/arch/osx/mem.c @@ -27,16 +27,16 @@ psutil_sys_vminfo(vm_statistics64_t vmstat) { mport = mach_host_self(); if (mport == MACH_PORT_NULL) { - PyErr_SetString(PyExc_RuntimeError, - "mach_host_self() returned MACH_PORT_NULL"); + psutil_runtime_error("mach_host_self() returned MACH_PORT_NULL"); return -1; } - ret = host_statistics64(mport, HOST_VM_INFO64, (host_info64_t)vmstat, &count); + ret = host_statistics64( + mport, HOST_VM_INFO64, (host_info64_t)vmstat, &count + ); mach_port_deallocate(mach_task_self(), mport); if (ret != KERN_SUCCESS) { - PyErr_Format( - PyExc_RuntimeError, + psutil_runtime_error( "host_statistics64(HOST_VM_INFO64) syscall failed: %s", mach_error_string(ret) ); @@ -54,7 +54,7 @@ psutil_sys_vminfo(vm_statistics64_t vmstat) { */ PyObject * psutil_virtual_mem(PyObject *self, PyObject *args) { - int mib[2]; + int mib[2]; uint64_t total; vm_statistics64_data_t vm; long pagesize = psutil_getpagesize(); @@ -72,12 +72,12 @@ psutil_virtual_mem(PyObject *self, PyObject *args) { return Py_BuildValue( "KKKKKK", - (unsigned long long) total, - (unsigned long long) vm.active_count * pagesize, // active - (unsigned long long) vm.inactive_count * pagesize, // inactive - (unsigned long long) vm.wire_count * pagesize, // wired - (unsigned long long) vm.free_count * pagesize, // free - (unsigned long long) vm.speculative_count * pagesize // speculative + (unsigned long long)total, + (unsigned long long)vm.active_count * pagesize, // active + (unsigned long long)vm.inactive_count * pagesize, // inactive + (unsigned long long)vm.wire_count * pagesize, // wired + (unsigned long long)vm.free_count * pagesize, // free + (unsigned long long)vm.speculative_count * pagesize // speculative ); } @@ -96,17 +96,17 @@ psutil_swap_mem(PyObject *self, PyObject *args) { mib[1] = VM_SWAPUSAGE; if (psutil_sysctl(mib, 2, &totals, sizeof(totals)) != 0) - return psutil_PyErr_SetFromOSErrnoWithSyscall("sysctl(VM_SWAPUSAGE)"); + return psutil_oserror_wsyscall("sysctl(VM_SWAPUSAGE)"); if (psutil_sys_vminfo(&vmstat) != 0) return NULL; return Py_BuildValue( "KKKKK", - (unsigned long long) totals.xsu_total, - (unsigned long long) totals.xsu_used, - (unsigned long long) totals.xsu_avail, - (unsigned long long) vmstat.pageins * pagesize, - (unsigned long long) vmstat.pageouts * pagesize + (unsigned long long)totals.xsu_total, + (unsigned long long)totals.xsu_used, + (unsigned long long)totals.xsu_avail, + (unsigned long long)vmstat.pageins * pagesize, + (unsigned long long)vmstat.pageouts * pagesize ); } diff --git a/contrib/python/psutil/py3/psutil/arch/osx/net.c b/contrib/python/psutil/py3/psutil/arch/osx/net.c index 93be69e5413..12847320fc2 100644 --- a/contrib/python/psutil/py3/psutil/arch/osx/net.c +++ b/contrib/python/psutil/py3/psutil/arch/osx/net.c @@ -30,11 +30,11 @@ psutil_net_io_counters(PyObject *self, PyObject *args) { if (py_retdict == NULL) return NULL; - mib[0] = CTL_NET; // networking subsystem - mib[1] = PF_ROUTE; // type of information - mib[2] = 0; // protocol (IPPROTO_xxx) - mib[3] = 0; // address family - mib[4] = NET_RT_IFLIST2; // operation + mib[0] = CTL_NET; // networking subsystem + mib[1] = PF_ROUTE; // type of information + mib[2] = 0; // protocol (IPPROTO_xxx) + mib[3] = 0; // address family + mib[4] = NET_RT_IFLIST2; // operation mib[5] = 0; if (psutil_sysctl_malloc(mib, 6, &buf, &len) != 0) @@ -42,7 +42,7 @@ psutil_net_io_counters(PyObject *self, PyObject *args) { lim = buf + len; - for (next = buf; next < lim; ) { + for (next = buf; next < lim;) { if ((size_t)(lim - next) < sizeof(struct if_msghdr)) { psutil_debug("struct if_msghdr size mismatch (skip entry)"); break; @@ -90,7 +90,8 @@ psutil_net_io_counters(PyObject *self, PyObject *args) { (unsigned long long)if2m->ifm_data.ifi_ierrors, (unsigned long long)if2m->ifm_data.ifi_oerrors, (unsigned long long)if2m->ifm_data.ifi_iqdrops, - 0); // dropout not supported + 0 + ); // dropout not supported if (!py_ifc_info) goto error; diff --git a/contrib/python/psutil/py3/psutil/arch/osx/pids.c b/contrib/python/psutil/py3/psutil/arch/osx/pids.c index 2c3ddaa82bf..debd8af4d65 100644 --- a/contrib/python/psutil/py3/psutil/arch/osx/pids.c +++ b/contrib/python/psutil/py3/psutil/arch/osx/pids.c @@ -28,7 +28,7 @@ _psutil_pids(pid_t **pids_array, int *pids_count) { return -1; if (len == 0) { - PyErr_Format(PyExc_RuntimeError, "no PIDs found"); + psutil_runtime_error("no PIDs found"); goto error; } diff --git a/contrib/python/psutil/py3/psutil/arch/osx/proc.c b/contrib/python/psutil/py3/psutil/arch/osx/proc.c index 43c91ffb73b..758f5ed15d1 100644 --- a/contrib/python/psutil/py3/psutil/arch/osx/proc.c +++ b/contrib/python/psutil/py3/psutil/arch/osx/proc.c @@ -11,7 +11,6 @@ // https://github.com/giampaolo/psutil/blame/efd7ed3/psutil/arch/osx/process_info.c #include <Python.h> -#include <assert.h> #include <errno.h> #include <stdbool.h> #include <stdlib.h> @@ -32,264 +31,31 @@ #include "../../arch/all/init.h" -#define PSUTIL_TV2DOUBLE(t) ((t).tv_sec + (t).tv_usec / 1000000.0) - - -// ==================================================================== -// --- utils -// ==================================================================== - - -static int -psutil_get_kinfo_proc(pid_t pid, struct kinfo_proc *kp) { - int mib[4]; - size_t len; - mib[0] = CTL_KERN; - mib[1] = KERN_PROC; - mib[2] = KERN_PROC_PID; - mib[3] = pid; - - if (pid < 0 || !kp) - return psutil_badargs("psutil_get_kinfo_proc"); - - len = sizeof(struct kinfo_proc); - - if (sysctl(mib, 4, kp, &len, NULL, 0) == -1) { - // raise an exception and throw errno as the error - psutil_PyErr_SetFromOSErrnoWithSyscall("sysctl"); - return -1; - } - - // sysctl succeeds but len is zero, happens when process has gone away - if (len == 0) { - NoSuchProcess("sysctl(kinfo_proc), len == 0"); - return -1; - } - return 0; -} - - -static int -is_zombie(size_t pid) { - struct kinfo_proc kp; - - if (pid < 0) - return psutil_badargs("is_zombie"); - - if (psutil_get_kinfo_proc(pid, &kp) == -1) { - PyErr_Clear(); - return 0; - } - if (kp.kp_proc.p_stat == SZOMB) - return 1; - return 0; -} - - -// Read process argument space. -static int -psutil_sysctl_procargs(pid_t pid, char *procargs, size_t *argmax) { - int mib[3]; - - mib[0] = CTL_KERN; - mib[1] = KERN_PROCARGS2; - mib[2] = pid; - - if (pid < 0 || !procargs || !argmax || *argmax == 0) - return psutil_badargs("psutil_sysctl_procargs"); - - if (sysctl(mib, 3, procargs, argmax, NULL, 0) < 0) { - if (psutil_pid_exists(pid) == 0) { - NoSuchProcess("psutil_pid_exists -> 0"); - return -1; - } - - if (is_zombie(pid) == 1) { - PyErr_SetString(ZombieProcessError, ""); - return -1; - } - - if (errno == EINVAL) { - psutil_debug("sysctl(KERN_PROCARGS2) -> EINVAL translated to AD"); - AccessDenied("sysctl(KERN_PROCARGS2) -> EINVAL"); - return -1; - } - - if (errno == EIO) { - psutil_debug("sysctl(KERN_PROCARGS2) -> EIO translated to AD"); - AccessDenied("sysctl(KERN_PROCARGS2) -> EIO"); - return -1; - } - psutil_PyErr_SetFromOSErrnoWithSyscall("sysctl(KERN_PROCARGS2)"); - return -1; - } - return 0; -} - - -/* - * A wrapper around proc_pidinfo(). - * https://opensource.apple.com/source/xnu/xnu-2050.7.9/bsd/kern/proc_info.c - * Returns 0 on failure. - */ +// macOS is apparently the only UNIX where the process "base" status +// (running, idle, etc.) is unreliable and must be guessed from flags: +// https://github.com/giampaolo/psutil/issues/2675 static int -psutil_proc_pidinfo(pid_t pid, int flavor, uint64_t arg, void *pti, int size) { - int ret; - - if (pid < 0 || !pti || size <= 0) - return psutil_badargs("psutil_proc_pidinfo"); +convert_status(struct extern_proc *p, struct eproc *e) { + int flag = p->p_flag; + int eflag = e->e_flag; - errno = 0; - ret = proc_pidinfo(pid, flavor, arg, pti, size); - if (ret <= 0) { - psutil_raise_for_pid(pid, "proc_pidinfo()"); - return -1; - } + // zombies and stopped + if (p->p_stat == SZOMB) + return SZOMB; + if (p->p_stat == SSTOP) + return SSTOP; - // check for truncated return size - if (ret < size) { - psutil_raise_for_pid( - pid, - "proc_pidinfo() returned less data than requested buffer size" - ); - return -1; - } + if (flag & P_SYSTEM) + return SIDL; // system idle + if (flag & P_WEXIT) + return SIDL; // waiting to exit + if (flag & P_PPWAIT) + return SIDL; // parent waiting + if (eflag & EPROC_SLEADER) + return SSLEEP; // session leader treated as sleeping - return 0; -} - - -/* - * A wrapper around task_for_pid() which sucks big time: - * - it's not documented - * - errno is set only sometimes - * - sometimes errno is ENOENT (?!?) - * - for PIDs != getpid() or PIDs which are not members of the procmod - * it requires root - * As such we can only guess what the heck went wrong and fail either - * with NoSuchProcess or give up with AccessDenied. - * References: - * https://github.com/giampaolo/psutil/issues/1181 - * https://github.com/giampaolo/psutil/issues/1209 - * https://github.com/giampaolo/psutil/issues/1291#issuecomment-396062519 - */ -static int -psutil_task_for_pid(pid_t pid, mach_port_t *task) { - kern_return_t err; - - if (pid < 0 || !task) - return psutil_badargs("psutil_task_for_pid"); - - err = task_for_pid(mach_task_self(), pid, task); - if (err != KERN_SUCCESS) { - if (psutil_pid_exists(pid) == 0) { - NoSuchProcess("task_for_pid"); - } - else if (is_zombie(pid) == 1) { - PyErr_SetString(ZombieProcessError, - "task_for_pid -> psutil_is_zombie -> 1"); - } - else { - psutil_debug( - "task_for_pid() failed (pid=%ld, err=%i, errno=%i, msg='%s'); " - "setting AccessDenied()", - (long)pid, err, errno, mach_error_string(err)); - AccessDenied("task_for_pid"); - } - return -1; - } - - return 0; -} - - -/* - * A wrapper around proc_pidinfo(PROC_PIDLISTFDS), which dynamically sets - * the buffer size. - */ -static struct proc_fdinfo* -psutil_proc_list_fds(pid_t pid, int *num_fds) { - int ret; - int fds_size = 0; - int max_size = 24 * 1024 * 1024; // 24M - struct proc_fdinfo *fds_pointer = NULL; - - if (pid < 0 || num_fds == NULL) { - psutil_badargs("psutil_proc_list_fds"); - return NULL; - } - - errno = 0; - ret = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, NULL, 0); - if (ret <= 0) { - psutil_raise_for_pid(pid, "proc_pidinfo(PROC_PIDLISTFDS) 1/2"); - goto error; - } - - while (1) { - if (ret > fds_size) { - while (ret > fds_size) { - fds_size += PROC_PIDLISTFD_SIZE * 32; - if (fds_size > max_size) { - PyErr_Format(PyExc_RuntimeError, - "prevent malloc() to allocate > 24M"); - goto error; - } - } - - if (fds_pointer != NULL) { - free(fds_pointer); - } - fds_pointer = malloc(fds_size); - - if (fds_pointer == NULL) { - PyErr_NoMemory(); - goto error; - } - } - - errno = 0; - ret = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, fds_pointer, fds_size); - if (ret <= 0) { - psutil_raise_for_pid(pid, "proc_pidinfo(PROC_PIDLISTFDS) 2/2"); - goto error; - } - - if (ret + (int)PROC_PIDLISTFD_SIZE >= fds_size) { - psutil_debug("PROC_PIDLISTFDS: make room for 1 extra fd"); - ret = fds_size + (int)PROC_PIDLISTFD_SIZE; - continue; - } - - break; - } - - *num_fds = (ret / (int)PROC_PIDLISTFD_SIZE); - return fds_pointer; - -error: - if (fds_pointer != NULL) - free(fds_pointer); - return NULL; -} - - -// ==================================================================== -// --- Python APIs -// ==================================================================== - - -// Return True if PID is a zombie else False, including if PID does not -// exist or the underlying function fails. -PyObject * -psutil_proc_is_zombie(PyObject *self, PyObject *args) { - pid_t pid; - - if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) - return NULL; - if (is_zombie(pid) == 1) - Py_RETURN_TRUE; - Py_RETURN_FALSE; + // Default: 99% is SRUN (running) + return p->p_stat; } @@ -304,17 +70,18 @@ psutil_proc_is_zombie(PyObject *self, PyObject *args) { PyObject * psutil_proc_kinfo_oneshot(PyObject *self, PyObject *args) { pid_t pid; + int status; struct kinfo_proc kp; PyObject *py_name = NULL; PyObject *py_retlist = NULL; - if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) + if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) return NULL; if (psutil_get_kinfo_proc(pid, &kp) == -1) return NULL; py_name = PyUnicode_DecodeFSDefault(kp.kp_proc.p_comm); - if (! py_name) { + if (!py_name) { // Likely a decoding error. We don't want to fail the whole // operation. The python module may retry with proc_name(). PyErr_Clear(); @@ -322,19 +89,21 @@ psutil_proc_kinfo_oneshot(PyObject *self, PyObject *args) { py_name = Py_None; } + status = convert_status(&kp.kp_proc, &kp.kp_eproc); + py_retlist = Py_BuildValue( _Py_PARSE_PID "llllllldiO", - kp.kp_eproc.e_ppid, // (pid_t) ppid - (long)kp.kp_eproc.e_pcred.p_ruid, // (long) real uid - (long)kp.kp_eproc.e_ucred.cr_uid, // (long) effective uid - (long)kp.kp_eproc.e_pcred.p_svuid, // (long) saved uid - (long)kp.kp_eproc.e_pcred.p_rgid, // (long) real gid - (long)kp.kp_eproc.e_ucred.cr_groups[0], // (long) effective gid - (long)kp.kp_eproc.e_pcred.p_svgid, // (long) saved gid - (long long)kp.kp_eproc.e_tdev, // (long long) tty nr + kp.kp_eproc.e_ppid, // (pid_t) ppid + (long)kp.kp_eproc.e_pcred.p_ruid, // (long) real uid + (long)kp.kp_eproc.e_ucred.cr_uid, // (long) effective uid + (long)kp.kp_eproc.e_pcred.p_svuid, // (long) saved uid + (long)kp.kp_eproc.e_pcred.p_rgid, // (long) real gid + (long)kp.kp_eproc.e_ucred.cr_groups[0], // (long) effective gid + (long)kp.kp_eproc.e_pcred.p_svgid, // (long) saved gid + (long long)kp.kp_eproc.e_tdev, // (long long) tty nr PSUTIL_TV2DOUBLE(kp.kp_proc.p_starttime), // (double) create time - (int)kp.kp_proc.p_stat, // (int) status - py_name // (pystr) name + status, // (int) status + py_name // (pystr) name ); Py_DECREF(py_name); @@ -357,7 +126,7 @@ psutil_proc_pidtaskinfo_oneshot(PyObject *self, PyObject *args) { uint64_t total_user; uint64_t total_system; - if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) + if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) return NULL; if (psutil_proc_pidinfo(pid, PROC_PIDTASKINFO, 0, &pti, sizeof(pti)) != 0) return NULL; @@ -369,22 +138,22 @@ psutil_proc_pidtaskinfo_oneshot(PyObject *self, PyObject *args) { return Py_BuildValue( "(ddKKkkkk)", - (float)total_user / 1000000000.0, // (float) cpu user time - (float)total_system / 1000000000.0, // (float) cpu sys time + (float)total_user / 1000000000.0, // (float) cpu user time + (float)total_system / 1000000000.0, // (float) cpu sys time // Note about memory: determining other mem stats on macOS is a mess: // http://www.opensource.apple.com/source/top/top-67/libtop.c?txt // I just give up. // struct proc_regioninfo pri; // psutil_proc_pidinfo(pid, PROC_PIDREGIONINFO, 0, &pri, sizeof(pri)) pti.pti_resident_size, // (uns long long) rss - pti.pti_virtual_size, // (uns long long) vms - pti.pti_faults, // (uns long) number of page faults (pages) - pti.pti_pageins, // (uns long) number of actual pageins (pages) - pti.pti_threadnum, // (uns long) num threads + pti.pti_virtual_size, // (uns long long) vms + pti.pti_faults, // (uns long) number of page faults (pages) + pti.pti_pageins, // (uns long) number of actual pageins (pages) + pti.pti_threadnum, // (uns long) num threads // Unvoluntary value seems not to be available; // pti.pti_csw probably refers to the sum of the two; // getrusage() numbers seems to confirm this theory. - pti.pti_csw // (uns long) voluntary ctx switches + pti.pti_csw // (uns long) voluntary ctx switches ); } @@ -397,7 +166,7 @@ psutil_proc_name(PyObject *self, PyObject *args) { pid_t pid; struct kinfo_proc kp; - if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) + if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) return NULL; if (psutil_get_kinfo_proc(pid, &kp) == -1) return NULL; @@ -414,11 +183,13 @@ psutil_proc_cwd(PyObject *self, PyObject *args) { pid_t pid; struct proc_vnodepathinfo pathinfo; - if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) + if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) return NULL; if (psutil_proc_pidinfo( - pid, PROC_PIDVNODEPATHINFO, 0, &pathinfo, sizeof(pathinfo)) != 0) + pid, PROC_PIDVNODEPATHINFO, 0, &pathinfo, sizeof(pathinfo) + ) + != 0) { return NULL; } @@ -436,13 +207,13 @@ psutil_proc_exe(PyObject *self, PyObject *args) { char buf[PATH_MAX]; int ret; - if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) + if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) return NULL; errno = 0; ret = proc_pidpath(pid, &buf, sizeof(buf)); if (ret == 0) { if (pid == 0) { - AccessDenied("automatically set for PID 0"); + psutil_oserror_ad("automatically set for PID 0"); return NULL; } else if (errno == ENOENT) { @@ -511,34 +282,39 @@ psutil_proc_memory_uss(PyObject *self, PyObject *args) { mach_port_t object_name; mach_vm_address_t prev_addr; - if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) + if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) return NULL; if (psutil_task_for_pid(pid, &task) != 0) return NULL; - if (psutil_sysctlbyname( - "sysctl.proc_cputype", &cpu_type, sizeof(cpu_type)) != 0) + if (psutil_sysctlbyname("sysctl.proc_cputype", &cpu_type, sizeof(cpu_type)) + != 0) { return NULL; } // Roughly based on libtop_update_vm_regions in // http://www.opensource.apple.com/source/top/top-100.1.2/libtop.c - for (addr = MACH_VM_MIN_ADDRESS; ; addr += size) { + for (addr = MACH_VM_MIN_ADDRESS;; addr += size) { prev_addr = addr; info_count = VM_REGION_TOP_INFO_COUNT; // reset before each call kr = mach_vm_region( - task, &addr, &size, VM_REGION_TOP_INFO, (vm_region_info_t)&info, - &info_count, &object_name); + task, + &addr, + &size, + VM_REGION_TOP_INFO, + (vm_region_info_t)&info, + &info_count, + &object_name + ); if (kr == KERN_INVALID_ADDRESS) { // Done iterating VM regions. break; } else if (kr != KERN_SUCCESS) { - PyErr_Format( - PyExc_RuntimeError, + psutil_runtime_error( "mach_vm_region(VM_REGION_TOP_INFO) syscall failed" ); mach_port_deallocate(mach_task_self(), task); @@ -550,8 +326,9 @@ psutil_proc_memory_uss(PyObject *self, PyObject *args) { break; } - if (psutil_in_shared_region(addr, cpu_type) && - info.share_mode != SM_PRIVATE) { + if (psutil_in_shared_region(addr, cpu_type) + && info.share_mode != SM_PRIVATE) + { continue; } @@ -603,7 +380,7 @@ psutil_proc_threads(PyObject *self, PyObject *args) { if (py_retlist == NULL) return NULL; - if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) + if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) goto error; if (psutil_task_for_pid(pid, &task) != 0) @@ -611,32 +388,38 @@ psutil_proc_threads(PyObject *self, PyObject *args) { // Get basic task info (optional, ignored if access denied) mach_msg_type_number_t info_count = TASK_BASIC_INFO_COUNT; - kr = task_info(task, TASK_BASIC_INFO, (task_info_t)&tasks_info, &info_count); + kr = task_info( + task, TASK_BASIC_INFO, (task_info_t)&tasks_info, &info_count + ); if (kr != KERN_SUCCESS) { if (kr == KERN_INVALID_ARGUMENT) { - AccessDenied("task_info(TASK_BASIC_INFO)"); + psutil_oserror_ad("task_info(TASK_BASIC_INFO)"); } else { // otherwise throw a runtime error with appropriate error code - PyErr_Format(PyExc_RuntimeError, - "task_info(TASK_BASIC_INFO) syscall failed"); + psutil_runtime_error("task_info(TASK_BASIC_INFO) syscall failed"); } goto error; } kr = task_threads(task, &thread_list, &thread_count); if (kr != KERN_SUCCESS) { - PyErr_Format(PyExc_RuntimeError, "task_threads() syscall failed"); + psutil_runtime_error("task_threads() syscall failed"); goto error; } for (j = 0; j < thread_count; j++) { thread_info_count = THREAD_INFO_MAX; - kr = thread_info(thread_list[j], THREAD_BASIC_INFO, - (thread_info_t)thinfo_basic, &thread_info_count); + kr = thread_info( + thread_list[j], + THREAD_BASIC_INFO, + (thread_info_t)thinfo_basic, + &thread_info_count + ); if (kr != KERN_SUCCESS) { - PyErr_Format(PyExc_RuntimeError, - "thread_info(THREAD_BASIC_INFO) syscall failed"); + psutil_runtime_error( + "thread_info(THREAD_BASIC_INFO) syscall failed" + ); goto error; } @@ -644,10 +427,10 @@ psutil_proc_threads(PyObject *self, PyObject *args) { py_tuple = Py_BuildValue( "Iff", j + 1, - basic_info_th->user_time.seconds + \ - (float)basic_info_th->user_time.microseconds / 1000000.0, - basic_info_th->system_time.seconds + \ - (float)basic_info_th->system_time.microseconds / 1000000.0 + basic_info_th->user_time.seconds + + (float)basic_info_th->user_time.microseconds / 1000000.0, + basic_info_th->system_time.seconds + + (float)basic_info_th->system_time.microseconds / 1000000.0 ); if (!py_tuple) goto error; @@ -657,8 +440,11 @@ psutil_proc_threads(PyObject *self, PyObject *args) { } if (thread_list != NULL) { - vm_deallocate(mach_task_self(), (vm_address_t)thread_list, - thread_count * sizeof(thread_act_t)); + vm_deallocate( + mach_task_self(), + (vm_address_t)thread_list, + thread_count * sizeof(thread_act_t) + ); } if (task != MACH_PORT_NULL) { mach_port_deallocate(mach_task_self(), task); @@ -671,8 +457,11 @@ error: Py_XDECREF(py_retlist); if (thread_list != NULL) { - vm_deallocate(mach_task_self(), (vm_address_t)thread_list, - thread_count * sizeof(thread_act_t)); + vm_deallocate( + mach_task_self(), + (vm_address_t)thread_list, + thread_count * sizeof(thread_act_t) + ); } if (task != MACH_PORT_NULL) { mach_port_deallocate(mach_task_self(), task); @@ -684,9 +473,9 @@ error: /* * Return process open files as a Python tuple. - * References: - * - lsof source code: https://github.com/apple-opensource/lsof/blob/28/lsof/dialects/darwin/libproc/dproc.c#L342 - * - /usr/include/sys/proc_info.h + * See lsof source code: + * https://github.com/apple-opensource/lsof/blob/28/lsof/dialects/darwin/libproc/dproc.c#L342 + * ...and /usr/include/sys/proc_info.h */ PyObject * psutil_proc_open_files(PyObject *self, PyObject *args) { @@ -704,7 +493,7 @@ psutil_proc_open_files(PyObject *self, PyObject *args) { if (py_retlist == NULL) return NULL; - if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) + if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) goto error; // see: https://github.com/giampaolo/psutil/issues/2116 @@ -720,11 +509,13 @@ psutil_proc_open_files(PyObject *self, PyObject *args) { if (fdp_pointer->proc_fdtype == PROX_FDTYPE_VNODE) { errno = 0; - nb = proc_pidfdinfo((pid_t)pid, - fdp_pointer->proc_fd, - PROC_PIDFDVNODEPATHINFO, - &vi, - sizeof(vi)); + nb = proc_pidfdinfo( + (pid_t)pid, + fdp_pointer->proc_fd, + PROC_PIDFDVNODEPATHINFO, + &vi, + sizeof(vi) + ); // --- errors checking if ((nb <= 0) || nb < sizeof(vi)) { @@ -735,7 +526,8 @@ psutil_proc_open_files(PyObject *self, PyObject *args) { } else { psutil_raise_for_pid( - pid, "proc_pidinfo(PROC_PIDFDVNODEPATHINFO)"); + pid, "proc_pidinfo(PROC_PIDFDVNODEPATHINFO)" + ); goto error; } } @@ -743,12 +535,11 @@ psutil_proc_open_files(PyObject *self, PyObject *args) { // --- construct python list py_path = PyUnicode_DecodeFSDefault(vi.pvip.vip_path); - if (! py_path) + if (!py_path) goto error; py_tuple = Py_BuildValue( - "(Oi)", - py_path, - (int)fdp_pointer->proc_fd); + "(Oi)", py_path, (int)fdp_pointer->proc_fd + ); if (!py_tuple) goto error; if (PyList_Append(py_retlist, py_tuple)) @@ -775,9 +566,9 @@ error: /* * Return process TCP and UDP connections as a list of tuples. * Raises NSP in case of zombie process. - * References: - * - lsof source code: https://github.com/apple-opensource/lsof/blob/28/lsof/dialects/darwin/libproc/dproc.c#L342 - * - /usr/include/sys/proc_info.h + * See lsof source code: + * https://github.com/apple-opensource/lsof/blob/28/lsof/dialects/darwin/libproc/dproc.c#L342 + * ...and /usr/include/sys/proc_info.h */ PyObject * psutil_proc_net_connections(PyObject *self, PyObject *args) { @@ -788,7 +579,7 @@ psutil_proc_net_connections(PyObject *self, PyObject *args) { struct proc_fdinfo *fds_pointer = NULL; struct proc_fdinfo *fdp_pointer; struct socket_fdinfo si; - const char* ntopret; + const char *ntopret; PyObject *py_retlist = PyList_New(0); PyObject *py_tuple = NULL; PyObject *py_laddr = NULL; @@ -799,8 +590,10 @@ psutil_proc_net_connections(PyObject *self, PyObject *args) { if (py_retlist == NULL) return NULL; - if (! PyArg_ParseTuple(args, _Py_PARSE_PID "OO", &pid, &py_af_filter, - &py_type_filter)) { + if (!PyArg_ParseTuple( + args, _Py_PARSE_PID "OO", &pid, &py_af_filter, &py_type_filter + )) + { goto error; } @@ -824,27 +617,37 @@ psutil_proc_net_connections(PyObject *self, PyObject *args) { fdp_pointer = &fds_pointer[i]; if (fdp_pointer->proc_fdtype == PROX_FDTYPE_SOCKET) { - nb = proc_pidfdinfo(pid, fdp_pointer->proc_fd, - PROC_PIDFDSOCKETINFO, &si, sizeof(si)); + nb = proc_pidfdinfo( + pid, + fdp_pointer->proc_fd, + PROC_PIDFDSOCKETINFO, + &si, + sizeof(si) + ); // --- errors checking if ((nb <= 0) || (nb < sizeof(si))) { if (errno == EBADF) { // let's assume socket has been closed - psutil_debug("proc_pidfdinfo(PROC_PIDFDSOCKETINFO) -> " - "EBADF (ignored)"); + psutil_debug( + "proc_pidfdinfo(PROC_PIDFDSOCKETINFO) -> " + "EBADF (ignored)" + ); continue; } else if (errno == EOPNOTSUPP) { // may happen sometimes, see: // https://github.com/giampaolo/psutil/issues/1512 - psutil_debug("proc_pidfdinfo(PROC_PIDFDSOCKETINFO) -> " - "EOPNOTSUPP (ignored)"); + psutil_debug( + "proc_pidfdinfo(PROC_PIDFDSOCKETINFO) -> " + "EOPNOTSUPP (ignored)" + ); continue; } else { psutil_raise_for_pid( - pid, "proc_pidinfo(PROC_PIDFDSOCKETINFO)"); + pid, "proc_pidinfo(PROC_PIDFDSOCKETINFO)" + ); goto error; } } @@ -882,22 +685,24 @@ psutil_proc_net_connections(PyObject *self, PyObject *args) { if (family == AF_INET) { ntopret = inet_ntop( AF_INET, - &si.psi.soi_proto.pri_tcp.tcpsi_ini.insi_laddr.ina_46.i46a_addr4, + &si.psi.soi_proto.pri_tcp.tcpsi_ini.insi_laddr.ina_46 + .i46a_addr4, lip, sizeof(lip) ); if (!ntopret) { - psutil_PyErr_SetFromOSErrnoWithSyscall("inet_ntop()"); + psutil_oserror_wsyscall("inet_ntop()"); goto error; } ntopret = inet_ntop( AF_INET, - &si.psi.soi_proto.pri_tcp.tcpsi_ini.insi_faddr.ina_46.i46a_addr4, + &si.psi.soi_proto.pri_tcp.tcpsi_ini.insi_faddr.ina_46 + .i46a_addr4, rip, sizeof(rip) ); if (!ntopret) { - psutil_PyErr_SetFromOSErrnoWithSyscall("inet_ntop()"); + psutil_oserror_wsyscall("inet_ntop()"); goto error; } } @@ -909,7 +714,7 @@ psutil_proc_net_connections(PyObject *self, PyObject *args) { sizeof(lip) ); if (!ntopret) { - psutil_PyErr_SetFromOSErrnoWithSyscall("inet_ntop()"); + psutil_oserror_wsyscall("inet_ntop()"); goto error; } ntopret = inet_ntop( @@ -919,7 +724,7 @@ psutil_proc_net_connections(PyObject *self, PyObject *args) { sizeof(rip) ); if (!ntopret) { - psutil_PyErr_SetFromOSErrnoWithSyscall("inet_ntop()"); + psutil_oserror_wsyscall("inet_ntop()"); goto error; } } @@ -942,7 +747,8 @@ psutil_proc_net_connections(PyObject *self, PyObject *args) { goto error; py_tuple = Py_BuildValue( - "(iiiNNi)", fd, family, type, py_laddr, py_raddr, state); + "(iiiNNi)", fd, family, type, py_laddr, py_raddr, state + ); if (!py_tuple) goto error; if (PyList_Append(py_retlist, py_tuple)) @@ -951,20 +757,25 @@ psutil_proc_net_connections(PyObject *self, PyObject *args) { } else if (family == AF_UNIX) { py_laddr = PyUnicode_DecodeFSDefault( - si.psi.soi_proto.pri_un.unsi_addr.ua_sun.sun_path); + si.psi.soi_proto.pri_un.unsi_addr.ua_sun.sun_path + ); if (!py_laddr) goto error; py_raddr = PyUnicode_DecodeFSDefault( - si.psi.soi_proto.pri_un.unsi_caddr.ua_sun.sun_path); + si.psi.soi_proto.pri_un.unsi_caddr.ua_sun.sun_path + ); if (!py_raddr) goto error; py_tuple = Py_BuildValue( "(iiiOOi)", - fd, family, type, + fd, + family, + type, py_laddr, py_raddr, - PSUTIL_CONN_NONE); + PSUTIL_CONN_NONE + ); if (!py_tuple) goto error; if (PyList_Append(py_retlist, py_tuple)) @@ -1000,7 +811,7 @@ psutil_proc_num_fds(PyObject *self, PyObject *args) { int num_fds; struct proc_fdinfo *fds_pointer; - if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) + if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) return NULL; fds_pointer = psutil_proc_list_fds(pid, &num_fds); @@ -1028,7 +839,7 @@ psutil_proc_cmdline(PyObject *self, PyObject *args) { if (py_retlist == NULL) return NULL; - if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) + if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) goto error; // special case for PID 0 (kernel_task) where cmdline cannot be fetched @@ -1073,7 +884,7 @@ psutil_proc_cmdline(PyObject *self, PyObject *args) { while (arg_ptr < arg_end && nargs > 0) { if (*arg_ptr++ == '\0') { py_arg = PyUnicode_DecodeFSDefault(curr_arg); - if (! py_arg) + if (!py_arg) goto error; if (PyList_Append(py_retlist, py_arg)) goto error; @@ -1103,7 +914,8 @@ error: // * target process is not cs_restricted // * SIP is off // * caller has an entitlement -// See: https://github.com/apple/darwin-xnu/blob/2ff845c2e033bd0ff64b5b6aa6063a1f8f65aa32/bsd/kern/kern_sysctl.c#L1315-L1321 +// See: +// https://github.com/apple/darwin-xnu/blob/2ff845c2e033bd0ff64b5b6aa6063a1f8f65aa32/bsd/kern/kern_sysctl.c#L1315-L1321 PyObject * psutil_proc_environ(PyObject *self, PyObject *args) { pid_t pid; @@ -1117,7 +929,7 @@ psutil_proc_environ(PyObject *self, PyObject *args) { size_t env_len; PyObject *py_ret = NULL; - if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) + if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) return NULL; // PID 0 (kernel_task) has no cmdline. diff --git a/contrib/python/psutil/py3/psutil/arch/osx/proc_utils.c b/contrib/python/psutil/py3/psutil/arch/osx/proc_utils.c new file mode 100644 index 00000000000..93e5e91f370 --- /dev/null +++ b/contrib/python/psutil/py3/psutil/arch/osx/proc_utils.c @@ -0,0 +1,254 @@ +/* + * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + +#include <Python.h> +#include <errno.h> +#include <stdlib.h> +#include <stdio.h> +#include <sys/types.h> +#include <sys/sysctl.h> +#include <sys/user.h> +#include <unistd.h> +#include <mach/mach.h> +#include <libproc.h> +#include <stdint.h> +#include <stdbool.h> + +#include "../../arch/all/init.h" + + +int +psutil_get_kinfo_proc(pid_t pid, struct kinfo_proc *kp) { + int mib[4]; + size_t len; + mib[0] = CTL_KERN; + mib[1] = KERN_PROC; + mib[2] = KERN_PROC_PID; + mib[3] = pid; + + if (pid < 0 || !kp) + return psutil_badargs("psutil_get_kinfo_proc"); + + len = sizeof(struct kinfo_proc); + + if (sysctl(mib, 4, kp, &len, NULL, 0) == -1) { + // raise an exception and throw errno as the error + psutil_oserror_wsyscall("sysctl"); + return -1; + } + + // sysctl succeeds but len is zero, happens when process has gone away + if (len == 0) { + psutil_oserror_nsp("sysctl(kinfo_proc), len == 0"); + return -1; + } + return 0; +} + + +// Return 1 if PID a zombie, else 0 (including on error). +int +is_zombie(size_t pid) { + struct kinfo_proc kp; + + if (psutil_get_kinfo_proc(pid, &kp) == -1) { + errno = 0; + PyErr_Clear(); + return 0; + } + return kp.kp_proc.p_stat == SZOMB; +} + + +// Read process argument space. +int +psutil_sysctl_procargs(pid_t pid, char *procargs, size_t *argmax) { + int mib[3]; + + mib[0] = CTL_KERN; + mib[1] = KERN_PROCARGS2; + mib[2] = pid; + + if (pid < 0 || !procargs || !argmax || *argmax == 0) + return psutil_badargs("psutil_sysctl_procargs"); + + if (sysctl(mib, 3, procargs, argmax, NULL, 0) < 0) { + if (psutil_pid_exists(pid) == 0) { + psutil_oserror_nsp("psutil_pid_exists -> 0"); + return -1; + } + + if (is_zombie(pid) == 1) { + PyErr_SetString(ZombieProcessError, ""); + return -1; + } + + if (errno == EINVAL) { + psutil_debug("sysctl(KERN_PROCARGS2) -> EINVAL translated to AD"); + psutil_oserror_ad("sysctl(KERN_PROCARGS2) -> EINVAL"); + return -1; + } + + if (errno == EIO) { + psutil_debug("sysctl(KERN_PROCARGS2) -> EIO translated to AD"); + psutil_oserror_ad("sysctl(KERN_PROCARGS2) -> EIO"); + return -1; + } + psutil_oserror_wsyscall("sysctl(KERN_PROCARGS2)"); + return -1; + } + return 0; +} + + +/* + * A wrapper around proc_pidinfo(). + * https://opensource.apple.com/source/xnu/xnu-2050.7.9/bsd/kern/proc_info.c + * Returns 0 on failure. + */ +int +psutil_proc_pidinfo(pid_t pid, int flavor, uint64_t arg, void *pti, int size) { + int ret; + + if (pid < 0 || !pti || size <= 0) + return psutil_badargs("psutil_proc_pidinfo"); + + errno = 0; + ret = proc_pidinfo(pid, flavor, arg, pti, size); + if (ret <= 0) { + psutil_raise_for_pid(pid, "proc_pidinfo()"); + return -1; + } + + // check for truncated return size + if (ret < size) { + psutil_raise_for_pid( + pid, "proc_pidinfo() returned less data than requested buffer size" + ); + return -1; + } + + return 0; +} + + +/* + * A wrapper around task_for_pid() which sucks big time: + * - it's not documented + * - errno is set only sometimes + * - sometimes errno is ENOENT (?!?) + * - for PIDs != getpid() or PIDs which are not members of the procmod + * it requires root + * As such we can only guess what the heck went wrong and fail either + * with NoSuchProcess or give up with AccessDenied. + * References: + * https://github.com/giampaolo/psutil/issues/1181 + * https://github.com/giampaolo/psutil/issues/1209 + * https://github.com/giampaolo/psutil/issues/1291#issuecomment-396062519 + */ +int +psutil_task_for_pid(pid_t pid, mach_port_t *task) { + kern_return_t err; + + if (pid < 0 || !task) + return psutil_badargs("psutil_task_for_pid"); + + err = task_for_pid(mach_task_self(), pid, task); + if (err != KERN_SUCCESS) { + if (psutil_pid_exists(pid) == 0) { + psutil_oserror_nsp("task_for_pid"); + } + else if (is_zombie(pid) == 1) { + PyErr_SetString( + ZombieProcessError, "task_for_pid -> psutil_is_zombie -> 1" + ); + } + else { + psutil_debug( + "task_for_pid() failed (pid=%ld, err=%i, errno=%i, msg='%s'); " + "setting EACCES", + (long)pid, + err, + errno, + mach_error_string(err) + ); + psutil_oserror_ad("task_for_pid"); + } + return -1; + } + + return 0; +} + + +/* + * A wrapper around proc_pidinfo(PROC_PIDLISTFDS), which dynamically sets + * the buffer size. + */ +struct proc_fdinfo * +psutil_proc_list_fds(pid_t pid, int *num_fds) { + int ret; + int fds_size = 0; + int max_size = 24 * 1024 * 1024; // 24M + struct proc_fdinfo *fds_pointer = NULL; + + if (pid < 0 || num_fds == NULL) { + psutil_badargs("psutil_proc_list_fds"); + return NULL; + } + + errno = 0; + ret = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, NULL, 0); + if (ret <= 0) { + psutil_raise_for_pid(pid, "proc_pidinfo(PROC_PIDLISTFDS) 1/2"); + goto error; + } + + while (1) { + if (ret > fds_size) { + while (ret > fds_size) { + fds_size += PROC_PIDLISTFD_SIZE * 32; + if (fds_size > max_size) { + psutil_runtime_error("prevent malloc() to allocate > 24M"); + goto error; + } + } + + if (fds_pointer != NULL) { + free(fds_pointer); + } + fds_pointer = malloc(fds_size); + + if (fds_pointer == NULL) { + PyErr_NoMemory(); + goto error; + } + } + + errno = 0; + ret = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, fds_pointer, fds_size); + if (ret <= 0) { + psutil_raise_for_pid(pid, "proc_pidinfo(PROC_PIDLISTFDS) 2/2"); + goto error; + } + + if (ret + (int)PROC_PIDLISTFD_SIZE >= fds_size) { + psutil_debug("PROC_PIDLISTFDS: make room for 1 extra fd"); + ret = fds_size + (int)PROC_PIDLISTFD_SIZE; + continue; + } + + break; + } + + *num_fds = (ret / (int)PROC_PIDLISTFD_SIZE); + return fds_pointer; + +error: + if (fds_pointer != NULL) + free(fds_pointer); + return NULL; +} diff --git a/contrib/python/psutil/py3/psutil/arch/osx/sensors.c b/contrib/python/psutil/py3/psutil/arch/osx/sensors.c index ea73d520357..c4b2afeed91 100644 --- a/contrib/python/psutil/py3/psutil/arch/osx/sensors.c +++ b/contrib/python/psutil/py3/psutil/arch/osx/sensors.c @@ -28,21 +28,19 @@ psutil_sensors_battery(PyObject *self, PyObject *args) { CFNumberRef capacity_ref = NULL; CFNumberRef time_to_empty_ref = NULL; CFStringRef ps_state_ref = NULL; - uint32_t capacity; /* units are percent */ - int time_to_empty; /* units are minutes */ + uint32_t capacity; // units are percent + int time_to_empty; // units are minutes int is_power_plugged; power_info = IOPSCopyPowerSourcesInfo(); if (!power_info) { - PyErr_SetString(PyExc_RuntimeError, - "IOPSCopyPowerSourcesInfo() syscall failed"); + psutil_runtime_error("IOPSCopyPowerSourcesInfo() syscall failed"); goto error; } power_sources_list = IOPSCopyPowerSourcesList(power_info); if (!power_sources_list) { - PyErr_SetString(PyExc_RuntimeError, - "IOPSCopyPowerSourcesList() syscall failed"); + psutil_runtime_error("IOPSCopyPowerSourcesList() syscall failed"); goto error; } @@ -52,35 +50,45 @@ psutil_sensors_battery(PyObject *self, PyObject *args) { } power_sources_information = IOPSGetPowerSourceDescription( - power_info, CFArrayGetValueAtIndex(power_sources_list, 0)); + power_info, CFArrayGetValueAtIndex(power_sources_list, 0) + ); if (!power_sources_information) { - PyErr_SetString( - PyExc_RuntimeError, "Failed to get power source description" - ); + psutil_runtime_error("Failed to get power source description"); goto error; } capacity_ref = (CFNumberRef)CFDictionaryGetValue( - power_sources_information, CFSTR(kIOPSCurrentCapacityKey)); - if (!capacity_ref || !CFNumberGetValue(capacity_ref, kCFNumberSInt32Type, &capacity)) { - PyErr_SetString(PyExc_RuntimeError, - "No battery capacity information in power sources info"); + power_sources_information, CFSTR(kIOPSCurrentCapacityKey) + ); + if (!capacity_ref + || !CFNumberGetValue(capacity_ref, kCFNumberSInt32Type, &capacity)) + { + psutil_runtime_error( + "No battery capacity information in power sources info" + ); goto error; } ps_state_ref = (CFStringRef)CFDictionaryGetValue( - power_sources_information, CFSTR(kIOPSPowerSourceStateKey)); + power_sources_information, CFSTR(kIOPSPowerSourceStateKey) + ); if (!ps_state_ref) { - PyErr_SetString(PyExc_RuntimeError, "power source state info missing"); + psutil_runtime_error("power source state info missing"); goto error; } is_power_plugged = CFStringCompare( - ps_state_ref, CFSTR(kIOPSACPowerValue), 0) == kCFCompareEqualTo; + ps_state_ref, CFSTR(kIOPSACPowerValue), 0 + ) + == kCFCompareEqualTo; time_to_empty_ref = (CFNumberRef)CFDictionaryGetValue( - power_sources_information, CFSTR(kIOPSTimeToEmptyKey)); - if (!time_to_empty_ref || !CFNumberGetValue(time_to_empty_ref, - kCFNumberIntType, &time_to_empty)) { + power_sources_information, CFSTR(kIOPSTimeToEmptyKey) + ); + if (!time_to_empty_ref + || !CFNumberGetValue( + time_to_empty_ref, kCFNumberIntType, &time_to_empty + )) + { /* This value is recommended for non-Apple power sources, so it's not * an error if it doesn't exist. We'll return -1 for "unknown" */ /* A value of -1 indicates "Still Calculating the Time" also for diff --git a/contrib/python/psutil/py3/psutil/arch/posix/init.c b/contrib/python/psutil/py3/psutil/arch/posix/init.c index 8a95a3151aa..503ae496591 100644 --- a/contrib/python/psutil/py3/psutil/arch/posix/init.c +++ b/contrib/python/psutil/py3/psutil/arch/posix/init.c @@ -10,7 +10,7 @@ #include "init.h" -PyObject *ZombieProcessError = NULL;; +PyObject *ZombieProcessError = NULL; /* * From "man getpagesize" on Linux, https://linux.die.net/man/2/getpagesize: @@ -33,7 +33,7 @@ psutil_getpagesize(void) { return sysconf(_SC_PAGE_SIZE); #else // legacy - return (long) getpagesize(); + return (long)getpagesize(); #endif } @@ -60,6 +60,9 @@ static PyMethodDef posix_methods[] = { #if !defined(PSUTIL_OPENBSD) && !defined(PSUTIL_AIX) {"users", psutil_users, METH_VARARGS}, #endif +#if defined(PSUTIL_OSX) || defined(PSUTIL_BSD) + {"proc_is_zombie", psutil_proc_is_zombie, METH_VARARGS}, +#endif {NULL, NULL, 0, NULL} }; @@ -97,10 +100,8 @@ psutil_posix_add_constants(PyObject *mod) { if (!mod) return -1; -#if defined(PSUTIL_BSD) || \ - defined(PSUTIL_OSX) || \ - defined(PSUTIL_SUNOS) || \ - defined(PSUTIL_AIX) +#if defined(PSUTIL_BSD) || defined(PSUTIL_OSX) || defined(PSUTIL_SUNOS) \ + || defined(PSUTIL_AIX) if (PyModule_AddIntConstant(mod, "AF_LINK", AF_LINK)) return -1; #endif @@ -158,7 +159,7 @@ psutil_posix_add_constants(PyObject *mod) { return -1; #endif -// Linux specific + // Linux specific #ifdef RLIMIT_LOCKS if (PyModule_AddIntConstant(mod, "RLIMIT_LOCKS", RLIMIT_LOCKS)) @@ -190,7 +191,7 @@ psutil_posix_add_constants(PyObject *mod) { return -1; #endif -// Free specific + // Free specific #ifdef RLIMIT_SWAP if (PyModule_AddIntConstant(mod, "RLIMIT_SWAP", RLIMIT_SWAP)) @@ -209,11 +210,12 @@ psutil_posix_add_constants(PyObject *mod) { #if defined(HAVE_LONG_LONG) if (sizeof(RLIM_INFINITY) > sizeof(long)) { - v = PyLong_FromLongLong((PY_LONG_LONG) RLIM_INFINITY); - } else + v = PyLong_FromLongLong((PY_LONG_LONG)RLIM_INFINITY); + } + else #endif { - v = PyLong_FromLong((long) RLIM_INFINITY); + v = PyLong_FromLong((long)RLIM_INFINITY); } if (v) { if (PyModule_AddObject(mod, "RLIM_INFINITY", v)) diff --git a/contrib/python/psutil/py3/psutil/arch/posix/init.h b/contrib/python/psutil/py3/psutil/arch/posix/init.h index 3e323ca149b..ec4391a6643 100644 --- a/contrib/python/psutil/py3/psutil/arch/posix/init.h +++ b/contrib/python/psutil/py3/psutil/arch/posix/init.h @@ -6,25 +6,28 @@ extern PyObject *ZombieProcessError; +// convert a timeval struct to a double +#ifdef PSUTIL_SUNOS +#define PSUTIL_TV2DOUBLE(t) (((t).tv_nsec * 0.000000001) + (t).tv_sec) +#else +#define PSUTIL_TV2DOUBLE(t) ((t).tv_sec + (t).tv_usec / 1000000.0) +#endif + +// clang-format off #if !defined(PSUTIL_OPENBSD) && !defined(PSUTIL_AIX) #define PSUTIL_HAS_POSIX_USERS - PyObject *psutil_users(PyObject *self, PyObject *args); #endif #if defined(PSUTIL_BSD) || defined(PSUTIL_OSX) #include <sys/types.h> - #define PSUTIL_HAS_SYSCTL - int psutil_sysctl(int *mib, u_int miblen, void *buf, size_t buflen); int psutil_sysctl_malloc(int *mib, u_int miblen, char **buf, size_t *buflen); size_t psutil_sysctl_argmax(); #if !defined(PSUTIL_OPENBSD) - #define PSUTIL_HAS_SYSCTLBYNAME - int psutil_sysctlbyname(const char *name, void *buf, size_t buflen); int psutil_sysctlbyname_malloc(const char *name, char **buf, size_t *buflen); #endif @@ -32,15 +35,19 @@ extern PyObject *ZombieProcessError; #if defined(PSUTIL_BSD) || defined(PSUTIL_OSX) #define PSUTIL_HAS_NET_IF_DUPLEX_SPEED - PyObject *psutil_net_if_duplex_speed(PyObject *self, PyObject *args); #endif +// clang-format on + +// --- internal utils int psutil_pid_exists(pid_t pid); long psutil_getpagesize(void); -void psutil_raise_for_pid(pid_t pid, char *msg); int psutil_posix_add_constants(PyObject *mod); int psutil_posix_add_methods(PyObject *mod); +PyObject *psutil_raise_for_pid(pid_t pid, char *msg); + +// --- Python wrappers PyObject *psutil_getpagesize_pywrapper(PyObject *self, PyObject *args); PyObject *psutil_net_if_addrs(PyObject *self, PyObject *args); @@ -49,3 +56,6 @@ PyObject *psutil_net_if_is_running(PyObject *self, PyObject *args); PyObject *psutil_net_if_mtu(PyObject *self, PyObject *args); PyObject *psutil_proc_priority_get(PyObject *self, PyObject *args); PyObject *psutil_proc_priority_set(PyObject *self, PyObject *args); +#if defined(PSUTIL_OSX) || defined(PSUTIL_BSD) +PyObject *psutil_proc_is_zombie(PyObject *self, PyObject *args); +#endif diff --git a/contrib/python/psutil/py3/psutil/arch/posix/net.c b/contrib/python/psutil/py3/psutil/arch/posix/net.c index a857a5dea84..fa19ba79ede 100644 --- a/contrib/python/psutil/py3/psutil/arch/posix/net.c +++ b/contrib/python/psutil/py3/psutil/arch/posix/net.c @@ -14,30 +14,33 @@ #include <unistd.h> #ifdef PSUTIL_AIX - #error #include "arch/aix/ifaddrs.h" +#error #include "arch/aix/ifaddrs.h" #else - #include <ifaddrs.h> +#include <ifaddrs.h> #endif #if defined(PSUTIL_LINUX) - #include <netdb.h> - #include <linux/types.h> - #include <linux/if_packet.h> +#include <netdb.h> +#include <linux/types.h> +#include <linux/if_packet.h> #endif + #if defined(PSUTIL_BSD) || defined(PSUTIL_OSX) - #include <netdb.h> - #include <netinet/in.h> - #include <net/if_dl.h> - #include <sys/sockio.h> - #include <net/if_media.h> - #include <net/if.h> +#include <netdb.h> +#include <netinet/in.h> +#include <net/if_dl.h> +#include <sys/sockio.h> +#include <net/if_media.h> +#include <net/if.h> #endif + #if defined(PSUTIL_SUNOS) - #include <netdb.h> - #include <sys/sockio.h> +#include <netdb.h> +#include <sys/sockio.h> #endif + #if defined(PSUTIL_AIX) - #include <netdb.h> +#include <netdb.h> #endif #include "../../arch/all/init.h" @@ -66,13 +69,14 @@ psutil_convert_ipaddr(struct sockaddr *addr, int family) { addrlen = sizeof(struct sockaddr_in); else addrlen = sizeof(struct sockaddr_in6); - err = getnameinfo(addr, addrlen, buf, sizeof(buf), NULL, 0, - NI_NUMERICHOST); + err = getnameinfo( + addr, addrlen, buf, sizeof(buf), NULL, 0, NI_NUMERICHOST + ); if (err != 0) { // XXX we get here on FreeBSD when processing 'lo' / AF_INET6 // broadcast. Not sure what to do other than returning None. // ifconfig does not show anything BTW. - // PyErr_Format(PyExc_RuntimeError, gai_strerror(err)); + // psutil_runtime_error(gai_strerror(err)); // return NULL; Py_INCREF(Py_None); return Py_None; @@ -106,7 +110,7 @@ psutil_convert_ipaddr(struct sockaddr *addr, int family) { if (len > 0) { ptr = buf; for (n = 0; n < len; ++n) { - sprintf(ptr, "%02x:", data[n] & 0xff); + str_format(ptr, sizeof(ptr), "%02x:", data[n] & 0xff); ptr += 3; } *--ptr = '\0'; @@ -123,8 +127,8 @@ psutil_convert_ipaddr(struct sockaddr *addr, int family) { * Return NICs information a-la ifconfig as a list of tuples. * TODO: on Solaris we won't get any MAC address. */ -PyObject* -psutil_net_if_addrs(PyObject* self, PyObject* args) { +PyObject * +psutil_net_if_addrs(PyObject *self, PyObject *args) { struct ifaddrs *ifaddr, *ifa; int family; @@ -138,7 +142,7 @@ psutil_net_if_addrs(PyObject* self, PyObject* args) { if (py_retlist == NULL) return NULL; if (getifaddrs(&ifaddr) == -1) { - PyErr_SetFromErrno(PyExc_OSError); + psutil_oserror(); goto error; } @@ -186,7 +190,7 @@ psutil_net_if_addrs(PyObject* self, PyObject* args) { py_ptp ); - if (! py_tuple) + if (!py_tuple) goto error; if (PyList_Append(py_retlist, py_tuple)) goto error; @@ -224,14 +228,14 @@ psutil_net_if_mtu(PyObject *self, PyObject *args) { int ret; struct ifreq ifr; - if (! PyArg_ParseTuple(args, "s", &nic_name)) + if (!PyArg_ParseTuple(args, "s", &nic_name)) return NULL; sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock == -1) goto error; - PSUTIL_STRNCPY(ifr.ifr_name, nic_name, sizeof(ifr.ifr_name)); + str_copy(ifr.ifr_name, sizeof(ifr.ifr_name), nic_name); ret = ioctl(sock, SIOCGIFMTU, &ifr); if (ret == -1) goto error; @@ -242,16 +246,15 @@ psutil_net_if_mtu(PyObject *self, PyObject *args) { error: if (sock != -1) close(sock); - return PyErr_SetFromErrno(PyExc_OSError); + return psutil_oserror(); } static int -append_flag(PyObject *py_retlist, const char *flag_name) -{ +append_flag(PyObject *py_retlist, const char *flag_name) { PyObject *py_str = NULL; py_str = PyUnicode_FromString(flag_name); - if (! py_str) + if (!py_str) return 0; if (PyList_Append(py_retlist, py_str)) { Py_DECREF(py_str); @@ -277,19 +280,19 @@ psutil_net_if_flags(PyObject *self, PyObject *args) { if (py_retlist == NULL) return NULL; - if (! PyArg_ParseTuple(args, "s", &nic_name)) + if (!PyArg_ParseTuple(args, "s", &nic_name)) goto error; sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock == -1) { - psutil_PyErr_SetFromOSErrnoWithSyscall("socket(SOCK_DGRAM)"); + psutil_oserror_wsyscall("socket(SOCK_DGRAM)"); goto error; } - PSUTIL_STRNCPY(ifr.ifr_name, nic_name, sizeof(ifr.ifr_name)); + str_copy(ifr.ifr_name, sizeof(ifr.ifr_name), nic_name); ret = ioctl(sock, SIOCGIFFLAGS, &ifr); if (ret == -1) { - psutil_PyErr_SetFromOSErrnoWithSyscall("ioctl(SIOCGIFFLAGS)"); + psutil_oserror_wsyscall("ioctl(SIOCGIFFLAGS)"); goto error; } @@ -298,10 +301,14 @@ psutil_net_if_flags(PyObject *self, PyObject *args) { flags = ifr.ifr_flags & 0xFFFF; - // Linux/glibc IFF flags: https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/gnu/net/if.h;h=251418f82331c0426e58707fe4473d454893b132;hb=HEAD - // macOS IFF flags: https://opensource.apple.com/source/xnu/xnu-792/bsd/net/if.h.auto.html - // AIX IFF flags: https://www.ibm.com/support/pages/how-hexadecimal-flags-displayed-ifconfig-are-calculated - // FreeBSD IFF flags: https://www.freebsd.org/cgi/man.cgi?query=if_allmulti&apropos=0&sektion=0&manpath=FreeBSD+10-current&format=html + // Linux/glibc IFF flags: + // https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/gnu/net/if.h;h=251418f82331c0426e58707fe4473d454893b132;hb=HEAD + // macOS IFF flags: + // https://opensource.apple.com/source/xnu/xnu-792/bsd/net/if.h.auto.html + // AIX IFF flags: + // https://www.ibm.com/support/pages/how-hexadecimal-flags-displayed-ifconfig-are-calculated + // FreeBSD IFF flags: + // https://www.freebsd.org/cgi/man.cgi?query=if_allmulti&apropos=0&sektion=0&manpath=FreeBSD+10-current&format=html #ifdef IFF_UP // Available in (at least) Linux, macOS, AIX, BSD @@ -458,14 +465,14 @@ psutil_net_if_is_running(PyObject *self, PyObject *args) { int ret; struct ifreq ifr; - if (! PyArg_ParseTuple(args, "s", &nic_name)) + if (!PyArg_ParseTuple(args, "s", &nic_name)) return NULL; sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock == -1) goto error; - PSUTIL_STRNCPY(ifr.ifr_name, nic_name, sizeof(ifr.ifr_name)); + str_copy(ifr.ifr_name, sizeof(ifr.ifr_name), nic_name); ret = ioctl(sock, SIOCGIFFLAGS, &ifr); if (ret == -1) goto error; @@ -479,86 +486,87 @@ psutil_net_if_is_running(PyObject *self, PyObject *args) { error: if (sock != -1) close(sock); - return PyErr_SetFromErrno(PyExc_OSError); + return psutil_oserror(); } - // net_if_stats() macOS/BSD implementation. #ifdef PSUTIL_HAS_NET_IF_DUPLEX_SPEED -int psutil_get_nic_speed(int ifm_active) { +int +psutil_get_nic_speed(int ifm_active) { // Determine NIC speed. Taken from: // http://www.i-scream.org/libstatgrab/ // Assuming only ETHER devices - switch(IFM_TYPE(ifm_active)) { + switch (IFM_TYPE(ifm_active)) { case IFM_ETHER: - switch(IFM_SUBTYPE(ifm_active)) { -#if defined(IFM_HPNA_1) && ((!defined(IFM_10G_LR)) \ - || (IFM_10G_LR != IFM_HPNA_1)) + switch (IFM_SUBTYPE(ifm_active)) { +#if defined(IFM_HPNA_1) \ + && ((!defined(IFM_10G_LR)) || (IFM_10G_LR != IFM_HPNA_1)) // HomePNA 1.0 (1Mb/s) - case(IFM_HPNA_1): + case (IFM_HPNA_1): return 1; #endif // 10 Mbit - case(IFM_10_T): // 10BaseT - RJ45 - case(IFM_10_2): // 10Base2 - Thinnet - case(IFM_10_5): // 10Base5 - AUI - case(IFM_10_STP): // 10BaseT over shielded TP - case(IFM_10_FL): // 10baseFL - Fiber + case (IFM_10_T): // 10BaseT - RJ45 + case (IFM_10_2): // 10Base2 - Thinnet + case (IFM_10_5): // 10Base5 - AUI + case (IFM_10_STP): // 10BaseT over shielded TP + case (IFM_10_FL): // 10baseFL - Fiber return 10; // 100 Mbit - case(IFM_100_TX): // 100BaseTX - RJ45 - case(IFM_100_FX): // 100BaseFX - Fiber - case(IFM_100_T4): // 100BaseT4 - 4 pair cat 3 - case(IFM_100_VG): // 100VG-AnyLAN - case(IFM_100_T2): // 100BaseT2 + case (IFM_100_TX): // 100BaseTX - RJ45 + case (IFM_100_FX): // 100BaseFX - Fiber + case (IFM_100_T4): // 100BaseT4 - 4 pair cat 3 + case (IFM_100_VG): // 100VG-AnyLAN + case (IFM_100_T2): // 100BaseT2 return 100; // 1000 Mbit - case(IFM_1000_SX): // 1000BaseSX - multi-mode fiber - case(IFM_1000_LX): // 1000baseLX - single-mode fiber - case(IFM_1000_CX): // 1000baseCX - 150ohm STP + case (IFM_1000_SX): // 1000BaseSX - multi-mode fiber + case (IFM_1000_LX): // 1000baseLX - single-mode fiber + case (IFM_1000_CX): // 1000baseCX - 150ohm STP #if defined(IFM_1000_TX) && !defined(PSUTIL_OPENBSD) - #define HAS_CASE_IFM_1000_TX 1 - // FreeBSD 4 and others (but NOT OpenBSD) -> #define IFM_1000_T in net/if_media.h - case(IFM_1000_TX): +#define HAS_CASE_IFM_1000_TX 1 + // FreeBSD 4 and others (but NOT OpenBSD) -> #define IFM_1000_T + // in net/if_media.h + case (IFM_1000_TX): #endif #ifdef IFM_1000_FX - case(IFM_1000_FX): + case (IFM_1000_FX): #endif #if defined(IFM_1000_T) && (!HAS_CASE_IFM_1000_TX || IFM_1000_T != IFM_1000_TX) - case(IFM_1000_T): + case (IFM_1000_T): #endif return 1000; #if defined(IFM_10G_SR) || defined(IFM_10G_LR) || defined(IFM_10G_CX4) \ - || defined(IFM_10G_T) + || defined(IFM_10G_T) #ifdef IFM_10G_SR - case(IFM_10G_SR): + case (IFM_10G_SR): #endif #ifdef IFM_10G_LR - case(IFM_10G_LR): + case (IFM_10G_LR): #endif #ifdef IFM_10G_CX4 - case(IFM_10G_CX4): + case (IFM_10G_CX4): #endif #ifdef IFM_10G_TWINAX - case(IFM_10G_TWINAX): + case (IFM_10G_TWINAX): #endif #ifdef IFM_10G_TWINAX_LONG - case(IFM_10G_TWINAX_LONG): + case (IFM_10G_TWINAX_LONG): #endif #ifdef IFM_10G_T - case(IFM_10G_T): + case (IFM_10G_T): #endif return 10000; #endif #if defined(IFM_2500_SX) #ifdef IFM_2500_SX - case(IFM_2500_SX): + case (IFM_2500_SX): #endif return 2500; -#endif // any 2.5GBit stuff... - // We don't know what it is +#endif // any 2.5GBit stuff... + // We don't know what it is default: return 0; } @@ -566,7 +574,7 @@ int psutil_get_nic_speed(int ifm_active) { #ifdef IFM_TOKEN case IFM_TOKEN: - switch(IFM_SUBTYPE(ifm_active)) { + switch (IFM_SUBTYPE(ifm_active)) { case IFM_TOK_STP4: // Shielded twisted pair 4m - DB9 case IFM_TOK_UTP4: // Unshielded twisted pair 4m - RJ45 return 4; @@ -591,7 +599,7 @@ int psutil_get_nic_speed(int ifm_active) { #ifdef IFM_FDDI case IFM_FDDI: - switch(IFM_SUBTYPE(ifm_active)) { + switch (IFM_SUBTYPE(ifm_active)) { // We don't know what it is default: return 0; @@ -599,7 +607,7 @@ int psutil_get_nic_speed(int ifm_active) { break; #endif case IFM_IEEE80211: - switch(IFM_SUBTYPE(ifm_active)) { + switch (IFM_SUBTYPE(ifm_active)) { case IFM_IEEE80211_FH1: // Frequency Hopping 1Mbps case IFM_IEEE80211_DS1: // Direct Sequence 1Mbps return 1; @@ -639,17 +647,17 @@ psutil_net_if_duplex_speed(PyObject *self, PyObject *args) { struct ifreq ifr; struct ifmediareq ifmed; - if (! PyArg_ParseTuple(args, "s", &nic_name)) + if (!PyArg_ParseTuple(args, "s", &nic_name)) return NULL; sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock == -1) - return PyErr_SetFromErrno(PyExc_OSError); - PSUTIL_STRNCPY(ifr.ifr_name, nic_name, sizeof(ifr.ifr_name)); + return psutil_oserror(); + str_copy(ifr.ifr_name, sizeof(ifr.ifr_name), nic_name); // speed / duplex memset(&ifmed, 0, sizeof(struct ifmediareq)); - strlcpy(ifmed.ifm_name, nic_name, sizeof(ifmed.ifm_name)); + str_copy(ifmed.ifm_name, sizeof(ifmed.ifm_name), nic_name); ret = ioctl(sock, SIOCGIFMEDIA, (caddr_t)&ifmed); if (ret == -1) { speed = 0; diff --git a/contrib/python/psutil/py3/psutil/arch/posix/pids.c b/contrib/python/psutil/py3/psutil/arch/posix/pids.c new file mode 100644 index 00000000000..368c53c91a8 --- /dev/null +++ b/contrib/python/psutil/py3/psutil/arch/posix/pids.c @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + +#include <sys/types.h> +#include <signal.h> +#include <errno.h> + +#include "../../arch/all/init.h" + + +static int +has_pid_zero(void) { +#if defined(PSUTIL_LINUX) || defined(PSUTIL_FREEBSD) + return 0; +#else + return 1; +#endif +} + + +// Check if PID exists. Return values: +// 1: exists +// 0: does not exist +// -1: error (Python exception is set) +int +psutil_pid_exists(pid_t pid) { + int ret; + + // No negative PID exists, plus -1 is an alias for sending signal + // too all processes except system ones. Not what we want. + if (pid < 0) + return 0; + + // As per "man 2 kill" PID 0 is an alias for sending the signal to + // every process in the process group of the calling process. Not + // what we want. Some platforms have PID 0, some do not. We decide + // that at runtime. + if (pid == 0) + return has_pid_zero(); + + ret = kill(pid, 0); + if (ret == 0) + return 1; + + // ESRCH == No such process + if (errno == ESRCH) + return 0; + + // EPERM clearly indicates there's a process to deny access to. + if (errno == EPERM) + return 1; + + // According to "man 2 kill" possible error values are (EINVAL, + // EPERM, ESRCH) therefore we should never get here. + return -1; +} diff --git a/contrib/python/psutil/py3/psutil/arch/posix/proc.c b/contrib/python/psutil/py3/psutil/arch/posix/proc.c index b0ddf7b0e64..f8cd7e6a92a 100644 --- a/contrib/python/psutil/py3/psutil/arch/posix/proc.c +++ b/contrib/python/psutil/py3/psutil/arch/posix/proc.c @@ -4,77 +4,48 @@ * found in the LICENSE file. */ - +#include <Python.h> #include <signal.h> +#include <errno.h> #include <sys/resource.h> #include "../../arch/all/init.h" -// Check if PID exists. Return values: -// 1: exists -// 0: does not exist -// -1: error (Python exception is set) -int -psutil_pid_exists(pid_t pid) { - int ret; - - // No negative PID exists, plus -1 is an alias for sending signal - // too all processes except system ones. Not what we want. - if (pid < 0) - return 0; - // As per "man 2 kill" PID 0 is an alias for sending the signal to - // every process in the process group of the calling process. - // Not what we want. Some platforms have PID 0, some do not. - // We decide that at runtime. - if (pid == 0) { -#if defined(PSUTIL_LINUX) || defined(PSUTIL_FREEBSD) - return 0; -#else - return 1; -#endif - } +#if defined(PSUTIL_OSX) || defined(PSUTIL_BSD) +// Return True if PID is a zombie else False, including if PID does not +// exist or the underlying function fails (never raise exception). +PyObject * +psutil_proc_is_zombie(PyObject *self, PyObject *args) { + pid_t pid; - ret = kill(pid , 0); - if (ret == 0) - return 1; - else { - if (errno == ESRCH) { - // ESRCH == No such process - return 0; - } - else if (errno == EPERM) { - // EPERM clearly indicates there's a process to deny - // access to. - return 1; - } - else { - // According to "man 2 kill" possible error values are - // (EINVAL, EPERM, ESRCH) therefore we should never get - // here. If we do let's be explicit in considering this - // an error. - PyErr_SetFromErrno(PyExc_OSError); - return -1; - } - } + if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) + return NULL; + if (is_zombie(pid) == 1) + Py_RETURN_TRUE; + else + Py_RETURN_FALSE; } +#endif // Utility used for those syscalls which do not return a meaningful -// error that we can translate into an exception which makes sense. As -// such, we'll have to guess. On UNIX, if errno is set, we return that -// one (OSError). Else, if PID does not exist we assume the syscall -// failed because of that so we raise NoSuchProcess. If none of this is -// true we giveup and raise RuntimeError(msg). This will always set a -// Python exception and return NULL. -void +// error that we can directly translate into an exception which makes +// sense. As such we'll have to guess, e.g. if errno is set or if PID +// does not exist. If reason can't be determined raise RuntimeError. +PyObject * psutil_raise_for_pid(pid_t pid, char *syscall) { if (errno != 0) - psutil_PyErr_SetFromOSErrnoWithSyscall(syscall); + psutil_oserror_wsyscall(syscall); else if (psutil_pid_exists(pid) == 0) - NoSuchProcess(syscall); + psutil_oserror_nsp(syscall); +#if defined(PSUTIL_OSX) || defined(PSUTIL_BSD) + else if (is_zombie(pid)) + PyErr_SetString(ZombieProcessError, ""); +#endif else - PyErr_Format(PyExc_RuntimeError, "%s syscall failed", syscall); + psutil_runtime_error("%s syscall failed", syscall); + return NULL; } @@ -85,7 +56,7 @@ psutil_proc_priority_get(PyObject *self, PyObject *args) { int priority; errno = 0; - if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) + if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) return NULL; #ifdef PSUTIL_OSX @@ -94,7 +65,7 @@ psutil_proc_priority_get(PyObject *self, PyObject *args) { priority = getpriority(PRIO_PROCESS, pid); #endif if (errno != 0) - return PyErr_SetFromErrno(PyExc_OSError); + return psutil_oserror(); return Py_BuildValue("i", priority); } @@ -106,7 +77,7 @@ psutil_proc_priority_set(PyObject *self, PyObject *args) { int priority; int retval; - if (! PyArg_ParseTuple(args, _Py_PARSE_PID "i", &pid, &priority)) + if (!PyArg_ParseTuple(args, _Py_PARSE_PID "i", &pid, &priority)) return NULL; #ifdef PSUTIL_OSX @@ -115,6 +86,6 @@ psutil_proc_priority_set(PyObject *self, PyObject *args) { retval = setpriority(PRIO_PROCESS, pid, priority); #endif if (retval == -1) - return PyErr_SetFromErrno(PyExc_OSError); + return psutil_oserror(); Py_RETURN_NONE; } diff --git a/contrib/python/psutil/py3/psutil/arch/posix/sysctl.c b/contrib/python/psutil/py3/psutil/arch/posix/sysctl.c index fbe1b561cb1..dbec5159db6 100644 --- a/contrib/python/psutil/py3/psutil/arch/posix/sysctl.c +++ b/contrib/python/psutil/py3/psutil/arch/posix/sysctl.c @@ -24,12 +24,12 @@ psutil_sysctl(int *mib, u_int miblen, void *buf, size_t buflen) { return psutil_badargs("psutil_sysctl"); if (sysctl(mib, miblen, buf, &len, NULL, 0) == -1) { - psutil_PyErr_SetFromOSErrnoWithSyscall("sysctl()"); + psutil_oserror_wsyscall("sysctl()"); return -1; } if (len != buflen) { - PyErr_SetString(PyExc_RuntimeError, "sysctl() size mismatch"); + psutil_runtime_error("sysctl() size mismatch"); return -1; } @@ -52,7 +52,7 @@ psutil_sysctl_malloc(int *mib, u_int miblen, char **buf, size_t *buflen) { // First query to determine required size ret = sysctl(mib, miblen, NULL, &needed, NULL, 0); if (ret == -1) { - psutil_PyErr_SetFromOSErrnoWithSyscall("sysctl() malloc 1/3"); + psutil_oserror_wsyscall("sysctl() malloc 1/3"); return -1; } @@ -85,7 +85,7 @@ psutil_sysctl_malloc(int *mib, u_int miblen, char **buf, size_t *buflen) { // Re-query needed size for next attempt if (sysctl(mib, miblen, NULL, &needed, NULL, 0) == -1) { - psutil_PyErr_SetFromOSErrnoWithSyscall("sysctl() malloc 2/3"); + psutil_oserror_wsyscall("sysctl() malloc 2/3"); return -1; } @@ -95,13 +95,11 @@ psutil_sysctl_malloc(int *mib, u_int miblen, char **buf, size_t *buflen) { // Other errors: clean up and give up free(buffer); - psutil_PyErr_SetFromOSErrnoWithSyscall("sysctl() malloc 3/3"); + psutil_oserror_wsyscall("sysctl() malloc 3/3"); return -1; } - PyErr_SetString( - PyExc_RuntimeError, "sysctl() buffer allocation retry limit exceeded" - ); + psutil_runtime_error("sysctl() buffer allocation retry limit exceeded"); return -1; } @@ -117,9 +115,7 @@ psutil_sysctl_argmax() { } if (argmax <= 0) { - PyErr_SetString( - PyExc_RuntimeError, "sysctl(KERN_ARGMAX) return <= 0" - ); + psutil_runtime_error("sysctl(KERN_ARGMAX) return <= 0"); return 0; } @@ -138,13 +134,13 @@ psutil_sysctlbyname(const char *name, void *buf, size_t buflen) { return psutil_badargs("psutil_sysctlbyname"); if (sysctlbyname(name, buf, &len, NULL, 0) == -1) { - snprintf(errbuf, sizeof(errbuf), "sysctlbyname('%s')", name); - psutil_PyErr_SetFromOSErrnoWithSyscall(errbuf); + str_format(errbuf, sizeof(errbuf), "sysctlbyname('%s')", name); + psutil_oserror_wsyscall(errbuf); return -1; } if (len != buflen) { - snprintf( + str_format( errbuf, sizeof(errbuf), "sysctlbyname('%s') size mismatch: returned %zu, expected %zu", @@ -152,7 +148,7 @@ psutil_sysctlbyname(const char *name, void *buf, size_t buflen) { len, buflen ); - PyErr_SetString(PyExc_RuntimeError, errbuf); + psutil_runtime_error(errbuf); return -1; } @@ -177,8 +173,10 @@ psutil_sysctlbyname_malloc(const char *name, char **buf, size_t *buflen) { // First query to determine required size. ret = sysctlbyname(name, NULL, &needed, NULL, 0); if (ret == -1) { - snprintf(errbuf, sizeof(errbuf), "sysctlbyname('%s') malloc 1/3", name); - psutil_PyErr_SetFromOSErrnoWithSyscall(errbuf); + str_format( + errbuf, sizeof(errbuf), "sysctlbyname('%s') malloc 1/3", name + ); + psutil_oserror_wsyscall(errbuf); return -1; } @@ -209,13 +207,13 @@ psutil_sysctlbyname_malloc(const char *name, char **buf, size_t *buflen) { buffer = NULL; if (sysctlbyname(name, NULL, &needed, NULL, 0) == -1) { - snprintf( + str_format( errbuf, sizeof(errbuf), "sysctlbyname('%s') malloc 2/3", name ); - psutil_PyErr_SetFromOSErrnoWithSyscall(errbuf); + psutil_oserror_wsyscall(errbuf); return -1; } @@ -225,20 +223,20 @@ psutil_sysctlbyname_malloc(const char *name, char **buf, size_t *buflen) { // Other errors: clean up and give up. free(buffer); - snprintf( + str_format( errbuf, sizeof(errbuf), "sysctlbyname('%s') malloc 3/3", name ); - psutil_PyErr_SetFromOSErrnoWithSyscall(errbuf); + psutil_oserror_wsyscall(errbuf); return -1; } - snprintf( + str_format( errbuf, sizeof(errbuf), "sysctlbyname('%s') buffer allocation retry limit exceeded", name ); - PyErr_SetString(PyExc_RuntimeError, errbuf); + psutil_runtime_error(errbuf); return -1; } #endif // PSUTIL_HAS_SYSCTLBYNAME diff --git a/contrib/python/psutil/py3/psutil/arch/posix/users.c b/contrib/python/psutil/py3/psutil/arch/posix/users.c index df33820e0ac..8c75bf33088 100644 --- a/contrib/python/psutil/py3/psutil/arch/posix/users.c +++ b/contrib/python/psutil/py3/psutil/arch/posix/users.c @@ -13,7 +13,6 @@ #include <utmpx.h> - static void setup() { UTXENT_MUTEX_LOCK(); @@ -49,17 +48,16 @@ psutil_users(PyObject *self, PyObject *args) { py_tuple = NULL; py_username = PyUnicode_DecodeFSDefault(ut->ut_user); - if (! py_username) + if (!py_username) goto error; py_tty = PyUnicode_DecodeFSDefault(ut->ut_line); - if (! py_tty) + if (!py_tty) goto error; host_len = strnlen(ut->ut_host, sizeof(ut->ut_host)); - if (host_len == 0 || - (strcmp(ut->ut_host, ":0") == 0) || - (strcmp(ut->ut_host, ":0.0") == 0)) + if (host_len == 0 || (strcmp(ut->ut_host, ":0") == 0) + || (strcmp(ut->ut_host, ":0.0") == 0)) { py_hostname = PyUnicode_DecodeFSDefault("localhost"); } @@ -76,13 +74,13 @@ psutil_users(PyObject *self, PyObject *args) { py_tuple = Py_BuildValue( "OOOd" _Py_PARSE_PID, - py_username, // username - py_tty, // tty - py_hostname, // hostname + py_username, // username + py_tty, // tty + py_hostname, // hostname (double)ut->ut_tv.tv_sec, // tstamp - ut->ut_pid // process id + ut->ut_pid // process id ); - if (! py_tuple) + if (!py_tuple) goto error; if (PyList_Append(py_retlist, py_tuple)) goto error; diff --git a/contrib/python/psutil/py3/psutil/arch/sunos/cpu.c b/contrib/python/psutil/py3/psutil/arch/sunos/cpu.c index 946bffd00fe..e0ca022ebcd 100644 --- a/contrib/python/psutil/py3/psutil/arch/sunos/cpu.c +++ b/contrib/python/psutil/py3/psutil/arch/sunos/cpu.c @@ -9,6 +9,8 @@ #include <sys/sysinfo.h> #include <kstat.h> +#include "../../arch/all/init.h" + // System-wide CPU times. PyObject * @@ -24,21 +26,23 @@ psutil_per_cpu_times(PyObject *self, PyObject *args) { kc = kstat_open(); if (kc == NULL) { - PyErr_SetFromErrno(PyExc_OSError); + psutil_oserror(); goto error; } for (ksp = kc->kc_chain; ksp != NULL; ksp = ksp->ks_next) { if (strcmp(ksp->ks_module, "cpu_stat") == 0) { if (kstat_read(kc, ksp, &cs) == -1) { - PyErr_SetFromErrno(PyExc_OSError); + psutil_oserror(); goto error; } - py_cputime = Py_BuildValue("ffff", - (float)cs.cpu_sysinfo.cpu[CPU_USER], - (float)cs.cpu_sysinfo.cpu[CPU_KERNEL], - (float)cs.cpu_sysinfo.cpu[CPU_IDLE], - (float)cs.cpu_sysinfo.cpu[CPU_WAIT]); + py_cputime = Py_BuildValue( + "ffff", + (float)cs.cpu_sysinfo.cpu[CPU_USER], + (float)cs.cpu_sysinfo.cpu[CPU_KERNEL], + (float)cs.cpu_sysinfo.cpu[CPU_IDLE], + (float)cs.cpu_sysinfo.cpu[CPU_WAIT] + ); if (py_cputime == NULL) goto error; if (PyList_Append(py_retlist, py_cputime)) @@ -108,14 +112,14 @@ psutil_cpu_stats(PyObject *self, PyObject *args) { kc = kstat_open(); if (kc == NULL) { - PyErr_SetFromErrno(PyExc_OSError); + psutil_oserror(); goto error; } for (ksp = kc->kc_chain; ksp != NULL; ksp = ksp->ks_next) { if (strcmp(ksp->ks_module, "cpu_stat") == 0) { if (kstat_read(kc, ksp, &cs) == -1) { - PyErr_SetFromErrno(PyExc_OSError); + psutil_oserror(); goto error; } // voluntary + involuntary @@ -127,8 +131,7 @@ psutil_cpu_stats(PyObject *self, PyObject *args) { } kstat_close(kc); - return Py_BuildValue( - "IIII", ctx_switches, interrupts, syscalls, traps); + return Py_BuildValue("IIII", ctx_switches, interrupts, syscalls, traps); error: if (kc != NULL) diff --git a/contrib/python/psutil/py3/psutil/arch/sunos/disk.c b/contrib/python/psutil/py3/psutil/arch/sunos/disk.c index f736984c769..d5ced15a30b 100644 --- a/contrib/python/psutil/py3/psutil/arch/sunos/disk.c +++ b/contrib/python/psutil/py3/psutil/arch/sunos/disk.c @@ -10,6 +10,8 @@ #include <sys/mnttab.h> #include <kstat.h> +#include "../../arch/all/init.h" + PyObject * psutil_disk_io_counters(PyObject *self, PyObject *args) { @@ -23,7 +25,7 @@ psutil_disk_io_counters(PyObject *self, PyObject *args) { return NULL; kc = kstat_open(); if (kc == NULL) { - PyErr_SetFromErrno(PyExc_OSError);; + psutil_oserror(); goto error; } ksp = kc->kc_chain; @@ -32,7 +34,8 @@ psutil_disk_io_counters(PyObject *self, PyObject *args) { if (strcmp(ksp->ks_class, "disk") == 0) { if (kstat_read(kc, ksp, &kio) == -1) { kstat_close(kc); - return PyErr_SetFromErrno(PyExc_OSError);; + return psutil_oserror(); + ; } py_disk_info = Py_BuildValue( "(IIKKLL)", @@ -41,12 +44,13 @@ psutil_disk_io_counters(PyObject *self, PyObject *args) { kio.nread, kio.nwritten, kio.rtime / 1000 / 1000, // from nano to milli secs - kio.wtime / 1000 / 1000 // from nano to milli secs + kio.wtime / 1000 / 1000 // from nano to milli secs ); if (!py_disk_info) goto error; - if (PyDict_SetItemString(py_retdict, ksp->ks_name, - py_disk_info)) + if (PyDict_SetItemString( + py_retdict, ksp->ks_name, py_disk_info + )) goto error; Py_CLEAR(py_disk_info); } @@ -80,23 +84,24 @@ psutil_disk_partitions(PyObject *self, PyObject *args) { file = fopen(MNTTAB, "rb"); if (file == NULL) { - PyErr_SetFromErrno(PyExc_OSError); + psutil_oserror(); goto error; } while (getmntent(file, &mt) == 0) { py_dev = PyUnicode_DecodeFSDefault(mt.mnt_special); - if (! py_dev) + if (!py_dev) goto error; py_mountp = PyUnicode_DecodeFSDefault(mt.mnt_mountp); - if (! py_mountp) + if (!py_mountp) goto error; py_tuple = Py_BuildValue( "(OOss)", - py_dev, // device - py_mountp, // mount point - mt.mnt_fstype, // fs type - mt.mnt_mntopts); // options + py_dev, // device + py_mountp, // mount point + mt.mnt_fstype, // fs type + mt.mnt_mntopts // options + ); if (py_tuple == NULL) goto error; if (PyList_Append(py_retlist, py_tuple)) diff --git a/contrib/python/psutil/py3/psutil/arch/sunos/environ.c b/contrib/python/psutil/py3/psutil/arch/sunos/environ.c index 458c7f22251..d3b0c422395 100644 --- a/contrib/python/psutil/py3/psutil/arch/sunos/environ.c +++ b/contrib/python/psutil/py3/psutil/arch/sunos/environ.c @@ -33,10 +33,10 @@ open_address_space(pid_t pid, const char *procfs_path) { int fd; char proc_path[PATH_MAX]; - snprintf(proc_path, PATH_MAX, "%s/%i/as", procfs_path, pid); + str_format(proc_path, PATH_MAX, "%s/%i/as", procfs_path, pid); fd = open(proc_path, O_RDONLY); if (fd < 0) - PyErr_SetFromErrno(PyExc_OSError); + psutil_oserror(); return fd; } @@ -54,7 +54,7 @@ open_address_space(pid_t pid, const char *procfs_path) { static size_t read_offt(int fd, off_t offset, char *buf, size_t buf_size) { size_t to_read = buf_size; - size_t stored = 0; + size_t stored = 0; int r; while (to_read) { @@ -70,8 +70,8 @@ read_offt(int fd, off_t offset, char *buf, size_t buf_size) { return stored; - error: - PyErr_SetFromErrno(PyExc_OSError); +error: + psutil_oserror(); return -1; } @@ -82,7 +82,7 @@ read_offt(int fd, off_t offset, char *buf, size_t buf_size) { * @param fd a file descriptor of opened address space. * @param offset an offset in specified file descriptor. * @return allocated null-terminated string or NULL in case of error. -*/ + */ static char * read_cstring_offt(int fd, off_t offset) { int r; @@ -93,7 +93,7 @@ read_cstring_offt(int fd, off_t offset) { char *result = NULL; if (lseek(fd, offset, SEEK_SET) == (off_t)-1) { - PyErr_SetFromErrno(PyExc_OSError); + psutil_oserror(); goto error; } @@ -101,15 +101,15 @@ read_cstring_offt(int fd, off_t offset) { for (;;) { r = read(fd, buf, sizeof(buf)); if (r == -1) { - PyErr_SetFromErrno(PyExc_OSError); + psutil_oserror(); goto error; } else if (r == 0) { break; } else { - for (i=0; i<r; i++) - if (! buf[i]) + for (i = 0; i < r; i++) + if (!buf[i]) goto found; } @@ -119,8 +119,8 @@ read_cstring_offt(int fd, off_t offset) { found: len = end + i - offset; - result = malloc(len+1); - if (! result) { + result = malloc(len + 1); + if (!result) { PyErr_NoMemory(); goto error; } @@ -134,7 +134,7 @@ found: result[len] = '\0'; return result; - error: +error: if (result) free(result); return NULL; @@ -167,7 +167,7 @@ read_cstrings_block(int fd, off_t offset, size_t ptr_size, size_t count) { pblock_size = ptr_size * count; pblock = malloc(pblock_size); - if (! pblock) { + if (!pblock) { PyErr_NoMemory(); goto error; } @@ -175,17 +175,17 @@ read_cstrings_block(int fd, off_t offset, size_t ptr_size, size_t count) { if (read_offt(fd, offset, pblock, pblock_size) != pblock_size) goto error; - result = (char **) calloc(count, sizeof(char *)); - if (! result) { + result = (char **)calloc(count, sizeof(char *)); + if (!result) { PyErr_NoMemory(); goto error; } - for (i=0; i<count; i++) { + for (i = 0; i < count; i++) { result[i] = read_cstring_offt( - fd, (ptr_size == 4? - ((uint32_t *) pblock)[i]: - ((uint64_t *) pblock)[i])); + fd, + (ptr_size == 4 ? ((uint32_t *)pblock)[i] : ((uint64_t *)pblock)[i]) + ); if (!result[i]) goto error; @@ -194,7 +194,7 @@ read_cstrings_block(int fd, off_t offset, size_t ptr_size, size_t count) { free(pblock); return result; - error: +error: if (result) psutil_free_cstrings_array(result, i); if (pblock) @@ -229,7 +229,7 @@ is_ptr_dereference_possible(psinfo_t info) { */ static inline int ptr_size_by_psinfo(psinfo_t info) { - return info.pr_dmodel == PR_MODEL_ILP32? 4 : 8; + return info.pr_dmodel == PR_MODEL_ILP32 ? 4 : 8; } @@ -245,14 +245,14 @@ search_pointers_vector_size_offt(int fd, off_t offt, size_t ptr_size) { int count = 0; size_t r; char buf[8]; - static const char zeros[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; + static const char zeros[8] = {0, 0, 0, 0, 0, 0, 0, 0}; assert(ptr_size == 4 || ptr_size == 8); if (lseek(fd, offt, SEEK_SET) == (off_t)-1) goto error; - for (;; count ++) { + for (;; count++) { r = read(fd, buf, ptr_size); if (r < 0) @@ -262,19 +262,18 @@ search_pointers_vector_size_offt(int fd, off_t offt, size_t ptr_size) { break; if (r != ptr_size) { - PyErr_SetString( - PyExc_RuntimeError, "pointer block is truncated"); + psutil_runtime_error("pointer block is truncated"); return -1; } - if (! memcmp(buf, zeros, ptr_size)) + if (!memcmp(buf, zeros, ptr_size)) break; } return count; - error: - PyErr_SetFromErrno(PyExc_OSError); +error: + psutil_oserror(); return -1; } @@ -295,16 +294,16 @@ psutil_read_raw_args(psinfo_t info, const char *procfs_path, size_t *count) { int as; char **result; - if (! is_ptr_dereference_possible(info)) { + if (!is_ptr_dereference_possible(info)) { PyErr_SetString( PyExc_NotImplementedError, - "can't get env of a 64 bit process from a 32 bit process"); + "can't get env of a 64 bit process from a 32 bit process" + ); return NULL; } - if (! (info.pr_argv && info.pr_argc)) { - PyErr_SetString( - PyExc_RuntimeError, "process doesn't have arguments block"); + if (!(info.pr_argv && info.pr_argc)) { + psutil_runtime_error("process doesn't have arguments block"); return NULL; } @@ -351,10 +350,11 @@ psutil_read_raw_env(psinfo_t info, const char *procfs_path, ssize_t *count) { int ptr_size; char **result = NULL; - if (! is_ptr_dereference_possible(info)) { + if (!is_ptr_dereference_possible(info)) { PyErr_SetString( PyExc_NotImplementedError, - "can't get env of a 64 bit process from a 32 bit process"); + "can't get env of a 64 bit process from a 32 bit process" + ); return NULL; } @@ -364,15 +364,13 @@ psutil_read_raw_env(psinfo_t info, const char *procfs_path, ssize_t *count) { ptr_size = ptr_size_by_psinfo(info); - env_count = search_pointers_vector_size_offt( - as, info.pr_envp, ptr_size); + env_count = search_pointers_vector_size_offt(as, info.pr_envp, ptr_size); if (env_count >= 0 && count) *count = env_count; if (env_count > 0) - result = read_cstrings_block( - as, info.pr_envp, ptr_size, env_count); + result = read_cstrings_block(as, info.pr_envp, ptr_size, env_count); close(as); return result; @@ -391,7 +389,7 @@ psutil_free_cstrings_array(char **array, size_t count) { if (!array) return; - for (i=0; i<count; i++) { + for (i = 0; i < count; i++) { if (array[i]) { free(array[i]); } diff --git a/contrib/python/psutil/py3/psutil/arch/sunos/init.h b/contrib/python/psutil/py3/psutil/arch/sunos/init.h index 52ac0139b32..754a792c89f 100644 --- a/contrib/python/psutil/py3/psutil/arch/sunos/init.h +++ b/contrib/python/psutil/py3/psutil/arch/sunos/init.h @@ -10,15 +10,16 @@ #ifndef PROCESS_AS_UTILS_H #define PROCESS_AS_UTILS_H -char ** -psutil_read_raw_args(psinfo_t info, const char *procfs_path, size_t *count); +char **psutil_read_raw_args( + psinfo_t info, const char *procfs_path, size_t *count +); -char ** -psutil_read_raw_env(psinfo_t info, const char *procfs_path, ssize_t *count); +char **psutil_read_raw_env( + psinfo_t info, const char *procfs_path, ssize_t *count +); -void -psutil_free_cstrings_array(char **array, size_t count); -#endif // PROCESS_AS_UTILS_H +void psutil_free_cstrings_array(char **array, size_t count); +#endif // PROCESS_AS_UTILS_H PyObject *psutil_boot_time(PyObject *self, PyObject *args); PyObject *psutil_cpu_count_cores(PyObject *self, PyObject *args); diff --git a/contrib/python/psutil/py3/psutil/arch/sunos/mem.c b/contrib/python/psutil/py3/psutil/arch/sunos/mem.c index c4bf97189bd..a4e41482aea 100644 --- a/contrib/python/psutil/py3/psutil/arch/sunos/mem.c +++ b/contrib/python/psutil/py3/psutil/arch/sunos/mem.c @@ -7,88 +7,90 @@ #include <Python.h> #include <kstat.h> -#include <string.h> #include <sys/sysinfo.h> +#include "../../arch/all/init.h" + PyObject * psutil_swap_mem(PyObject *self, PyObject *args) { -// XXX (arghhh!) -// total/free swap mem: commented out as for some reason I can't -// manage to get the same results shown by "swap -l", despite the -// code below is exactly the same as: -// http://cvs.opensolaris.org/source/xref/onnv/onnv-gate/usr/src/ -// cmd/swap/swap.c -// We're going to parse "swap -l" output from Python (sigh!) + // XXX (arghhh!) + // total/free swap mem: commented out as for some reason I can't + // manage to get the same results shown by "swap -l", despite the + // code below is exactly the same as: + // http://cvs.opensolaris.org/source/xref/onnv/onnv-gate/usr/src/ + // cmd/swap/swap.c + // We're going to parse "swap -l" output from Python (sigh!) -/* - struct swaptable *st; - struct swapent *swapent; - int i; - struct stat64 statbuf; - char *path; - char fullpath[MAXPATHLEN+1]; - int num; + /* + struct swaptable *st; + struct swapent *swapent; + int i; + struct stat64 statbuf; + char *path; + char fullpath[MAXPATHLEN+1]; + int num; - if ((num = swapctl(SC_GETNSWP, NULL)) == -1) { - PyErr_SetFromErrno(PyExc_OSError); - return NULL; - } - if (num == 0) { - PyErr_SetString(PyExc_RuntimeError, "no swap devices configured"); - return NULL; - } - if ((st = malloc(num * sizeof(swapent_t) + sizeof (int))) == NULL) { - PyErr_SetString(PyExc_RuntimeError, "malloc failed"); - return NULL; - } - if ((path = malloc(num * MAXPATHLEN)) == NULL) { - PyErr_SetString(PyExc_RuntimeError, "malloc failed"); - return NULL; - } - swapent = st->swt_ent; - for (i = 0; i < num; i++, swapent++) { - swapent->ste_path = path; - path += MAXPATHLEN; - } - st->swt_n = num; - if ((num = swapctl(SC_LIST, st)) == -1) { - PyErr_SetFromErrno(PyExc_OSError); - return NULL; - } + if ((num = swapctl(SC_GETNSWP, NULL)) == -1) { + psutil_oserror(); + return NULL; + } + if (num == 0) { + psutil_runtime_error("no swap devices configured"); + return NULL; + } + if ((st = malloc(num * sizeof(swapent_t) + sizeof (int))) == NULL) { + psutil_runtime_error("malloc failed"); + return NULL; + } + if ((path = malloc(num * MAXPATHLEN)) == NULL) { + psutil_runtime_error("malloc failed"); + return NULL; + } + swapent = st->swt_ent; + for (i = 0; i < num; i++, swapent++) { + swapent->ste_path = path; + path += MAXPATHLEN; + } + st->swt_n = num; + if ((num = swapctl(SC_LIST, st)) == -1) { + psutil_oserror(); + return NULL; + } - swapent = st->swt_ent; - long t = 0, f = 0; - for (i = 0; i < num; i++, swapent++) { - int diskblks_per_page =(int)(sysconf(_SC_PAGESIZE) >> DEV_BSHIFT); - t += (long)swapent->ste_pages; - f += (long)swapent->ste_free; - } + swapent = st->swt_ent; + long t = 0, f = 0; + for (i = 0; i < num; i++, swapent++) { + int diskblks_per_page =(int)(sysconf(_SC_PAGESIZE) >> DEV_BSHIFT); + t += (long)swapent->ste_pages; + f += (long)swapent->ste_free; + } - free(st); - return Py_BuildValue("(kk)", t, f); -*/ + free(st); + return Py_BuildValue("(kk)", t, f); + */ kstat_ctl_t *kc; - kstat_t *k; - cpu_stat_t *cpu; - int cpu_count = 0; - int flag = 0; - uint_t sin = 0; - uint_t sout = 0; + kstat_t *k; + cpu_stat_t *cpu; + int cpu_count = 0; + int flag = 0; + uint_t sin = 0; + uint_t sout = 0; kc = kstat_open(); if (kc == NULL) - return PyErr_SetFromErrno(PyExc_OSError);; + return psutil_oserror(); + ; k = kc->kc_chain; while (k != NULL) { - if ((strncmp(k->ks_name, "cpu_stat", 8) == 0) && \ - (kstat_read(kc, k, NULL) != -1) ) + if ((strncmp(k->ks_name, "cpu_stat", 8) == 0) + && (kstat_read(kc, k, NULL) != -1)) { flag = 1; - cpu = (cpu_stat_t *) k->ks_data; - sin += cpu->cpu_vminfo.pgswapin; // num pages swapped in + cpu = (cpu_stat_t *)k->ks_data; + sin += cpu->cpu_vminfo.pgswapin; // num pages swapped in sout += cpu->cpu_vminfo.pgswapout; // num pages swapped out } cpu_count += 1; @@ -96,7 +98,7 @@ psutil_swap_mem(PyObject *self, PyObject *args) { } kstat_close(kc); if (!flag) { - PyErr_SetString(PyExc_RuntimeError, "no swap device was found"); + psutil_runtime_error("no swap device was found"); return NULL; } return Py_BuildValue("(II)", sin, sout); diff --git a/contrib/python/psutil/py3/psutil/arch/sunos/net.c b/contrib/python/psutil/py3/psutil/arch/sunos/net.c index 1d1432b6db5..12353d4c75d 100644 --- a/contrib/python/psutil/py3/psutil/arch/sunos/net.c +++ b/contrib/python/psutil/py3/psutil/arch/sunos/net.c @@ -27,7 +27,7 @@ PyObject * psutil_net_io_counters(PyObject *self, PyObject *args) { - kstat_ctl_t *kc = NULL; + kstat_ctl_t *kc = NULL; kstat_t *ksp; kstat_named_t *rbytes, *wbytes, *rpkts, *wpkts, *ierrs, *oerrs; int ret; @@ -45,7 +45,7 @@ psutil_net_io_counters(PyObject *self, PyObject *args) { sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock == -1) { - PyErr_SetFromErrno(PyExc_OSError); + psutil_oserror(); goto error; } @@ -61,7 +61,7 @@ psutil_net_io_counters(PyObject *self, PyObject *args) { goto next; // check if this is a network interface by sending a ioctl - PSUTIL_STRNCPY(ifr.lifr_name, ksp->ks_name, sizeof(ifr.lifr_name)); + str_copy(ifr.lifr_name, sizeof(ifr.lifr_name), ksp->ks_name); ret = ioctl(sock, SIOCGLIFFLAGS, &ifr); if (ret == -1) goto next; @@ -78,38 +78,38 @@ psutil_net_io_counters(PyObject *self, PyObject *args) { ierrs = (kstat_named_t *)kstat_data_lookup(ksp, "ierrors"); oerrs = (kstat_named_t *)kstat_data_lookup(ksp, "oerrors"); - if ((rbytes == NULL) || (wbytes == NULL) || (rpkts == NULL) || - (wpkts == NULL) || (ierrs == NULL) || (oerrs == NULL)) + if ((rbytes == NULL) || (wbytes == NULL) || (rpkts == NULL) + || (wpkts == NULL) || (ierrs == NULL) || (oerrs == NULL)) { - PyErr_SetString(PyExc_RuntimeError, "kstat_data_lookup() failed"); + psutil_runtime_error("kstat_data_lookup() failed"); goto error; } - if (rbytes->data_type == KSTAT_DATA_UINT64) - { - py_ifc_info = Py_BuildValue("(KKKKIIii)", - wbytes->value.ui64, - rbytes->value.ui64, - wpkts->value.ui64, - rpkts->value.ui64, - ierrs->value.ui32, - oerrs->value.ui32, - 0, // dropin not supported - 0 // dropout not supported - ); + if (rbytes->data_type == KSTAT_DATA_UINT64) { + py_ifc_info = Py_BuildValue( + "(KKKKIIii)", + wbytes->value.ui64, + rbytes->value.ui64, + wpkts->value.ui64, + rpkts->value.ui64, + ierrs->value.ui32, + oerrs->value.ui32, + 0, // dropin not supported + 0 // dropout not supported + ); } - else - { - py_ifc_info = Py_BuildValue("(IIIIIIii)", - wbytes->value.ui32, - rbytes->value.ui32, - wpkts->value.ui32, - rpkts->value.ui32, - ierrs->value.ui32, - oerrs->value.ui32, - 0, // dropin not supported - 0 // dropout not supported - ); + else { + py_ifc_info = Py_BuildValue( + "(IIIIIIii)", + wbytes->value.ui32, + rbytes->value.ui32, + wpkts->value.ui32, + rpkts->value.ui32, + ierrs->value.ui32, + oerrs->value.ui32, + 0, // dropin not supported + 0 // dropout not supported + ); } if (!py_ifc_info) goto error; @@ -118,7 +118,7 @@ psutil_net_io_counters(PyObject *self, PyObject *args) { Py_CLEAR(py_ifc_info); goto next; -next: + next: ksp = ksp->ks_next; } @@ -141,8 +141,8 @@ error: // Return stats about a particular network interface. Refs: // * https://github.com/dpaleino/wicd/blob/master/wicd/backends/be-ioctl.py // * http://www.i-scream.org/libstatgrab/ -PyObject* -psutil_net_if_stats(PyObject* self, PyObject* args) { +PyObject * +psutil_net_if_stats(PyObject *self, PyObject *args) { kstat_ctl_t *kc = NULL; kstat_t *ksp; kstat_named_t *knp; @@ -162,7 +162,7 @@ psutil_net_if_stats(PyObject* self, PyObject* args) { goto error; sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock == -1) { - PyErr_SetFromErrno(PyExc_OSError); + psutil_oserror(); goto error; } @@ -176,7 +176,7 @@ psutil_net_if_stats(PyObject* self, PyObject* args) { if (strcmp(ksp->ks_class, "net") != 0) continue; - PSUTIL_STRNCPY(ifr.lifr_name, ksp->ks_name, sizeof(ifr.lifr_name)); + str_copy(ifr.lifr_name, sizeof(ifr.lifr_name), ksp->ks_name); ret = ioctl(sock, SIOCGLIFFLAGS, &ifr); if (ret == -1) continue; // not a network interface @@ -219,8 +219,9 @@ psutil_net_if_stats(PyObject* self, PyObject* args) { if (ret == -1) goto error; - py_ifc_info = Py_BuildValue("(Oiii)", py_is_up, duplex, speed, - ifr.lifr_mtu); + py_ifc_info = Py_BuildValue( + "(Oiii)", py_is_up, duplex, speed, ifr.lifr_mtu + ); if (!py_ifc_info) goto error; if (PyDict_SetItemString(py_retdict, ksp->ks_name, py_ifc_info)) @@ -241,7 +242,7 @@ error: close(sock); if (kc != NULL) kstat_close(kc); - PyErr_SetFromErrno(PyExc_OSError); + psutil_oserror(); return NULL; } @@ -262,10 +263,10 @@ psutil_net_connections(PyObject *self, PyObject *args) { long pid; int sd = 0; mib2_tcpConnEntry_t tp; - mib2_udpEntry_t ude; + mib2_udpEntry_t ude; #if defined(AF_INET6) mib2_tcp6ConnEntry_t tp6; - mib2_udp6Entry_t ude6; + mib2_udp6Entry_t ude6; #endif char buf[512]; int i, flags, getcode, num_ent, state, ret; @@ -276,8 +277,8 @@ psutil_net_connections(PyObject *self, PyObject *args) { struct strbuf ctlbuf, databuf; struct T_optmgmt_req tor = {0}; struct T_optmgmt_ack toa = {0}; - struct T_error_ack tea = {0}; - struct opthdr mibhdr = {0}; + struct T_error_ack tea = {0}; + struct opthdr mibhdr = {0}; PyObject *py_retlist = PyList_New(0); PyObject *py_tuple = NULL; @@ -286,7 +287,7 @@ psutil_net_connections(PyObject *self, PyObject *args) { if (py_retlist == NULL) return NULL; - if (! PyArg_ParseTuple(args, "l", &pid)) + if (!PyArg_ParseTuple(args, "l", &pid)) goto error; sd = open("/dev/arp", O_RDWR); @@ -297,12 +298,12 @@ psutil_net_connections(PyObject *self, PyObject *args) { ret = ioctl(sd, I_PUSH, "tcp"); if (ret == -1) { - PyErr_SetFromErrno(PyExc_OSError); + psutil_oserror(); goto error; } ret = ioctl(sd, I_PUSH, "udp"); if (ret == -1) { - PyErr_SetFromErrno(PyExc_OSError); + psutil_oserror(); goto error; } // @@ -311,13 +312,13 @@ psutil_net_connections(PyObject *self, PyObject *args) { // function. Also see: // http://stackoverflow.com/questions/8723598/ tor.PRIM_type = T_SVR4_OPTMGMT_REQ; - tor.OPT_offset = sizeof (struct T_optmgmt_req); - tor.OPT_length = sizeof (struct opthdr); + tor.OPT_offset = sizeof(struct T_optmgmt_req); + tor.OPT_length = sizeof(struct opthdr); tor.MGMT_flags = T_CURRENT; mibhdr.level = MIB2_IP; - mibhdr.name = 0; + mibhdr.name = 0; - mibhdr.len = 1; + mibhdr.len = 1; memcpy(buf, &tor, sizeof tor); memcpy(buf + tor.OPT_offset, &mibhdr, sizeof mibhdr); @@ -326,36 +327,33 @@ psutil_net_connections(PyObject *self, PyObject *args) { flags = 0; // request to be sent in non-priority if (putmsg(sd, &ctlbuf, (struct strbuf *)0, flags) == -1) { - PyErr_SetFromErrno(PyExc_OSError); + psutil_oserror(); goto error; } - ctlbuf.maxlen = sizeof (buf); + ctlbuf.maxlen = sizeof(buf); for (;;) { flags = 0; getcode = getmsg(sd, &ctlbuf, (struct strbuf *)0, &flags); memcpy(&toa, buf, sizeof toa); memcpy(&tea, buf, sizeof tea); - if (getcode != MOREDATA || - ctlbuf.len < (int)sizeof (struct T_optmgmt_ack) || - toa.PRIM_type != T_OPTMGMT_ACK || - toa.MGMT_flags != T_SUCCESS) + if (getcode != MOREDATA + || ctlbuf.len < (int)sizeof(struct T_optmgmt_ack) + || toa.PRIM_type != T_OPTMGMT_ACK || toa.MGMT_flags != T_SUCCESS) { break; } - if (ctlbuf.len >= (int)sizeof (struct T_error_ack) && - tea.PRIM_type == T_ERROR_ACK) + if (ctlbuf.len >= (int)sizeof(struct T_error_ack) + && tea.PRIM_type == T_ERROR_ACK) { - PyErr_SetString(PyExc_RuntimeError, "ERROR_ACK"); + psutil_runtime_error("ERROR_ACK"); goto error; } - if (getcode == 0 && - ctlbuf.len >= (int)sizeof (struct T_optmgmt_ack) && - toa.PRIM_type == T_OPTMGMT_ACK && - toa.MGMT_flags == T_SUCCESS) + if (getcode == 0 && ctlbuf.len >= (int)sizeof(struct T_optmgmt_ack) + && toa.PRIM_type == T_OPTMGMT_ACK && toa.MGMT_flags == T_SUCCESS) { - PyErr_SetString(PyExc_RuntimeError, "ERROR_T_OPTMGMT_ACK"); + psutil_runtime_error("ERROR_T_OPTMGMT_ACK"); goto error; } @@ -374,7 +372,7 @@ psutil_net_connections(PyObject *self, PyObject *args) { flags = 0; getcode = getmsg(sd, (struct strbuf *)0, &databuf, &flags); if (getcode < 0) { - PyErr_SetFromErrno(PyExc_OSError); + psutil_oserror(); goto error; } @@ -406,9 +404,16 @@ psutil_net_connections(PyObject *self, PyObject *args) { state = tp.tcpConnEntryInfo.ce_state; // add item - py_tuple = Py_BuildValue("(iiiNNiI)", -1, AF_INET, SOCK_STREAM, - py_laddr, py_raddr, state, - processed_pid); + py_tuple = Py_BuildValue( + "(iiiNNiI)", + -1, + AF_INET, + SOCK_STREAM, + py_laddr, + py_raddr, + state, + processed_pid + ); if (!py_tuple) goto error; if (PyList_Append(py_retlist, py_tuple)) @@ -418,8 +423,7 @@ psutil_net_connections(PyObject *self, PyObject *args) { } #if defined(AF_INET6) // TCPv6 - else if (mibhdr.level == MIB2_TCP6 && mibhdr.name == MIB2_TCP6_CONN) - { + else if (mibhdr.level == MIB2_TCP6 && mibhdr.name == MIB2_TCP6_CONN) { num_ent = mibhdr.len / sizeof(mib2_tcp6ConnEntry_t); for (i = 0; i < num_ent; i++) { @@ -428,7 +432,9 @@ psutil_net_connections(PyObject *self, PyObject *args) { if (pid != -1 && processed_pid != pid) continue; // construct local/remote addresses - inet_ntop(AF_INET6, &tp6.tcp6ConnLocalAddress, lip, sizeof(lip)); + inet_ntop( + AF_INET6, &tp6.tcp6ConnLocalAddress, lip, sizeof(lip) + ); inet_ntop(AF_INET6, &tp6.tcp6ConnRemAddress, rip, sizeof(rip)); lport = tp6.tcp6ConnLocalPort; rport = tp6.tcp6ConnRemPort; @@ -446,8 +452,16 @@ psutil_net_connections(PyObject *self, PyObject *args) { state = tp6.tcp6ConnEntryInfo.ce_state; // add item - py_tuple = Py_BuildValue("(iiiNNiI)", -1, AF_INET6, SOCK_STREAM, - py_laddr, py_raddr, state, processed_pid); + py_tuple = Py_BuildValue( + "(iiiNNiI)", + -1, + AF_INET6, + SOCK_STREAM, + py_laddr, + py_raddr, + state, + processed_pid + ); if (!py_tuple) goto error; if (PyList_Append(py_retlist, py_tuple)) @@ -480,9 +494,16 @@ psutil_net_connections(PyObject *self, PyObject *args) { py_raddr = Py_BuildValue("()"); if (!py_raddr) goto error; - py_tuple = Py_BuildValue("(iiiNNiI)", -1, AF_INET, SOCK_DGRAM, - py_laddr, py_raddr, PSUTIL_CONN_NONE, - processed_pid); + py_tuple = Py_BuildValue( + "(iiiNNiI)", + -1, + AF_INET, + SOCK_DGRAM, + py_laddr, + py_raddr, + PSUTIL_CONN_NONE, + processed_pid + ); if (!py_tuple) goto error; if (PyList_Append(py_retlist, py_tuple)) @@ -492,9 +513,8 @@ psutil_net_connections(PyObject *self, PyObject *args) { } #if defined(AF_INET6) // UDPv6 - else if (mibhdr.level == MIB2_UDP6 || - mibhdr.level == MIB2_UDP6_ENTRY) - { + else if (mibhdr.level == MIB2_UDP6 || mibhdr.level == MIB2_UDP6_ENTRY) + { num_ent = mibhdr.len / sizeof(mib2_udp6Entry_t); for (i = 0; i < num_ent; i++) { memcpy(&ude6, databuf.buf + i * sizeof ude6, sizeof ude6); @@ -509,9 +529,16 @@ psutil_net_connections(PyObject *self, PyObject *args) { py_raddr = Py_BuildValue("()"); if (!py_raddr) goto error; - py_tuple = Py_BuildValue("(iiiNNiI)", -1, AF_INET6, SOCK_DGRAM, - py_laddr, py_raddr, PSUTIL_CONN_NONE, - processed_pid); + py_tuple = Py_BuildValue( + "(iiiNNiI)", + -1, + AF_INET6, + SOCK_DGRAM, + py_laddr, + py_raddr, + PSUTIL_CONN_NONE, + processed_pid + ); if (!py_tuple) goto error; if (PyList_Append(py_retlist, py_tuple)) diff --git a/contrib/python/psutil/py3/psutil/arch/sunos/proc.c b/contrib/python/psutil/py3/psutil/arch/sunos/proc.c index f892353f0b2..c1867021814 100644 --- a/contrib/python/psutil/py3/psutil/arch/sunos/proc.c +++ b/contrib/python/psutil/py3/psutil/arch/sunos/proc.c @@ -11,8 +11,6 @@ #include "../../arch/all/init.h" -#define PSUTIL_TV2DOUBLE(t) (((t).tv_nsec * 0.000000001) + (t).tv_sec) - // Read a file content and fills a C structure with it. static int @@ -27,13 +25,12 @@ psutil_file_to_struct(char *path, void *fstruct, size_t size) { nbytes = read(fd, fstruct, size); if (nbytes == -1) { close(fd); - PyErr_SetFromErrno(PyExc_OSError); + psutil_oserror(); return 0; } - if (nbytes != (ssize_t) size) { + if (nbytes != (ssize_t)size) { close(fd); - PyErr_SetString( - PyExc_RuntimeError, "read() file structure size mismatch"); + psutil_runtime_error("read() file structure size mismatch"); return 0; } close(fd); @@ -52,27 +49,27 @@ psutil_proc_basic_info(PyObject *self, PyObject *args) { psinfo_t info; const char *procfs_path; - if (! PyArg_ParseTuple(args, "is", &pid, &procfs_path)) + if (!PyArg_ParseTuple(args, "is", &pid, &procfs_path)) return NULL; - sprintf(path, "%s/%i/psinfo", procfs_path, pid); - if (! psutil_file_to_struct(path, (void *)&info, sizeof(info))) + str_format(path, sizeof(path), "%s/%i/psinfo", procfs_path, pid); + if (!psutil_file_to_struct(path, (void *)&info, sizeof(info))) return NULL; return Py_BuildValue( "ikkdiiikiiii", - info.pr_ppid, // parent pid - info.pr_rssize, // rss - info.pr_size, // vms + info.pr_ppid, // parent pid + info.pr_rssize, // rss + info.pr_size, // vms PSUTIL_TV2DOUBLE(info.pr_start), // create time - info.pr_lwp.pr_nice, // nice - info.pr_nlwp, // no. of threads - info.pr_lwp.pr_state, // status code - info.pr_ttydev, // tty nr - (int)info.pr_uid, // real user id - (int)info.pr_euid, // effective user id - (int)info.pr_gid, // real group id - (int)info.pr_egid // effective group id - ); + info.pr_lwp.pr_nice, // nice + info.pr_nlwp, // no. of threads + info.pr_lwp.pr_state, // status code + info.pr_ttydev, // tty nr + (int)info.pr_uid, // real user id + (int)info.pr_euid, // effective user id + (int)info.pr_gid, // real group id + (int)info.pr_egid // effective group id + ); } @@ -95,18 +92,19 @@ psutil_proc_name_and_args(PyObject *self, PyObject *args) { PyObject *py_args_list = NULL; PyObject *py_rettuple = NULL; - if (! PyArg_ParseTuple(args, "is", &pid, &procfs_path)) + if (!PyArg_ParseTuple(args, "is", &pid, &procfs_path)) return NULL; - sprintf(path, "%s/%i/psinfo", procfs_path, pid); - if (! psutil_file_to_struct(path, (void *)&info, sizeof(info))) + str_format(path, sizeof(path), "%s/%i/psinfo", procfs_path, pid); + if (!psutil_file_to_struct(path, (void *)&info, sizeof(info))) return NULL; py_name = PyUnicode_DecodeFSDefault(info.pr_fname); if (!py_name) goto error; - /* SunOS truncates arguments to length PRARGSZ and has them space-separated. - * The only way to retrieve full properly-split command line is to parse process memory */ + // SunOS truncates arguments to length PRARGSZ and has them + // space-separated. The only way to retrieve full properly-split + // command line is to parse process memory. argv = psutil_read_raw_args(info, procfs_path, &argc); if (argv) { py_args_list = PyList_New(argc); @@ -189,41 +187,41 @@ psutil_proc_environ(PyObject *self, PyObject *args) { PyObject *py_envval = NULL; PyObject *py_retdict = PyDict_New(); - if (! py_retdict) + if (!py_retdict) return PyErr_NoMemory(); - if (! PyArg_ParseTuple(args, "is", &pid, &procfs_path)) + if (!PyArg_ParseTuple(args, "is", &pid, &procfs_path)) return NULL; - sprintf(path, "%s/%i/psinfo", procfs_path, pid); - if (! psutil_file_to_struct(path, (void *)&info, sizeof(info))) + str_format(path, sizeof(path), "%s/%i/psinfo", procfs_path, pid); + if (!psutil_file_to_struct(path, (void *)&info, sizeof(info))) goto error; - if (! info.pr_envp) { - AccessDenied("/proc/pid/psinfo struct not set"); + if (!info.pr_envp) { + psutil_oserror_ad("/proc/pid/psinfo struct not set"); goto error; } env = psutil_read_raw_env(info, procfs_path, &env_count); - if (! env && env_count != 0) + if (!env && env_count != 0) goto error; - for (i=0; i<env_count; i++) { - if (! env[i]) + for (i = 0; i < env_count; i++) { + if (!env[i]) break; dm = strchr(env[i], '='); - if (! dm) + if (!dm) continue; *dm = '\0'; py_envname = PyUnicode_DecodeFSDefault(env[i]); - if (! py_envname) + if (!py_envname) goto error; - py_envval = PyUnicode_DecodeFSDefault(dm+1); - if (! py_envname) + py_envval = PyUnicode_DecodeFSDefault(dm + 1); + if (!py_envname) goto error; if (PyDict_SetItem(py_retdict, py_envname, py_envval) < 0) @@ -236,7 +234,7 @@ psutil_proc_environ(PyObject *self, PyObject *args) { psutil_free_cstrings_array(env, env_count); return py_retdict; - error: +error: if (env && env_count >= 0) psutil_free_cstrings_array(env, env_count); @@ -257,18 +255,18 @@ psutil_proc_cpu_times(PyObject *self, PyObject *args) { pstatus_t info; const char *procfs_path; - if (! PyArg_ParseTuple(args, "is", &pid, &procfs_path)) + if (!PyArg_ParseTuple(args, "is", &pid, &procfs_path)) return NULL; - sprintf(path, "%s/%i/status", procfs_path, pid); - if (! psutil_file_to_struct(path, (void *)&info, sizeof(info))) + str_format(path, sizeof(path), "%s/%i/status", procfs_path, pid); + if (!psutil_file_to_struct(path, (void *)&info, sizeof(info))) return NULL; // results are more precise than os.times() return Py_BuildValue( "(dddd)", - PSUTIL_TV2DOUBLE(info.pr_utime), - PSUTIL_TV2DOUBLE(info.pr_stime), - PSUTIL_TV2DOUBLE(info.pr_cutime), - PSUTIL_TV2DOUBLE(info.pr_cstime) + PSUTIL_TV2DOUBLE(info.pr_utime), + PSUTIL_TV2DOUBLE(info.pr_stime), + PSUTIL_TV2DOUBLE(info.pr_cutime), + PSUTIL_TV2DOUBLE(info.pr_cstime) ); } @@ -289,10 +287,10 @@ psutil_proc_cpu_num(PyObject *self, PyObject *args) { ssize_t nbytes; const char *procfs_path; - if (! PyArg_ParseTuple(args, "is", &pid, &procfs_path)) + if (!PyArg_ParseTuple(args, "is", &pid, &procfs_path)) return NULL; - sprintf(path, "%s/%i/lpsinfo", procfs_path, pid); + str_format(path, sizeof(path), "%s/%i/lpsinfo", procfs_path, pid); fd = open(path, O_RDONLY); if (fd == -1) { PyErr_SetFromErrnoWithFilename(PyExc_OSError, path); @@ -302,12 +300,11 @@ psutil_proc_cpu_num(PyObject *self, PyObject *args) { // read header nbytes = pread(fd, &header, sizeof(header), 0); if (nbytes == -1) { - PyErr_SetFromErrno(PyExc_OSError); + psutil_oserror(); goto error; } if (nbytes != sizeof(header)) { - PyErr_SetString( - PyExc_RuntimeError, "read() file structure size mismatch"); + psutil_runtime_error("read() file structure size mismatch"); goto error; } @@ -323,12 +320,11 @@ psutil_proc_cpu_num(PyObject *self, PyObject *args) { // read the rest nbytes = pread(fd, lwp, size, sizeof(header)); if (nbytes == -1) { - PyErr_SetFromErrno(PyExc_OSError); + psutil_oserror(); goto error; } if (nbytes != size) { - PyErr_SetString( - PyExc_RuntimeError, "read() file structure size mismatch"); + psutil_runtime_error("read() file structure size mismatch"); goto error; } @@ -356,14 +352,20 @@ psutil_proc_cred(PyObject *self, PyObject *args) { prcred_t info; const char *procfs_path; - if (! PyArg_ParseTuple(args, "is", &pid, &procfs_path)) + if (!PyArg_ParseTuple(args, "is", &pid, &procfs_path)) return NULL; - sprintf(path, "%s/%i/cred", procfs_path, pid); - if (! psutil_file_to_struct(path, (void *)&info, sizeof(info))) + str_format(path, sizeof(path), "%s/%i/cred", procfs_path, pid); + if (!psutil_file_to_struct(path, (void *)&info, sizeof(info))) return NULL; - return Py_BuildValue("iiiiii", - info.pr_ruid, info.pr_euid, info.pr_suid, - info.pr_rgid, info.pr_egid, info.pr_sgid); + return Py_BuildValue( + "iiiiii", + info.pr_ruid, + info.pr_euid, + info.pr_suid, + info.pr_rgid, + info.pr_egid, + info.pr_sgid + ); } @@ -377,10 +379,10 @@ psutil_proc_num_ctx_switches(PyObject *self, PyObject *args) { prusage_t info; const char *procfs_path; - if (! PyArg_ParseTuple(args, "is", &pid, &procfs_path)) + if (!PyArg_ParseTuple(args, "is", &pid, &procfs_path)) return NULL; - sprintf(path, "%s/%i/usage", procfs_path, pid); - if (! psutil_file_to_struct(path, (void *)&info, sizeof(info))) + str_format(path, sizeof(path), "%s/%i/usage", procfs_path, pid); + if (!psutil_file_to_struct(path, (void *)&info, sizeof(info))) return NULL; return Py_BuildValue("kk", info.pr_vctx, info.pr_ictx); } @@ -406,7 +408,7 @@ proc_io_counters(PyObject* self, PyObject* args) { if (! PyArg_ParseTuple(args, "is", &pid, &procfs_path)) return NULL; - sprintf(path, "%s/%i/usage", procfs_path, pid); + str_format(path, sizeof(path), "%s/%i/usage", procfs_path, pid); if (! psutil_file_to_struct(path, (void *)&info, sizeof(info))) return NULL; @@ -434,14 +436,16 @@ psutil_proc_query_thread(PyObject *self, PyObject *args) { lwpstatus_t info; const char *procfs_path; - if (! PyArg_ParseTuple(args, "iis", &pid, &tid, &procfs_path)) + if (!PyArg_ParseTuple(args, "iis", &pid, &tid, &procfs_path)) return NULL; - sprintf(path, "%s/%i/lwp/%i/lwpstatus", procfs_path, pid, tid); - if (! psutil_file_to_struct(path, (void *)&info, sizeof(info))) + str_format( + path, sizeof(path), "%s/%i/lwp/%i/lwpstatus", procfs_path, pid, tid + ); + if (!psutil_file_to_struct(path, (void *)&info, sizeof(info))) return NULL; - return Py_BuildValue("dd", - PSUTIL_TV2DOUBLE(info.pr_utime), - PSUTIL_TV2DOUBLE(info.pr_stime)); + return Py_BuildValue( + "dd", PSUTIL_TV2DOUBLE(info.pr_utime), PSUTIL_TV2DOUBLE(info.pr_stime) + ); } @@ -472,16 +476,16 @@ psutil_proc_memory_maps(PyObject *self, PyObject *args) { if (py_retlist == NULL) return NULL; - if (! PyArg_ParseTuple(args, "is", &pid, &procfs_path)) + if (!PyArg_ParseTuple(args, "is", &pid, &procfs_path)) goto error; - sprintf(path, "%s/%i/status", procfs_path, pid); - if (! psutil_file_to_struct(path, (void *)&status, sizeof(status))) + str_format(path, sizeof(path), "%s/%i/status", procfs_path, pid); + if (!psutil_file_to_struct(path, (void *)&status, sizeof(status))) goto error; - sprintf(path, "%s/%i/xmap", procfs_path, pid); + str_format(path, sizeof(path), "%s/%i/xmap", procfs_path, pid); if (stat(path, &st) == -1) { - PyErr_SetFromErrno(PyExc_OSError); + psutil_oserror(); goto error; } @@ -489,7 +493,7 @@ psutil_proc_memory_maps(PyObject *self, PyObject *args) { fd = open(path, O_RDONLY); if (fd == -1) { - PyErr_SetFromErrno(PyExc_OSError); + psutil_oserror(); goto error; } @@ -514,10 +518,15 @@ psutil_proc_memory_maps(PyObject *self, PyObject *args) { pr_addr_sz = p->pr_vaddr + p->pr_size; // perms - sprintf(perms, "%c%c%c%c", p->pr_mflags & MA_READ ? 'r' : '-', - p->pr_mflags & MA_WRITE ? 'w' : '-', - p->pr_mflags & MA_EXEC ? 'x' : '-', - p->pr_mflags & MA_SHARED ? 's' : '-'); + str_format( + perms, + sizeof(perms), + "%c%c%c%c", + p->pr_mflags & MA_READ ? 'r' : '-', + p->pr_mflags & MA_WRITE ? 'w' : '-', + p->pr_mflags & MA_EXEC ? 'x' : '-', + p->pr_mflags & MA_SHARED ? 's' : '-' + ); // name if (strlen(p->pr_mapname) > 0) { @@ -531,13 +540,15 @@ psutil_proc_memory_maps(PyObject *self, PyObject *args) { stk_base_sz = status.pr_stkbase + status.pr_stksize; brk_base_sz = status.pr_brkbase + status.pr_brksize; - if ((pr_addr_sz > status.pr_stkbase) && - (p->pr_vaddr < stk_base_sz)) { + if ((pr_addr_sz > status.pr_stkbase) + && (p->pr_vaddr < stk_base_sz)) + { name = "[stack]"; } - else if ((p->pr_mflags & MA_ANON) && \ - (pr_addr_sz > status.pr_brkbase) && \ - (p->pr_vaddr < brk_base_sz)) { + else if ((p->pr_mflags & MA_ANON) + && (pr_addr_sz > status.pr_brkbase) + && (p->pr_vaddr < brk_base_sz)) + { name = "[heap]"; } else { @@ -547,7 +558,7 @@ psutil_proc_memory_maps(PyObject *self, PyObject *args) { } py_path = PyUnicode_DecodeFSDefault(name); - if (! py_path) + if (!py_path) goto error; py_tuple = Py_BuildValue( "kksOkkk", @@ -557,7 +568,8 @@ psutil_proc_memory_maps(PyObject *self, PyObject *args) { py_path, (unsigned long)p->pr_rss * p->pr_pagesize, (unsigned long)p->pr_anon * p->pr_pagesize, - (unsigned long)p->pr_locked * p->pr_pagesize); + (unsigned long)p->pr_locked * p->pr_pagesize + ); if (!py_tuple) goto error; if (PyList_Append(py_retlist, py_tuple)) diff --git a/contrib/python/psutil/py3/psutil/arch/sunos/sys.c b/contrib/python/psutil/py3/psutil/arch/sunos/sys.c index d9f3ae4bfbf..e0d147debd2 100644 --- a/contrib/python/psutil/py3/psutil/arch/sunos/sys.c +++ b/contrib/python/psutil/py3/psutil/arch/sunos/sys.c @@ -28,7 +28,7 @@ psutil_boot_time(PyObject *self, PyObject *args) { UTXENT_MUTEX_UNLOCK(); if (fabs(boot_time) < 0.000001) { /* could not find BOOT_TIME in getutxent loop */ - PyErr_SetString(PyExc_RuntimeError, "can't determine boot time"); + psutil_runtime_error("can't determine boot time"); return NULL; } return Py_BuildValue("f", boot_time); diff --git a/contrib/python/psutil/py3/psutil/arch/windows/cpu.c b/contrib/python/psutil/py3/psutil/arch/windows/cpu.c index 6d70ab37cc8..c4a5f7f531d 100644 --- a/contrib/python/psutil/py3/psutil/arch/windows/cpu.c +++ b/contrib/python/psutil/py3/psutil/arch/windows/cpu.c @@ -23,17 +23,17 @@ psutil_get_num_cpus(int fail_on_err) { if (GetActiveProcessorCount != NULL) { ncpus = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS); if ((ncpus == 0) && (fail_on_err == 1)) { - PyErr_SetFromWindowsErr(0); + psutil_oserror(); } } else { - psutil_debug("GetActiveProcessorCount() not available; " - "using GetSystemInfo()"); + psutil_debug( + "GetActiveProcessorCount() not available; " + "using GetSystemInfo()" + ); ncpus = (unsigned int)PSUTIL_SYSTEM_INFO.dwNumberOfProcessors; if ((ncpus <= 0) && (fail_on_err == 1)) { - PyErr_SetString( - PyExc_RuntimeError, - "GetSystemInfo() failed to retrieve CPU count"); + psutil_runtime_error("GetSystemInfo failed to retrieve CPU count"); } } return ncpus; @@ -51,16 +51,16 @@ psutil_cpu_times(PyObject *self, PyObject *args) { FILETIME idle_time, kernel_time, user_time; if (!GetSystemTimes(&idle_time, &kernel_time, &user_time)) { - PyErr_SetFromWindowsErr(0); + psutil_oserror(); return NULL; } - idle = (double)((HI_T * idle_time.dwHighDateTime) + \ - (LO_T * idle_time.dwLowDateTime)); - user = (double)((HI_T * user_time.dwHighDateTime) + \ - (LO_T * user_time.dwLowDateTime)); - kernel = (double)((HI_T * kernel_time.dwHighDateTime) + \ - (LO_T * kernel_time.dwLowDateTime)); + idle = (double)((HI_T * idle_time.dwHighDateTime) + + (LO_T * idle_time.dwLowDateTime)); + user = (double)((HI_T * user_time.dwHighDateTime) + + (LO_T * user_time.dwLowDateTime)); + kernel = (double)((HI_T * kernel_time.dwHighDateTime) + + (LO_T * kernel_time.dwLowDateTime)); // Kernel time includes idle time. // We return only busy kernel time subtracting idle time from @@ -93,8 +93,9 @@ psutil_per_cpu_times(PyObject *self, PyObject *args) { // allocates an array of _SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION // structures, one per processor - sppi = (_SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION *) \ - malloc(ncpus * sizeof(_SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION)); + sppi = (_SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION *)malloc( + ncpus * sizeof(_SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION) + ); if (sppi == NULL) { PyErr_NoMemory(); goto error; @@ -105,8 +106,9 @@ psutil_per_cpu_times(PyObject *self, PyObject *args) { SystemProcessorPerformanceInformation, sppi, ncpus * sizeof(_SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION), - NULL); - if (! NT_SUCCESS(status)) { + NULL + ); + if (!NT_SUCCESS(status)) { psutil_SetFromNTStatusErr( status, "NtQuerySystemInformation(SystemProcessorPerformanceInformation)" @@ -119,28 +121,23 @@ psutil_per_cpu_times(PyObject *self, PyObject *args) { idle = user = kernel = interrupt = dpc = 0; for (i = 0; i < ncpus; i++) { py_tuple = NULL; - user = (double)((HI_T * sppi[i].UserTime.HighPart) + - (LO_T * sppi[i].UserTime.LowPart)); - idle = (double)((HI_T * sppi[i].IdleTime.HighPart) + - (LO_T * sppi[i].IdleTime.LowPart)); - kernel = (double)((HI_T * sppi[i].KernelTime.HighPart) + - (LO_T * sppi[i].KernelTime.LowPart)); - interrupt = (double)((HI_T * sppi[i].InterruptTime.HighPart) + - (LO_T * sppi[i].InterruptTime.LowPart)); - dpc = (double)((HI_T * sppi[i].DpcTime.HighPart) + - (LO_T * sppi[i].DpcTime.LowPart)); + user = (double)((HI_T * sppi[i].UserTime.HighPart) + + (LO_T * sppi[i].UserTime.LowPart)); + idle = (double)((HI_T * sppi[i].IdleTime.HighPart) + + (LO_T * sppi[i].IdleTime.LowPart)); + kernel = (double)((HI_T * sppi[i].KernelTime.HighPart) + + (LO_T * sppi[i].KernelTime.LowPart)); + interrupt = (double)((HI_T * sppi[i].InterruptTime.HighPart) + + (LO_T * sppi[i].InterruptTime.LowPart)); + dpc = (double)((HI_T * sppi[i].DpcTime.HighPart) + + (LO_T * sppi[i].DpcTime.LowPart)); // kernel time includes idle time on windows // we return only busy kernel time subtracting // idle time from kernel time systemt = kernel - idle; py_tuple = Py_BuildValue( - "(ddddd)", - user, - systemt, - idle, - interrupt, - dpc + "(ddddd)", user, systemt, idle, interrupt, dpc ); if (!py_tuple) goto error; @@ -200,23 +197,24 @@ psutil_cpu_count_cores(PyObject *self, PyObject *args) { } while (1) { - rc = GetLogicalProcessorInformationEx( - RelationAll, buffer, &length); + rc = GetLogicalProcessorInformationEx(RelationAll, buffer, &length); if (rc == FALSE) { if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) { if (buffer) { free(buffer); } - buffer = \ - (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX)malloc(length); + buffer = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX + )malloc(length); if (NULL == buffer) { PyErr_NoMemory(); return NULL; } } else { - psutil_debug("GetLogicalProcessorInformationEx() returned %u", - GetLastError()); + psutil_debug( + "GetLogicalProcessorInformationEx() returned %u", + GetLastError() + ); goto return_none; } } @@ -229,8 +227,8 @@ psutil_cpu_count_cores(PyObject *self, PyObject *args) { while (offset < length) { // Advance ptr by the size of the previous // SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX struct. - ptr = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*) \ - (((char*)ptr) + prev_processor_info_size); + ptr = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX + *)(((char *)ptr) + prev_processor_info_size); if (ptr->Relationship == RelationProcessorCore) { ncpus += 1; @@ -278,8 +276,9 @@ psutil_cpu_stats(PyObject *self, PyObject *args) { goto error; // get syscalls / ctx switches - spi = (_SYSTEM_PERFORMANCE_INFORMATION *) \ - malloc(ncpus * sizeof(_SYSTEM_PERFORMANCE_INFORMATION)); + spi = (_SYSTEM_PERFORMANCE_INFORMATION *)malloc( + ncpus * sizeof(_SYSTEM_PERFORMANCE_INFORMATION) + ); if (spi == NULL) { PyErr_NoMemory(); goto error; @@ -288,16 +287,19 @@ psutil_cpu_stats(PyObject *self, PyObject *args) { SystemPerformanceInformation, spi, ncpus * sizeof(_SYSTEM_PERFORMANCE_INFORMATION), - NULL); - if (! NT_SUCCESS(status)) { + NULL + ); + if (!NT_SUCCESS(status)) { psutil_SetFromNTStatusErr( - status, "NtQuerySystemInformation(SystemPerformanceInformation)"); + status, "NtQuerySystemInformation(SystemPerformanceInformation)" + ); goto error; } // get DPCs - InterruptInformation = \ - malloc(sizeof(_SYSTEM_INTERRUPT_INFORMATION) * ncpus); + InterruptInformation = malloc( + sizeof(_SYSTEM_INTERRUPT_INFORMATION) * ncpus + ); if (InterruptInformation == NULL) { PyErr_NoMemory(); goto error; @@ -307,10 +309,12 @@ psutil_cpu_stats(PyObject *self, PyObject *args) { SystemInterruptInformation, InterruptInformation, ncpus * sizeof(SYSTEM_INTERRUPT_INFORMATION), - NULL); - if (! NT_SUCCESS(status)) { + NULL + ); + if (!NT_SUCCESS(status)) { psutil_SetFromNTStatusErr( - status, "NtQuerySystemInformation(SystemInterruptInformation)"); + status, "NtQuerySystemInformation(SystemInterruptInformation)" + ); goto error; } for (i = 0; i < ncpus; i++) { @@ -318,8 +322,9 @@ psutil_cpu_stats(PyObject *self, PyObject *args) { } // get interrupts - sppi = (_SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION *) \ - malloc(ncpus * sizeof(_SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION)); + sppi = (_SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION *)malloc( + ncpus * sizeof(_SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION) + ); if (sppi == NULL) { PyErr_NoMemory(); goto error; @@ -329,11 +334,13 @@ psutil_cpu_stats(PyObject *self, PyObject *args) { SystemProcessorPerformanceInformation, sppi, ncpus * sizeof(_SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION), - NULL); - if (! NT_SUCCESS(status)) { + NULL + ); + if (!NT_SUCCESS(status)) { psutil_SetFromNTStatusErr( status, - "NtQuerySystemInformation(SystemProcessorPerformanceInformation)"); + "NtQuerySystemInformation(SystemProcessorPerformanceInformation)" + ); goto error; } @@ -384,18 +391,16 @@ psutil_cpu_freq(PyObject *self, PyObject *args) { // Allocate size. size = ncpus * sizeof(PROCESSOR_POWER_INFORMATION); - pBuffer = (BYTE*)LocalAlloc(LPTR, size); - if (! pBuffer) { - PyErr_SetFromWindowsErr(0); + pBuffer = (BYTE *)LocalAlloc(LPTR, size); + if (!pBuffer) { + psutil_oserror(); return NULL; } // Syscall. - ret = CallNtPowerInformation( - ProcessorInformation, NULL, 0, pBuffer, size); + ret = CallNtPowerInformation(ProcessorInformation, NULL, 0, pBuffer, size); if (ret != 0) { - PyErr_SetString(PyExc_RuntimeError, - "CallNtPowerInformation syscall failed"); + psutil_runtime_error("CallNtPowerInformation syscall failed"); goto error; } diff --git a/contrib/python/psutil/py3/psutil/arch/windows/disk.c b/contrib/python/psutil/py3/psutil/arch/windows/disk.c index 625a975f917..844e6bcd034 100644 --- a/contrib/python/psutil/py3/psutil/arch/windows/disk.c +++ b/contrib/python/psutil/py3/psutil/arch/windows/disk.c @@ -13,10 +13,11 @@ #ifndef _ARRAYSIZE -#define _ARRAYSIZE(a) (sizeof(a)/sizeof(a[0])) +#define _ARRAYSIZE(a) (sizeof(a) / sizeof(a[0])) #endif -static char *psutil_get_drive_type(int type) { +static char * +psutil_get_drive_type(int type) { switch (type) { case DRIVE_FIXED: return "fixed"; @@ -38,15 +39,14 @@ static char *psutil_get_drive_type(int type) { } -/* - * Return path's disk total and free as a Python tuple. - */ +// Return path's disk total, used, and free space. PyObject * psutil_disk_usage(PyObject *self, PyObject *args) { - BOOL retval; - ULARGE_INTEGER _, total, free; PyObject *py_path; - wchar_t *path; + wchar_t *path = NULL; + ULARGE_INTEGER total, free, avail; + BOOL retval; + ULONGLONG used; if (!PyArg_ParseTuple(args, "U", &py_path)) { return NULL; @@ -58,15 +58,19 @@ psutil_disk_usage(PyObject *self, PyObject *args) { } Py_BEGIN_ALLOW_THREADS - retval = GetDiskFreeSpaceExW(path, &_, &total, &free); + retval = GetDiskFreeSpaceExW(path, &avail, &total, &free); Py_END_ALLOW_THREADS PyMem_Free(path); - if (retval == 0) - return PyErr_SetExcFromWindowsErrWithFilenameObject(PyExc_OSError, 0, py_path); + if (retval == 0) { + return PyErr_SetExcFromWindowsErrWithFilenameObject( + PyExc_OSError, 0, py_path + ); + } - return Py_BuildValue("(LL)", total.QuadPart, free.QuadPart); + used = total.QuadPart - free.QuadPart; + return Py_BuildValue("(KKK)", total.QuadPart, used, free.QuadPart); } @@ -96,9 +100,16 @@ psutil_disk_io_counters(PyObject *self, PyObject *args) { // in the alphabet (from A:\ to Z:\). for (devNum = 0; devNum <= 32; ++devNum) { py_tuple = NULL; - sprintf_s(szDevice, MAX_PATH, "\\\\.\\PhysicalDrive%d", devNum); - hDevice = CreateFile(szDevice, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, - NULL, OPEN_EXISTING, 0, NULL); + str_format(szDevice, MAX_PATH, "\\\\.\\PhysicalDrive%d", devNum); + hDevice = CreateFile( + szDevice, + 0, + FILE_SHARE_READ | FILE_SHARE_WRITE, + NULL, + OPEN_EXISTING, + 0, + NULL + ); if (hDevice == INVALID_HANDLE_VALUE) continue; @@ -108,8 +119,15 @@ psutil_disk_io_counters(PyObject *self, PyObject *args) { while (1) { i += 1; ret = DeviceIoControl( - hDevice, IOCTL_DISK_PERFORMANCE, NULL, 0, &diskPerformance, - ioctrlSize, &dwSize, NULL); + hDevice, + IOCTL_DISK_PERFORMANCE, + NULL, + 0, + &diskPerformance, + ioctrlSize, + &dwSize, + NULL + ); if (ret != 0) break; // OK! if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) { @@ -125,14 +143,20 @@ psutil_disk_io_counters(PyObject *self, PyObject *args) { // 1364/job/ascpdi271b06jle3 // Assume it means we're dealing with some exotic disk // and go on. - psutil_debug("DeviceIoControl -> ERROR_INVALID_FUNCTION; " - "ignore PhysicalDrive%i", devNum); + psutil_debug( + "DeviceIoControl -> ERROR_INVALID_FUNCTION; " + "ignore PhysicalDrive%i", + devNum + ); goto next; } else if (GetLastError() == ERROR_NOT_SUPPORTED) { // Again, let's assume we're dealing with some exotic disk. - psutil_debug("DeviceIoControl -> ERROR_NOT_SUPPORTED; " - "ignore PhysicalDrive%i", devNum); + psutil_debug( + "DeviceIoControl -> ERROR_NOT_SUPPORTED; " + "ignore PhysicalDrive%i", + devNum + ); goto next; } // XXX: it seems we should also catch ERROR_INVALID_PARAMETER: @@ -143,11 +167,11 @@ psutil_disk_io_counters(PyObject *self, PyObject *args) { // XXX: we can also bump into ERROR_MORE_DATA in which case // (quoting doc) we're supposed to retry with a bigger buffer // and specify a new "starting point", whatever it means. - PyErr_SetFromWindowsErr(0); + psutil_oserror(); goto error; } - sprintf_s(szDeviceDisplay, MAX_PATH, "PhysicalDrive%i", devNum); + str_format(szDeviceDisplay, MAX_PATH, "PhysicalDrive%i", devNum); py_tuple = Py_BuildValue( "(IILLKK)", diskPerformance.ReadCount, @@ -156,17 +180,16 @@ psutil_disk_io_counters(PyObject *self, PyObject *args) { diskPerformance.BytesWritten, // convert to ms: // https://github.com/giampaolo/psutil/issues/1012 - (unsigned long long) - (diskPerformance.ReadTime.QuadPart) / 10000000, - (unsigned long long) - (diskPerformance.WriteTime.QuadPart) / 10000000); + (unsigned long long)(diskPerformance.ReadTime.QuadPart) / 10000000, + (unsigned long long)(diskPerformance.WriteTime.QuadPart) / 10000000 + ); if (!py_tuple) goto error; if (PyDict_SetItemString(py_retdict, szDeviceDisplay, py_tuple)) goto error; Py_CLEAR(py_tuple); -next: + next: CloseHandle(hDevice); } @@ -198,8 +221,8 @@ psutil_disk_partitions(PyObject *self, PyObject *args) { unsigned int old_mode = 0; char opts[50]; HANDLE mp_h; - BOOL mp_flag= TRUE; - LPTSTR fs_type[MAX_PATH + 1] = { 0 }; + BOOL mp_flag = TRUE; + LPTSTR fs_type[MAX_PATH + 1] = {0}; DWORD pflags = 0; DWORD lpMaximumComponentLength = 0; // max file name PyObject *py_all; @@ -214,7 +237,7 @@ psutil_disk_partitions(PyObject *self, PyObject *args) { // see https://github.com/giampaolo/psutil/issues/264 old_mode = SetErrorMode(SEM_FAILCRITICALERRORS); - if (! PyArg_ParseTuple(args, "O", &py_all)) + if (!PyArg_ParseTuple(args, "O", &py_all)) goto error; all = PyObject_IsTrue(py_all); @@ -223,7 +246,7 @@ psutil_disk_partitions(PyObject *self, PyObject *args) { Py_END_ALLOW_THREADS if (num_bytes == 0) { - PyErr_SetFromWindowsErr(0); + psutil_oserror(); goto error; } @@ -238,16 +261,16 @@ psutil_disk_partitions(PyObject *self, PyObject *args) { // by default we only show hard drives and cd-roms if (all == 0) { - if ((type == DRIVE_UNKNOWN) || - (type == DRIVE_NO_ROOT_DIR) || - (type == DRIVE_REMOTE) || - (type == DRIVE_RAMDISK)) { + if ((type == DRIVE_UNKNOWN) || (type == DRIVE_NO_ROOT_DIR) + || (type == DRIVE_REMOTE) || (type == DRIVE_RAMDISK)) + { goto next; } // floppy disk: skip it by default as it introduces a // considerable slowdown. - if ((type == DRIVE_REMOVABLE) && - (strcmp(drive_letter, "A:\\") == 0)) { + if ((type == DRIVE_REMOVABLE) + && (strcmp(drive_letter, "A:\\") == 0)) + { goto next; } } @@ -260,47 +283,54 @@ psutil_disk_partitions(PyObject *self, PyObject *args) { &lpMaximumComponentLength, &pflags, (LPTSTR)fs_type, - _ARRAYSIZE(fs_type)); + _ARRAYSIZE(fs_type) + ); if (ret == 0) { // We might get here in case of a floppy hard drive, in // which case the error is (21, "device not ready"). // Let's pretend it didn't happen as we already have // the drive name and type ('removable'). - strcat_s(opts, _countof(opts), ""); + str_append(opts, sizeof(opts), ""); SetLastError(0); } else { if (pflags & FILE_READ_ONLY_VOLUME) - strcat_s(opts, _countof(opts), "ro"); + str_append(opts, sizeof(opts), "ro"); else - strcat_s(opts, _countof(opts), "rw"); + str_append(opts, sizeof(opts), "rw"); if (pflags & FILE_VOLUME_IS_COMPRESSED) - strcat_s(opts, _countof(opts), ",compressed"); + str_append(opts, sizeof(opts), ",compressed"); if (pflags & FILE_READ_ONLY_VOLUME) - strcat_s(opts, _countof(opts), ",readonly"); + str_append(opts, sizeof(opts), ",readonly"); // Check for mount points on this volume and add/get info // (checks first to know if we can even have mount points) if (pflags & FILE_SUPPORTS_REPARSE_POINTS) { mp_h = FindFirstVolumeMountPoint( - drive_letter, mp_buf, MAX_PATH); + drive_letter, mp_buf, MAX_PATH + ); if (mp_h != INVALID_HANDLE_VALUE) { mp_flag = TRUE; while (mp_flag) { // Append full mount path with drive letter - strcpy_s(mp_path, _countof(mp_path), drive_letter); - strcat_s(mp_path, _countof(mp_path), mp_buf); + str_copy( + mp_path, sizeof(mp_path), drive_letter + ); // initialize + str_append( + mp_path, sizeof(mp_path), mp_buf + ); // append mount point py_tuple = Py_BuildValue( "(ssss)", drive_letter, mp_path, - fs_type, // typically "NTFS" + fs_type, // typically "NTFS" opts ); - if (!py_tuple || - PyList_Append(py_retlist, py_tuple) == -1) { + if (!py_tuple + || PyList_Append(py_retlist, py_tuple) == -1) + { FindVolumeMountPointClose(mp_h); goto error; } @@ -309,17 +339,17 @@ psutil_disk_partitions(PyObject *self, PyObject *args) { // Continue looking for more mount points mp_flag = FindNextVolumeMountPoint( - mp_h, mp_buf, MAX_PATH); + mp_h, mp_buf, MAX_PATH + ); } FindVolumeMountPointClose(mp_h); } - } } if (strlen(opts) > 0) - strcat_s(opts, _countof(opts), ","); - strcat_s(opts, _countof(opts), psutil_get_drive_type(type)); + str_append(opts, sizeof(opts), ","); + str_append(opts, sizeof(opts), psutil_get_drive_type(type)); py_tuple = Py_BuildValue( "(ssss)", @@ -335,7 +365,7 @@ psutil_disk_partitions(PyObject *self, PyObject *args) { Py_CLEAR(py_tuple); goto next; -next: + next: drive_letter = strchr(drive_letter, 0) + 1; } diff --git a/contrib/python/psutil/py3/psutil/arch/windows/init.c b/contrib/python/psutil/py3/psutil/arch/windows/init.c index b410d5670f3..544b9110e09 100644 --- a/contrib/python/psutil/py3/psutil/arch/windows/init.c +++ b/contrib/python/psutil/py3/psutil/arch/windows/init.c @@ -13,8 +13,8 @@ // Needed to make these globally visible. int PSUTIL_WINVER; -SYSTEM_INFO PSUTIL_SYSTEM_INFO; -CRITICAL_SECTION PSUTIL_CRITICAL_SECTION; +SYSTEM_INFO PSUTIL_SYSTEM_INFO; +CRITICAL_SECTION PSUTIL_CRITICAL_SECTION; // ==================================================================== @@ -32,12 +32,14 @@ PyErr_SetFromWindowsErrWithFilename(int winerr, const char *filename) { if (winerr == 0) winerr = GetLastError(); if (filename == NULL) { - py_exc = PyObject_CallFunction(PyExc_OSError, "(is)", winerr, - strerror(winerr)); + py_exc = PyObject_CallFunction( + PyExc_OSError, "(is)", winerr, strerror(winerr) + ); } else { - py_exc = PyObject_CallFunction(PyExc_OSError, "(iss)", winerr, - strerror(winerr), filename); + py_exc = PyObject_CallFunction( + PyExc_OSError, "(iss)", winerr, strerror(winerr), filename + ); } if (py_exc == NULL) return NULL; @@ -62,13 +64,13 @@ error: #if !defined(PyErr_SetExcFromWindowsErrWithFilenameObject) PyObject * PyErr_SetExcFromWindowsErrWithFilenameObject( - PyObject *type, int ierr, PyObject *filename) -{ + PyObject *type, int ierr, PyObject *filename +) { // Original function is too complex. Just raise OSError without // filename. return PyErr_SetFromWindowsErrWithFilename(ierr, NULL); } -#endif // !defined(PyErr_SetExcFromWindowsErrWithFilenameObject) +#endif // !defined(PyErr_SetExcFromWindowsErrWithFilenameObject) #endif // defined(PYPY_VERSION) @@ -89,7 +91,7 @@ psutil_SetFromNTStatusErr(NTSTATUS status, const char *syscall) { err = RtlNtStatusToDosErrorNoTeb(status); // if (GetLastError() != 0) // err = GetLastError(); - sprintf(fullmsg, "(originated from %s)", syscall); + str_format(fullmsg, sizeof(fullmsg), "(originated from %s)", syscall); return PyErr_SetFromWindowsErrWithFilename(err, fullmsg); } @@ -125,7 +127,7 @@ psutil_GetProcAddressFromLib(LPCSTR libname, LPCSTR apiname) { Py_BEGIN_ALLOW_THREADS mod = LoadLibraryA(libname); Py_END_ALLOW_THREADS - if (mod == NULL) { + if (mod == NULL) { psutil_debug("%s lib not supported (needed for %s)", libname, apiname); PyErr_SetFromWindowsErrWithFilename(0, libname); return NULL; @@ -158,7 +160,7 @@ _to_unix_time(ULONGLONG hiPart, ULONGLONG loPart) { // Change starting time to the Epoch (00:00:00 UTC, January 1, 1970). ret -= 116444736000000000ull; // Convert nano secs to secs. - return (double) ret / 10000000ull; + return (double)ret / 10000000ull; } @@ -172,9 +174,7 @@ psutil_FiletimeToUnixTime(FILETIME ft) { double psutil_LargeIntegerToUnixTime(LARGE_INTEGER li) { - return _to_unix_time( - (ULONGLONG)li.HighPart, (ULONGLONG)li.LowPart - ); + return _to_unix_time((ULONGLONG)li.HighPart, (ULONGLONG)li.LowPart); } @@ -187,80 +187,92 @@ static int psutil_loadlibs() { // --- Mandatory NtQuerySystemInformation = psutil_GetProcAddressFromLib( - "ntdll.dll", "NtQuerySystemInformation"); - if (! NtQuerySystemInformation) + "ntdll.dll", "NtQuerySystemInformation" + ); + if (!NtQuerySystemInformation) return -1; NtQueryInformationProcess = psutil_GetProcAddress( - "ntdll.dll", "NtQueryInformationProcess"); - if (! NtQueryInformationProcess) + "ntdll.dll", "NtQueryInformationProcess" + ); + if (!NtQueryInformationProcess) return -1; NtSetInformationProcess = psutil_GetProcAddress( - "ntdll.dll", "NtSetInformationProcess"); - if (! NtSetInformationProcess) + "ntdll.dll", "NtSetInformationProcess" + ); + if (!NtSetInformationProcess) return -1; - NtQueryObject = psutil_GetProcAddressFromLib( - "ntdll.dll", "NtQueryObject"); - if (! NtQueryObject) + NtQueryObject = psutil_GetProcAddressFromLib("ntdll.dll", "NtQueryObject"); + if (!NtQueryObject) return -1; RtlIpv4AddressToStringA = psutil_GetProcAddressFromLib( - "ntdll.dll", "RtlIpv4AddressToStringA"); - if (! RtlIpv4AddressToStringA) + "ntdll.dll", "RtlIpv4AddressToStringA" + ); + if (!RtlIpv4AddressToStringA) return -1; GetExtendedTcpTable = psutil_GetProcAddressFromLib( - "iphlpapi.dll", "GetExtendedTcpTable"); - if (! GetExtendedTcpTable) + "iphlpapi.dll", "GetExtendedTcpTable" + ); + if (!GetExtendedTcpTable) return -1; GetExtendedUdpTable = psutil_GetProcAddressFromLib( - "iphlpapi.dll", "GetExtendedUdpTable"); - if (! GetExtendedUdpTable) + "iphlpapi.dll", "GetExtendedUdpTable" + ); + if (!GetExtendedUdpTable) return -1; - RtlGetVersion = psutil_GetProcAddressFromLib( - "ntdll.dll", "RtlGetVersion"); - if (! RtlGetVersion) + RtlGetVersion = psutil_GetProcAddressFromLib("ntdll.dll", "RtlGetVersion"); + if (!RtlGetVersion) return -1; NtSuspendProcess = psutil_GetProcAddressFromLib( - "ntdll", "NtSuspendProcess"); - if (! NtSuspendProcess) + "ntdll", "NtSuspendProcess" + ); + if (!NtSuspendProcess) return -1; - NtResumeProcess = psutil_GetProcAddressFromLib( - "ntdll", "NtResumeProcess"); - if (! NtResumeProcess) + NtResumeProcess = psutil_GetProcAddressFromLib("ntdll", "NtResumeProcess"); + if (!NtResumeProcess) return -1; NtQueryVirtualMemory = psutil_GetProcAddressFromLib( - "ntdll", "NtQueryVirtualMemory"); - if (! NtQueryVirtualMemory) + "ntdll", "NtQueryVirtualMemory" + ); + if (!NtQueryVirtualMemory) return -1; RtlNtStatusToDosErrorNoTeb = psutil_GetProcAddressFromLib( - "ntdll", "RtlNtStatusToDosErrorNoTeb"); - if (! RtlNtStatusToDosErrorNoTeb) + "ntdll", "RtlNtStatusToDosErrorNoTeb" + ); + if (!RtlNtStatusToDosErrorNoTeb) return -1; - GetTickCount64 = psutil_GetProcAddress( - "kernel32", "GetTickCount64"); - if (! GetTickCount64) + GetTickCount64 = psutil_GetProcAddress("kernel32", "GetTickCount64"); + if (!GetTickCount64) return -1; RtlIpv6AddressToStringA = psutil_GetProcAddressFromLib( - "ntdll.dll", "RtlIpv6AddressToStringA"); - if (! RtlIpv6AddressToStringA) + "ntdll.dll", "RtlIpv6AddressToStringA" + ); + if (!RtlIpv6AddressToStringA) return -1; // --- Optional // minimum requirement: Win 7 QueryInterruptTime = psutil_GetProcAddressFromLib( - "kernelbase.dll", "QueryInterruptTime"); + "kernelbase.dll", "QueryInterruptTime" + ); // minimum requirement: Win 7 GetActiveProcessorCount = psutil_GetProcAddress( - "kernel32", "GetActiveProcessorCount"); + "kernel32", "GetActiveProcessorCount" + ); // minimum requirement: Win 7 GetLogicalProcessorInformationEx = psutil_GetProcAddressFromLib( - "kernel32", "GetLogicalProcessorInformationEx"); + "kernel32", "GetLogicalProcessorInformationEx" + ); // minimum requirements: Windows Server Core WTSEnumerateSessionsW = psutil_GetProcAddressFromLib( - "wtsapi32.dll", "WTSEnumerateSessionsW"); + "wtsapi32.dll", "WTSEnumerateSessionsW" + ); WTSQuerySessionInformationW = psutil_GetProcAddressFromLib( - "wtsapi32.dll", "WTSQuerySessionInformationW"); + "wtsapi32.dll", "WTSQuerySessionInformationW" + ); WTSFreeMemory = psutil_GetProcAddressFromLib( - "wtsapi32.dll", "WTSFreeMemory"); + "wtsapi32.dll", "WTSFreeMemory" + ); PyErr_Clear(); return 0; diff --git a/contrib/python/psutil/py3/psutil/arch/windows/init.h b/contrib/python/psutil/py3/psutil/arch/windows/init.h index 2b3905dd35c..3bba7339594 100644 --- a/contrib/python/psutil/py3/psutil/arch/windows/init.h +++ b/contrib/python/psutil/py3/psutil/arch/windows/init.h @@ -12,8 +12,8 @@ extern int PSUTIL_WINVER; -extern SYSTEM_INFO PSUTIL_SYSTEM_INFO; -extern CRITICAL_SECTION PSUTIL_CRITICAL_SECTION; +extern SYSTEM_INFO PSUTIL_SYSTEM_INFO; +extern CRITICAL_SECTION PSUTIL_CRITICAL_SECTION; #define PSUTIL_WINDOWS_VISTA 60 #define PSUTIL_WINDOWS_7 61 @@ -34,31 +34,22 @@ extern CRITICAL_SECTION PSUTIL_CRITICAL_SECTION; #define NT_NTWIN32(status) (_NT_FACILITY(status) == FACILITY_WIN32) #define WIN32_FROM_NTSTATUS(status) (((ULONG)(status)) & 0xffff) -#define PSUTIL_FIRST_PROCESS(Processes) ( \ - (PSYSTEM_PROCESS_INFORMATION)(Processes)) -#define PSUTIL_NEXT_PROCESS(Process) ( \ - ((PSYSTEM_PROCESS_INFORMATION)(Process))->NextEntryOffset ? \ - (PSYSTEM_PROCESS_INFORMATION)((PCHAR)(Process) + \ - ((PSYSTEM_PROCESS_INFORMATION)(Process))->NextEntryOffset) : NULL) - #define LO_T 1e-7 #define HI_T 429.4967296 #ifndef AF_INET6 - #define AF_INET6 23 +#define AF_INET6 23 #endif #if defined(PSUTIL_WINDOWS) && defined(PYPY_VERSION) - #if !defined(PyErr_SetFromWindowsErrWithFilename) - PyObject *PyErr_SetFromWindowsErrWithFilename( - int ierr, const char *filename - ); - #endif - #if !defined(PyErr_SetExcFromWindowsErrWithFilenameObject) - PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject( - PyObject *type, int ierr, PyObject *filename - ); - #endif +#if !defined(PyErr_SetFromWindowsErrWithFilename) +PyObject *PyErr_SetFromWindowsErrWithFilename(int ierr, const char *filename); +#endif +#if !defined(PyErr_SetExcFromWindowsErrWithFilenameObject) +PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject( + PyObject *type, int ierr, PyObject *filename +); +#endif #endif double psutil_FiletimeToUnixTime(FILETIME ft); @@ -79,9 +70,14 @@ int psutil_assert_pid_exists(DWORD pid, char *err); int psutil_assert_pid_not_exists(DWORD pid, char *err); int psutil_pid_is_running(DWORD pid); int psutil_set_se_debug(); -SC_HANDLE psutil_get_service_handle(char service_name, DWORD scm_access, DWORD access); +SC_HANDLE psutil_get_service_handle( + char service_name, DWORD scm_access, DWORD access +); + +int psutil_get_proc_info( + DWORD pid, PSYSTEM_PROCESS_INFORMATION *retProcess, PVOID *retBuffer +); -int psutil_get_proc_info(DWORD pid, PSYSTEM_PROCESS_INFORMATION *retProcess, PVOID *retBuffer); PyObject *psutil_cpu_count_cores(PyObject *self, PyObject *args); PyObject *psutil_cpu_count_logical(PyObject *self, PyObject *args); PyObject *psutil_cpu_freq(PyObject *self, PyObject *args); @@ -102,7 +98,7 @@ PyObject *psutil_per_cpu_times(PyObject *self, PyObject *args); PyObject *psutil_pid_exists(PyObject *self, PyObject *args); PyObject *psutil_pids(PyObject *self, PyObject *args); PyObject *psutil_ppid_map(PyObject *self, PyObject *args); -PyObject *psutil_proc_cmdline(PyObject *self, PyObject *args, PyObject *kwdict); +PyObject *psutil_proc_cmdline(PyObject *self, PyObject *args, PyObject *kw); PyObject *psutil_proc_cpu_affinity_get(PyObject *self, PyObject *args); PyObject *psutil_proc_cpu_affinity_set(PyObject *self, PyObject *args); PyObject *psutil_proc_cwd(PyObject *self, PyObject *args); diff --git a/contrib/python/psutil/py3/psutil/arch/windows/mem.c b/contrib/python/psutil/py3/psutil/arch/windows/mem.c index 03b85777d01..058838de963 100644 --- a/contrib/python/psutil/py3/psutil/arch/windows/mem.c +++ b/contrib/python/psutil/py3/psutil/arch/windows/mem.c @@ -25,8 +25,8 @@ psutil_virtual_mem(PyObject *self, PyObject *args) { unsigned long long totalPhys, availPhys, totalSys, availSys, pageSize; PERFORMANCE_INFORMATION perfInfo; - if (! GetPerformanceInfo(&perfInfo, sizeof(PERFORMANCE_INFORMATION))) { - PyErr_SetFromWindowsErr(0); + if (!GetPerformanceInfo(&perfInfo, sizeof(PERFORMANCE_INFORMATION))) { + psutil_oserror(); return NULL; } // values are size_t, widen (if needed) to long long @@ -35,12 +35,7 @@ psutil_virtual_mem(PyObject *self, PyObject *args) { availPhys = perfInfo.PhysicalAvailable * pageSize; totalSys = perfInfo.CommitLimit * pageSize; availSys = totalSys - perfInfo.CommitTotal * pageSize; - return Py_BuildValue( - "(LLLL)", - totalPhys, - availPhys, - totalSys, - availSys); + return Py_BuildValue("(LLLL)", totalPhys, availPhys, totalSys, availSys); } @@ -56,16 +51,16 @@ psutil_swap_percent(PyObject *self, PyObject *args) { double percentUsage; if ((PdhOpenQueryW(NULL, 0, &hQuery)) != ERROR_SUCCESS) { - PyErr_Format(PyExc_RuntimeError, "PdhOpenQueryW failed"); + psutil_runtime_error("PdhOpenQueryW failed"); return NULL; } s = PdhAddEnglishCounterW(hQuery, szCounterPath, 0, &hCounter); if (s != ERROR_SUCCESS) { PdhCloseQuery(hQuery); - PyErr_Format( - PyExc_RuntimeError, - "PdhAddEnglishCounterW failed. Performance counters may be disabled." + psutil_runtime_error( + "PdhAddEnglishCounterW failed. Performance counters may be " + "disabled." ); return NULL; } @@ -78,11 +73,11 @@ psutil_swap_percent(PyObject *self, PyObject *args) { } else { s = PdhGetFormattedCounterValue( - (PDH_HCOUNTER)hCounter, PDH_FMT_DOUBLE, 0, &counterValue); + (PDH_HCOUNTER)hCounter, PDH_FMT_DOUBLE, 0, &counterValue + ); if (s != ERROR_SUCCESS) { PdhCloseQuery(hQuery); - PyErr_Format( - PyExc_RuntimeError, "PdhGetFormattedCounterValue failed"); + psutil_runtime_error("PdhGetFormattedCounterValue failed"); return NULL; } percentUsage = counterValue.doubleValue; diff --git a/contrib/python/psutil/py3/psutil/arch/windows/net.c b/contrib/python/psutil/py3/psutil/arch/windows/net.c index b9ca07dc0fd..8e9a8186da5 100644 --- a/contrib/python/psutil/py3/psutil/arch/windows/net.c +++ b/contrib/python/psutil/py3/psutil/arch/windows/net.c @@ -21,10 +21,9 @@ psutil_get_nic_addresses(void) { PIP_ADAPTER_ADDRESSES buffer; if (GetAdaptersAddresses(AF_UNSPEC, 0, NULL, NULL, &bufferLength) - != ERROR_BUFFER_OVERFLOW) + != ERROR_BUFFER_OVERFLOW) { - PyErr_SetString(PyExc_RuntimeError, - "GetAdaptersAddresses() syscall failed."); + psutil_runtime_error("GetAdaptersAddresses() syscall failed."); return NULL; } @@ -36,11 +35,10 @@ psutil_get_nic_addresses(void) { memset(buffer, 0, bufferLength); if (GetAdaptersAddresses(AF_UNSPEC, 0, NULL, buffer, &bufferLength) - != ERROR_SUCCESS) + != ERROR_SUCCESS) { free(buffer); - PyErr_SetString(PyExc_RuntimeError, - "GetAdaptersAddresses() syscall failed."); + psutil_runtime_error("GetAdaptersAddresses() syscall failed."); return NULL; } @@ -54,7 +52,7 @@ psutil_get_nic_addresses(void) { PyObject * psutil_net_io_counters(PyObject *self, PyObject *args) { DWORD dwRetVal = 0; - MIB_IF_ROW2 *pIfRow = NULL; + MIB_IF_ROW2 ifRow; PIP_ADAPTER_ADDRESSES pAddresses = NULL; PIP_ADAPTER_ADDRESSES pCurrAddresses = NULL; PyObject *py_retdict = PyDict_New(); @@ -66,52 +64,52 @@ psutil_net_io_counters(PyObject *self, PyObject *args) { pAddresses = psutil_get_nic_addresses(); if (pAddresses == NULL) goto error; + pCurrAddresses = pAddresses; while (pCurrAddresses) { - py_nic_name = NULL; py_nic_info = NULL; + py_nic_name = NULL; - pIfRow = (MIB_IF_ROW2 *) malloc(sizeof(MIB_IF_ROW2)); - if (pIfRow == NULL) { - PyErr_NoMemory(); - goto error; - } + SecureZeroMemory(&ifRow, sizeof(ifRow)); + ifRow.InterfaceIndex = pCurrAddresses->IfIndex; - SecureZeroMemory((PVOID)pIfRow, sizeof(MIB_IF_ROW2)); - pIfRow->InterfaceIndex = pCurrAddresses->IfIndex; - dwRetVal = GetIfEntry2(pIfRow); + dwRetVal = GetIfEntry2(&ifRow); if (dwRetVal != NO_ERROR) { - PyErr_SetString(PyExc_RuntimeError, - "GetIfEntry() or GetIfEntry2() syscalls failed."); + psutil_runtime_error( + "GetIfEntry2() syscall failed for interface %lu", + (unsigned long)ifRow.InterfaceIndex + ); goto error; } py_nic_info = Py_BuildValue( "(KKKKKKKK)", - pIfRow->OutOctets, - pIfRow->InOctets, - (pIfRow->OutUcastPkts + pIfRow->OutNUcastPkts), - (pIfRow->InUcastPkts + pIfRow->InNUcastPkts), - pIfRow->InErrors, - pIfRow->OutErrors, - pIfRow->InDiscards, - pIfRow->OutDiscards); + ifRow.OutOctets, + ifRow.InOctets, + ifRow.OutUcastPkts + ifRow.OutNUcastPkts, + ifRow.InUcastPkts + ifRow.InNUcastPkts, + ifRow.InErrors, + ifRow.OutErrors, + ifRow.InDiscards, + ifRow.OutDiscards + ); if (!py_nic_info) goto error; py_nic_name = PyUnicode_FromWideChar( pCurrAddresses->FriendlyName, - wcslen(pCurrAddresses->FriendlyName)); - - if (py_nic_name == NULL) + wcsnlen(pCurrAddresses->FriendlyName, IF_MAX_STRING_SIZE) + ); + if (!py_nic_name) goto error; + if (PyDict_SetItem(py_retdict, py_nic_name, py_nic_info)) goto error; - Py_CLEAR(py_nic_name); + Py_CLEAR(py_nic_info); + Py_CLEAR(py_nic_name); - free(pIfRow); pCurrAddresses = pCurrAddresses->Next; } @@ -119,13 +117,11 @@ psutil_net_io_counters(PyObject *self, PyObject *args) { return py_retdict; error: - Py_XDECREF(py_nic_name); Py_XDECREF(py_nic_info); + Py_XDECREF(py_nic_name); Py_DECREF(py_retdict); - if (pAddresses != NULL) + if (pAddresses) free(pAddresses); - if (pIfRow != NULL) - free(pIfRow); return NULL; } @@ -146,6 +142,8 @@ psutil_net_if_addrs(PyObject *self, PyObject *args) { DWORD dwRetVal = 0; ULONG converted_netmask; UINT netmask_bits; + int n; + size_t remaining; struct in_addr in_netmask; PIP_ADAPTER_ADDRESSES pAddresses = NULL; PIP_ADAPTER_ADDRESSES pCurrAddresses = NULL; @@ -172,27 +170,39 @@ psutil_net_if_addrs(PyObject *self, PyObject *args) { netmaskIntRet = NULL; py_nic_name = NULL; py_nic_name = PyUnicode_FromWideChar( - pCurrAddresses->FriendlyName, - wcslen(pCurrAddresses->FriendlyName)); + pCurrAddresses->FriendlyName, wcslen(pCurrAddresses->FriendlyName) + ); if (py_nic_name == NULL) goto error; // MAC address if (pCurrAddresses->PhysicalAddressLength != 0) { ptr = buff_macaddr; - *ptr = '\0'; - for (i = 0; i < (int) pCurrAddresses->PhysicalAddressLength; i++) { - if (i == (pCurrAddresses->PhysicalAddressLength - 1)) { - sprintf_s(ptr, _countof(buff_macaddr), "%.2X\n", - (int)pCurrAddresses->PhysicalAddress[i]); + remaining = sizeof(buff_macaddr); + for (i = 0; i < pCurrAddresses->PhysicalAddressLength; i++) { + if (i == pCurrAddresses->PhysicalAddressLength - 1) { + n = str_format( + ptr, + remaining, + "%.2X", + (int)pCurrAddresses->PhysicalAddress[i] + ); } else { - sprintf_s(ptr, _countof(buff_macaddr), "%.2X-", - (int)pCurrAddresses->PhysicalAddress[i]); + n = str_format( + ptr, + remaining, + "%.2X-", + (int)pCurrAddresses->PhysicalAddress[i] + ); } - ptr += 3; + if (n < 0) { // error or truncated + psutil_runtime_error("str_format() error"); + break; + } + ptr += n; + remaining -= n; } - *--ptr = '\0'; py_mac_address = Py_BuildValue("s", buff_macaddr); if (py_mac_address == NULL) @@ -210,7 +220,7 @@ psutil_net_if_addrs(PyObject *self, PyObject *args) { Py_None, // broadcast (not supported) Py_None // ptp (not supported on Windows) ); - if (! py_tuple) + if (!py_tuple) goto error; if (PyList_Append(py_retlist, py_tuple)) goto error; @@ -223,29 +233,42 @@ psutil_net_if_addrs(PyObject *self, PyObject *args) { for (i = 0; pUnicast != NULL; i++) { family = pUnicast->Address.lpSockaddr->sa_family; if (family == AF_INET) { - struct sockaddr_in *sa_in = (struct sockaddr_in *) - pUnicast->Address.lpSockaddr; - intRet = inet_ntop(AF_INET, &(sa_in->sin_addr), buff_addr, - sizeof(buff_addr)); + struct sockaddr_in *sa_in = (struct sockaddr_in *)pUnicast + ->Address.lpSockaddr; + intRet = inet_ntop( + AF_INET, + &(sa_in->sin_addr), + buff_addr, + sizeof(buff_addr) + ); if (!intRet) goto error; netmask_bits = pUnicast->OnLinkPrefixLength; dwRetVal = ConvertLengthToIpv4Mask( - netmask_bits, &converted_netmask); + netmask_bits, &converted_netmask + ); if (dwRetVal == NO_ERROR) { in_netmask.s_addr = converted_netmask; netmaskIntRet = inet_ntop( - AF_INET, &in_netmask, buff_netmask, - sizeof(buff_netmask)); + AF_INET, + &in_netmask, + buff_netmask, + sizeof(buff_netmask) + ); if (!netmaskIntRet) goto error; } } else if (family == AF_INET6) { struct sockaddr_in6 *sa_in6 = (struct sockaddr_in6 *) - pUnicast->Address.lpSockaddr; - intRet = inet_ntop(AF_INET6, &(sa_in6->sin6_addr), - buff_addr, sizeof(buff_addr)); + pUnicast->Address + .lpSockaddr; + intRet = inet_ntop( + AF_INET6, + &(sa_in6->sin6_addr), + buff_addr, + sizeof(buff_addr) + ); if (!intRet) goto error; } @@ -279,7 +302,7 @@ psutil_net_if_addrs(PyObject *self, PyObject *args) { Py_None // ptp (not supported on Windows) ); - if (! py_tuple) + if (!py_tuple) goto error; if (PyList_Append(py_retlist, py_tuple)) goto error; @@ -337,7 +360,7 @@ psutil_net_if_stats(PyObject *self, PyObject *args) { if (pAddresses == NULL) goto error; - pIfTable = (MIB_IFTABLE *) malloc(sizeof (MIB_IFTABLE)); + pIfTable = (MIB_IFTABLE *)malloc(sizeof(MIB_IFTABLE)); if (pIfTable == NULL) { PyErr_NoMemory(); goto error; @@ -345,7 +368,7 @@ psutil_net_if_stats(PyObject *self, PyObject *args) { dwSize = sizeof(MIB_IFTABLE); if (GetIfTable(pIfTable, &dwSize, FALSE) == ERROR_INSUFFICIENT_BUFFER) { free(pIfTable); - pIfTable = (MIB_IFTABLE *) malloc(dwSize); + pIfTable = (MIB_IFTABLE *)malloc(dwSize); if (pIfTable == NULL) { PyErr_NoMemory(); goto error; @@ -354,12 +377,12 @@ psutil_net_if_stats(PyObject *self, PyObject *args) { // Make a second call to GetIfTable to get the actual // data we want. if ((dwRetVal = GetIfTable(pIfTable, &dwSize, FALSE)) != NO_ERROR) { - PyErr_SetString(PyExc_RuntimeError, "GetIfTable() syscall failed"); + psutil_runtime_error("GetIfTable() syscall failed"); goto error; } - for (i = 0; i < (int) pIfTable->dwNumEntries; i++) { - pIfRow = (MIB_IFROW *) & pIfTable->table[i]; + for (i = 0; i < (int)pIfTable->dwNumEntries; i++) { + pIfRow = (MIB_IFROW *)&pIfTable->table[i]; // GetIfTable is not able to give us NIC with "friendly names" // so we determine them via GetAdapterAddresses() which @@ -368,11 +391,12 @@ psutil_net_if_stats(PyObject *self, PyObject *args) { ifname_found = 0; pCurrAddresses = pAddresses; while (pCurrAddresses) { - sprintf_s(descr, MAX_PATH, "%wS", pCurrAddresses->Description); + str_format(descr, MAX_PATH, "%wS", pCurrAddresses->Description); if (lstrcmp(descr, pIfRow->bDescr) == 0) { py_nic_name = PyUnicode_FromWideChar( pCurrAddresses->FriendlyName, - wcslen(pCurrAddresses->FriendlyName)); + wcslen(pCurrAddresses->FriendlyName) + ); if (py_nic_name == NULL) goto error; ifname_found = 1; @@ -388,9 +412,10 @@ psutil_net_if_stats(PyObject *self, PyObject *args) { } // is up? - if ((pIfRow->dwOperStatus == MIB_IF_OPER_STATUS_CONNECTED || - pIfRow->dwOperStatus == MIB_IF_OPER_STATUS_OPERATIONAL) && - pIfRow->dwAdminStatus == 1 ) { + if ((pIfRow->dwOperStatus == MIB_IF_OPER_STATUS_CONNECTED + || pIfRow->dwOperStatus == MIB_IF_OPER_STATUS_OPERATIONAL) + && pIfRow->dwAdminStatus == 1) + { py_is_up = Py_True; } else { diff --git a/contrib/python/psutil/py3/psutil/arch/windows/ntextapi.h b/contrib/python/psutil/py3/psutil/arch/windows/ntextapi.h index 742d7181003..c3679cb1f0c 100644 --- a/contrib/python/psutil/py3/psutil/arch/windows/ntextapi.h +++ b/contrib/python/psutil/py3/psutil/arch/windows/ntextapi.h @@ -5,6 +5,7 @@ * Define Windows structs and constants which are considered private. */ +// clang-format off #if !defined(__NTEXTAPI_H__) #define __NTEXTAPI_H__ #include <winternl.h> @@ -711,3 +712,4 @@ PSUTIL_MAYBE_EXTERN ULONG (WINAPI *_RtlNtStatusToDosErrorNoTeb) ( #define RtlNtStatusToDosErrorNoTeb _RtlNtStatusToDosErrorNoTeb #endif // __NTEXTAPI_H__ +// clang-format on diff --git a/contrib/python/psutil/py3/psutil/arch/windows/pids.c b/contrib/python/psutil/py3/psutil/arch/windows/pids.c index 6f4b4ee6a2a..8101aaeee81 100644 --- a/contrib/python/psutil/py3/psutil/arch/windows/pids.c +++ b/contrib/python/psutil/py3/psutil/arch/windows/pids.c @@ -8,6 +8,9 @@ #include <windows.h> #include <psapi.h> +#include "../../arch/all/init.h" + + int _psutil_pids(DWORD **pids_array, int *pids_count) { DWORD *proc_array = NULL; @@ -32,7 +35,7 @@ _psutil_pids(DWORD **pids_array, int *pids_count) { if (!EnumProcesses(proc_array, proc_array_bytes, &enum_return_bytes)) { free(proc_array); - PyErr_SetFromWindowsErr(0); + psutil_oserror(); return -1; } diff --git a/contrib/python/psutil/py3/psutil/arch/windows/proc.c b/contrib/python/psutil/py3/psutil/arch/windows/proc.c index c62897bb417..ff22340fbf0 100644 --- a/contrib/python/psutil/py3/psutil/arch/windows/proc.c +++ b/contrib/python/psutil/py3/psutil/arch/windows/proc.c @@ -9,7 +9,7 @@ * psutil/_psutil_windows.c in 2023. For reference, here's the GIT blame * history before the move: * https://github.com/giampaolo/psutil/blame/59504a5/psutil/_psutil_windows.c -*/ + */ // Fixes clash between winsock2.h and windows.h #define WIN32_LEAN_AND_MEAN @@ -39,12 +39,12 @@ psutil_pid_exists(PyObject *self, PyObject *args) { DWORD pid; int status; - if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) + if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) return NULL; status = psutil_pid_is_running(pid); if (-1 == status) - return NULL; // exception raised in psutil_pid_is_running() + return NULL; // exception raised in psutil_pid_is_running() return PyBool_FromLong(status); } @@ -58,22 +58,22 @@ psutil_proc_kill(PyObject *self, PyObject *args) { DWORD pid; DWORD access = PROCESS_TERMINATE | PROCESS_QUERY_LIMITED_INFORMATION; - if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) + if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) return NULL; if (pid == 0) - return AccessDenied("automatically set for PID 0"); + return psutil_oserror_ad("automatically set for PID 0"); hProcess = psutil_handle_from_pid(pid, access); if (hProcess == NULL) { return NULL; } - if (! TerminateProcess(hProcess, SIGTERM)) { + if (!TerminateProcess(hProcess, SIGTERM)) { // ERROR_ACCESS_DENIED may happen if the process already died. See: // https://github.com/giampaolo/psutil/issues/1099 // http://bugs.python.org/issue14252 if (GetLastError() != ERROR_ACCESS_DENIED) { - psutil_PyErr_SetFromOSErrnoWithSyscall("TerminateProcess"); + psutil_oserror_wsyscall("TerminateProcess"); return NULL; } } @@ -94,13 +94,14 @@ psutil_proc_wait(PyObject *self, PyObject *args) { DWORD pid; long timeout; - if (! PyArg_ParseTuple(args, _Py_PARSE_PID "l", &pid, &timeout)) + if (!PyArg_ParseTuple(args, _Py_PARSE_PID "l", &pid, &timeout)) return NULL; if (pid == 0) - return AccessDenied("automatically set for PID 0"); + return psutil_oserror_ad("automatically set for PID 0"); - hProcess = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION, - FALSE, pid); + hProcess = OpenProcess( + SYNCHRONIZE | PROCESS_QUERY_INFORMATION, FALSE, pid + ); if (hProcess == NULL) { if (GetLastError() == ERROR_INVALID_PARAMETER) { // no such process; we do not want to raise NSP but @@ -108,7 +109,7 @@ psutil_proc_wait(PyObject *self, PyObject *args) { Py_RETURN_NONE; } else { - psutil_PyErr_SetFromOSErrnoWithSyscall("OpenProcess"); + psutil_oserror_wsyscall("OpenProcess"); return NULL; } } @@ -120,20 +121,22 @@ psutil_proc_wait(PyObject *self, PyObject *args) { // handle return code if (retVal == WAIT_FAILED) { - psutil_PyErr_SetFromOSErrnoWithSyscall("WaitForSingleObject"); + psutil_oserror_wsyscall("WaitForSingleObject"); CloseHandle(hProcess); return NULL; } if (retVal == WAIT_TIMEOUT) { - PyErr_SetString(TimeoutExpired, - "WaitForSingleObject() returned WAIT_TIMEOUT"); + PyErr_SetString( + TimeoutExpired, "WaitForSingleObject() returned WAIT_TIMEOUT" + ); CloseHandle(hProcess); return NULL; } if (retVal == WAIT_ABANDONED) { psutil_debug("WaitForSingleObject() -> WAIT_ABANDONED"); - PyErr_SetString(TimeoutAbandoned, - "WaitForSingleObject() returned WAIT_ABANDONED"); + PyErr_SetString( + TimeoutAbandoned, "WaitForSingleObject() returned WAIT_ABANDONED" + ); CloseHandle(hProcess); return NULL; } @@ -142,14 +145,14 @@ psutil_proc_wait(PyObject *self, PyObject *args) { // process is gone so we can get its process exit code. The PID // may still stick around though but we'll handle that from Python. if (GetExitCodeProcess(hProcess, &ExitCode) == 0) { - psutil_PyErr_SetFromOSErrnoWithSyscall("GetExitCodeProcess"); + psutil_oserror_wsyscall("GetExitCodeProcess"); CloseHandle(hProcess); return NULL; } CloseHandle(hProcess); - return PyLong_FromLong((long) ExitCode); + return PyLong_FromLong((long)ExitCode); } @@ -158,25 +161,25 @@ psutil_proc_wait(PyObject *self, PyObject *args) { */ PyObject * psutil_proc_times(PyObject *self, PyObject *args) { - DWORD pid; - HANDLE hProcess; - FILETIME ftCreate, ftExit, ftKernel, ftUser; + DWORD pid; + HANDLE hProcess; + FILETIME ftCreate, ftExit, ftKernel, ftUser; - if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) + if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) return NULL; hProcess = psutil_handle_from_pid(pid, PROCESS_QUERY_LIMITED_INFORMATION); if (hProcess == NULL) return NULL; - if (! GetProcessTimes(hProcess, &ftCreate, &ftExit, &ftKernel, &ftUser)) { + if (!GetProcessTimes(hProcess, &ftCreate, &ftExit, &ftKernel, &ftUser)) { if (GetLastError() == ERROR_ACCESS_DENIED) { // usually means the process has died so we throw a NoSuchProcess // here - NoSuchProcess("GetProcessTimes -> ERROR_ACCESS_DENIED"); + psutil_oserror_nsp("GetProcessTimes -> ERROR_ACCESS_DENIED"); } else { - PyErr_SetFromWindowsErr(0); + psutil_oserror(); } CloseHandle(hProcess); return NULL; @@ -194,13 +197,12 @@ psutil_proc_times(PyObject *self, PyObject *args) { * below from Python's Modules/posixmodule.c */ return Py_BuildValue( - "(ddd)", - (double)(ftUser.dwHighDateTime * HI_T + \ - ftUser.dwLowDateTime * LO_T), - (double)(ftKernel.dwHighDateTime * HI_T + \ - ftKernel.dwLowDateTime * LO_T), - psutil_FiletimeToUnixTime(ftCreate) - ); + "(ddd)", + (double)(ftUser.dwHighDateTime * HI_T + ftUser.dwLowDateTime * LO_T), + (double)(ftKernel.dwHighDateTime * HI_T + ftKernel.dwLowDateTime * LO_T + ), + psutil_FiletimeToUnixTime(ftCreate) + ); } @@ -215,23 +217,23 @@ psutil_proc_exe(PyObject *self, PyObject *args) { DWORD pid; NTSTATUS status; PVOID buffer = NULL; - ULONG bufferSize = 0x104 * 2; // WIN_MAX_PATH * sizeof(wchar_t) + ULONG bufferSize = 0x104 * 2; // WIN_MAX_PATH * sizeof(wchar_t) SYSTEM_PROCESS_ID_INFORMATION processIdInfo; PyObject *py_exe; - if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) + if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) return NULL; if (pid == 0) - return AccessDenied("automatically set for PID 0"); + return psutil_oserror_ad("automatically set for PID 0"); // ...because NtQuerySystemInformation can succeed for terminated // processes. if (psutil_pid_is_running(pid) == 0) - return NoSuchProcess("psutil_pid_is_running -> 0"); + return psutil_oserror_nsp("psutil_pid_is_running -> 0"); buffer = MALLOC_ZERO(bufferSize); - if (! buffer) { + if (!buffer) { PyErr_NoMemory(); return NULL; } @@ -245,10 +247,11 @@ psutil_proc_exe(PyObject *self, PyObject *args) { SystemProcessIdInformation, &processIdInfo, sizeof(SYSTEM_PROCESS_ID_INFORMATION), - NULL); + NULL + ); - if ((status == STATUS_INFO_LENGTH_MISMATCH) && - (processIdInfo.ImageName.MaximumLength <= bufferSize)) + if ((status == STATUS_INFO_LENGTH_MISMATCH) + && (processIdInfo.ImageName.MaximumLength <= bufferSize)) { // Required length was NOT stored in MaximumLength (WOW64 issue). ULONG maxBufferSize = 0x7FFF * 2; // NTFS_MAX_PATH * sizeof(wchar_t) @@ -257,7 +260,7 @@ psutil_proc_exe(PyObject *self, PyObject *args) { bufferSize *= 2; FREE(buffer); buffer = MALLOC_ZERO(bufferSize); - if (! buffer) { + if (!buffer) { PyErr_NoMemory(); return NULL; } @@ -269,15 +272,16 @@ psutil_proc_exe(PyObject *self, PyObject *args) { SystemProcessIdInformation, &processIdInfo, sizeof(SYSTEM_PROCESS_ID_INFORMATION), - NULL); - } while ((status == STATUS_INFO_LENGTH_MISMATCH) && - (bufferSize <= maxBufferSize)); + NULL + ); + } while ((status == STATUS_INFO_LENGTH_MISMATCH) + && (bufferSize <= maxBufferSize)); } else if (status == STATUS_INFO_LENGTH_MISMATCH) { // Required length is stored in MaximumLength. FREE(buffer); buffer = MALLOC_ZERO(processIdInfo.ImageName.MaximumLength); - if (! buffer) { + if (!buffer) { PyErr_NoMemory(); return NULL; } @@ -288,13 +292,14 @@ psutil_proc_exe(PyObject *self, PyObject *args) { SystemProcessIdInformation, &processIdInfo, sizeof(SYSTEM_PROCESS_ID_INFORMATION), - NULL); + NULL + ); } - if (! NT_SUCCESS(status)) { + if (!NT_SUCCESS(status)) { FREE(buffer); if (psutil_pid_is_running(pid) == 0) - NoSuchProcess("psutil_pid_is_running -> 0"); + psutil_oserror_nsp("psutil_pid_is_running -> 0"); else psutil_SetFromNTStatusErr(status, "NtQuerySystemInformation"); return NULL; @@ -305,8 +310,9 @@ psutil_proc_exe(PyObject *self, PyObject *args) { py_exe = Py_BuildValue("s", ""); } else { - py_exe = PyUnicode_FromWideChar(processIdInfo.ImageName.Buffer, - processIdInfo.ImageName.Length / 2); + py_exe = PyUnicode_FromWideChar( + processIdInfo.ImageName.Buffer, processIdInfo.ImageName.Length / 2 + ); } FREE(buffer); return py_exe; @@ -322,16 +328,18 @@ psutil_proc_memory_info(PyObject *self, PyObject *args) { DWORD pid; PROCESS_MEMORY_COUNTERS_EX cnt; - if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) + if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) return NULL; hProcess = psutil_handle_from_pid(pid, PROCESS_QUERY_LIMITED_INFORMATION); if (NULL == hProcess) return NULL; - if (! GetProcessMemoryInfo(hProcess, (PPROCESS_MEMORY_COUNTERS)&cnt, - sizeof(cnt))) { - PyErr_SetFromWindowsErr(0); + if (!GetProcessMemoryInfo( + hProcess, (PPROCESS_MEMORY_COUNTERS)&cnt, sizeof(cnt) + )) + { + psutil_oserror(); CloseHandle(hProcess); return NULL; } @@ -353,11 +361,12 @@ psutil_proc_memory_info(PyObject *self, PyObject *args) { (unsigned long long)cnt.QuotaNonPagedPoolUsage, (unsigned long long)cnt.PagefileUsage, (unsigned long long)cnt.PeakPagefileUsage, - (unsigned long long)cnt.PrivateUsage); + (unsigned long long)cnt.PrivateUsage + ); #else return Py_BuildValue( "(kIIIIIIIII)", - cnt.PageFaultCount, // unsigned long + cnt.PageFaultCount, // unsigned long (unsigned int)cnt.PeakWorkingSetSize, (unsigned int)cnt.WorkingSetSize, (unsigned int)cnt.QuotaPeakPagedPoolUsage, @@ -366,46 +375,46 @@ psutil_proc_memory_info(PyObject *self, PyObject *args) { (unsigned int)cnt.QuotaNonPagedPoolUsage, (unsigned int)cnt.PagefileUsage, (unsigned int)cnt.PeakPagefileUsage, - (unsigned int)cnt.PrivateUsage); + (unsigned int)cnt.PrivateUsage + ); #endif } static int psutil_GetProcWsetInformation( - DWORD pid, - HANDLE hProcess, - PMEMORY_WORKING_SET_INFORMATION *wSetInfo) -{ + DWORD pid, HANDLE hProcess, PMEMORY_WORKING_SET_INFORMATION *wSetInfo +) { NTSTATUS status; PVOID buffer; SIZE_T bufferSize; bufferSize = 0x8000; buffer = MALLOC_ZERO(bufferSize); - if (! buffer) { + if (!buffer) { PyErr_NoMemory(); return -1; } while ((status = NtQueryVirtualMemory( - hProcess, - NULL, - MemoryWorkingSetInformation, - buffer, - bufferSize, - NULL)) == STATUS_INFO_LENGTH_MISMATCH) + hProcess, + NULL, + MemoryWorkingSetInformation, + buffer, + bufferSize, + NULL + )) + == STATUS_INFO_LENGTH_MISMATCH) { FREE(buffer); bufferSize *= 2; // Fail if we're resizing the buffer to something very large. if (bufferSize > 256 * 1024 * 1024) { - PyErr_SetString(PyExc_RuntimeError, - "NtQueryVirtualMemory bufsize is too large"); + psutil_runtime_error("NtQueryVirtualMemory bufsize is too large"); return -1; } buffer = MALLOC_ZERO(bufferSize); - if (! buffer) { + if (!buffer) { PyErr_NoMemory(); return -1; } @@ -413,15 +422,16 @@ psutil_GetProcWsetInformation( if (!NT_SUCCESS(status)) { if (status == STATUS_ACCESS_DENIED) { - AccessDenied("NtQueryVirtualMemory -> STATUS_ACCESS_DENIED"); + psutil_oserror_ad("NtQueryVirtualMemory -> STATUS_ACCESS_DENIED"); } else if (psutil_pid_is_running(pid) == 0) { - NoSuchProcess("psutil_pid_is_running -> 0"); + psutil_oserror_nsp("psutil_pid_is_running -> 0"); } else { PyErr_Clear(); psutil_SetFromNTStatusErr( - status, "NtQueryVirtualMemory(MemoryWorkingSetInformation)"); + status, "NtQueryVirtualMemory(MemoryWorkingSetInformation)" + ); } HeapFree(GetProcessHeap(), 0, buffer); return -1; @@ -446,7 +456,7 @@ psutil_proc_memory_uss(PyObject *self, PyObject *args) { PMEMORY_WORKING_SET_INFORMATION wsInfo; ULONG_PTR i; - if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) + if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) return NULL; hProcess = psutil_handle_from_pid(pid, PROCESS_QUERY_INFORMATION); if (hProcess == NULL) @@ -472,8 +482,9 @@ psutil_proc_memory_uss(PyObject *self, PyObject *args) { // This is what we do: count shared pages that only one process // is using as private (USS). - if (!wsInfo->WorkingSetInfo[i].Shared || - wsInfo->WorkingSetInfo[i].ShareCount <= 1) { + if (!wsInfo->WorkingSetInfo[i].Shared + || wsInfo->WorkingSetInfo[i].ShareCount <= 1) + { wsCounters.NumberOfPrivatePages++; } } @@ -494,9 +505,9 @@ psutil_proc_suspend_or_resume(PyObject *self, PyObject *args) { NTSTATUS status; HANDLE hProcess; DWORD access = PROCESS_SUSPEND_RESUME | PROCESS_QUERY_LIMITED_INFORMATION; - PyObject* suspend; + PyObject *suspend; - if (! PyArg_ParseTuple(args, _Py_PARSE_PID "O", &pid, &suspend)) + if (!PyArg_ParseTuple(args, _Py_PARSE_PID "O", &pid, &suspend)) return NULL; hProcess = psutil_handle_from_pid(pid, access); @@ -508,7 +519,7 @@ psutil_proc_suspend_or_resume(PyObject *self, PyObject *args) { else status = NtResumeProcess(hProcess); - if (! NT_SUCCESS(status)) { + if (!NT_SUCCESS(status)) { CloseHandle(hProcess); return psutil_SetFromNTStatusErr(status, "NtSuspend|ResumeProcess"); } @@ -532,18 +543,18 @@ psutil_proc_threads(PyObject *self, PyObject *args) { if (py_retlist == NULL) return NULL; - if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) + if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) goto error; if (pid == 0) { // raise AD instead of returning 0 as procexp is able to // retrieve useful information somehow - AccessDenied("forced for PID 0"); + psutil_oserror_ad("forced for PID 0"); goto error; } pid_return = psutil_pid_is_running(pid); if (pid_return == 0) { - NoSuchProcess("psutil_pid_is_running -> 0"); + psutil_oserror_nsp("psutil_pid_is_running -> 0"); goto error; } if (pid_return == -1) @@ -551,15 +562,15 @@ psutil_proc_threads(PyObject *self, PyObject *args) { hThreadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); if (hThreadSnap == INVALID_HANDLE_VALUE) { - psutil_PyErr_SetFromOSErrnoWithSyscall("CreateToolhelp32Snapshot"); + psutil_oserror_wsyscall("CreateToolhelp32Snapshot"); goto error; } // Fill in the size of the structure before using it te32.dwSize = sizeof(THREADENTRY32); - if (! Thread32First(hThreadSnap, &te32)) { - psutil_PyErr_SetFromOSErrnoWithSyscall("Thread32First"); + if (!Thread32First(hThreadSnap, &te32)) { + psutil_oserror_wsyscall("Thread32First"); goto error; } @@ -569,17 +580,19 @@ psutil_proc_threads(PyObject *self, PyObject *args) { if (te32.th32OwnerProcessID == pid) { py_tuple = NULL; hThread = NULL; - hThread = OpenThread(THREAD_QUERY_INFORMATION, - FALSE, te32.th32ThreadID); + hThread = OpenThread( + THREAD_QUERY_INFORMATION, FALSE, te32.th32ThreadID + ); if (hThread == NULL) { // thread has disappeared on us continue; } - rc = GetThreadTimes(hThread, &ftDummy, &ftDummy, &ftKernel, - &ftUser); + rc = GetThreadTimes( + hThread, &ftDummy, &ftDummy, &ftKernel, &ftUser + ); if (rc == 0) { - psutil_PyErr_SetFromOSErrnoWithSyscall("GetThreadTimes"); + psutil_oserror_wsyscall("GetThreadTimes"); goto error; } @@ -595,10 +608,11 @@ psutil_proc_threads(PyObject *self, PyObject *args) { py_tuple = Py_BuildValue( "kdd", te32.th32ThreadID, - (double)(ftUser.dwHighDateTime * HI_T + \ - ftUser.dwLowDateTime * LO_T), - (double)(ftKernel.dwHighDateTime * HI_T + \ - ftKernel.dwLowDateTime * LO_T)); + (double)(ftUser.dwHighDateTime * HI_T + + ftUser.dwLowDateTime * LO_T), + (double)(ftKernel.dwHighDateTime * HI_T + + ftKernel.dwLowDateTime * LO_T) + ); if (!py_tuple) goto error; if (PyList_Append(py_retlist, py_tuple)) @@ -630,7 +644,7 @@ psutil_proc_open_files(PyObject *self, PyObject *args) { DWORD access = PROCESS_DUP_HANDLE | PROCESS_QUERY_INFORMATION; PyObject *py_retlist; - if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) + if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) return NULL; processHandle = psutil_handle_from_pid(pid, access); @@ -655,7 +669,7 @@ _psutil_user_token_from_pid(DWORD pid) { return NULL; if (!OpenProcessToken(hProcess, TOKEN_QUERY, &hToken)) { - psutil_PyErr_SetFromOSErrnoWithSyscall("OpenProcessToken"); + psutil_oserror_wsyscall("OpenProcessToken"); goto error; } @@ -666,15 +680,16 @@ _psutil_user_token_from_pid(DWORD pid) { PyErr_NoMemory(); goto error; } - if (!GetTokenInformation(hToken, TokenUser, userToken, bufferSize, - &bufferSize)) + if (!GetTokenInformation( + hToken, TokenUser, userToken, bufferSize, &bufferSize + )) { if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) { free(userToken); continue; } else { - psutil_PyErr_SetFromOSErrnoWithSyscall("GetTokenInformation"); + psutil_oserror_wsyscall("GetTokenInformation"); goto error; } } @@ -710,7 +725,7 @@ psutil_proc_username(PyObject *self, PyObject *args) { PyObject *py_domain = NULL; PyObject *py_tuple = NULL; - if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) + if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) return NULL; userToken = _psutil_user_token_from_pid(pid); if (userToken == NULL) @@ -728,8 +743,15 @@ psutil_proc_username(PyObject *self, PyObject *args) { PyErr_NoMemory(); goto error; } - if (!LookupAccountSidW(NULL, userToken->User.Sid, userName, &nameSize, - domainName, &domainNameSize, &nameUse)) + if (!LookupAccountSidW( + NULL, + userToken->User.Sid, + userName, + &nameSize, + domainName, + &domainNameSize, + &nameUse + )) { if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) { free(userName); @@ -746,11 +768,11 @@ psutil_proc_username(PyObject *self, PyObject *args) { // name. It also occurs for SIDs that have no corresponding // account name, such as a logon SID that identifies a logon // session. - AccessDenied("LookupAccountSidW -> ERROR_NONE_MAPPED"); + psutil_oserror_ad("LookupAccountSidW -> ERROR_NONE_MAPPED"); goto error; } else { - psutil_PyErr_SetFromOSErrnoWithSyscall("LookupAccountSidW"); + psutil_oserror_wsyscall("LookupAccountSidW"); goto error; } } @@ -758,13 +780,13 @@ psutil_proc_username(PyObject *self, PyObject *args) { } py_domain = PyUnicode_FromWideChar(domainName, wcslen(domainName)); - if (! py_domain) + if (!py_domain) goto error; py_username = PyUnicode_FromWideChar(userName, wcslen(userName)); - if (! py_username) + if (!py_username) goto error; py_tuple = Py_BuildValue("OO", py_domain, py_username); - if (! py_tuple) + if (!py_tuple) goto error; Py_DECREF(py_domain); Py_DECREF(py_username); @@ -797,7 +819,7 @@ psutil_proc_priority_get(PyObject *self, PyObject *args) { DWORD priority; HANDLE hProcess; - if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) + if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) return NULL; hProcess = psutil_handle_from_pid(pid, PROCESS_QUERY_LIMITED_INFORMATION); @@ -806,7 +828,7 @@ psutil_proc_priority_get(PyObject *self, PyObject *args) { priority = GetPriorityClass(hProcess); if (priority == 0) { - PyErr_SetFromWindowsErr(0); + psutil_oserror(); CloseHandle(hProcess); return NULL; } @@ -826,7 +848,7 @@ psutil_proc_priority_set(PyObject *self, PyObject *args) { HANDLE hProcess; DWORD access = PROCESS_QUERY_INFORMATION | PROCESS_SET_INFORMATION; - if (! PyArg_ParseTuple(args, _Py_PARSE_PID "i", &pid, &priority)) + if (!PyArg_ParseTuple(args, _Py_PARSE_PID "i", &pid, &priority)) return NULL; hProcess = psutil_handle_from_pid(pid, access); if (hProcess == NULL) @@ -834,7 +856,7 @@ psutil_proc_priority_set(PyObject *self, PyObject *args) { retval = SetPriorityClass(hProcess, priority); if (retval == 0) { - PyErr_SetFromWindowsErr(0); + psutil_oserror(); CloseHandle(hProcess); return NULL; } @@ -854,7 +876,7 @@ psutil_proc_io_priority_get(PyObject *self, PyObject *args) { DWORD IoPriority; NTSTATUS status; - if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) + if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) return NULL; hProcess = psutil_handle_from_pid(pid, PROCESS_QUERY_LIMITED_INFORMATION); @@ -862,15 +884,11 @@ psutil_proc_io_priority_get(PyObject *self, PyObject *args) { return NULL; status = NtQueryInformationProcess( - hProcess, - ProcessIoPriority, - &IoPriority, - sizeof(DWORD), - NULL + hProcess, ProcessIoPriority, &IoPriority, sizeof(DWORD), NULL ); CloseHandle(hProcess); - if (! NT_SUCCESS(status)) + if (!NT_SUCCESS(status)) return psutil_SetFromNTStatusErr(status, "NtQueryInformationProcess"); return Py_BuildValue("i", IoPriority); } @@ -887,7 +905,7 @@ psutil_proc_io_priority_set(PyObject *self, PyObject *args) { NTSTATUS status; DWORD access = PROCESS_QUERY_INFORMATION | PROCESS_SET_INFORMATION; - if (! PyArg_ParseTuple(args, _Py_PARSE_PID "i", &pid, &prio)) + if (!PyArg_ParseTuple(args, _Py_PARSE_PID "i", &pid, &prio)) return NULL; hProcess = psutil_handle_from_pid(pid, access); @@ -895,14 +913,11 @@ psutil_proc_io_priority_set(PyObject *self, PyObject *args) { return NULL; status = NtSetInformationProcess( - hProcess, - ProcessIoPriority, - (PVOID)&prio, - sizeof(DWORD) + hProcess, ProcessIoPriority, (PVOID)&prio, sizeof(DWORD) ); CloseHandle(hProcess); - if (! NT_SUCCESS(status)) + if (!NT_SUCCESS(status)) return psutil_SetFromNTStatusErr(status, "NtSetInformationProcess"); Py_RETURN_NONE; } @@ -917,26 +932,28 @@ psutil_proc_io_counters(PyObject *self, PyObject *args) { HANDLE hProcess; IO_COUNTERS IoCounters; - if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) + if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) return NULL; hProcess = psutil_handle_from_pid(pid, PROCESS_QUERY_LIMITED_INFORMATION); if (NULL == hProcess) return NULL; - if (! GetProcessIoCounters(hProcess, &IoCounters)) { - PyErr_SetFromWindowsErr(0); + if (!GetProcessIoCounters(hProcess, &IoCounters)) { + psutil_oserror(); CloseHandle(hProcess); return NULL; } CloseHandle(hProcess); - return Py_BuildValue("(KKKKKK)", - IoCounters.ReadOperationCount, - IoCounters.WriteOperationCount, - IoCounters.ReadTransferCount, - IoCounters.WriteTransferCount, - IoCounters.OtherOperationCount, - IoCounters.OtherTransferCount); + return Py_BuildValue( + "(KKKKKK)", + IoCounters.ReadOperationCount, + IoCounters.WriteOperationCount, + IoCounters.ReadTransferCount, + IoCounters.WriteTransferCount, + IoCounters.OtherOperationCount, + IoCounters.OtherTransferCount + ); } @@ -950,14 +967,14 @@ psutil_proc_cpu_affinity_get(PyObject *self, PyObject *args) { DWORD_PTR proc_mask; DWORD_PTR system_mask; - if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) + if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) return NULL; hProcess = psutil_handle_from_pid(pid, PROCESS_QUERY_LIMITED_INFORMATION); if (hProcess == NULL) { return NULL; } if (GetProcessAffinityMask(hProcess, &proc_mask, &system_mask) == 0) { - PyErr_SetFromWindowsErr(0); + psutil_oserror(); CloseHandle(hProcess); return NULL; } @@ -982,9 +999,9 @@ psutil_proc_cpu_affinity_set(PyObject *self, PyObject *args) { DWORD_PTR mask; #ifdef _WIN64 - if (! PyArg_ParseTuple(args, _Py_PARSE_PID "K", &pid, &mask)) + if (!PyArg_ParseTuple(args, _Py_PARSE_PID "K", &pid, &mask)) #else - if (! PyArg_ParseTuple(args, _Py_PARSE_PID "k", &pid, &mask)) + if (!PyArg_ParseTuple(args, _Py_PARSE_PID "k", &pid, &mask)) #endif { return NULL; @@ -994,7 +1011,7 @@ psutil_proc_cpu_affinity_set(PyObject *self, PyObject *args) { return NULL; if (SetProcessAffinityMask(hProcess, mask) == 0) { - PyErr_SetFromWindowsErr(0); + psutil_oserror(); CloseHandle(hProcess); return NULL; } @@ -1014,13 +1031,13 @@ psutil_proc_is_suspended(PyObject *self, PyObject *args) { PSYSTEM_PROCESS_INFORMATION process; PVOID buffer; - if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) + if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) return NULL; if (psutil_get_proc_info(pid, &process, &buffer) != 0) return NULL; for (i = 0; i < process->NumberOfThreads; i++) { - if (process->Threads[i].ThreadState != Waiting || - process->Threads[i].WaitReason != Suspended) + if (process->Threads[i].ThreadState != Waiting + || process->Threads[i].WaitReason != Suspended) { free(buffer); Py_RETURN_FALSE; @@ -1040,13 +1057,13 @@ psutil_proc_num_handles(PyObject *self, PyObject *args) { HANDLE hProcess; DWORD handleCount; - if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) + if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) return NULL; hProcess = psutil_handle_from_pid(pid, PROCESS_QUERY_LIMITED_INFORMATION); if (NULL == hProcess) return NULL; - if (! GetProcessHandleCount(hProcess, &handleCount)) { - PyErr_SetFromWindowsErr(0); + if (!GetProcessHandleCount(hProcess, &handleCount)) { + psutil_oserror(); CloseHandle(hProcess); return NULL; } @@ -1055,7 +1072,8 @@ psutil_proc_num_handles(PyObject *self, PyObject *args) { } -static char *get_region_protection_string(ULONG protection) { +static char * +get_region_protection_string(ULONG protection) { switch (protection & 0xff) { case PAGE_NOACCESS: return ""; @@ -1098,7 +1116,7 @@ psutil_proc_memory_maps(PyObject *self, PyObject *args) { if (py_retlist == NULL) return NULL; - if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) + if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) goto error; hProcess = psutil_handle_from_pid(pid, access); if (NULL == hProcess) @@ -1107,31 +1125,35 @@ psutil_proc_memory_maps(PyObject *self, PyObject *args) { maxAddr = PSUTIL_SYSTEM_INFO.lpMaximumApplicationAddress; baseAddress = NULL; - while (VirtualQueryEx(hProcess, baseAddress, &basicInfo, - sizeof(MEMORY_BASIC_INFORMATION))) + while (VirtualQueryEx( + hProcess, baseAddress, &basicInfo, sizeof(MEMORY_BASIC_INFORMATION) + )) { py_tuple = NULL; if (baseAddress > maxAddr) break; - if (GetMappedFileNameW(hProcess, baseAddress, mappedFileName, - sizeof(mappedFileName))) + if (GetMappedFileNameW( + hProcess, baseAddress, mappedFileName, sizeof(mappedFileName) + )) { - py_str = PyUnicode_FromWideChar(mappedFileName, - wcslen(mappedFileName)); + py_str = PyUnicode_FromWideChar( + mappedFileName, wcslen(mappedFileName) + ); if (py_str == NULL) goto error; #ifdef _WIN64 - py_tuple = Py_BuildValue( - "(KsOI)", - (unsigned long long)baseAddress, + py_tuple = Py_BuildValue( + "(KsOI)", + (unsigned long long)baseAddress, #else - py_tuple = Py_BuildValue( - "(ksOI)", - (unsigned long)baseAddress, + py_tuple = Py_BuildValue( + "(ksOI)", + (unsigned long)baseAddress, #endif - get_region_protection_string(basicInfo.Protect), - py_str, - basicInfo.RegionSize); + get_region_protection_string(basicInfo.Protect), + py_str, + basicInfo.RegionSize + ); if (!py_tuple) goto error; @@ -1172,7 +1194,7 @@ psutil_ppid_map(PyObject *self, PyObject *args) { return NULL; handle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (handle == INVALID_HANDLE_VALUE) { - PyErr_SetFromWindowsErr(0); + psutil_oserror(); Py_DECREF(py_retdict); return NULL; } diff --git a/contrib/python/psutil/py3/psutil/arch/windows/proc_handles.c b/contrib/python/psutil/py3/psutil/arch/windows/proc_handles.c index 471944c6438..ab996938efd 100644 --- a/contrib/python/psutil/py3/psutil/arch/windows/proc_handles.c +++ b/contrib/python/psutil/py3/psutil/arch/windows/proc_handles.c @@ -45,20 +45,18 @@ psutil_enum_handles(PSYSTEM_HANDLE_INFORMATION_EX *handles) { } while ((status = NtQuerySystemInformation( - SystemExtendedHandleInformation, - buffer, - bufferSize, - NULL - )) == STATUS_INFO_LENGTH_MISMATCH) + SystemExtendedHandleInformation, buffer, bufferSize, NULL + )) + == STATUS_INFO_LENGTH_MISMATCH) { FREE(buffer); bufferSize *= 2; // Fail if we're resizing the buffer to something very large. if (bufferSize > 256 * 1024 * 1024) { - PyErr_SetString( - PyExc_RuntimeError, - "SystemExtendedHandleInformation buffer too big"); + psutil_runtime_error( + "SystemExtendedHandleInformation buffer too big" + ); return -1; } @@ -69,7 +67,7 @@ psutil_enum_handles(PSYSTEM_HANDLE_INFORMATION_EX *handles) { } } - if (! NT_SUCCESS(status)) { + if (!NT_SUCCESS(status)) { psutil_SetFromNTStatusErr(status, "NtQuerySystemInformation"); FREE(buffer); return -1; @@ -82,7 +80,7 @@ psutil_enum_handles(PSYSTEM_HANDLE_INFORMATION_EX *handles) { static int psutil_get_filename(LPVOID lpvParam) { - HANDLE hFile = *((HANDLE*)lpvParam); + HANDLE hFile = *((HANDLE *)lpvParam); NTSTATUS status; ULONG bufferSize; ULONG attempts = 8; @@ -111,10 +109,10 @@ psutil_get_filename(LPVOID lpvParam) { globalFileName, bufferSize, &bufferSize - ); - if (status == STATUS_BUFFER_OVERFLOW || - status == STATUS_INFO_LENGTH_MISMATCH || - status == STATUS_BUFFER_TOO_SMALL) + ); + if (status == STATUS_BUFFER_OVERFLOW + || status == STATUS_INFO_LENGTH_MISMATCH + || status == STATUS_BUFFER_TOO_SMALL) { FREE(globalFileName); globalFileName = MALLOC_ZERO(bufferSize); @@ -128,7 +126,7 @@ psutil_get_filename(LPVOID lpvParam) { } } while (--attempts); - if (! NT_SUCCESS(status)) { + if (!NT_SUCCESS(status)) { psutil_SetFromNTStatusErr(status, "NtQuerySystemInformation"); FREE(globalFileName); globalFileName = NULL; @@ -153,9 +151,10 @@ psutil_threaded_get_filename(HANDLE hFile) { DWORD threadRetValue; hThread = CreateThread( - NULL, 0, (LPTHREAD_START_ROUTINE)psutil_get_filename, &hFile, 0, NULL); + NULL, 0, (LPTHREAD_START_ROUTINE)psutil_get_filename, &hFile, 0, NULL + ); if (hThread == NULL) { - psutil_PyErr_SetFromOSErrnoWithSyscall("CreateThread"); + psutil_oserror_wsyscall("CreateThread"); return -1; } @@ -165,9 +164,10 @@ psutil_threaded_get_filename(HANDLE hFile) { // If the thread hangs, kill it and cleanup. if (dwWait == WAIT_TIMEOUT) { psutil_debug( - "get handle name thread timed out after %i ms", THREAD_TIMEOUT); + "get handle name thread timed out after %i ms", THREAD_TIMEOUT + ); if (TerminateThread(hThread, 0) == 0) { - psutil_PyErr_SetFromOSErrnoWithSyscall("TerminateThread"); + psutil_oserror_wsyscall("TerminateThread"); CloseHandle(hThread); return -1; } @@ -178,20 +178,20 @@ psutil_threaded_get_filename(HANDLE hFile) { if (dwWait == WAIT_FAILED) { psutil_debug("WaitForSingleObject -> WAIT_FAILED"); if (TerminateThread(hThread, 0) == 0) { - psutil_PyErr_SetFromOSErrnoWithSyscall( + psutil_oserror_wsyscall( "WaitForSingleObject -> WAIT_FAILED -> TerminateThread" ); CloseHandle(hThread); return -1; } - psutil_PyErr_SetFromOSErrnoWithSyscall("WaitForSingleObject"); + psutil_oserror_wsyscall("WaitForSingleObject"); CloseHandle(hThread); return -1; } if (GetExitCodeThread(hThread, &threadRetValue) == 0) { if (TerminateThread(hThread, 0) == 0) { - psutil_PyErr_SetFromOSErrnoWithSyscall( + psutil_oserror_wsyscall( "GetExitCodeThread (failed) -> TerminateThread" ); CloseHandle(hThread); @@ -199,7 +199,7 @@ psutil_threaded_get_filename(HANDLE hFile) { } CloseHandle(hThread); - psutil_PyErr_SetFromOSErrnoWithSyscall("GetExitCodeThread"); + psutil_oserror_wsyscall("GetExitCodeThread"); return -1; } CloseHandle(hThread); @@ -209,13 +209,14 @@ psutil_threaded_get_filename(HANDLE hFile) { PyObject * psutil_get_open_files(DWORD dwPid, HANDLE hProcess) { - PSYSTEM_HANDLE_INFORMATION_EX handlesList = NULL; - PSYSTEM_HANDLE_TABLE_ENTRY_INFO_EX hHandle = NULL; - HANDLE hFile = NULL; - ULONG i = 0; - BOOLEAN errorOccurred = FALSE; - PyObject* py_path = NULL; - PyObject* py_retlist = PyList_New(0);; + PSYSTEM_HANDLE_INFORMATION_EX handlesList = NULL; + PSYSTEM_HANDLE_TABLE_ENTRY_INFO_EX hHandle = NULL; + HANDLE hFile = NULL; + ULONG i = 0; + BOOLEAN errorOccurred = FALSE; + PyObject *py_path = NULL; + PyObject *py_retlist = PyList_New(0); + ; if (!py_retlist) return NULL; @@ -231,14 +232,15 @@ psutil_get_open_files(DWORD dwPid, HANDLE hProcess) { hHandle = &handlesList->Handles[i]; if ((ULONG_PTR)hHandle->UniqueProcessId != dwPid) continue; - if (! DuplicateHandle( + if (!DuplicateHandle( hProcess, hHandle->HandleValue, GetCurrentProcess(), &hFile, 0, TRUE, - DUPLICATE_SAME_ACCESS)) + DUPLICATE_SAME_ACCESS + )) { // Will fail if not a regular file; just skip it. continue; @@ -249,9 +251,10 @@ psutil_get_open_files(DWORD dwPid, HANDLE hProcess) { goto error; if ((globalFileName != NULL) && (globalFileName->Length > 0)) { - py_path = PyUnicode_FromWideChar(globalFileName->Buffer, - wcslen(globalFileName->Buffer)); - if (! py_path) + py_path = PyUnicode_FromWideChar( + globalFileName->Buffer, wcslen(globalFileName->Buffer) + ); + if (!py_path) goto error; if (PyList_Append(py_retlist, py_path)) goto error; diff --git a/contrib/python/psutil/py3/psutil/arch/windows/proc_info.c b/contrib/python/psutil/py3/psutil/arch/windows/proc_info.c index 75bd17c7bb2..6dca9cd2ee5 100644 --- a/contrib/python/psutil/py3/psutil/arch/windows/proc_info.c +++ b/contrib/python/psutil/py3/psutil/arch/windows/proc_info.c @@ -14,20 +14,25 @@ #ifndef _WIN64 -typedef NTSTATUS (NTAPI *__NtQueryInformationProcess)( +typedef NTSTATUS(NTAPI *__NtQueryInformationProcess)( HANDLE ProcessHandle, DWORD ProcessInformationClass, PVOID ProcessInformation, DWORD ProcessInformationLength, - PDWORD ReturnLength); + PDWORD ReturnLength +); #endif -#define PSUTIL_FIRST_PROCESS(Processes) ( \ - (PSYSTEM_PROCESS_INFORMATION)(Processes)) -#define PSUTIL_NEXT_PROCESS(Process) ( \ - ((PSYSTEM_PROCESS_INFORMATION)(Process))->NextEntryOffset ? \ - (PSYSTEM_PROCESS_INFORMATION)((PCHAR)(Process) + \ - ((PSYSTEM_PROCESS_INFORMATION)(Process))->NextEntryOffset) : NULL) +#define PSUTIL_FIRST_PROCESS(Processes) \ + ((PSYSTEM_PROCESS_INFORMATION)(Processes)) + +#define PSUTIL_NEXT_PROCESS(Process) \ + (((PSYSTEM_PROCESS_INFORMATION)(Process))->NextEntryOffset \ + ? (PSYSTEM_PROCESS_INFORMATION)((PCHAR)(Process) \ + + ((PSYSTEM_PROCESS_INFORMATION)(Process \ + )) \ + ->NextEntryOffset) \ + : NULL) /* @@ -39,11 +44,11 @@ psutil_get_process_region_size(HANDLE hProcess, LPCVOID src, SIZE_T *psize) { MEMORY_BASIC_INFORMATION info; if (!VirtualQueryEx(hProcess, src, &info, sizeof(info))) { - psutil_PyErr_SetFromOSErrnoWithSyscall("VirtualQueryEx"); + psutil_oserror_wsyscall("VirtualQueryEx"); return -1; } - *psize = info.RegionSize - ((char*)src - (char*)info.BaseAddress); + *psize = info.RegionSize - ((char *)src - (char *)info.BaseAddress); return 0; } @@ -56,22 +61,22 @@ enum psutil_process_data_kind { static void -psutil_convert_winerr(ULONG err, char* syscall) { +psutil_convert_winerr(ULONG err, char *syscall) { char fullmsg[8192]; - if (err == ERROR_NOACCESS) { - sprintf(fullmsg, "%s -> ERROR_NOACCESS", syscall); + if (err == ERROR_NOACCESS) { + str_format(fullmsg, sizeof(fullmsg), "%s -> ERROR_NOACCESS", syscall); psutil_debug(fullmsg); - AccessDenied(fullmsg); + psutil_oserror_ad(fullmsg); } else { - psutil_PyErr_SetFromOSErrnoWithSyscall(syscall); + psutil_oserror_wsyscall(syscall); } } static void -psutil_convert_ntstatus_err(NTSTATUS status, char* syscall) { +psutil_convert_ntstatus_err(NTSTATUS status, char *syscall) { ULONG err; if (NT_NTWIN32(status)) @@ -83,17 +88,19 @@ psutil_convert_ntstatus_err(NTSTATUS status, char* syscall) { static void -psutil_giveup_with_ad(NTSTATUS status, char* syscall) { +psutil_giveup_with_ad(NTSTATUS status, char *syscall) { ULONG err; - char fullmsg[8192]; + char fullmsg[2048]; if (NT_NTWIN32(status)) err = WIN32_FROM_NTSTATUS(status); else err = RtlNtStatusToDosErrorNoTeb(status); - sprintf(fullmsg, "%s -> %lu (%s)", syscall, err, strerror(err)); + str_format( + fullmsg, sizeof(fullmsg), "%s -> %lu (%s)", syscall, err, strerror(err) + ); psutil_debug(fullmsg); - AccessDenied(fullmsg); + psutil_oserror_ad(fullmsg); } @@ -105,10 +112,9 @@ psutil_giveup_with_ad(NTSTATUS status, char* syscall) { * -1 is returned, and an appropriate Python exception is set. */ static int -psutil_get_process_data(DWORD pid, - enum psutil_process_data_kind kind, - WCHAR **pdata, - SIZE_T *psize) { +psutil_get_process_data( + DWORD pid, enum psutil_process_data_kind kind, WCHAR **pdata, SIZE_T *psize +) { /* This function is quite complex because there are several cases to be considered: @@ -157,15 +163,13 @@ psutil_get_process_data(DWORD pid, /* 64 bit case. Check if the target is a 32 bit process running in WoW64 * mode. */ status = NtQueryInformationProcess( - hProcess, - ProcessWow64Information, - &ppeb32, - sizeof(LPVOID), - NULL); + hProcess, ProcessWow64Information, &ppeb32, sizeof(LPVOID), NULL + ); if (!NT_SUCCESS(status)) { psutil_SetFromNTStatusErr( - status, "NtQueryInformationProcess(ProcessWow64Information)"); + status, "NtQueryInformationProcess(ProcessWow64Information)" + ); goto error; } @@ -175,7 +179,8 @@ psutil_get_process_data(DWORD pid, RTL_USER_PROCESS_PARAMETERS32 procParameters32; // read PEB - if (!ReadProcessMemory(hProcess, ppeb32, &peb32, sizeof(peb32), NULL)) { + if (!ReadProcessMemory(hProcess, ppeb32, &peb32, sizeof(peb32), NULL)) + { // May fail with ERROR_PARTIAL_COPY, see: // https://github.com/giampaolo/psutil/issues/875 psutil_convert_winerr(GetLastError(), "ReadProcessMemory"); @@ -183,11 +188,13 @@ psutil_get_process_data(DWORD pid, } // read process parameters - if (!ReadProcessMemory(hProcess, - UlongToPtr(peb32.ProcessParameters), - &procParameters32, - sizeof(procParameters32), - NULL)) + if (!ReadProcessMemory( + hProcess, + UlongToPtr(peb32.ProcessParameters), + &procParameters32, + sizeof(procParameters32), + NULL + )) { // May fail with ERROR_PARTIAL_COPY, see: // https://github.com/giampaolo/psutil/issues/875 @@ -208,7 +215,8 @@ psutil_get_process_data(DWORD pid, src = UlongToPtr(procParameters32.env); break; } - } else + } + else #else // #ifdef _WIN64 // 32 bit process. In here we may run into a lot of errors, e.g.: // * [Error 0] The operation completed successfully @@ -222,9 +230,10 @@ psutil_get_process_data(DWORD pid, // in case of any error from NtWow64* APIs we raise AccessDenied. // 32 bit case. Check if the target is also 32 bit. - if (!IsWow64Process(GetCurrentProcess(), &weAreWow64) || - !IsWow64Process(hProcess, &theyAreWow64)) { - psutil_PyErr_SetFromOSErrnoWithSyscall("IsWow64Process"); + if (!IsWow64Process(GetCurrentProcess(), &weAreWow64) + || !IsWow64Process(hProcess, &theyAreWow64)) + { + psutil_oserror_wsyscall("IsWow64Process"); goto error; } @@ -235,32 +244,33 @@ psutil_get_process_data(DWORD pid, RTL_USER_PROCESS_PARAMETERS64 procParameters64; if (NtWow64QueryInformationProcess64 == NULL) { - NtWow64QueryInformationProcess64 = \ - psutil_GetProcAddressFromLib( - "ntdll.dll", "NtWow64QueryInformationProcess64"); + NtWow64QueryInformationProcess64 = psutil_GetProcAddressFromLib( + "ntdll.dll", "NtWow64QueryInformationProcess64" + ); if (NtWow64QueryInformationProcess64 == NULL) { PyErr_Clear(); - AccessDenied("can't query 64-bit process in 32-bit-WoW mode"); + psutil_oserror_ad( + "can't query 64-bit process in 32-bit-WoW mode" + ); goto error; } } if (NtWow64ReadVirtualMemory64 == NULL) { - NtWow64ReadVirtualMemory64 = \ - psutil_GetProcAddressFromLib( - "ntdll.dll", "NtWow64ReadVirtualMemory64"); + NtWow64ReadVirtualMemory64 = psutil_GetProcAddressFromLib( + "ntdll.dll", "NtWow64ReadVirtualMemory64" + ); if (NtWow64ReadVirtualMemory64 == NULL) { PyErr_Clear(); - AccessDenied("can't query 64-bit process in 32-bit-WoW mode"); + psutil_oserror_ad( + "can't query 64-bit process in 32-bit-WoW mode" + ); goto error; } } status = NtWow64QueryInformationProcess64( - hProcess, - ProcessBasicInformation, - &pbi64, - sizeof(pbi64), - NULL); + hProcess, ProcessBasicInformation, &pbi64, sizeof(pbi64), NULL + ); if (!NT_SUCCESS(status)) { /* psutil_convert_ntstatus_err( @@ -269,43 +279,42 @@ psutil_get_process_data(DWORD pid, */ psutil_giveup_with_ad( status, - "NtWow64QueryInformationProcess64(ProcessBasicInformation)"); + "NtWow64QueryInformationProcess64(ProcessBasicInformation)" + ); goto error; } // read peb status = NtWow64ReadVirtualMemory64( - hProcess, - pbi64.PebBaseAddress, - &peb64, - sizeof(peb64), - NULL); + hProcess, pbi64.PebBaseAddress, &peb64, sizeof(peb64), NULL + ); if (!NT_SUCCESS(status)) { /* psutil_convert_ntstatus_err( status, "NtWow64ReadVirtualMemory64(pbi64.PebBaseAddress)"); */ psutil_giveup_with_ad( - status, - "NtWow64ReadVirtualMemory64(pbi64.PebBaseAddress)"); + status, "NtWow64ReadVirtualMemory64(pbi64.PebBaseAddress)" + ); goto error; } // read process parameters status = NtWow64ReadVirtualMemory64( - hProcess, - peb64.ProcessParameters, - &procParameters64, - sizeof(procParameters64), - NULL); + hProcess, + peb64.ProcessParameters, + &procParameters64, + sizeof(procParameters64), + NULL + ); if (!NT_SUCCESS(status)) { /* psutil_convert_ntstatus_err( status, "NtWow64ReadVirtualMemory64(peb64.ProcessParameters)"); */ psutil_giveup_with_ad( - status, - "NtWow64ReadVirtualMemory64(peb64.ProcessParameters)"); + status, "NtWow64ReadVirtualMemory64(peb64.ProcessParameters)" + ); goto error; } @@ -322,7 +331,8 @@ psutil_get_process_data(DWORD pid, src64 = procParameters64.env; break; } - } else + } + else #endif /* Target process is of the same bitness as us. */ { @@ -331,25 +341,21 @@ psutil_get_process_data(DWORD pid, RTL_USER_PROCESS_PARAMETERS_ procParameters; status = NtQueryInformationProcess( - hProcess, - ProcessBasicInformation, - &pbi, - sizeof(pbi), - NULL); + hProcess, ProcessBasicInformation, &pbi, sizeof(pbi), NULL + ); if (!NT_SUCCESS(status)) { psutil_SetFromNTStatusErr( - status, "NtQueryInformationProcess(ProcessBasicInformation)"); + status, "NtQueryInformationProcess(ProcessBasicInformation)" + ); goto error; } // read peb - if (!ReadProcessMemory(hProcess, - pbi.PebBaseAddress, - &peb, - sizeof(peb), - NULL)) + if (!ReadProcessMemory( + hProcess, pbi.PebBaseAddress, &peb, sizeof(peb), NULL + )) { // May fail with ERROR_PARTIAL_COPY, see: // https://github.com/giampaolo/psutil/issues/875 @@ -358,11 +364,13 @@ psutil_get_process_data(DWORD pid, } // read process parameters - if (!ReadProcessMemory(hProcess, - peb.ProcessParameters, - &procParameters, - sizeof(procParameters), - NULL)) + if (!ReadProcessMemory( + hProcess, + peb.ProcessParameters, + &procParameters, + sizeof(procParameters), + NULL + )) { // May fail with ERROR_PARTIAL_COPY, see: // https://github.com/giampaolo/psutil/issues/875 @@ -388,12 +396,12 @@ psutil_get_process_data(DWORD pid, if (kind == KIND_ENVIRON) { #ifndef _WIN64 if (weAreWow64 && !theyAreWow64) { - AccessDenied("can't query 64-bit process in 32-bit-WoW mode"); + psutil_oserror_ad("can't query 64-bit process in 32-bit-WoW mode"); goto error; } else #endif - if (psutil_get_process_region_size(hProcess, src, &size) != 0) + if (psutil_get_process_region_size(hProcess, src, &size) != 0) goto error; } @@ -406,19 +414,19 @@ psutil_get_process_data(DWORD pid, #ifndef _WIN64 if (weAreWow64 && !theyAreWow64) { status = NtWow64ReadVirtualMemory64( - hProcess, - src64, - buffer, - size, - NULL); + hProcess, src64, buffer, size, NULL + ); if (!NT_SUCCESS(status)) { - // psutil_convert_ntstatus_err(status, "NtWow64ReadVirtualMemory64"); + // psutil_convert_ntstatus_err(status, + // "NtWow64ReadVirtualMemory64"); psutil_giveup_with_ad(status, "NtWow64ReadVirtualMemory64"); goto error; } - } else + } + else #endif - if (!ReadProcessMemory(hProcess, src, buffer, size, NULL)) { + if (!ReadProcessMemory(hProcess, src, buffer, size, NULL)) + { // May fail with ERROR_PARTIAL_COPY, see: // https://github.com/giampaolo/psutil/issues/875 psutil_convert_winerr(GetLastError(), "ReadProcessMemory"); @@ -451,15 +459,14 @@ psutil_cmdline_query_proc(DWORD pid, WCHAR **pdata, SIZE_T *psize) { HANDLE hProcess = NULL; ULONG bufLen = 0; NTSTATUS status; - char * buffer = NULL; - WCHAR * bufWchar = NULL; + char *buffer = NULL; + WCHAR *bufWchar = NULL; PUNICODE_STRING tmp = NULL; size_t size; int ProcessCommandLineInformation = 60; if (PSUTIL_WINVER < PSUTIL_WINDOWS_8_1) { - PyErr_SetString( - PyExc_RuntimeError, "requires Windows 8.1+"); + psutil_runtime_error("requires Windows 8.1+"); goto error; } @@ -469,24 +476,24 @@ psutil_cmdline_query_proc(DWORD pid, WCHAR **pdata, SIZE_T *psize) { // get the right buf size status = NtQueryInformationProcess( - hProcess, - ProcessCommandLineInformation, - NULL, - 0, - &bufLen); + hProcess, ProcessCommandLineInformation, NULL, 0, &bufLen + ); // https://github.com/giampaolo/psutil/issues/1501 if (status == STATUS_NOT_FOUND) { - AccessDenied("NtQueryInformationProcess(ProcessBasicInformation) -> " - "STATUS_NOT_FOUND"); + psutil_oserror_ad( + "NtQueryInformationProcess(ProcessBasicInformation) -> " + "STATUS_NOT_FOUND" + ); goto error; } - if (status != STATUS_BUFFER_OVERFLOW && \ - status != STATUS_BUFFER_TOO_SMALL && \ - status != STATUS_INFO_LENGTH_MISMATCH) { + if (status != STATUS_BUFFER_OVERFLOW && status != STATUS_BUFFER_TOO_SMALL + && status != STATUS_INFO_LENGTH_MISMATCH) + { psutil_SetFromNTStatusErr( - status, "NtQueryInformationProcess(ProcessBasicInformation)"); + status, "NtQueryInformationProcess(ProcessBasicInformation)" + ); goto error; } @@ -499,15 +506,12 @@ psutil_cmdline_query_proc(DWORD pid, WCHAR **pdata, SIZE_T *psize) { // get the cmdline status = NtQueryInformationProcess( - hProcess, - ProcessCommandLineInformation, - buffer, - bufLen, - &bufLen + hProcess, ProcessCommandLineInformation, buffer, bufLen, &bufLen ); if (!NT_SUCCESS(status)) { psutil_SetFromNTStatusErr( - status, "NtQueryInformationProcess(ProcessCommandLineInformation)"); + status, "NtQueryInformationProcess(ProcessCommandLineInformation)" + ); goto error; } @@ -557,8 +561,9 @@ psutil_proc_cmdline(PyObject *self, PyObject *args, PyObject *kwdict) { PyObject *py_unicode = NULL; static char *keywords[] = {"pid", "use_peb", NULL}; - if (! PyArg_ParseTupleAndKeywords(args, kwdict, _Py_PARSE_PID "|O", - keywords, &pid, &py_usepeb)) + if (!PyArg_ParseTupleAndKeywords( + args, kwdict, _Py_PARSE_PID "|O", keywords, &pid, &py_usepeb + )) { return NULL; } @@ -567,7 +572,7 @@ psutil_proc_cmdline(PyObject *self, PyObject *args, PyObject *kwdict) { pid_return = psutil_pid_is_running(pid); if (pid_return == 0) - return NoSuchProcess("psutil_pid_is_running -> 0"); + return psutil_oserror_nsp("psutil_pid_is_running -> 0"); if (pid_return == -1) return NULL; @@ -592,7 +597,7 @@ psutil_proc_cmdline(PyObject *self, PyObject *args, PyObject *kwdict) { // attempt to parse the command line using Win32 API szArglist = CommandLineToArgvW(data, &nArgs); if (szArglist == NULL) { - psutil_PyErr_SetFromOSErrnoWithSyscall("CommandLineToArgvW"); + psutil_oserror_wsyscall("CommandLineToArgvW"); goto error; } @@ -602,8 +607,9 @@ psutil_proc_cmdline(PyObject *self, PyObject *args, PyObject *kwdict) { if (py_retlist == NULL) goto error; for (i = 0; i < nArgs; i++) { - py_unicode = PyUnicode_FromWideChar(szArglist[i], - wcslen(szArglist[i])); + py_unicode = PyUnicode_FromWideChar( + szArglist[i], wcslen(szArglist[i]) + ); if (py_unicode == NULL) goto error; PyList_SetItem(py_retlist, i, py_unicode); @@ -633,12 +639,12 @@ psutil_proc_cwd(PyObject *self, PyObject *args) { SIZE_T size; int pid_return; - if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) + if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) return NULL; pid_return = psutil_pid_is_running(pid); if (pid_return == 0) - return NoSuchProcess("psutil_pid_is_running -> 0"); + return psutil_oserror_nsp("psutil_pid_is_running -> 0"); if (pid_return == -1) return NULL; @@ -668,14 +674,14 @@ psutil_proc_environ(PyObject *self, PyObject *args) { int pid_return; PyObject *ret = NULL; - if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) + if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) return NULL; if ((pid == 0) || (pid == 4)) return Py_BuildValue("s", ""); pid_return = psutil_pid_is_running(pid); if (pid_return == 0) - return NoSuchProcess("psutil_pid_is_running -> 0"); + return psutil_oserror_nsp("psutil_pid_is_running -> 0"); if (pid_return == -1) return NULL; @@ -702,8 +708,9 @@ out: * On success return 0, else -1 with Python exception already set. */ int -psutil_get_proc_info(DWORD pid, PSYSTEM_PROCESS_INFORMATION *retProcess, - PVOID *retBuffer) { +psutil_get_proc_info( + DWORD pid, PSYSTEM_PROCESS_INFORMATION *retProcess, PVOID *retBuffer +) { static ULONG initialBufferSize = 0x4000; NTSTATUS status; PVOID buffer; @@ -719,12 +726,10 @@ psutil_get_proc_info(DWORD pid, PSYSTEM_PROCESS_INFORMATION *retProcess, while (TRUE) { status = NtQuerySystemInformation( - SystemProcessInformation, - buffer, - bufferSize, - &bufferSize); - if (status == STATUS_BUFFER_TOO_SMALL || - status == STATUS_INFO_LENGTH_MISMATCH) + SystemProcessInformation, buffer, bufferSize, &bufferSize + ); + if (status == STATUS_BUFFER_TOO_SMALL + || status == STATUS_INFO_LENGTH_MISMATCH) { free(buffer); buffer = malloc(bufferSize); @@ -738,9 +743,10 @@ psutil_get_proc_info(DWORD pid, PSYSTEM_PROCESS_INFORMATION *retProcess, } } - if (! NT_SUCCESS(status)) { + if (!NT_SUCCESS(status)) { psutil_SetFromNTStatusErr( - status, "NtQuerySystemInformation(SystemProcessInformation)"); + status, "NtQuerySystemInformation(SystemProcessInformation)" + ); goto error; } @@ -756,7 +762,7 @@ psutil_get_proc_info(DWORD pid, PSYSTEM_PROCESS_INFORMATION *retProcess, } } while ((process = PSUTIL_NEXT_PROCESS(process))); - NoSuchProcess("NtQuerySystemInformation (no PID found)"); + psutil_oserror_nsp("NtQuerySystemInformation (no PID found)"); goto error; error: @@ -792,17 +798,17 @@ psutil_proc_info(PyObject *self, PyObject *args) { double create_time; PyObject *py_retlist; - if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) + if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid)) return NULL; if (psutil_get_proc_info(pid, &process, &buffer) != 0) return NULL; for (i = 0; i < process->NumberOfThreads; i++) ctx_switches += process->Threads[i].ContextSwitches; - user_time = (double)process->UserTime.HighPart * HI_T + \ - (double)process->UserTime.LowPart * LO_T; - kernel_time = (double)process->KernelTime.HighPart * HI_T + \ - (double)process->KernelTime.LowPart * LO_T; + user_time = (double)process->UserTime.HighPart * HI_T + + (double)process->UserTime.LowPart * LO_T; + kernel_time = (double)process->KernelTime.HighPart * HI_T + + (double)process->KernelTime.LowPart * LO_T; // Convert the LARGE_INTEGER union to a Unix time. // It's the best I could find by googling and borrowing code here @@ -817,34 +823,36 @@ psutil_proc_info(PyObject *self, PyObject *args) { py_retlist = Py_BuildValue( #if defined(_WIN64) - "kkdddkKKKKKK" "kKKKKKKKKK", + "kkdddkKKKKKK" + "kKKKKKKKKK", #else - "kkdddkKKKKKK" "kIIIIIIIII", + "kkdddkKKKKKK" + "kIIIIIIIII", #endif - process->HandleCount, // num handles - ctx_switches, // num ctx switches - user_time, // cpu user time - kernel_time, // cpu kernel time - create_time, // create time - process->NumberOfThreads, // num threads + process->HandleCount, // num handles + ctx_switches, // num ctx switches + user_time, // cpu user time + kernel_time, // cpu kernel time + create_time, // create time + process->NumberOfThreads, // num threads // IO counters - process->ReadOperationCount.QuadPart, // io rcount + process->ReadOperationCount.QuadPart, // io rcount process->WriteOperationCount.QuadPart, // io wcount - process->ReadTransferCount.QuadPart, // io rbytes - process->WriteTransferCount.QuadPart, // io wbytes + process->ReadTransferCount.QuadPart, // io rbytes + process->WriteTransferCount.QuadPart, // io wbytes process->OtherOperationCount.QuadPart, // io others count - process->OtherTransferCount.QuadPart, // io others bytes + process->OtherTransferCount.QuadPart, // io others bytes // memory - process->PageFaultCount, // num page faults - process->PeakWorkingSetSize, // peak wset - process->WorkingSetSize, // wset - process->QuotaPeakPagedPoolUsage, // peak paged pool - process->QuotaPagedPoolUsage, // paged pool - process->QuotaPeakNonPagedPoolUsage, // peak non paged pool - process->QuotaNonPagedPoolUsage, // non paged pool - process->PagefileUsage, // pagefile - process->PeakPagefileUsage, // peak pagefile - process->PrivatePageCount // private + process->PageFaultCount, // num page faults + process->PeakWorkingSetSize, // peak wset + process->WorkingSetSize, // wset + process->QuotaPeakPagedPoolUsage, // peak paged pool + process->QuotaPagedPoolUsage, // paged pool + process->QuotaPeakNonPagedPoolUsage, // peak non paged pool + process->QuotaNonPagedPoolUsage, // non paged pool + process->PagefileUsage, // pagefile + process->PeakPagefileUsage, // peak pagefile + process->PrivatePageCount // private ); free(buffer); diff --git a/contrib/python/psutil/py3/psutil/arch/windows/proc_utils.c b/contrib/python/psutil/py3/psutil/arch/windows/proc_utils.c index d272e91251c..43ad7b6531a 100644 --- a/contrib/python/psutil/py3/psutil/arch/windows/proc_utils.c +++ b/contrib/python/psutil/py3/psutil/arch/windows/proc_utils.c @@ -13,7 +13,6 @@ #include "../../arch/all/init.h" - // Return 1 if PID exists, 0 if not, -1 on error. int psutil_pid_in_pids(DWORD pid) { @@ -47,7 +46,7 @@ psutil_check_phandle(HANDLE hProcess, DWORD pid, int check_exit_code) { if (GetLastError() == ERROR_INVALID_PARAMETER) { // Yeah, this is the actual error code in case of // "no such process". - NoSuchProcess("OpenProcess -> ERROR_INVALID_PARAMETER"); + psutil_oserror_nsp("OpenProcess -> ERROR_INVALID_PARAMETER"); return NULL; } if (GetLastError() == ERROR_SUCCESS) { @@ -55,15 +54,15 @@ psutil_check_phandle(HANDLE hProcess, DWORD pid, int check_exit_code) { // https://github.com/giampaolo/psutil/issues/1877 if (psutil_pid_in_pids(pid) == 1) { psutil_debug("OpenProcess -> ERROR_SUCCESS turned into AD"); - AccessDenied("OpenProcess -> ERROR_SUCCESS"); + psutil_oserror_ad("OpenProcess -> ERROR_SUCCESS"); } else { psutil_debug("OpenProcess -> ERROR_SUCCESS turned into NSP"); - NoSuchProcess("OpenProcess -> ERROR_SUCCESS"); + psutil_oserror_nsp("OpenProcess -> ERROR_SUCCESS"); } return NULL; } - psutil_PyErr_SetFromOSErrnoWithSyscall("OpenProcess"); + psutil_oserror_wsyscall("OpenProcess"); return NULL; } @@ -80,7 +79,7 @@ psutil_check_phandle(HANDLE hProcess, DWORD pid, int check_exit_code) { return hProcess; } CloseHandle(hProcess); - NoSuchProcess("GetExitCodeProcess != STILL_ACTIVE"); + psutil_oserror_nsp("GetExitCodeProcess != STILL_ACTIVE"); return NULL; } @@ -89,7 +88,7 @@ psutil_check_phandle(HANDLE hProcess, DWORD pid, int check_exit_code) { SetLastError(0); return hProcess; } - psutil_PyErr_SetFromOSErrnoWithSyscall("GetExitCodeProcess"); + psutil_oserror_wsyscall("GetExitCodeProcess"); CloseHandle(hProcess); return NULL; } @@ -105,13 +104,13 @@ psutil_handle_from_pid(DWORD pid, DWORD access) { if (pid == 0) { // otherwise we'd get NoSuchProcess - return AccessDenied("automatically set for PID 0"); + return psutil_oserror_ad("automatically set for PID 0"); } hProcess = OpenProcess(access, FALSE, pid); if ((hProcess == NULL) && (GetLastError() == ERROR_ACCESS_DENIED)) { - psutil_PyErr_SetFromOSErrnoWithSyscall("OpenProcess"); + psutil_oserror_wsyscall("OpenProcess"); return NULL; } diff --git a/contrib/python/psutil/py3/psutil/arch/windows/security.c b/contrib/python/psutil/py3/psutil/arch/windows/security.c index 8beeb7cb8e2..b00483747b7 100644 --- a/contrib/python/psutil/py3/psutil/arch/windows/security.c +++ b/contrib/python/psutil/py3/psutil/arch/windows/security.c @@ -20,8 +20,8 @@ psutil_set_privilege(HANDLE hToken, LPCTSTR Privilege, BOOL bEnablePrivilege) { TOKEN_PRIVILEGES tpPrevious; DWORD cbPrevious = sizeof(TOKEN_PRIVILEGES); - if (! LookupPrivilegeValue(NULL, Privilege, &luid)) { - psutil_PyErr_SetFromOSErrnoWithSyscall("LookupPrivilegeValue"); + if (!LookupPrivilegeValue(NULL, Privilege, &luid)) { + psutil_oserror_wsyscall("LookupPrivilegeValue"); return -1; } @@ -30,15 +30,16 @@ psutil_set_privilege(HANDLE hToken, LPCTSTR Privilege, BOOL bEnablePrivilege) { tp.Privileges[0].Luid = luid; tp.Privileges[0].Attributes = 0; - if (! AdjustTokenPrivileges( + if (!AdjustTokenPrivileges( hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), &tpPrevious, - &cbPrevious)) + &cbPrevious + )) { - psutil_PyErr_SetFromOSErrnoWithSyscall("AdjustTokenPrivileges"); + psutil_oserror_wsyscall("AdjustTokenPrivileges"); return -1; } @@ -52,15 +53,11 @@ psutil_set_privilege(HANDLE hToken, LPCTSTR Privilege, BOOL bEnablePrivilege) { tpPrevious.Privileges[0].Attributes ^= (SE_PRIVILEGE_ENABLED & tpPrevious.Privileges[0].Attributes); - if (! AdjustTokenPrivileges( - hToken, - FALSE, - &tpPrevious, - cbPrevious, - NULL, - NULL)) + if (!AdjustTokenPrivileges( + hToken, FALSE, &tpPrevious, cbPrevious, NULL, NULL + )) { - psutil_PyErr_SetFromOSErrnoWithSyscall("AdjustTokenPrivileges"); + psutil_oserror_wsyscall("AdjustTokenPrivileges"); return -1; } @@ -73,24 +70,23 @@ psutil_get_thisproc_token() { HANDLE hToken = NULL; HANDLE me = GetCurrentProcess(); - if (! OpenProcessToken( - me, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) + if (!OpenProcessToken(me, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) { - if (GetLastError() == ERROR_NO_TOKEN) - { - if (! ImpersonateSelf(SecurityImpersonation)) { - psutil_PyErr_SetFromOSErrnoWithSyscall("ImpersonateSelf"); + if (GetLastError() == ERROR_NO_TOKEN) { + if (!ImpersonateSelf(SecurityImpersonation)) { + psutil_oserror_wsyscall("ImpersonateSelf"); return NULL; } - if (! OpenProcessToken( - me, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) + if (!OpenProcessToken( + me, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken + )) { - psutil_PyErr_SetFromOSErrnoWithSyscall("OpenProcessToken"); + psutil_oserror_wsyscall("OpenProcessToken"); return NULL; } } else { - psutil_PyErr_SetFromOSErrnoWithSyscall("OpenProcessToken"); + psutil_oserror_wsyscall("OpenProcessToken"); return NULL; } } @@ -101,7 +97,8 @@ psutil_get_thisproc_token() { static void psutil_print_err() { - char *msg = "psutil module couldn't set SE DEBUG mode for this process; " \ + char *msg = + "psutil module couldn't set SE DEBUG mode for this process; " "please file an issue against psutil bug tracker"; psutil_debug(msg); if (GetLastError() != ERROR_ACCESS_DENIED) diff --git a/contrib/python/psutil/py3/psutil/arch/windows/sensors.c b/contrib/python/psutil/py3/psutil/arch/windows/sensors.c index 8bb636c44e2..6b599659f0e 100644 --- a/contrib/python/psutil/py3/psutil/arch/windows/sensors.c +++ b/contrib/python/psutil/py3/psutil/arch/windows/sensors.c @@ -17,7 +17,7 @@ psutil_sensors_battery(PyObject *self, PyObject *args) { SYSTEM_POWER_STATUS sps; if (GetSystemPowerStatus(&sps) == 0) { - PyErr_SetFromWindowsErr(0); + psutil_oserror(); return NULL; } return Py_BuildValue( diff --git a/contrib/python/psutil/py3/psutil/arch/windows/services.c b/contrib/python/psutil/py3/psutil/arch/windows/services.c index 8ea99a8daff..59178c5363a 100644 --- a/contrib/python/psutil/py3/psutil/arch/windows/services.c +++ b/contrib/python/psutil/py3/psutil/arch/windows/services.c @@ -18,22 +18,20 @@ SC_HANDLE psutil_get_service_handler( - const wchar_t *service_name, - DWORD scm_access, - DWORD access) -{ + const wchar_t *service_name, DWORD scm_access, DWORD access +) { SC_HANDLE sc = NULL; SC_HANDLE hService = NULL; sc = OpenSCManagerW(NULL, NULL, scm_access); if (sc == NULL) { - psutil_PyErr_SetFromOSErrnoWithSyscall("OpenSCManagerW"); + psutil_oserror_wsyscall("OpenSCManagerW"); return NULL; } hService = OpenServiceW(sc, service_name, access); if (hService == NULL) { - psutil_PyErr_SetFromOSErrnoWithSyscall("OpenServiceW"); + psutil_oserror_wsyscall("OpenServiceW"); CloseServiceHandle(sc); return NULL; } @@ -47,11 +45,8 @@ psutil_get_service_handler( // returns NULL on error. On success, fills *service_name_out. static SC_HANDLE psutil_get_service_from_args( - PyObject *args, - DWORD scm_access, - DWORD access, - wchar_t **service_name_out) -{ + PyObject *args, DWORD scm_access, DWORD access, wchar_t **service_name_out +) { PyObject *py_service_name = NULL; wchar_t *service_name = NULL; Py_ssize_t wlen; @@ -77,7 +72,6 @@ psutil_get_service_from_args( } - // XXX - expose these as constants? static const char * get_startup_string(DWORD startup) { @@ -88,14 +82,12 @@ get_startup_string(DWORD startup) { return "manual"; case SERVICE_DISABLED: return "disabled"; -/* // drivers only (since we use EnumServicesStatusEx() with // SERVICE_WIN32) - case SERVICE_BOOT_START: - return "boot-start"; - case SERVICE_SYSTEM_START: - return "system-start"; -*/ + // case SERVICE_BOOT_START: + // return "boot-start"; + // case SERVICE_SYSTEM_START: + // return "system-start"; default: return "unknown"; } @@ -153,7 +145,7 @@ psutil_winservice_enumerate(PyObject *self, PyObject *args) { sc = OpenSCManager(NULL, NULL, SC_MANAGER_ENUMERATE_SERVICE); if (sc == NULL) { - psutil_PyErr_SetFromOSErrnoWithSyscall("OpenSCManager"); + psutil_oserror_wsyscall("OpenSCManager"); return NULL; } @@ -168,26 +160,29 @@ psutil_winservice_enumerate(PyObject *self, PyObject *args) { &bytesNeeded, &srvCount, &resumeHandle, - NULL); + NULL + ); if (ok || (GetLastError() != ERROR_MORE_DATA)) break; if (lpService) free(lpService); dwBytes = bytesNeeded; - lpService = (ENUM_SERVICE_STATUS_PROCESSW*)malloc(dwBytes); + lpService = (ENUM_SERVICE_STATUS_PROCESSW *)malloc(dwBytes); } for (i = 0; i < srvCount; i++) { // Get unicode name / display name. py_name = NULL; py_name = PyUnicode_FromWideChar( - lpService[i].lpServiceName, wcslen(lpService[i].lpServiceName)); + lpService[i].lpServiceName, wcslen(lpService[i].lpServiceName) + ); if (py_name == NULL) goto error; py_display_name = NULL; py_display_name = PyUnicode_FromWideChar( - lpService[i].lpDisplayName, wcslen(lpService[i].lpDisplayName)); + lpService[i].lpDisplayName, wcslen(lpService[i].lpDisplayName) + ); if (py_display_name == NULL) goto error; @@ -240,10 +235,7 @@ psutil_winservice_query_config(PyObject *self, PyObject *args) { PyObject *py_unicode_username = NULL; hService = psutil_get_service_from_args( - args, - SC_MANAGER_ENUMERATE_SERVICE, - SERVICE_QUERY_CONFIG, - &service_name + args, SC_MANAGER_ENUMERATE_SERVICE, SERVICE_QUERY_CONFIG, &service_name ); if (hService == NULL) return NULL; @@ -253,7 +245,7 @@ psutil_winservice_query_config(PyObject *self, PyObject *args) { bytesNeeded = 0; QueryServiceConfigW(hService, NULL, 0, &bytesNeeded); if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) { - psutil_PyErr_SetFromOSErrnoWithSyscall("QueryServiceConfigW"); + psutil_oserror_wsyscall("QueryServiceConfigW"); goto error; } @@ -265,25 +257,28 @@ psutil_winservice_query_config(PyObject *self, PyObject *args) { ok = QueryServiceConfigW(hService, qsc, bytesNeeded, &bytesNeeded); if (!ok) { - psutil_PyErr_SetFromOSErrnoWithSyscall("QueryServiceConfigW"); + psutil_oserror_wsyscall("QueryServiceConfigW"); goto error; } // Get unicode display name. py_unicode_display_name = PyUnicode_FromWideChar( - qsc->lpDisplayName, wcslen(qsc->lpDisplayName)); + qsc->lpDisplayName, wcslen(qsc->lpDisplayName) + ); if (py_unicode_display_name == NULL) goto error; // Get unicode bin path. py_unicode_binpath = PyUnicode_FromWideChar( - qsc->lpBinaryPathName, wcslen(qsc->lpBinaryPathName)); + qsc->lpBinaryPathName, wcslen(qsc->lpBinaryPathName) + ); if (py_unicode_binpath == NULL) goto error; // Get unicode username. py_unicode_username = PyUnicode_FromWideChar( - qsc->lpServiceStartName, wcslen(qsc->lpServiceStartName)); + qsc->lpServiceStartName, wcslen(qsc->lpServiceStartName) + ); if (py_unicode_username == NULL) goto error; @@ -337,18 +332,16 @@ psutil_winservice_query_status(PyObject *self, PyObject *args) { PyObject *py_tuple = NULL; hService = psutil_get_service_from_args( - args, - SC_MANAGER_ENUMERATE_SERVICE, - SERVICE_QUERY_STATUS, - &service_name + args, SC_MANAGER_ENUMERATE_SERVICE, SERVICE_QUERY_STATUS, &service_name ); if (hService == NULL) return NULL; // First call to QueryServiceStatusEx() is necessary to get the // right size. - QueryServiceStatusEx(hService, SC_STATUS_PROCESS_INFO, NULL, 0, - &bytesNeeded); + QueryServiceStatusEx( + hService, SC_STATUS_PROCESS_INFO, NULL, 0, &bytesNeeded + ); if (GetLastError() == ERROR_MUI_FILE_NOT_FOUND) { // Also services.msc fails in the same manner, so we return an // empty string. @@ -357,28 +350,33 @@ psutil_winservice_query_status(PyObject *self, PyObject *args) { return Py_BuildValue("s", ""); } if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) { - psutil_PyErr_SetFromOSErrnoWithSyscall("QueryServiceStatusEx"); + psutil_oserror_wsyscall("QueryServiceStatusEx"); goto error; } - ssp = (SERVICE_STATUS_PROCESS *)HeapAlloc(GetProcessHeap(), 0, bytesNeeded); + ssp = (SERVICE_STATUS_PROCESS *)HeapAlloc( + GetProcessHeap(), 0, bytesNeeded + ); if (ssp == NULL) { PyErr_NoMemory(); goto error; } // Actual call. - ok = QueryServiceStatusEx(hService, SC_STATUS_PROCESS_INFO, (LPBYTE)ssp, - bytesNeeded, &bytesNeeded); + ok = QueryServiceStatusEx( + hService, + SC_STATUS_PROCESS_INFO, + (LPBYTE)ssp, + bytesNeeded, + &bytesNeeded + ); if (!ok) { - psutil_PyErr_SetFromOSErrnoWithSyscall("QueryServiceStatusEx"); + psutil_oserror_wsyscall("QueryServiceStatusEx"); goto error; } py_tuple = Py_BuildValue( - "(sk)", - get_state_string(ssp->dwCurrentState), - ssp->dwProcessId + "(sk)", get_state_string(ssp->dwCurrentState), ssp->dwProcessId ); if (py_tuple == NULL) goto error; @@ -409,18 +407,17 @@ psutil_winservice_query_descr(PyObject *self, PyObject *args) { PyObject *py_retstr = NULL; hService = psutil_get_service_from_args( - args, - SC_MANAGER_ENUMERATE_SERVICE, - SERVICE_QUERY_CONFIG, - &service_name + args, SC_MANAGER_ENUMERATE_SERVICE, SERVICE_QUERY_CONFIG, &service_name ); if (hService == NULL) return NULL; - QueryServiceConfig2W(hService, SERVICE_CONFIG_DESCRIPTION, NULL, 0, &bytesNeeded); + QueryServiceConfig2W( + hService, SERVICE_CONFIG_DESCRIPTION, NULL, 0, &bytesNeeded + ); - if ((GetLastError() == ERROR_NOT_FOUND) || - (GetLastError() == ERROR_MUI_FILE_NOT_FOUND)) + if ((GetLastError() == ERROR_NOT_FOUND) + || (GetLastError() == ERROR_MUI_FILE_NOT_FOUND)) { // E.g. services.msc fails in this manner, so we return an // empty string. @@ -431,7 +428,7 @@ psutil_winservice_query_descr(PyObject *self, PyObject *args) { } if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) { - psutil_PyErr_SetFromOSErrnoWithSyscall("QueryServiceConfig2W"); + psutil_oserror_wsyscall("QueryServiceConfig2W"); goto error; } @@ -441,10 +438,15 @@ psutil_winservice_query_descr(PyObject *self, PyObject *args) { goto error; } - ok = QueryServiceConfig2W(hService, SERVICE_CONFIG_DESCRIPTION, - (LPBYTE)scd, bytesNeeded, &bytesNeeded); + ok = QueryServiceConfig2W( + hService, + SERVICE_CONFIG_DESCRIPTION, + (LPBYTE)scd, + bytesNeeded, + &bytesNeeded + ); if (!ok) { - psutil_PyErr_SetFromOSErrnoWithSyscall("QueryServiceConfig2W"); + psutil_oserror_wsyscall("QueryServiceConfig2W"); goto error; } @@ -453,7 +455,8 @@ psutil_winservice_query_descr(PyObject *self, PyObject *args) { } else { py_retstr = PyUnicode_FromWideChar( - scd->lpDescription, wcslen(scd->lpDescription)); + scd->lpDescription, wcslen(scd->lpDescription) + ); } if (!py_retstr) @@ -486,17 +489,14 @@ psutil_winservice_start(PyObject *self, PyObject *args) { wchar_t *service_name = NULL; hService = psutil_get_service_from_args( - args, - SC_MANAGER_ALL_ACCESS, - SERVICE_START, - &service_name + args, SC_MANAGER_ALL_ACCESS, SERVICE_START, &service_name ); if (hService == NULL) return NULL; ok = StartService(hService, 0, NULL); if (!ok) { - psutil_PyErr_SetFromOSErrnoWithSyscall("StartService"); + psutil_oserror_wsyscall("StartService"); goto error; } @@ -525,10 +525,7 @@ psutil_winservice_stop(PyObject *self, PyObject *args) { SERVICE_STATUS ssp; hService = psutil_get_service_from_args( - args, - SC_MANAGER_ALL_ACCESS, - SERVICE_STOP, - &service_name + args, SC_MANAGER_ALL_ACCESS, SERVICE_STOP, &service_name ); if (hService == NULL) return NULL; @@ -538,7 +535,7 @@ psutil_winservice_stop(PyObject *self, PyObject *args) { ok = ControlService(hService, SERVICE_CONTROL_STOP, &ssp); Py_END_ALLOW_THREADS if (!ok) { - psutil_PyErr_SetFromOSErrnoWithSyscall("ControlService"); + psutil_oserror_wsyscall("ControlService"); goto error; } diff --git a/contrib/python/psutil/py3/psutil/arch/windows/socks.c b/contrib/python/psutil/py3/psutil/arch/windows/socks.c index 09bee6820b3..12c2fb153bd 100644 --- a/contrib/python/psutil/py3/psutil/arch/windows/socks.c +++ b/contrib/python/psutil/py3/psutil/arch/windows/socks.c @@ -25,7 +25,8 @@ // https://github.com/giampaolo/psutil/issues/1294 -static PVOID __GetExtendedTcpTable(ULONG family) { +static PVOID +__GetExtendedTcpTable(ULONG family) { DWORD err; PVOID table; ULONG size = 0; @@ -51,12 +52,13 @@ static PVOID __GetExtendedTcpTable(ULONG family) { return __GetExtendedTcpTable(family); } - PyErr_SetString(PyExc_RuntimeError, "GetExtendedTcpTable failed"); + psutil_runtime_error("GetExtendedTcpTable failed"); return NULL; } -static PVOID __GetExtendedUdpTable(ULONG family) { +static PVOID +__GetExtendedUdpTable(ULONG family) { DWORD err; PVOID table; ULONG size = 0; @@ -82,15 +84,15 @@ static PVOID __GetExtendedUdpTable(ULONG family) { return __GetExtendedUdpTable(family); } - PyErr_SetString(PyExc_RuntimeError, "GetExtendedUdpTable failed"); + psutil_runtime_error("GetExtendedUdpTable failed"); return NULL; } #define psutil_conn_decref_objs() \ - Py_DECREF(_AF_INET); \ - Py_DECREF(_AF_INET6);\ - Py_DECREF(_SOCK_STREAM);\ + Py_DECREF(_AF_INET); \ + Py_DECREF(_AF_INET6); \ + Py_DECREF(_SOCK_STREAM); \ Py_DECREF(_SOCK_DGRAM); @@ -99,7 +101,7 @@ static PVOID __GetExtendedUdpTable(ULONG family) { */ PyObject * psutil_net_connections(PyObject *self, PyObject *args) { - static long null_address[4] = { 0, 0, 0, 0 }; + static long null_address[4] = {0, 0, 0, 0}; DWORD pid; int pid_return; PVOID table = NULL; @@ -122,8 +124,9 @@ psutil_net_connections(PyObject *self, PyObject *args) { PyObject *_SOCK_STREAM = PyLong_FromLong((long)SOCK_STREAM); PyObject *_SOCK_DGRAM = PyLong_FromLong((long)SOCK_DGRAM); - if (! PyArg_ParseTuple(args, _Py_PARSE_PID "OO", &pid, &py_af_filter, - &py_type_filter)) + if (!PyArg_ParseTuple( + args, _Py_PARSE_PID "OO", &pid, &py_af_filter, &py_type_filter + )) { goto error; } @@ -138,7 +141,7 @@ psutil_net_connections(PyObject *self, PyObject *args) { pid_return = psutil_pid_is_running(pid); if (pid_return == 0) { psutil_conn_decref_objs(); - return NoSuchProcess("psutil_pid_is_running"); + return psutil_oserror_nsp("psutil_pid_is_running"); } else if (pid_return == -1) { psutil_conn_decref_objs(); @@ -154,8 +157,8 @@ psutil_net_connections(PyObject *self, PyObject *args) { // TCP IPv4 - if ((PySequence_Contains(py_af_filter, _AF_INET) == 1) && - (PySequence_Contains(py_type_filter, _SOCK_STREAM) == 1)) + if ((PySequence_Contains(py_af_filter, _AF_INET) == 1) + && (PySequence_Contains(py_type_filter, _SOCK_STREAM) == 1)) { table = NULL; py_conn_tuple = NULL; @@ -173,8 +176,8 @@ psutil_net_connections(PyObject *self, PyObject *args) { } } - if (tcp4Table->table[i].dwLocalAddr != 0 || - tcp4Table->table[i].dwLocalPort != 0) + if (tcp4Table->table[i].dwLocalAddr != 0 + || tcp4Table->table[i].dwLocalPort != 0) { struct in_addr addr; @@ -183,7 +186,8 @@ psutil_net_connections(PyObject *self, PyObject *args) { py_addr_tuple_local = Py_BuildValue( "(si)", addressBufferLocal, - BYTESWAP_USHORT(tcp4Table->table[i].dwLocalPort)); + BYTESWAP_USHORT(tcp4Table->table[i].dwLocalPort) + ); } else { py_addr_tuple_local = PyTuple_New(0); @@ -194,9 +198,9 @@ psutil_net_connections(PyObject *self, PyObject *args) { // On Windows <= XP, remote addr is filled even if socket // is in LISTEN mode in which case we just ignore it. - if ((tcp4Table->table[i].dwRemoteAddr != 0 || - tcp4Table->table[i].dwRemotePort != 0) && - (tcp4Table->table[i].dwState != MIB_TCP_STATE_LISTEN)) + if ((tcp4Table->table[i].dwRemoteAddr != 0 + || tcp4Table->table[i].dwRemotePort != 0) + && (tcp4Table->table[i].dwState != MIB_TCP_STATE_LISTEN)) { struct in_addr addr; @@ -205,10 +209,10 @@ psutil_net_connections(PyObject *self, PyObject *args) { py_addr_tuple_remote = Py_BuildValue( "(si)", addressBufferRemote, - BYTESWAP_USHORT(tcp4Table->table[i].dwRemotePort)); + BYTESWAP_USHORT(tcp4Table->table[i].dwRemotePort) + ); } - else - { + else { py_addr_tuple_remote = PyTuple_New(0); } @@ -223,7 +227,8 @@ psutil_net_connections(PyObject *self, PyObject *args) { py_addr_tuple_local, py_addr_tuple_remote, tcp4Table->table[i].dwState, - tcp4Table->table[i].dwOwningPid); + tcp4Table->table[i].dwOwningPid + ); if (!py_conn_tuple) goto error; if (PyList_Append(py_retlist, py_conn_tuple)) @@ -236,9 +241,9 @@ psutil_net_connections(PyObject *self, PyObject *args) { } // TCP IPv6 - if ((PySequence_Contains(py_af_filter, _AF_INET6) == 1) && - (PySequence_Contains(py_type_filter, _SOCK_STREAM) == 1) && - (RtlIpv6AddressToStringA != NULL)) + if ((PySequence_Contains(py_af_filter, _AF_INET6) == 1) + && (PySequence_Contains(py_type_filter, _SOCK_STREAM) == 1) + && (RtlIpv6AddressToStringA != NULL)) { table = NULL; py_conn_tuple = NULL; @@ -249,16 +254,15 @@ psutil_net_connections(PyObject *self, PyObject *args) { if (table == NULL) goto error; tcp6Table = table; - for (i = 0; i < tcp6Table->dwNumEntries; i++) - { + for (i = 0; i < tcp6Table->dwNumEntries; i++) { if (pid != -1) { if (tcp6Table->table[i].dwOwningPid != pid) { continue; } } - if (memcmp(tcp6Table->table[i].ucLocalAddr, null_address, 16) - != 0 || tcp6Table->table[i].dwLocalPort != 0) + if (memcmp(tcp6Table->table[i].ucLocalAddr, null_address, 16) != 0 + || tcp6Table->table[i].dwLocalPort != 0) { struct in6_addr addr; @@ -267,7 +271,8 @@ psutil_net_connections(PyObject *self, PyObject *args) { py_addr_tuple_local = Py_BuildValue( "(si)", addressBufferLocal, - BYTESWAP_USHORT(tcp6Table->table[i].dwLocalPort)); + BYTESWAP_USHORT(tcp6Table->table[i].dwLocalPort) + ); } else { py_addr_tuple_local = PyTuple_New(0); @@ -279,9 +284,9 @@ psutil_net_connections(PyObject *self, PyObject *args) { // On Windows <= XP, remote addr is filled even if socket // is in LISTEN mode in which case we just ignore it. if ((memcmp(tcp6Table->table[i].ucRemoteAddr, null_address, 16) - != 0 || - tcp6Table->table[i].dwRemotePort != 0) && - (tcp6Table->table[i].dwState != MIB_TCP_STATE_LISTEN)) + != 0 + || tcp6Table->table[i].dwRemotePort != 0) + && (tcp6Table->table[i].dwState != MIB_TCP_STATE_LISTEN)) { struct in6_addr addr; @@ -290,7 +295,8 @@ psutil_net_connections(PyObject *self, PyObject *args) { py_addr_tuple_remote = Py_BuildValue( "(si)", addressBufferRemote, - BYTESWAP_USHORT(tcp6Table->table[i].dwRemotePort)); + BYTESWAP_USHORT(tcp6Table->table[i].dwRemotePort) + ); } else { py_addr_tuple_remote = PyTuple_New(0); @@ -307,7 +313,8 @@ psutil_net_connections(PyObject *self, PyObject *args) { py_addr_tuple_local, py_addr_tuple_remote, tcp6Table->table[i].dwState, - tcp6Table->table[i].dwOwningPid); + tcp6Table->table[i].dwOwningPid + ); if (!py_conn_tuple) goto error; if (PyList_Append(py_retlist, py_conn_tuple)) @@ -321,8 +328,8 @@ psutil_net_connections(PyObject *self, PyObject *args) { // UDP IPv4 - if ((PySequence_Contains(py_af_filter, _AF_INET) == 1) && - (PySequence_Contains(py_type_filter, _SOCK_DGRAM) == 1)) + if ((PySequence_Contains(py_af_filter, _AF_INET) == 1) + && (PySequence_Contains(py_type_filter, _SOCK_DGRAM) == 1)) { table = NULL; py_conn_tuple = NULL; @@ -332,16 +339,15 @@ psutil_net_connections(PyObject *self, PyObject *args) { if (table == NULL) goto error; udp4Table = table; - for (i = 0; i < udp4Table->dwNumEntries; i++) - { + for (i = 0; i < udp4Table->dwNumEntries; i++) { if (pid != -1) { if (udp4Table->table[i].dwOwningPid != pid) { continue; } } - if (udp4Table->table[i].dwLocalAddr != 0 || - udp4Table->table[i].dwLocalPort != 0) + if (udp4Table->table[i].dwLocalAddr != 0 + || udp4Table->table[i].dwLocalPort != 0) { struct in_addr addr; @@ -350,7 +356,8 @@ psutil_net_connections(PyObject *self, PyObject *args) { py_addr_tuple_local = Py_BuildValue( "(si)", addressBufferLocal, - BYTESWAP_USHORT(udp4Table->table[i].dwLocalPort)); + BYTESWAP_USHORT(udp4Table->table[i].dwLocalPort) + ); } else { py_addr_tuple_local = PyTuple_New(0); @@ -367,7 +374,8 @@ psutil_net_connections(PyObject *self, PyObject *args) { py_addr_tuple_local, PyTuple_New(0), PSUTIL_CONN_NONE, - udp4Table->table[i].dwOwningPid); + udp4Table->table[i].dwOwningPid + ); if (!py_conn_tuple) goto error; if (PyList_Append(py_retlist, py_conn_tuple)) @@ -381,9 +389,9 @@ psutil_net_connections(PyObject *self, PyObject *args) { // UDP IPv6 - if ((PySequence_Contains(py_af_filter, _AF_INET6) == 1) && - (PySequence_Contains(py_type_filter, _SOCK_DGRAM) == 1) && - (RtlIpv6AddressToStringA != NULL)) + if ((PySequence_Contains(py_af_filter, _AF_INET6) == 1) + && (PySequence_Contains(py_type_filter, _SOCK_DGRAM) == 1) + && (RtlIpv6AddressToStringA != NULL)) { table = NULL; py_conn_tuple = NULL; @@ -400,8 +408,8 @@ psutil_net_connections(PyObject *self, PyObject *args) { } } - if (memcmp(udp6Table->table[i].ucLocalAddr, null_address, 16) - != 0 || udp6Table->table[i].dwLocalPort != 0) + if (memcmp(udp6Table->table[i].ucLocalAddr, null_address, 16) != 0 + || udp6Table->table[i].dwLocalPort != 0) { struct in6_addr addr; @@ -410,7 +418,8 @@ psutil_net_connections(PyObject *self, PyObject *args) { py_addr_tuple_local = Py_BuildValue( "(si)", addressBufferLocal, - BYTESWAP_USHORT(udp6Table->table[i].dwLocalPort)); + BYTESWAP_USHORT(udp6Table->table[i].dwLocalPort) + ); } else { py_addr_tuple_local = PyTuple_New(0); @@ -427,7 +436,8 @@ psutil_net_connections(PyObject *self, PyObject *args) { py_addr_tuple_local, PyTuple_New(0), PSUTIL_CONN_NONE, - udp6Table->table[i].dwOwningPid); + udp6Table->table[i].dwOwningPid + ); if (!py_conn_tuple) goto error; if (PyList_Append(py_retlist, py_conn_tuple)) diff --git a/contrib/python/psutil/py3/psutil/arch/windows/sys.c b/contrib/python/psutil/py3/psutil/arch/windows/sys.c index 597b78d0b0e..4271a1a1684 100644 --- a/contrib/python/psutil/py3/psutil/arch/windows/sys.c +++ b/contrib/python/psutil/py3/psutil/arch/windows/sys.c @@ -9,8 +9,10 @@ System related functions. Original code moved in here from psutil/_psutil_windows.c in 2023. For reference, here's the GIT blame history before the move: -* boot_time(): https://github.com/giampaolo/psutil/blame/efd7ed3/psutil/_psutil_windows.c#L51-L60 -* users(): https://github.com/giampaolo/psutil/blame/efd7ed3/psutil/_psutil_windows.c#L1103-L1244 +- boot_time(): + https://github.com/giampaolo/psutil/blame/efd7ed3/psutil/_psutil_windows.c#L51-L60 +- users(): + https://github.com/giampaolo/psutil/blame/efd7ed3/psutil/_psutil_windows.c#L1103-L1244 */ #include <Python.h> @@ -63,21 +65,22 @@ psutil_users(PyObject *self, PyObject *args) { if (py_retlist == NULL) return NULL; - if (WTSEnumerateSessionsW == NULL || - WTSQuerySessionInformationW == NULL || - WTSFreeMemory == NULL) { - // If we don't run in an environment that is a Remote Desktop Services environment - // the Wtsapi32 proc might not be present. - // https://docs.microsoft.com/en-us/windows/win32/termserv/run-time-linking-to-wtsapi32-dll - return py_retlist; + if (WTSEnumerateSessionsW == NULL || WTSQuerySessionInformationW == NULL + || WTSFreeMemory == NULL) + { + // If we don't run in an environment that is a Remote Desktop Services + // environment the Wtsapi32 proc might not be present. + // https://docs.microsoft.com/en-us/windows/win32/termserv/run-time-linking-to-wtsapi32-dll + return py_retlist; } if (WTSEnumerateSessionsW(hServer, 0, 1, &sessions, &count) == 0) { if (ERROR_CALL_NOT_IMPLEMENTED == GetLastError()) { - // On Windows Nano server, the Wtsapi32 API can be present, but return WinError 120. + // On Windows Nano server, the Wtsapi32 API can be present, but + // return WinError 120. return py_retlist; } - psutil_PyErr_SetFromOSErrnoWithSyscall("WTSEnumerateSessionsW"); + psutil_oserror_wsyscall("WTSEnumerateSessionsW"); goto error; } @@ -98,11 +101,12 @@ psutil_users(PyObject *self, PyObject *args) { // username bytes = 0; - if (WTSQuerySessionInformationW(hServer, sessionId, WTSUserName, - &buffer_user, &bytes) == 0) { - psutil_PyErr_SetFromOSErrnoWithSyscall( - "WTSQuerySessionInformationW" - ); + if (WTSQuerySessionInformationW( + hServer, sessionId, WTSUserName, &buffer_user, &bytes + ) + == 0) + { + psutil_oserror_wsyscall("WTSQuerySessionInformationW"); goto error; } if (bytes <= 2) @@ -110,24 +114,28 @@ psutil_users(PyObject *self, PyObject *args) { // address bytes = 0; - if (WTSQuerySessionInformationW(hServer, sessionId, WTSClientAddress, - &buffer_addr, &bytes) == 0) { - psutil_PyErr_SetFromOSErrnoWithSyscall( - "WTSQuerySessionInformationW" - ); + if (WTSQuerySessionInformationW( + hServer, sessionId, WTSClientAddress, &buffer_addr, &bytes + ) + == 0) + { + psutil_oserror_wsyscall("WTSQuerySessionInformationW"); goto error; } address = (PWTS_CLIENT_ADDRESS)buffer_addr; if (address->AddressFamily == 2) { // AF_INET == 2 - sprintf_s(address_str, - _countof(address_str), - "%u.%u.%u.%u", - // The IP address is offset by two bytes from the start of the Address member of the WTS_CLIENT_ADDRESS structure. - address->Address[2], - address->Address[3], - address->Address[4], - address->Address[5]); + str_format( + address_str, + sizeof(address_str), + "%u.%u.%u.%u", + // The IP address is offset by two bytes from the start of the + // Address member of the WTS_CLIENT_ADDRESS structure. + address->Address[2], + address->Address[3], + address->Address[4], + address->Address[5] + ); py_address = Py_BuildValue("s", address_str); if (!py_address) goto error; @@ -139,11 +147,12 @@ psutil_users(PyObject *self, PyObject *args) { // login time bytes = 0; - if (WTSQuerySessionInformationW(hServer, sessionId, WTSSessionInfo, - &buffer_info, &bytes) == 0) { - psutil_PyErr_SetFromOSErrnoWithSyscall( - "WTSQuerySessionInformationW" - ); + if (WTSQuerySessionInformationW( + hServer, sessionId, WTSSessionInfo, &buffer_info, &bytes + ) + == 0) + { + psutil_oserror_wsyscall("WTSQuerySessionInformationW"); goto error; } wts_info = (PWTSINFOW)buffer_info; diff --git a/contrib/python/psutil/py3/psutil/arch/windows/wmi.c b/contrib/python/psutil/py3/psutil/arch/windows/wmi.c index 04ba3ee4c59..c98db341306 100644 --- a/contrib/python/psutil/py3/psutil/arch/windows/wmi.c +++ b/contrib/python/psutil/py3/psutil/arch/windows/wmi.c @@ -21,8 +21,8 @@ // // This formula comes from linux's include/linux/sched/loadavg.h // https://github.com/torvalds/linux/blob/345671ea0f9258f410eb057b9ced9cefbbe5dc78/include/linux/sched/loadavg.h#L20-L23 -#define LOADAVG_FACTOR_1F 0.9200444146293232478931553241 -#define LOADAVG_FACTOR_5F 0.9834714538216174894737477501 +#define LOADAVG_FACTOR_1F 0.9200444146293232478931553241 +#define LOADAVG_FACTOR_5F 0.9834714538216174894737477501 #define LOADAVG_FACTOR_15F 0.9944598480048967508795473394 // The time interval in seconds between taking load counts, same as Linux #define SAMPLING_INTERVAL 5 @@ -31,6 +31,7 @@ double load_avg_1m = 0; double load_avg_5m = 0; double load_avg_15m = 0; +// clang-format off #ifdef Py_GIL_DISABLED static PyMutex mutex; #define MUTEX_LOCK(m) PyMutex_Lock(m) @@ -39,15 +40,18 @@ double load_avg_15m = 0; #define MUTEX_LOCK(m) #define MUTEX_UNLOCK(m) #endif +// clang-format on -VOID CALLBACK LoadAvgCallback(PVOID hCounter, BOOLEAN timedOut) { +VOID CALLBACK +LoadAvgCallback(PVOID hCounter, BOOLEAN timedOut) { PDH_FMT_COUNTERVALUE displayValue; double currentLoad; PDH_STATUS err; err = PdhGetFormattedCounterValue( - (PDH_HCOUNTER)hCounter, PDH_FMT_DOUBLE, 0, &displayValue); + (PDH_HCOUNTER)hCounter, PDH_FMT_DOUBLE, 0, &displayValue + ); // Skip updating the load if we can't get the value successfully if (err != ERROR_SUCCESS) { return; @@ -55,12 +59,12 @@ VOID CALLBACK LoadAvgCallback(PVOID hCounter, BOOLEAN timedOut) { currentLoad = displayValue.doubleValue; MUTEX_LOCK(&mutex); - load_avg_1m = load_avg_1m * LOADAVG_FACTOR_1F + currentLoad * \ - (1.0 - LOADAVG_FACTOR_1F); - load_avg_5m = load_avg_5m * LOADAVG_FACTOR_5F + currentLoad * \ - (1.0 - LOADAVG_FACTOR_5F); - load_avg_15m = load_avg_15m * LOADAVG_FACTOR_15F + currentLoad * \ - (1.0 - LOADAVG_FACTOR_15F); + load_avg_1m = load_avg_1m * LOADAVG_FACTOR_1F + + currentLoad * (1.0 - LOADAVG_FACTOR_1F); + load_avg_5m = load_avg_5m * LOADAVG_FACTOR_5F + + currentLoad * (1.0 - LOADAVG_FACTOR_5F); + load_avg_15m = load_avg_15m * LOADAVG_FACTOR_15F + + currentLoad * (1.0 - LOADAVG_FACTOR_15F); MUTEX_UNLOCK(&mutex); } @@ -76,28 +80,28 @@ psutil_init_loadavg_counter(PyObject *self, PyObject *args) { HANDLE waitHandle; if ((PdhOpenQueryW(NULL, 0, &hQuery)) != ERROR_SUCCESS) { - PyErr_Format(PyExc_RuntimeError, "PdhOpenQueryW failed"); + psutil_runtime_error("PdhOpenQueryW failed"); return NULL; } s = PdhAddEnglishCounterW(hQuery, szCounterPath, 0, &hCounter); if (s != ERROR_SUCCESS) { - PyErr_Format( - PyExc_RuntimeError, - "PdhAddEnglishCounterW failed. Performance counters may be disabled." + psutil_runtime_error( + "PdhAddEnglishCounterW failed. Performance counters may be " + "disabled." ); return NULL; } event = CreateEventW(NULL, FALSE, FALSE, L"LoadUpdateEvent"); if (event == NULL) { - psutil_PyErr_SetFromOSErrnoWithSyscall("CreateEventW"); + psutil_oserror_wsyscall("CreateEventW"); return NULL; } s = PdhCollectQueryDataEx(hQuery, SAMPLING_INTERVAL, event); if (s != ERROR_SUCCESS) { - PyErr_Format(PyExc_RuntimeError, "PdhCollectQueryDataEx failed"); + psutil_runtime_error("PdhCollectQueryDataEx failed"); return NULL; } @@ -105,13 +109,13 @@ psutil_init_loadavg_counter(PyObject *self, PyObject *args) { &waitHandle, event, (WAITORTIMERCALLBACK)LoadAvgCallback, - (PVOID) - hCounter, + (PVOID)hCounter, INFINITE, - WT_EXECUTEDEFAULT); + WT_EXECUTEDEFAULT + ); if (ret == 0) { - psutil_PyErr_SetFromOSErrnoWithSyscall("RegisterWaitForSingleObject"); + psutil_oserror_wsyscall("RegisterWaitForSingleObject"); return NULL; } @@ -132,5 +136,7 @@ psutil_get_loadavg(PyObject *self, PyObject *args) { double load_avg_5m_l = load_avg_5m; double load_avg_15m_l = load_avg_15m; MUTEX_UNLOCK(&mutex); - return Py_BuildValue("(ddd)", load_avg_1m_l, load_avg_5m_l, load_avg_15m_l); + return Py_BuildValue( + "(ddd)", load_avg_1m_l, load_avg_5m_l, load_avg_15m_l + ); } diff --git a/contrib/python/psutil/py3/ya.make b/contrib/python/psutil/py3/ya.make index 972033716ab..24171b71fc1 100644 --- a/contrib/python/psutil/py3/ya.make +++ b/contrib/python/psutil/py3/ya.make @@ -2,7 +2,7 @@ PY3_LIBRARY() -VERSION(7.1.2) +VERSION(7.1.3) LICENSE(BSD-3-Clause) @@ -27,12 +27,14 @@ NO_CHECK_IMPORTS( NO_UTIL() CFLAGS( - -DPSUTIL_VERSION=712 + -DPSUTIL_VERSION=713 ) SRCS( + psutil/arch/all/errors.c psutil/arch/all/init.c psutil/arch/all/pids.c + psutil/arch/all/str.c ) IF (OS_LINUX) @@ -49,6 +51,7 @@ IF (OS_LINUX) psutil/arch/linux/proc.c psutil/arch/posix/init.c psutil/arch/posix/net.c + psutil/arch/posix/pids.c psutil/arch/posix/proc.c psutil/arch/posix/sysctl.c psutil/arch/posix/users.c @@ -79,10 +82,12 @@ IF (OS_DARWIN) psutil/arch/osx/net.c psutil/arch/osx/pids.c psutil/arch/osx/proc.c + psutil/arch/osx/proc_utils.c psutil/arch/osx/sensors.c psutil/arch/osx/sys.c psutil/arch/posix/init.c psutil/arch/posix/net.c + psutil/arch/posix/pids.c psutil/arch/posix/proc.c psutil/arch/posix/sysctl.c psutil/arch/posix/users.c |
