repo
stringlengths 1
152
⌀ | file
stringlengths 14
221
| code
stringlengths 501
25k
| file_length
int64 501
25k
| avg_line_length
float64 20
99.5
| max_line_length
int64 21
134
| extension_type
stringclasses 2
values |
---|---|---|---|---|---|---|
psutil | psutil-master/psutil/_psutil_bsd.c | /*
* Copyright (c) 2009, Jay Loden, Giampaolo Rodola', Landry Breuil
* (OpenBSD implementation), Ryo Onodera (NetBSD implementation).
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*
* Platform-specific module methods for FreeBSD and OpenBSD.
* OpenBSD references:
* - OpenBSD source code: https://github.com/openbsd/src
*
* OpenBSD / NetBSD: missing APIs compared to FreeBSD implementation:
* - psutil.net_connections()
* - psutil.Process.get/set_cpu_affinity() (not supported natively)
* - psutil.Process.memory_maps()
*/
#include <Python.h>
#include <sys/proc.h>
#include <sys/param.h> // BSD version
#include <netinet/tcp_fsm.h> // for TCP connection states
#include "_psutil_common.h"
#include "_psutil_posix.h"
#include "arch/bsd/cpu.h"
#include "arch/bsd/disk.h"
#include "arch/bsd/net.h"
#include "arch/bsd/proc.h"
#include "arch/bsd/sys.h"
#ifdef PSUTIL_FREEBSD
#include "arch/freebsd/cpu.h"
#include "arch/freebsd/disk.h"
#include "arch/freebsd/mem.h"
#include "arch/freebsd/proc.h"
#include "arch/freebsd/proc_socks.h"
#include "arch/freebsd/sensors.h"
#include "arch/freebsd/sys_socks.h"
#elif PSUTIL_OPENBSD
#include "arch/openbsd/cpu.h"
#include "arch/openbsd/disk.h"
#include "arch/openbsd/mem.h"
#include "arch/openbsd/proc.h"
#include "arch/openbsd/socks.h"
#elif PSUTIL_NETBSD
#include "arch/netbsd/cpu.h"
#include "arch/netbsd/disk.h"
#include "arch/netbsd/mem.h"
#include "arch/netbsd/proc.h"
#include "arch/netbsd/socks.h"
#endif
/*
* define the psutil C module methods and initialize the module.
*/
static PyMethodDef mod_methods[] = {
// --- per-process functions
{"proc_cmdline", psutil_proc_cmdline, METH_VARARGS},
{"proc_name", psutil_proc_name, METH_VARARGS},
{"proc_oneshot_info", psutil_proc_oneshot_info, METH_VARARGS},
{"proc_threads", psutil_proc_threads, METH_VARARGS},
#if defined(PSUTIL_FREEBSD)
{"proc_connections", psutil_proc_connections, METH_VARARGS},
#endif
{"proc_cwd", psutil_proc_cwd, METH_VARARGS},
#if defined(__FreeBSD_version) && __FreeBSD_version >= 800000 || PSUTIL_OPENBSD || defined(PSUTIL_NETBSD)
{"proc_num_fds", psutil_proc_num_fds, METH_VARARGS},
{"proc_open_files", psutil_proc_open_files, METH_VARARGS},
#endif
#if defined(PSUTIL_FREEBSD) || defined(PSUTIL_NETBSD)
{"proc_num_threads", psutil_proc_num_threads, METH_VARARGS},
#endif
#if defined(PSUTIL_FREEBSD)
{"cpu_topology", psutil_cpu_topology, METH_VARARGS},
{"proc_cpu_affinity_get", psutil_proc_cpu_affinity_get, METH_VARARGS},
{"proc_cpu_affinity_set", psutil_proc_cpu_affinity_set, METH_VARARGS},
{"proc_exe", psutil_proc_exe, METH_VARARGS},
{"proc_getrlimit", psutil_proc_getrlimit, METH_VARARGS},
{"proc_memory_maps", psutil_proc_memory_maps, METH_VARARGS},
{"proc_setrlimit", psutil_proc_setrlimit, METH_VARARGS},
#endif
{"proc_environ", psutil_proc_environ, METH_VARARGS},
// --- system-related functions
{"boot_time", psutil_boot_time, METH_VARARGS},
{"cpu_count_logical", psutil_cpu_count_logical, METH_VARARGS},
{"cpu_stats", psutil_cpu_stats, METH_VARARGS},
{"cpu_times", psutil_cpu_times, METH_VARARGS},
{"disk_io_counters", psutil_disk_io_counters, METH_VARARGS},
{"disk_partitions", psutil_disk_partitions, METH_VARARGS},
{"net_connections", psutil_net_connections, METH_VARARGS},
{"net_io_counters", psutil_net_io_counters, METH_VARARGS},
{"per_cpu_times", psutil_per_cpu_times, METH_VARARGS},
{"pids", psutil_pids, METH_VARARGS},
{"swap_mem", psutil_swap_mem, METH_VARARGS},
{"users", psutil_users, METH_VARARGS},
{"virtual_mem", psutil_virtual_mem, METH_VARARGS},
#if defined(PSUTIL_FREEBSD) || defined(PSUTIL_OPENBSD)
{"cpu_freq", psutil_cpu_freq, METH_VARARGS},
#endif
#if defined(PSUTIL_FREEBSD)
{"sensors_battery", psutil_sensors_battery, METH_VARARGS},
{"sensors_cpu_temperature", psutil_sensors_cpu_temperature, METH_VARARGS},
#endif
// --- others
{"check_pid_range", psutil_check_pid_range, METH_VARARGS},
{"set_debug", psutil_set_debug, METH_VARARGS},
{NULL, NULL, 0, NULL}
};
#if PY_MAJOR_VERSION >= 3
#define INITERR return NULL
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"_psutil_bsd",
NULL,
-1,
mod_methods,
NULL,
NULL,
NULL,
NULL
};
PyObject *PyInit__psutil_bsd(void)
#else /* PY_MAJOR_VERSION */
#define INITERR return
void init_psutil_bsd(void)
#endif /* PY_MAJOR_VERSION */
{
PyObject *v;
#if PY_MAJOR_VERSION >= 3
PyObject *mod = PyModule_Create(&moduledef);
#else
PyObject *mod = Py_InitModule("_psutil_bsd", mod_methods);
#endif
if (mod == NULL)
INITERR;
if (PyModule_AddIntConstant(mod, "version", PSUTIL_VERSION)) INITERR;
// process status constants
#ifdef PSUTIL_FREEBSD
if (PyModule_AddIntConstant(mod, "SIDL", SIDL)) INITERR;
if (PyModule_AddIntConstant(mod, "SRUN", SRUN)) INITERR;
if (PyModule_AddIntConstant(mod, "SSLEEP", SSLEEP)) INITERR;
if (PyModule_AddIntConstant(mod, "SSTOP", SSTOP)) INITERR;
if (PyModule_AddIntConstant(mod, "SZOMB", SZOMB)) INITERR;
if (PyModule_AddIntConstant(mod, "SWAIT", SWAIT)) INITERR;
if (PyModule_AddIntConstant(mod, "SLOCK", SLOCK)) INITERR;
#elif PSUTIL_OPENBSD
if (PyModule_AddIntConstant(mod, "SIDL", SIDL)) INITERR;
if (PyModule_AddIntConstant(mod, "SRUN", SRUN)) INITERR;
if (PyModule_AddIntConstant(mod, "SSLEEP", SSLEEP)) INITERR;
if (PyModule_AddIntConstant(mod, "SSTOP", SSTOP)) INITERR;
if (PyModule_AddIntConstant(mod, "SZOMB", SZOMB)) INITERR; // unused
if (PyModule_AddIntConstant(mod, "SDEAD", SDEAD)) INITERR;
if (PyModule_AddIntConstant(mod, "SONPROC", SONPROC)) INITERR;
#elif defined(PSUTIL_NETBSD)
if (PyModule_AddIntConstant(mod, "SIDL", LSIDL)) INITERR;
if (PyModule_AddIntConstant(mod, "SRUN", LSRUN)) INITERR;
if (PyModule_AddIntConstant(mod, "SSLEEP", LSSLEEP)) INITERR;
if (PyModule_AddIntConstant(mod, "SSTOP", LSSTOP)) INITERR;
if (PyModule_AddIntConstant(mod, "SZOMB", LSZOMB)) INITERR;
#if __NetBSD_Version__ < 500000000
if (PyModule_AddIntConstant(mod, "SDEAD", LSDEAD)) INITERR;
#endif
if (PyModule_AddIntConstant(mod, "SONPROC", LSONPROC)) INITERR;
// unique to NetBSD
if (PyModule_AddIntConstant(mod, "SSUSPENDED", LSSUSPENDED)) INITERR;
#endif
// connection status constants
if (PyModule_AddIntConstant(mod, "TCPS_CLOSED", TCPS_CLOSED))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_CLOSING", TCPS_CLOSING))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_CLOSE_WAIT", TCPS_CLOSE_WAIT))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_LISTEN", TCPS_LISTEN))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_ESTABLISHED", TCPS_ESTABLISHED))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_SYN_SENT", TCPS_SYN_SENT))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_SYN_RECEIVED", TCPS_SYN_RECEIVED))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_FIN_WAIT_1", TCPS_FIN_WAIT_1))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_FIN_WAIT_2", TCPS_FIN_WAIT_2))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_LAST_ACK", TCPS_LAST_ACK))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_TIME_WAIT", TCPS_TIME_WAIT))
INITERR;
// PSUTIL_CONN_NONE
if (PyModule_AddIntConstant(mod, "PSUTIL_CONN_NONE", 128)) INITERR;
psutil_setup();
if (mod == NULL)
INITERR;
#if PY_MAJOR_VERSION >= 3
return mod;
#endif
}
| 7,772 | 35.492958 | 105 | c |
psutil | psutil-master/psutil/_psutil_common.c | /*
* 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.
*
* Routines common to all platforms.
*/
#include <Python.h>
#include "_psutil_common.h"
// ====================================================================
// --- Global vars
// ====================================================================
int PSUTIL_DEBUG = 0;
// ====================================================================
// --- Backward compatibility with missing Python.h APIs
// ====================================================================
// PyPy on Windows
#if defined(PSUTIL_WINDOWS) && defined(PYPY_VERSION)
#if !defined(PyErr_SetFromWindowsErrWithFilename)
PyObject *
PyErr_SetFromWindowsErrWithFilename(int winerr, const char *filename) {
PyObject *py_exc = NULL;
PyObject *py_winerr = NULL;
if (winerr == 0)
winerr = GetLastError();
if (filename == NULL) {
py_exc = PyObject_CallFunction(PyExc_OSError, "(is)", winerr,
strerror(winerr));
}
else {
py_exc = PyObject_CallFunction(PyExc_OSError, "(iss)", winerr,
strerror(winerr), filename);
}
if (py_exc == NULL)
return NULL;
py_winerr = Py_BuildValue("i", winerr);
if (py_winerr == NULL)
goto error;
if (PyObject_SetAttrString(py_exc, "winerror", py_winerr) != 0)
goto error;
PyErr_SetObject(PyExc_OSError, py_exc);
Py_XDECREF(py_exc);
return NULL;
error:
Py_XDECREF(py_exc);
Py_XDECREF(py_winerr);
return NULL;
}
#endif // !defined(PyErr_SetFromWindowsErrWithFilename)
// PyPy 2.7
#if !defined(PyErr_SetFromWindowsErr)
PyObject *
PyErr_SetFromWindowsErr(int winerr) {
return PyErr_SetFromWindowsErrWithFilename(winerr, "");
}
#endif // !defined(PyErr_SetFromWindowsErr)
#endif // defined(PSUTIL_WINDOWS) && defined(PYPY_VERSION)
// ====================================================================
// --- Custom exceptions
// ====================================================================
/*
* Same as PyErr_SetFromErrno(0) but adds the syscall to the exception
* message.
*/
PyObject *
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;
}
/*
* 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;
}
/*
* 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;
}
// Enable or disable PSUTIL_DEBUG messages.
PyObject *
psutil_set_debug(PyObject *self, PyObject *args) {
PyObject *value;
int x;
if (!PyArg_ParseTuple(args, "O", &value))
return NULL;
x = PyObject_IsTrue(value);
if (x < 0) {
return NULL;
}
else if (x == 0) {
PSUTIL_DEBUG = 0;
}
else {
PSUTIL_DEBUG = 1;
}
Py_RETURN_NONE;
}
// ============================================================================
// Utility functions (BSD)
// ============================================================================
#if defined(PSUTIL_FREEBSD) || defined(PSUTIL_OPENBSD) || defined(PSUTIL_NETBSD)
void
convert_kvm_err(const char *syscall, char *errbuf) {
char fullmsg[8192];
sprintf(fullmsg, "(originated from %s: %s)", syscall, errbuf);
if (strstr(errbuf, "Permission denied") != NULL)
AccessDenied(fullmsg);
else if (strstr(errbuf, "Operation not permitted") != NULL)
AccessDenied(fullmsg);
else
PyErr_Format(PyExc_RuntimeError, fullmsg);
}
#endif
// ====================================================================
// --- macOS
// ====================================================================
#ifdef PSUTIL_OSX
#include <mach/mach_time.h>
struct mach_timebase_info PSUTIL_MACH_TIMEBASE_INFO;
#endif
// ====================================================================
// --- Windows
// ====================================================================
#ifdef PSUTIL_WINDOWS
#include <windows.h>
// Needed to make these globally visible.
int PSUTIL_WINVER;
SYSTEM_INFO PSUTIL_SYSTEM_INFO;
CRITICAL_SECTION PSUTIL_CRITICAL_SECTION;
// A wrapper around GetModuleHandle and GetProcAddress.
PVOID
psutil_GetProcAddress(LPCSTR libname, LPCSTR procname) {
HMODULE mod;
FARPROC addr;
if ((mod = GetModuleHandleA(libname)) == NULL) {
PyErr_SetFromWindowsErrWithFilename(0, libname);
return NULL;
}
if ((addr = GetProcAddress(mod, procname)) == NULL) {
PyErr_SetFromWindowsErrWithFilename(0, procname);
return NULL;
}
return addr;
}
// A wrapper around LoadLibrary and GetProcAddress.
PVOID
psutil_GetProcAddressFromLib(LPCSTR libname, LPCSTR procname) {
HMODULE mod;
FARPROC addr;
Py_BEGIN_ALLOW_THREADS
mod = LoadLibraryA(libname);
Py_END_ALLOW_THREADS
if (mod == NULL) {
PyErr_SetFromWindowsErrWithFilename(0, libname);
return NULL;
}
if ((addr = GetProcAddress(mod, procname)) == NULL) {
PyErr_SetFromWindowsErrWithFilename(0, procname);
FreeLibrary(mod);
return NULL;
}
// Causes crash.
// FreeLibrary(mod);
return addr;
}
/*
* Convert a NTSTATUS value to a Win32 error code and set the proper
* Python exception.
*/
PVOID
psutil_SetFromNTStatusErr(NTSTATUS Status, const char *syscall) {
ULONG err;
char fullmsg[1024];
if (NT_NTWIN32(Status))
err = WIN32_FROM_NTSTATUS(Status);
else
err = RtlNtStatusToDosErrorNoTeb(Status);
// if (GetLastError() != 0)
// err = GetLastError();
sprintf(fullmsg, "(originated from %s)", syscall);
return PyErr_SetFromWindowsErrWithFilename(err, fullmsg);
}
static int
psutil_loadlibs() {
// --- Mandatory
NtQuerySystemInformation = psutil_GetProcAddressFromLib(
"ntdll.dll", "NtQuerySystemInformation");
if (! NtQuerySystemInformation)
return 1;
NtQueryInformationProcess = psutil_GetProcAddress(
"ntdll.dll", "NtQueryInformationProcess");
if (! NtQueryInformationProcess)
return 1;
NtSetInformationProcess = psutil_GetProcAddress(
"ntdll.dll", "NtSetInformationProcess");
if (! NtSetInformationProcess)
return 1;
NtQueryObject = psutil_GetProcAddressFromLib(
"ntdll.dll", "NtQueryObject");
if (! NtQueryObject)
return 1;
RtlIpv4AddressToStringA = psutil_GetProcAddressFromLib(
"ntdll.dll", "RtlIpv4AddressToStringA");
if (! RtlIpv4AddressToStringA)
return 1;
GetExtendedTcpTable = psutil_GetProcAddressFromLib(
"iphlpapi.dll", "GetExtendedTcpTable");
if (! GetExtendedTcpTable)
return 1;
GetExtendedUdpTable = psutil_GetProcAddressFromLib(
"iphlpapi.dll", "GetExtendedUdpTable");
if (! GetExtendedUdpTable)
return 1;
RtlGetVersion = psutil_GetProcAddressFromLib(
"ntdll.dll", "RtlGetVersion");
if (! RtlGetVersion)
return 1;
NtSuspendProcess = psutil_GetProcAddressFromLib(
"ntdll", "NtSuspendProcess");
if (! NtSuspendProcess)
return 1;
NtResumeProcess = psutil_GetProcAddressFromLib(
"ntdll", "NtResumeProcess");
if (! NtResumeProcess)
return 1;
NtQueryVirtualMemory = psutil_GetProcAddressFromLib(
"ntdll", "NtQueryVirtualMemory");
if (! NtQueryVirtualMemory)
return 1;
RtlNtStatusToDosErrorNoTeb = psutil_GetProcAddressFromLib(
"ntdll", "RtlNtStatusToDosErrorNoTeb");
if (! RtlNtStatusToDosErrorNoTeb)
return 1;
GetTickCount64 = psutil_GetProcAddress(
"kernel32", "GetTickCount64");
if (! GetTickCount64)
return 1;
RtlIpv6AddressToStringA = psutil_GetProcAddressFromLib(
"ntdll.dll", "RtlIpv6AddressToStringA");
if (! RtlIpv6AddressToStringA)
return 1;
// --- Optional
// minimum requirement: Win 7
GetActiveProcessorCount = psutil_GetProcAddress(
"kernel32", "GetActiveProcessorCount");
// minimum requirement: Win 7
GetLogicalProcessorInformationEx = psutil_GetProcAddressFromLib(
"kernel32", "GetLogicalProcessorInformationEx");
// minimum requirements: Windows Server Core
WTSEnumerateSessionsW = psutil_GetProcAddressFromLib(
"wtsapi32.dll", "WTSEnumerateSessionsW");
WTSQuerySessionInformationW = psutil_GetProcAddressFromLib(
"wtsapi32.dll", "WTSQuerySessionInformationW");
WTSFreeMemory = psutil_GetProcAddressFromLib(
"wtsapi32.dll", "WTSFreeMemory");
PyErr_Clear();
return 0;
}
static int
psutil_set_winver() {
RTL_OSVERSIONINFOEXW versionInfo;
ULONG maj;
ULONG min;
versionInfo.dwOSVersionInfoSize = sizeof(RTL_OSVERSIONINFOEXW);
memset(&versionInfo, 0, sizeof(RTL_OSVERSIONINFOEXW));
RtlGetVersion((PRTL_OSVERSIONINFOW)&versionInfo);
maj = versionInfo.dwMajorVersion;
min = versionInfo.dwMinorVersion;
if (maj == 6 && min == 0)
PSUTIL_WINVER = PSUTIL_WINDOWS_VISTA; // or Server 2008
else if (maj == 6 && min == 1)
PSUTIL_WINVER = PSUTIL_WINDOWS_7;
else if (maj == 6 && min == 2)
PSUTIL_WINVER = PSUTIL_WINDOWS_8;
else if (maj == 6 && min == 3)
PSUTIL_WINVER = PSUTIL_WINDOWS_8_1;
else if (maj == 10 && min == 0)
PSUTIL_WINVER = PSUTIL_WINDOWS_10;
else
PSUTIL_WINVER = PSUTIL_WINDOWS_NEW;
return 0;
}
/*
* Convert the hi and lo parts of a FILETIME structure or a LARGE_INTEGER
* to a UNIX time.
* A FILETIME contains a 64-bit value representing the number of
* 100-nanosecond intervals since January 1, 1601 (UTC).
* A UNIX time is the number of seconds that have elapsed since the
* UNIX epoch, that is the time 00:00:00 UTC on 1 January 1970.
*/
static double
_to_unix_time(ULONGLONG hiPart, ULONGLONG loPart) {
ULONGLONG ret;
// 100 nanosecond intervals since January 1, 1601.
ret = hiPart << 32;
ret += 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;
}
double
psutil_FiletimeToUnixTime(FILETIME ft) {
return _to_unix_time((ULONGLONG)ft.dwHighDateTime,
(ULONGLONG)ft.dwLowDateTime);
}
double
psutil_LargeIntegerToUnixTime(LARGE_INTEGER li) {
return _to_unix_time((ULONGLONG)li.HighPart,
(ULONGLONG)li.LowPart);
}
#endif // PSUTIL_WINDOWS
// Called on module import on all platforms.
int
psutil_setup(void) {
if (getenv("PSUTIL_DEBUG") != NULL)
PSUTIL_DEBUG = 1;
#ifdef PSUTIL_WINDOWS
if (psutil_loadlibs() != 0)
return 1;
if (psutil_set_winver() != 0)
return 1;
GetSystemInfo(&PSUTIL_SYSTEM_INFO);
InitializeCriticalSection(&PSUTIL_CRITICAL_SECTION);
#endif
#ifdef PSUTIL_OSX
mach_timebase_info(&PSUTIL_MACH_TIMEBASE_INFO);
#endif
return 0;
}
| 12,644 | 27.608597 | 80 | c |
psutil | psutil-master/psutil/_psutil_common.h | /*
* 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>
// ====================================================================
// --- Global vars / constants
// ====================================================================
extern int PSUTIL_DEBUG;
// a signaler for connections without an actual status
static const int PSUTIL_CONN_NONE = 128;
// strncpy() variant which appends a null terminator.
#define PSUTIL_STRNCPY(dst, src, n) \
strncpy(dst, src, n - 1); \
dst[n - 1] = '\0'
// ====================================================================
// --- Backward compatibility with missing Python.h APIs
// ====================================================================
#if PY_MAJOR_VERSION < 3
// On Python 2 we just return a plain byte string, which is never
// supposed to raise decoding errors, see:
// https://github.com/giampaolo/psutil/issues/1040
#define PyUnicode_DecodeFSDefault PyString_FromString
#define PyUnicode_DecodeFSDefaultAndSize PyString_FromStringAndSize
#endif
#if defined(PSUTIL_WINDOWS) && \
defined(PYPY_VERSION) && \
!defined(PyErr_SetFromWindowsErrWithFilename)
PyObject *PyErr_SetFromWindowsErrWithFilename(int ierr,
const char *filename);
#endif
// --- _Py_PARSE_PID
// SIZEOF_INT|LONG is missing on Linux + PyPy (only?).
// SIZEOF_PID_T is missing on Windows + Python2.
// In this case we guess it from setup.py. It's not 100% bullet proof,
// If wrong we'll probably get compiler warnings.
// FWIW on all UNIX platforms I've seen pid_t is defined as an int.
// _getpid() on Windows also returns an int.
#if !defined(SIZEOF_INT)
#define SIZEOF_INT 4
#endif
#if !defined(SIZEOF_LONG)
#define SIZEOF_LONG 8
#endif
#if !defined(SIZEOF_PID_T)
#define SIZEOF_PID_T PSUTIL_SIZEOF_PID_T // set as a macro in setup.py
#endif
// _Py_PARSE_PID is Python 3 only, but since it's private make sure it's
// always present.
#ifndef _Py_PARSE_PID
#if SIZEOF_PID_T == SIZEOF_INT
#define _Py_PARSE_PID "i"
#elif SIZEOF_PID_T == SIZEOF_LONG
#define _Py_PARSE_PID "l"
#elif defined(SIZEOF_LONG_LONG) && SIZEOF_PID_T == SIZEOF_LONG_LONG
#define _Py_PARSE_PID "L"
#else
#error "_Py_PARSE_PID: sizeof(pid_t) is neither sizeof(int), "
"sizeof(long) or sizeof(long long)"
#endif
#endif
// Python 2 or PyPy on Windows
#ifndef PyLong_FromPid
#if ((SIZEOF_PID_T == SIZEOF_INT) || (SIZEOF_PID_T == SIZEOF_LONG))
#if PY_MAJOR_VERSION >= 3
#define PyLong_FromPid PyLong_FromLong
#else
#define PyLong_FromPid PyInt_FromLong
#endif
#elif defined(SIZEOF_LONG_LONG) && SIZEOF_PID_T == SIZEOF_LONG_LONG
#define PyLong_FromPid PyLong_FromLongLong
#else
#error "PyLong_FromPid: sizeof(pid_t) is neither sizeof(int), "
"sizeof(long) or sizeof(long long)"
#endif
#endif
// ====================================================================
// --- Custom exceptions
// ====================================================================
PyObject* AccessDenied(const char *msg);
PyObject* NoSuchProcess(const char *msg);
PyObject* PyErr_SetFromOSErrnoWithSyscall(const char *syscall);
// ====================================================================
// --- Global utils
// ====================================================================
PyObject* psutil_check_pid_range(PyObject *self, PyObject *args);
PyObject* psutil_set_debug(PyObject *self, PyObject *args);
int psutil_setup(void);
// 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)
// ====================================================================
// --- BSD
// ====================================================================
void convert_kvm_err(const char *syscall, char *errbuf);
// ====================================================================
// --- macOS
// ====================================================================
#ifdef PSUTIL_OSX
#include <mach/mach_time.h>
extern struct mach_timebase_info PSUTIL_MACH_TIMEBASE_INFO;
#endif
// ====================================================================
// --- Windows
// ====================================================================
#ifdef PSUTIL_WINDOWS
#include <windows.h>
// make it available to any file which includes this module
#include "arch/windows/ntextapi.h"
extern int PSUTIL_WINVER;
extern SYSTEM_INFO PSUTIL_SYSTEM_INFO;
extern CRITICAL_SECTION PSUTIL_CRITICAL_SECTION;
#define PSUTIL_WINDOWS_VISTA 60
#define PSUTIL_WINDOWS_7 61
#define PSUTIL_WINDOWS_8 62
#define PSUTIL_WINDOWS_8_1 63
#define PSUTIL_WINDOWS_10 100
#define PSUTIL_WINDOWS_NEW MAXLONG
#define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
#define MALLOC_ZERO(x) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, (x))
#define FREE(x) HeapFree(GetProcessHeap(), 0, (x))
#define _NT_FACILITY_MASK 0xfff
#define _NT_FACILITY_SHIFT 16
#define _NT_FACILITY(status) \
((((ULONG)(status)) >> _NT_FACILITY_SHIFT) & _NT_FACILITY_MASK)
#define NT_NTWIN32(status) (_NT_FACILITY(status) == FACILITY_WIN32)
#define WIN32_FROM_NTSTATUS(status) (((ULONG)(status)) & 0xffff)
#define LO_T 1e-7
#define HI_T 429.4967296
#ifndef AF_INET6
#define AF_INET6 23
#endif
PVOID psutil_GetProcAddress(LPCSTR libname, LPCSTR procname);
PVOID psutil_GetProcAddressFromLib(LPCSTR libname, LPCSTR procname);
PVOID psutil_SetFromNTStatusErr(NTSTATUS Status, const char *syscall);
double psutil_FiletimeToUnixTime(FILETIME ft);
double psutil_LargeIntegerToUnixTime(LARGE_INTEGER li);
#endif
| 6,118 | 33.570621 | 77 | h |
psutil | psutil-master/psutil/_psutil_linux.c | /*
* 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.
*
* Linux-specific functions.
*/
#ifndef _GNU_SOURCE
#define _GNU_SOURCE 1
#endif
#include <Python.h>
#include <errno.h>
#include <stdlib.h>
#include <mntent.h>
#include <features.h>
#include <utmp.h>
#include <sched.h>
#include <linux/version.h>
#include <sys/syscall.h>
#include <sys/sysinfo.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <linux/sockios.h>
#include <linux/if.h>
#include <sys/resource.h>
// 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;
#endif
/* Avoid redefinition of struct sysinfo with musl libc */
#define _LINUX_SYSINFO_H
#include <linux/ethtool.h>
/* The minimum number of CPUs allocated in a cpu_set_t */
static const int NCPUS_START = sizeof(unsigned long) * CHAR_BIT;
// Linux >= 2.6.13
#define PSUTIL_HAVE_IOPRIO defined(__NR_ioprio_get) && defined(__NR_ioprio_set)
// Should exist starting from CentOS 6 (year 2011).
#ifdef CPU_ALLOC
#define PSUTIL_HAVE_CPU_AFFINITY
#endif
#include "_psutil_common.h"
#include "_psutil_posix.h"
// May happen on old RedHat versions, see:
// https://github.com/giampaolo/psutil/issues/607
#ifndef DUPLEX_UNKNOWN
#define DUPLEX_UNKNOWN 0xff
#endif
#ifndef SPEED_UNKNOWN
#define SPEED_UNKNOWN -1
#endif
#if PSUTIL_HAVE_IOPRIO
enum {
IOPRIO_WHO_PROCESS = 1,
};
static inline int
ioprio_get(int which, int who) {
return syscall(__NR_ioprio_get, which, who);
}
static inline int
ioprio_set(int which, int who, int ioprio) {
return syscall(__NR_ioprio_set, which, who, ioprio);
}
// * 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
static inline uint32_t
psutil_ethtool_cmd_speed(const struct ethtool_cmd *ecmd) {
#if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 27)
return ecmd->speed;
#else
return (ecmd->speed_hi << 16) | ecmd->speed;
#endif
}
#define IOPRIO_CLASS_SHIFT 13
#define IOPRIO_PRIO_MASK ((1UL << IOPRIO_CLASS_SHIFT) - 1)
#define IOPRIO_PRIO_CLASS(mask) ((mask) >> IOPRIO_CLASS_SHIFT)
#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.
*/
static PyObject *
psutil_proc_ioprio_get(PyObject *self, PyObject *args) {
pid_t pid;
int ioprio, ioclass, iodata;
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);
ioclass = IOPRIO_PRIO_CLASS(ioprio);
iodata = IOPRIO_PRIO_DATA(ioprio);
return Py_BuildValue("ii", ioclass, iodata);
}
/*
* A wrapper around ioprio_set(); sets process I/O priority.
* ioclass can be either IOPRIO_CLASS_RT, IOPRIO_CLASS_BE, IOPRIO_CLASS_IDLE
* or 0. iodata goes from 0 to 7 depending on ioclass specified.
*/
static PyObject *
psutil_proc_ioprio_set(PyObject *self, PyObject *args) {
pid_t pid;
int ioprio, ioclass, iodata;
int retval;
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);
Py_RETURN_NONE;
}
#endif
/*
* Return disk mounted partitions as a list of tuples including device,
* mount point and filesystem type
*/
static PyObject *
psutil_disk_partitions(PyObject *self, PyObject *args) {
FILE *file = NULL;
struct mntent *entry;
char *mtab_path;
PyObject *py_dev = NULL;
PyObject *py_mountp = NULL;
PyObject *py_tuple = NULL;
PyObject *py_retlist = PyList_New(0);
if (py_retlist == NULL)
return NULL;
if (!PyArg_ParseTuple(args, "s", &mtab_path))
return NULL;
Py_BEGIN_ALLOW_THREADS
file = setmntent(mtab_path, "r");
Py_END_ALLOW_THREADS
if ((file == 0) || (file == NULL)) {
psutil_debug("setmntent() failed");
PyErr_SetFromErrnoWithFilename(PyExc_OSError, mtab_path);
goto error;
}
while ((entry = getmntent(file))) {
if (entry == NULL) {
PyErr_Format(PyExc_RuntimeError, "getmntent() syscall failed");
goto error;
}
py_dev = PyUnicode_DecodeFSDefault(entry->mnt_fsname);
if (! py_dev)
goto error;
py_mountp = PyUnicode_DecodeFSDefault(entry->mnt_dir);
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)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_CLEAR(py_dev);
Py_CLEAR(py_mountp);
Py_CLEAR(py_tuple);
}
endmntent(file);
return py_retlist;
error:
if (file != NULL)
endmntent(file);
Py_XDECREF(py_dev);
Py_XDECREF(py_mountp);
Py_XDECREF(py_tuple);
Py_DECREF(py_retlist);
return NULL;
}
/*
* A wrapper around sysinfo(), return system memory usage statistics.
*/
static PyObject *
psutil_linux_sysinfo(PyObject *self, PyObject *args) {
struct sysinfo info;
if (sysinfo(&info) != 0)
return PyErr_SetFromErrno(PyExc_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.freeswap, // swap free
info.mem_unit // multiplier
);
}
/*
* Return process CPU affinity as a Python list
*/
#ifdef PSUTIL_HAVE_CPU_AFFINITY
static PyObject *
psutil_proc_cpu_affinity_get(PyObject *self, PyObject *args) {
int cpu, ncpus, count, cpucount_s;
pid_t pid;
size_t setsize;
cpu_set_t *mask = NULL;
PyObject *py_list = NULL;
if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
return NULL;
ncpus = NCPUS_START;
while (1) {
setsize = CPU_ALLOC_SIZE(ncpus);
mask = CPU_ALLOC(ncpus);
if (mask == NULL) {
psutil_debug("CPU_ALLOC() failed");
return PyErr_NoMemory();
}
if (sched_getaffinity(pid, setsize, mask) == 0)
break;
CPU_FREE(mask);
if (errno != EINVAL)
return PyErr_SetFromErrno(PyExc_OSError);
if (ncpus > INT_MAX / 2) {
PyErr_SetString(PyExc_OverflowError, "could not allocate "
"a large enough CPU set");
return NULL;
}
ncpus = ncpus * 2;
}
py_list = PyList_New(0);
if (py_list == NULL)
goto error;
cpucount_s = CPU_COUNT_S(setsize, mask);
for (cpu = 0, count = cpucount_s; count; cpu++) {
if (CPU_ISSET_S(cpu, setsize, mask)) {
#if PY_MAJOR_VERSION >= 3
PyObject *cpu_num = PyLong_FromLong(cpu);
#else
PyObject *cpu_num = PyInt_FromLong(cpu);
#endif
if (cpu_num == NULL)
goto error;
if (PyList_Append(py_list, cpu_num)) {
Py_DECREF(cpu_num);
goto error;
}
Py_DECREF(cpu_num);
--count;
}
}
CPU_FREE(mask);
return py_list;
error:
if (mask)
CPU_FREE(mask);
Py_XDECREF(py_list);
return NULL;
}
/*
* Set process CPU affinity; expects a bitmask
*/
static PyObject *
psutil_proc_cpu_affinity_set(PyObject *self, PyObject *args) {
cpu_set_t cpu_set;
size_t len;
pid_t pid;
Py_ssize_t i, seq_len;
PyObject *py_cpu_set;
if (!PyArg_ParseTuple(args, _Py_PARSE_PID "O", &pid, &py_cpu_set))
return NULL;
if (!PySequence_Check(py_cpu_set)) {
return PyErr_Format(
PyExc_TypeError,
#if PY_MAJOR_VERSION >= 3
"sequence argument expected, got %R", Py_TYPE(py_cpu_set)
#else
"sequence argument expected, got %s", Py_TYPE(py_cpu_set)->tp_name
#endif
);
}
seq_len = PySequence_Size(py_cpu_set);
if (seq_len < 0) {
return NULL;
}
CPU_ZERO(&cpu_set);
for (i = 0; i < seq_len; i++) {
PyObject *item = PySequence_GetItem(py_cpu_set, i);
if (!item) {
return NULL;
}
#if PY_MAJOR_VERSION >= 3
long value = PyLong_AsLong(item);
#else
long value = PyInt_AsLong(item);
#endif
Py_XDECREF(item);
if ((value == -1) || PyErr_Occurred()) {
if (!PyErr_Occurred())
PyErr_SetString(PyExc_ValueError, "invalid CPU value");
return NULL;
}
CPU_SET(value, &cpu_set);
}
len = sizeof(cpu_set);
if (sched_setaffinity(pid, len, &cpu_set)) {
return PyErr_SetFromErrno(PyExc_OSError);
}
Py_RETURN_NONE;
}
#endif /* PSUTIL_HAVE_CPU_AFFINITY */
/*
* Return currently connected users as a list of tuples.
*/
static PyObject *
psutil_users(PyObject *self, PyObject *args) {
struct utmp *ut;
PyObject *py_retlist = PyList_New(0);
PyObject *py_tuple = NULL;
PyObject *py_username = NULL;
PyObject *py_tty = NULL;
PyObject *py_hostname = NULL;
PyObject *py_user_proc = NULL;
if (py_retlist == NULL)
return NULL;
setutent();
while (NULL != (ut = getutent())) {
py_tuple = NULL;
py_user_proc = NULL;
if (ut->ut_type == USER_PROCESS)
py_user_proc = Py_True;
else
py_user_proc = Py_False;
py_username = PyUnicode_DecodeFSDefault(ut->ut_user);
if (! py_username)
goto error;
py_tty = PyUnicode_DecodeFSDefault(ut->ut_line);
if (! py_tty)
goto error;
py_hostname = PyUnicode_DecodeFSDefault(ut->ut_host);
if (! py_hostname)
goto error;
py_tuple = Py_BuildValue(
"OOOdO" _Py_PARSE_PID,
py_username, // username
py_tty, // tty
py_hostname, // hostname
(double)ut->ut_tv.tv_sec, // tstamp
py_user_proc, // (bool) user process
ut->ut_pid // process id
);
if (! py_tuple)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_CLEAR(py_username);
Py_CLEAR(py_tty);
Py_CLEAR(py_hostname);
Py_CLEAR(py_tuple);
}
endutent();
return py_retlist;
error:
Py_XDECREF(py_username);
Py_XDECREF(py_tty);
Py_XDECREF(py_hostname);
Py_XDECREF(py_tuple);
Py_DECREF(py_retlist);
endutent();
return NULL;
}
/*
* Return stats about a particular network
* interface. References:
* https://github.com/dpaleino/wicd/blob/master/wicd/backends/be-ioctl.py
* http://www.i-scream.org/libstatgrab/
*/
static PyObject*
psutil_net_if_duplex_speed(PyObject* self, PyObject* args) {
char *nic_name;
int sock = 0;
int ret;
int duplex;
__u32 uint_speed;
int speed;
struct ifreq ifr;
struct ethtool_cmd ethcmd;
PyObject *py_retlist = NULL;
if (! PyArg_ParseTuple(args, "s", &nic_name))
return NULL;
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock == -1)
return PyErr_SetFromOSErrnoWithSyscall("socket()");
PSUTIL_STRNCPY(ifr.ifr_name, nic_name, sizeof(ifr.ifr_name));
// duplex and speed
memset(ðcmd, 0, sizeof ethcmd);
ethcmd.cmd = ETHTOOL_GSET;
ifr.ifr_data = (void *)ðcmd;
ret = ioctl(sock, SIOCETHTOOL, &ifr);
if (ret != -1) {
duplex = ethcmd.duplex;
// speed is returned from ethtool as a __u32 ranging from 0 to INT_MAX
// or SPEED_UNKNOWN (-1)
uint_speed = psutil_ethtool_cmd_speed(ðcmd);
if (uint_speed == (__u32)SPEED_UNKNOWN || uint_speed > INT_MAX) {
speed = 0;
}
else {
speed = (int)uint_speed;
}
}
else {
if ((errno == EOPNOTSUPP) || (errno == EINVAL)) {
// EOPNOTSUPP may occur in case of wi-fi cards.
// For EINVAL see:
// https://github.com/giampaolo/psutil/issues/797
// #issuecomment-202999532
duplex = DUPLEX_UNKNOWN;
speed = 0;
}
else {
PyErr_SetFromOSErrnoWithSyscall("ioctl(SIOCETHTOOL)");
goto error;
}
}
py_retlist = Py_BuildValue("[ii]", duplex, speed);
if (!py_retlist)
goto error;
close(sock);
return py_retlist;
error:
if (sock != -1)
close(sock);
return NULL;
}
/*
* Module init.
*/
static PyMethodDef mod_methods[] = {
// --- per-process functions
#if PSUTIL_HAVE_IOPRIO
{"proc_ioprio_get", psutil_proc_ioprio_get, METH_VARARGS},
{"proc_ioprio_set", psutil_proc_ioprio_set, METH_VARARGS},
#endif
#ifdef PSUTIL_HAVE_CPU_AFFINITY
{"proc_cpu_affinity_get", psutil_proc_cpu_affinity_get, METH_VARARGS},
{"proc_cpu_affinity_set", psutil_proc_cpu_affinity_set, METH_VARARGS},
#endif
// --- system related functions
{"disk_partitions", psutil_disk_partitions, METH_VARARGS},
{"users", psutil_users, METH_VARARGS},
{"net_if_duplex_speed", psutil_net_if_duplex_speed, METH_VARARGS},
// --- linux specific
{"linux_sysinfo", psutil_linux_sysinfo, METH_VARARGS},
// --- others
{"check_pid_range", psutil_check_pid_range, METH_VARARGS},
{"set_debug", psutil_set_debug, METH_VARARGS},
{NULL, NULL, 0, NULL}
};
#if PY_MAJOR_VERSION >= 3
#define INITERR return NULL
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"_psutil_linux",
NULL,
-1,
mod_methods,
NULL,
NULL,
NULL,
NULL
};
PyObject *PyInit__psutil_linux(void)
#else /* PY_MAJOR_VERSION */
#define INITERR return
void init_psutil_linux(void)
#endif /* PY_MAJOR_VERSION */
{
#if PY_MAJOR_VERSION >= 3
PyObject *mod = PyModule_Create(&moduledef);
#else
PyObject *mod = Py_InitModule("_psutil_linux", mod_methods);
#endif
if (mod == NULL)
INITERR;
if (PyModule_AddIntConstant(mod, "version", PSUTIL_VERSION)) INITERR;
if (PyModule_AddIntConstant(mod, "DUPLEX_HALF", DUPLEX_HALF)) INITERR;
if (PyModule_AddIntConstant(mod, "DUPLEX_FULL", DUPLEX_FULL)) INITERR;
if (PyModule_AddIntConstant(mod, "DUPLEX_UNKNOWN", DUPLEX_UNKNOWN)) INITERR;
psutil_setup();
if (mod == NULL)
INITERR;
#if PY_MAJOR_VERSION >= 3
return mod;
#endif
}
| 15,257 | 25.721541 | 80 | c |
psutil | psutil-master/psutil/_psutil_osx.c | /*
* 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.
*
* macOS platform-specific module methods.
*/
#include <Python.h>
#include <sys/proc.h>
#include <netinet/tcp_fsm.h>
#include "_psutil_common.h"
#include "arch/osx/cpu.h"
#include "arch/osx/disk.h"
#include "arch/osx/mem.h"
#include "arch/osx/net.h"
#include "arch/osx/proc.h"
#include "arch/osx/sensors.h"
#include "arch/osx/sys.h"
static PyMethodDef mod_methods[] = {
// --- per-process functions
{"proc_cmdline", psutil_proc_cmdline, METH_VARARGS},
{"proc_connections", psutil_proc_connections, METH_VARARGS},
{"proc_cwd", psutil_proc_cwd, METH_VARARGS},
{"proc_environ", psutil_proc_environ, METH_VARARGS},
{"proc_exe", psutil_proc_exe, METH_VARARGS},
{"proc_kinfo_oneshot", psutil_proc_kinfo_oneshot, METH_VARARGS},
{"proc_memory_uss", psutil_proc_memory_uss, METH_VARARGS},
{"proc_name", psutil_proc_name, 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_threads", psutil_proc_threads, METH_VARARGS},
// --- system-related functions
{"boot_time", psutil_boot_time, METH_VARARGS},
{"cpu_count_cores", psutil_cpu_count_cores, METH_VARARGS},
{"cpu_count_logical", psutil_cpu_count_logical, METH_VARARGS},
{"cpu_freq", psutil_cpu_freq, METH_VARARGS},
{"cpu_stats", psutil_cpu_stats, METH_VARARGS},
{"cpu_times", psutil_cpu_times, METH_VARARGS},
{"disk_io_counters", psutil_disk_io_counters, METH_VARARGS},
{"disk_partitions", psutil_disk_partitions, METH_VARARGS},
{"disk_usage_used", psutil_disk_usage_used, METH_VARARGS},
{"net_io_counters", psutil_net_io_counters, METH_VARARGS},
{"per_cpu_times", psutil_per_cpu_times, METH_VARARGS},
{"pids", psutil_pids, METH_VARARGS},
{"sensors_battery", psutil_sensors_battery, METH_VARARGS},
{"swap_mem", psutil_swap_mem, METH_VARARGS},
{"users", psutil_users, METH_VARARGS},
{"virtual_mem", psutil_virtual_mem, METH_VARARGS},
// --- others
{"check_pid_range", psutil_check_pid_range, METH_VARARGS},
{"set_debug", psutil_set_debug, METH_VARARGS},
{NULL, NULL, 0, NULL}
};
#if PY_MAJOR_VERSION >= 3
#define INITERR return NULL
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"_psutil_osx",
NULL,
-1,
mod_methods,
NULL,
NULL,
NULL,
NULL
};
PyObject *PyInit__psutil_osx(void)
#else /* PY_MAJOR_VERSION */
#define INITERR return
void init_psutil_osx(void)
#endif /* PY_MAJOR_VERSION */
{
#if PY_MAJOR_VERSION >= 3
PyObject *mod = PyModule_Create(&moduledef);
#else
PyObject *mod = Py_InitModule("_psutil_osx", mod_methods);
#endif
if (mod == NULL)
INITERR;
if (psutil_setup() != 0)
INITERR;
if (PyModule_AddIntConstant(mod, "version", PSUTIL_VERSION))
INITERR;
// process status constants, defined in:
// http://fxr.watson.org/fxr/source/bsd/sys/proc.h?v=xnu-792.6.70#L149
if (PyModule_AddIntConstant(mod, "SIDL", SIDL))
INITERR;
if (PyModule_AddIntConstant(mod, "SRUN", SRUN))
INITERR;
if (PyModule_AddIntConstant(mod, "SSLEEP", SSLEEP))
INITERR;
if (PyModule_AddIntConstant(mod, "SSTOP", SSTOP))
INITERR;
if (PyModule_AddIntConstant(mod, "SZOMB", SZOMB))
INITERR;
// connection status constants
if (PyModule_AddIntConstant(mod, "TCPS_CLOSED", TCPS_CLOSED))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_CLOSING", TCPS_CLOSING))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_CLOSE_WAIT", TCPS_CLOSE_WAIT))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_LISTEN", TCPS_LISTEN))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_ESTABLISHED", TCPS_ESTABLISHED))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_SYN_SENT", TCPS_SYN_SENT))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_SYN_RECEIVED", TCPS_SYN_RECEIVED))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_FIN_WAIT_1", TCPS_FIN_WAIT_1))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_FIN_WAIT_2", TCPS_FIN_WAIT_2))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_LAST_ACK", TCPS_LAST_ACK))
INITERR;
if (PyModule_AddIntConstant(mod, "TCPS_TIME_WAIT", TCPS_TIME_WAIT))
INITERR;
if (PyModule_AddIntConstant(mod, "PSUTIL_CONN_NONE", PSUTIL_CONN_NONE))
INITERR;
if (mod == NULL)
INITERR;
#if PY_MAJOR_VERSION >= 3
return mod;
#endif
}
| 4,821 | 32.72028 | 80 | c |
psutil | psutil-master/psutil/_psutil_windows.c | /*
* 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.
*
* Windows platform-specific module methods for _psutil_windows.
*
* List of undocumented Windows NT APIs which are used in here and in
* other modules:
* - NtQuerySystemInformation
* - NtQueryInformationProcess
* - NtQueryObject
* - NtSuspendProcess
* - NtResumeProcess
*/
#include <Python.h>
#include <windows.h>
#include "_psutil_common.h"
#include "arch/windows/cpu.h"
#include "arch/windows/disk.h"
#include "arch/windows/mem.h"
#include "arch/windows/net.h"
#include "arch/windows/proc.h"
#include "arch/windows/proc_handles.h"
#include "arch/windows/proc_info.h"
#include "arch/windows/proc_utils.h"
#include "arch/windows/security.h"
#include "arch/windows/sensors.h"
#include "arch/windows/services.h"
#include "arch/windows/socks.h"
#include "arch/windows/sys.h"
#include "arch/windows/wmi.h"
// ------------------------ Python init ---------------------------
static PyMethodDef
PsutilMethods[] = {
// --- per-process functions
{"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},
{"proc_cwd", psutil_proc_cwd, METH_VARARGS},
{"proc_environ", psutil_proc_environ, METH_VARARGS},
{"proc_exe", psutil_proc_exe, METH_VARARGS},
{"proc_io_counters", psutil_proc_io_counters, METH_VARARGS},
{"proc_io_priority_get", psutil_proc_io_priority_get, METH_VARARGS},
{"proc_io_priority_set", psutil_proc_io_priority_set, METH_VARARGS},
{"proc_is_suspended", psutil_proc_is_suspended, METH_VARARGS},
{"proc_kill", psutil_proc_kill, METH_VARARGS},
{"proc_memory_info", psutil_proc_memory_info, METH_VARARGS},
{"proc_memory_maps", psutil_proc_memory_maps, METH_VARARGS},
{"proc_memory_uss", psutil_proc_memory_uss, METH_VARARGS},
{"proc_num_handles", psutil_proc_num_handles, METH_VARARGS},
{"proc_open_files", psutil_proc_open_files, METH_VARARGS},
{"proc_priority_get", psutil_proc_priority_get, METH_VARARGS},
{"proc_priority_set", psutil_proc_priority_set, METH_VARARGS},
{"proc_suspend_or_resume", psutil_proc_suspend_or_resume, METH_VARARGS},
{"proc_threads", psutil_proc_threads, METH_VARARGS},
{"proc_times", psutil_proc_times, METH_VARARGS},
{"proc_username", psutil_proc_username, METH_VARARGS},
{"proc_wait", psutil_proc_wait, METH_VARARGS},
// --- alternative pinfo interface
{"proc_info", psutil_proc_info, METH_VARARGS},
// --- system-related functions
{"boot_time", psutil_boot_time, METH_VARARGS},
{"cpu_count_cores", psutil_cpu_count_cores, METH_VARARGS},
{"cpu_count_logical", psutil_cpu_count_logical, METH_VARARGS},
{"cpu_freq", psutil_cpu_freq, METH_VARARGS},
{"cpu_stats", psutil_cpu_stats, METH_VARARGS},
{"cpu_times", psutil_cpu_times, METH_VARARGS},
{"disk_io_counters", psutil_disk_io_counters, METH_VARARGS},
{"disk_partitions", psutil_disk_partitions, METH_VARARGS},
{"disk_usage", psutil_disk_usage, METH_VARARGS},
{"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},
{"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},
{"net_io_counters", psutil_net_io_counters, METH_VARARGS},
{"per_cpu_times", psutil_per_cpu_times, METH_VARARGS},
{"pid_exists", psutil_pid_exists, METH_VARARGS},
{"pids", psutil_pids, METH_VARARGS},
{"ppid_map", psutil_ppid_map, METH_VARARGS},
{"sensors_battery", psutil_sensors_battery, METH_VARARGS},
{"users", psutil_users, METH_VARARGS},
{"virtual_mem", psutil_virtual_mem, METH_VARARGS},
// --- windows services
{"winservice_enumerate", psutil_winservice_enumerate, METH_VARARGS},
{"winservice_query_config", psutil_winservice_query_config, METH_VARARGS},
{"winservice_query_descr", psutil_winservice_query_descr, METH_VARARGS},
{"winservice_query_status", psutil_winservice_query_status, METH_VARARGS},
{"winservice_start", psutil_winservice_start, METH_VARARGS},
{"winservice_stop", psutil_winservice_stop, METH_VARARGS},
// --- windows API bindings
{"QueryDosDevice", psutil_QueryDosDevice, METH_VARARGS},
// --- others
{"check_pid_range", psutil_check_pid_range, METH_VARARGS},
{"set_debug", psutil_set_debug, METH_VARARGS},
{NULL, NULL, 0, NULL}
};
struct module_state {
PyObject *error;
};
#if PY_MAJOR_VERSION >= 3
#define GETSTATE(m) ((struct module_state*)PyModule_GetState(m))
#else
#define GETSTATE(m) (&_state)
static struct module_state _state;
#endif
#if PY_MAJOR_VERSION >= 3
static int psutil_windows_traverse(PyObject *m, visitproc visit, void *arg) {
Py_VISIT(GETSTATE(m)->error);
return 0;
}
static int psutil_windows_clear(PyObject *m) {
Py_CLEAR(GETSTATE(m)->error);
return 0;
}
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"psutil_windows",
NULL,
sizeof(struct module_state),
PsutilMethods,
NULL,
psutil_windows_traverse,
psutil_windows_clear,
NULL
};
#define INITERROR return NULL
PyMODINIT_FUNC PyInit__psutil_windows(void)
#else
#define INITERROR return
void init_psutil_windows(void)
#endif
{
struct module_state *st = NULL;
#if PY_MAJOR_VERSION >= 3
PyObject *module = PyModule_Create(&moduledef);
#else
PyObject *module = Py_InitModule("_psutil_windows", PsutilMethods);
#endif
if (module == NULL)
INITERROR;
if (psutil_setup() != 0)
INITERROR;
if (psutil_set_se_debug() != 0)
INITERROR;
st = GETSTATE(module);
st->error = PyErr_NewException("_psutil_windows.Error", NULL, NULL);
if (st->error == NULL) {
Py_DECREF(module);
INITERROR;
}
// Exceptions.
TimeoutExpired = PyErr_NewException(
"_psutil_windows.TimeoutExpired", NULL, NULL);
Py_INCREF(TimeoutExpired);
PyModule_AddObject(module, "TimeoutExpired", TimeoutExpired);
TimeoutAbandoned = PyErr_NewException(
"_psutil_windows.TimeoutAbandoned", NULL, NULL);
Py_INCREF(TimeoutAbandoned);
PyModule_AddObject(module, "TimeoutAbandoned", TimeoutAbandoned);
// version constant
PyModule_AddIntConstant(module, "version", PSUTIL_VERSION);
// process status constants
// http://msdn.microsoft.com/en-us/library/ms683211(v=vs.85).aspx
PyModule_AddIntConstant(
module, "ABOVE_NORMAL_PRIORITY_CLASS", ABOVE_NORMAL_PRIORITY_CLASS);
PyModule_AddIntConstant(
module, "BELOW_NORMAL_PRIORITY_CLASS", BELOW_NORMAL_PRIORITY_CLASS);
PyModule_AddIntConstant(
module, "HIGH_PRIORITY_CLASS", HIGH_PRIORITY_CLASS);
PyModule_AddIntConstant(
module, "IDLE_PRIORITY_CLASS", IDLE_PRIORITY_CLASS);
PyModule_AddIntConstant(
module, "NORMAL_PRIORITY_CLASS", NORMAL_PRIORITY_CLASS);
PyModule_AddIntConstant(
module, "REALTIME_PRIORITY_CLASS", REALTIME_PRIORITY_CLASS);
// connection status constants
// http://msdn.microsoft.com/en-us/library/cc669305.aspx
PyModule_AddIntConstant(
module, "MIB_TCP_STATE_CLOSED", MIB_TCP_STATE_CLOSED);
PyModule_AddIntConstant(
module, "MIB_TCP_STATE_CLOSING", MIB_TCP_STATE_CLOSING);
PyModule_AddIntConstant(
module, "MIB_TCP_STATE_CLOSE_WAIT", MIB_TCP_STATE_CLOSE_WAIT);
PyModule_AddIntConstant(
module, "MIB_TCP_STATE_LISTEN", MIB_TCP_STATE_LISTEN);
PyModule_AddIntConstant(
module, "MIB_TCP_STATE_ESTAB", MIB_TCP_STATE_ESTAB);
PyModule_AddIntConstant(
module, "MIB_TCP_STATE_SYN_SENT", MIB_TCP_STATE_SYN_SENT);
PyModule_AddIntConstant(
module, "MIB_TCP_STATE_SYN_RCVD", MIB_TCP_STATE_SYN_RCVD);
PyModule_AddIntConstant(
module, "MIB_TCP_STATE_FIN_WAIT1", MIB_TCP_STATE_FIN_WAIT1);
PyModule_AddIntConstant(
module, "MIB_TCP_STATE_FIN_WAIT2", MIB_TCP_STATE_FIN_WAIT2);
PyModule_AddIntConstant(
module, "MIB_TCP_STATE_LAST_ACK", MIB_TCP_STATE_LAST_ACK);
PyModule_AddIntConstant(
module, "MIB_TCP_STATE_TIME_WAIT", MIB_TCP_STATE_TIME_WAIT);
PyModule_AddIntConstant(
module, "MIB_TCP_STATE_TIME_WAIT", MIB_TCP_STATE_TIME_WAIT);
PyModule_AddIntConstant(
module, "MIB_TCP_STATE_DELETE_TCB", MIB_TCP_STATE_DELETE_TCB);
PyModule_AddIntConstant(
module, "PSUTIL_CONN_NONE", PSUTIL_CONN_NONE);
// service status constants
/*
PyModule_AddIntConstant(
module, "SERVICE_CONTINUE_PENDING", SERVICE_CONTINUE_PENDING);
PyModule_AddIntConstant(
module, "SERVICE_PAUSE_PENDING", SERVICE_PAUSE_PENDING);
PyModule_AddIntConstant(
module, "SERVICE_PAUSED", SERVICE_PAUSED);
PyModule_AddIntConstant(
module, "SERVICE_RUNNING", SERVICE_RUNNING);
PyModule_AddIntConstant(
module, "SERVICE_START_PENDING", SERVICE_START_PENDING);
PyModule_AddIntConstant(
module, "SERVICE_STOP_PENDING", SERVICE_STOP_PENDING);
PyModule_AddIntConstant(
module, "SERVICE_STOPPED", SERVICE_STOPPED);
*/
// ...for internal use in _psutil_windows.py
PyModule_AddIntConstant(
module, "INFINITE", INFINITE);
PyModule_AddIntConstant(
module, "ERROR_ACCESS_DENIED", ERROR_ACCESS_DENIED);
PyModule_AddIntConstant(
module, "ERROR_INVALID_NAME", ERROR_INVALID_NAME);
PyModule_AddIntConstant(
module, "ERROR_SERVICE_DOES_NOT_EXIST", ERROR_SERVICE_DOES_NOT_EXIST);
PyModule_AddIntConstant(
module, "ERROR_PRIVILEGE_NOT_HELD", ERROR_PRIVILEGE_NOT_HELD);
PyModule_AddIntConstant(
module, "WINVER", PSUTIL_WINVER);
PyModule_AddIntConstant(
module, "WINDOWS_VISTA", PSUTIL_WINDOWS_VISTA);
PyModule_AddIntConstant(
module, "WINDOWS_7", PSUTIL_WINDOWS_7);
PyModule_AddIntConstant(
module, "WINDOWS_8", PSUTIL_WINDOWS_8);
PyModule_AddIntConstant(
module, "WINDOWS_8_1", PSUTIL_WINDOWS_8_1);
PyModule_AddIntConstant(
module, "WINDOWS_10", PSUTIL_WINDOWS_10);
#if PY_MAJOR_VERSION >= 3
return module;
#endif
}
| 10,563 | 35.937063 | 85 | c |
psutil | psutil-master/psutil/arch/aix/common.c | /*
* Copyright (c) 2017, Arnon Yaari
* 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 <sys/core.h>
#include <stdlib.h>
#include "common.h"
/* psutil_kread() - read from kernel memory */
int
psutil_kread(
int Kd, /* kernel memory file descriptor */
KA_T addr, /* kernel memory address */
char *buf, /* buffer to receive data */
size_t len) { /* length to read */
int br;
if (lseek64(Kd, (off64_t)addr, L_SET) == (off64_t)-1) {
PyErr_SetFromErrno(PyExc_OSError);
return 1;
}
br = read(Kd, buf, len);
if (br == -1) {
PyErr_SetFromErrno(PyExc_OSError);
return 1;
}
if (br != len) {
PyErr_SetString(PyExc_RuntimeError,
"size mismatch when reading kernel memory fd");
return 1;
}
return 0;
}
struct procentry64 *
psutil_read_process_table(int * num) {
size_t msz;
pid32_t pid = 0;
struct procentry64 *processes = (struct procentry64 *)NULL;
struct procentry64 *p;
int Np = 0; /* number of processes allocated in 'processes' */
int np = 0; /* number of processes read into 'processes' */
int i; /* number of processes read in current iteration */
msz = (size_t)(PROCSIZE * PROCINFO_INCR);
processes = (struct procentry64 *)malloc(msz);
if (!processes) {
PyErr_NoMemory();
return NULL;
}
Np = PROCINFO_INCR;
p = processes;
while ((i = getprocs64(p, PROCSIZE, (struct fdsinfo64 *)NULL, 0, &pid,
PROCINFO_INCR))
== PROCINFO_INCR) {
np += PROCINFO_INCR;
if (np >= Np) {
msz = (size_t)(PROCSIZE * (Np + PROCINFO_INCR));
processes = (struct procentry64 *)realloc((char *)processes, msz);
if (!processes) {
PyErr_NoMemory();
return NULL;
}
Np += PROCINFO_INCR;
}
p = (struct procentry64 *)((char *)processes + (np * PROCSIZE));
}
/* add the number of processes read in the last iteration */
if (i > 0)
np += i;
*num = np;
return processes;
}
| 2,285 | 27.575 | 78 | c |
psutil | psutil-master/psutil/arch/aix/common.h | /*
* Copyright (c) 2017, Arnon Yaari
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef __PSUTIL_AIX_COMMON_H__
#define __PSUTIL_AIX_COMMON_H__
#include <sys/core.h>
#define PROCINFO_INCR (256)
#define PROCSIZE (sizeof(struct procentry64))
#define FDSINFOSIZE (sizeof(struct fdsinfo64))
#define KMEM "/dev/kmem"
typedef u_longlong_t KA_T;
/* psutil_kread() - read from kernel memory */
int psutil_kread(int Kd, /* kernel memory file descriptor */
KA_T addr, /* kernel memory address */
char *buf, /* buffer to receive data */
size_t len); /* length to read */
struct procentry64 *
psutil_read_process_table(
int * num /* out - number of processes read */
);
#endif /* __PSUTIL_AIX_COMMON_H__ */
| 894 | 26.96875 | 73 | h |
psutil | psutil-master/psutil/arch/aix/ifaddrs.c | /*
* Copyright (c) 2017, Arnon Yaari
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
/*! Based on code from
https://lists.samba.org/archive/samba-technical/2009-February/063079.html
!*/
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <net/if.h>
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include "ifaddrs.h"
#define MAX(x,y) ((x)>(y)?(x):(y))
#define SIZE(p) MAX((p).sa_len,sizeof(p))
static struct sockaddr *
sa_dup(struct sockaddr *sa1)
{
struct sockaddr *sa2;
size_t sz = sa1->sa_len;
sa2 = (struct sockaddr *) calloc(1, sz);
if (sa2 == NULL)
return NULL;
memcpy(sa2, sa1, sz);
return sa2;
}
void freeifaddrs(struct ifaddrs *ifp)
{
if (NULL == ifp) return;
free(ifp->ifa_name);
free(ifp->ifa_addr);
free(ifp->ifa_netmask);
free(ifp->ifa_dstaddr);
freeifaddrs(ifp->ifa_next);
free(ifp);
}
int getifaddrs(struct ifaddrs **ifap)
{
int sd, ifsize;
char *ccp, *ecp;
struct ifconf ifc;
struct ifreq *ifr;
struct ifaddrs *cifa = NULL; /* current */
struct ifaddrs *pifa = NULL; /* previous */
const size_t IFREQSZ = sizeof(struct ifreq);
int fam;
*ifap = NULL;
sd = socket(AF_INET, SOCK_DGRAM, 0);
if (sd == -1)
goto error;
/* find how much memory to allocate for the SIOCGIFCONF call */
if (ioctl(sd, SIOCGSIZIFCONF, (caddr_t)&ifsize) < 0)
goto error;
ifc.ifc_req = (struct ifreq *) calloc(1, ifsize);
if (ifc.ifc_req == NULL)
goto error;
ifc.ifc_len = ifsize;
if (ioctl(sd, SIOCGIFCONF, &ifc) < 0)
goto error;
ccp = (char *)ifc.ifc_req;
ecp = ccp + ifsize;
while (ccp < ecp) {
ifr = (struct ifreq *) ccp;
ifsize = sizeof(ifr->ifr_name) + SIZE(ifr->ifr_addr);
fam = ifr->ifr_addr.sa_family;
if (fam == AF_INET || fam == AF_INET6) {
cifa = (struct ifaddrs *) calloc(1, sizeof(struct ifaddrs));
if (cifa == NULL)
goto error;
cifa->ifa_next = NULL;
if (pifa == NULL) *ifap = cifa; /* first one */
else pifa->ifa_next = cifa;
cifa->ifa_name = strdup(ifr->ifr_name);
if (cifa->ifa_name == NULL)
goto error;
cifa->ifa_flags = 0;
cifa->ifa_dstaddr = NULL;
cifa->ifa_addr = sa_dup(&ifr->ifr_addr);
if (cifa->ifa_addr == NULL)
goto error;
if (fam == AF_INET) {
if (ioctl(sd, SIOCGIFNETMASK, ifr, IFREQSZ) < 0)
goto error;
cifa->ifa_netmask = sa_dup(&ifr->ifr_addr);
if (cifa->ifa_netmask == NULL)
goto error;
}
if (0 == ioctl(sd, SIOCGIFFLAGS, ifr)) /* optional */
cifa->ifa_flags = ifr->ifr_flags;
if (fam == AF_INET) {
if (ioctl(sd, SIOCGIFDSTADDR, ifr, IFREQSZ) < 0) {
if (0 == ioctl(sd, SIOCGIFBRDADDR, ifr, IFREQSZ)) {
cifa->ifa_dstaddr = sa_dup(&ifr->ifr_addr);
if (cifa->ifa_dstaddr == NULL)
goto error;
}
}
else {
cifa->ifa_dstaddr = sa_dup(&ifr->ifr_addr);
if (cifa->ifa_dstaddr == NULL)
goto error;
}
}
pifa = cifa;
}
ccp += ifsize;
}
free(ifc.ifc_req);
close(sd);
return 0;
error:
if (ifc.ifc_req != NULL)
free(ifc.ifc_req);
if (sd != -1)
close(sd);
freeifaddrs(*ifap);
return (-1);
}
| 3,840 | 24.606667 | 77 | c |
psutil | psutil-master/psutil/arch/aix/ifaddrs.h | /*
* Copyright (c) 2017, Arnon Yaari
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
/*! Based on code from
https://lists.samba.org/archive/samba-technical/2009-February/063079.html
!*/
#ifndef GENERIC_AIX_IFADDRS_H
#define GENERIC_AIX_IFADDRS_H
#include <sys/socket.h>
#include <net/if.h>
#undef ifa_dstaddr
#undef ifa_broadaddr
#define ifa_broadaddr ifa_dstaddr
struct ifaddrs {
struct ifaddrs *ifa_next;
char *ifa_name;
unsigned int ifa_flags;
struct sockaddr *ifa_addr;
struct sockaddr *ifa_netmask;
struct sockaddr *ifa_dstaddr;
};
extern int getifaddrs(struct ifaddrs **);
extern void freeifaddrs(struct ifaddrs *);
#endif
| 767 | 20.942857 | 77 | h |
psutil | psutil-master/psutil/arch/aix/net_connections.c | /*
* Copyright (c) 2017, Arnon Yaari
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
/* Baded on code from lsof:
* http://www.ibm.com/developerworks/aix/library/au-lsof.html
* - dialects/aix/dproc.c:gather_proc_info
* - lib/prfp.c:process_file
* - dialects/aix/dsock.c:process_socket
* - dialects/aix/dproc.c:get_kernel_access
*/
#include <Python.h>
#include <stdlib.h>
#include <fcntl.h>
#define _KERNEL
#include <sys/file.h>
#undef _KERNEL
#include <sys/types.h>
#include <sys/core.h>
#include <sys/domain.h>
#include <sys/un.h>
#include <netinet/in_pcb.h>
#include <arpa/inet.h>
#include "../../_psutil_common.h"
#include "net_kernel_structs.h"
#include "net_connections.h"
#include "common.h"
#define NO_SOCKET (PyObject *)(-1)
static int
read_unp_addr(
int Kd,
KA_T unp_addr,
char *buf,
size_t buflen
) {
struct sockaddr_un *ua = (struct sockaddr_un *)NULL;
struct sockaddr_un un;
struct mbuf64 mb;
int uo;
if (psutil_kread(Kd, unp_addr, (char *)&mb, sizeof(mb))) {
return 1;
}
uo = (int)(mb.m_hdr.mh_data - unp_addr);
if ((uo + sizeof(struct sockaddr)) <= sizeof(mb))
ua = (struct sockaddr_un *)((char *)&mb + uo);
else {
if (psutil_kread(Kd, (KA_T)mb.m_hdr.mh_data,
(char *)&un, sizeof(un))) {
return 1;
}
ua = &un;
}
if (ua && ua->sun_path[0]) {
if (mb.m_len > sizeof(struct sockaddr_un))
mb.m_len = sizeof(struct sockaddr_un);
*((char *)ua + mb.m_len - 1) = '\0';
snprintf(buf, buflen, "%s", ua->sun_path);
}
return 0;
}
static PyObject *
process_file(int Kd, pid32_t pid, int fd, KA_T fp) {
struct file64 f;
struct socket64 s;
struct protosw64 p;
struct domain d;
struct inpcb64 inp;
int fam;
struct tcpcb64 t;
int state = PSUTIL_CONN_NONE;
unsigned char *laddr = (unsigned char *)NULL;
unsigned char *raddr = (unsigned char *)NULL;
int rport, lport;
char laddr_str[INET6_ADDRSTRLEN];
char raddr_str[INET6_ADDRSTRLEN];
struct unpcb64 unp;
char unix_laddr_str[PATH_MAX] = { 0 };
char unix_raddr_str[PATH_MAX] = { 0 };
/* Read file structure */
if (psutil_kread(Kd, fp, (char *)&f, sizeof(f))) {
return NULL;
}
if (!f.f_count || f.f_type != DTYPE_SOCKET) {
return NO_SOCKET;
}
if (psutil_kread(Kd, (KA_T) f.f_data, (char *) &s, sizeof(s))) {
return NULL;
}
if (!s.so_type) {
return NO_SOCKET;
}
if (!s.so_proto) {
PyErr_SetString(PyExc_RuntimeError, "invalid socket protocol handle");
return NULL;
}
if (psutil_kread(Kd, (KA_T)s.so_proto, (char *)&p, sizeof(p))) {
return NULL;
}
if (!p.pr_domain) {
PyErr_SetString(PyExc_RuntimeError, "invalid socket protocol domain");
return NULL;
}
if (psutil_kread(Kd, (KA_T)p.pr_domain, (char *)&d, sizeof(d))) {
return NULL;
}
fam = d.dom_family;
if (fam == AF_INET || fam == AF_INET6) {
/* Read protocol control block */
if (!s.so_pcb) {
PyErr_SetString(PyExc_RuntimeError, "invalid socket PCB");
return NULL;
}
if (psutil_kread(Kd, (KA_T) s.so_pcb, (char *) &inp, sizeof(inp))) {
return NULL;
}
if (p.pr_protocol == IPPROTO_TCP) {
/* If this is a TCP socket, read its control block */
if (inp.inp_ppcb
&& !psutil_kread(Kd, (KA_T)inp.inp_ppcb,
(char *)&t, sizeof(t)))
state = t.t_state;
}
if (fam == AF_INET6) {
laddr = (unsigned char *)&inp.inp_laddr6;
if (!IN6_IS_ADDR_UNSPECIFIED(&inp.inp_faddr6)) {
raddr = (unsigned char *)&inp.inp_faddr6;
rport = (int)ntohs(inp.inp_fport);
}
}
if (fam == AF_INET) {
laddr = (unsigned char *)&inp.inp_laddr;
if (inp.inp_faddr.s_addr != INADDR_ANY || inp.inp_fport != 0) {
raddr = (unsigned char *)&inp.inp_faddr;
rport = (int)ntohs(inp.inp_fport);
}
}
lport = (int)ntohs(inp.inp_lport);
inet_ntop(fam, laddr, laddr_str, sizeof(laddr_str));
if (raddr != NULL) {
inet_ntop(fam, raddr, raddr_str, sizeof(raddr_str));
return Py_BuildValue("(iii(si)(si)ii)", fd, fam,
s.so_type, laddr_str, lport, raddr_str,
rport, state, pid);
}
else {
return Py_BuildValue("(iii(si)()ii)", fd, fam,
s.so_type, laddr_str, lport, state,
pid);
}
}
if (fam == AF_UNIX) {
if (psutil_kread(Kd, (KA_T) s.so_pcb, (char *)&unp, sizeof(unp))) {
return NULL;
}
if ((KA_T) f.f_data != (KA_T) unp.unp_socket) {
PyErr_SetString(PyExc_RuntimeError, "unp_socket mismatch");
return NULL;
}
if (unp.unp_addr) {
if (read_unp_addr(Kd, unp.unp_addr, unix_laddr_str,
sizeof(unix_laddr_str))) {
return NULL;
}
}
if (unp.unp_conn) {
if (psutil_kread(Kd, (KA_T) unp.unp_conn, (char *)&unp,
sizeof(unp))) {
return NULL;
}
if (read_unp_addr(Kd, unp.unp_addr, unix_raddr_str,
sizeof(unix_raddr_str))) {
return NULL;
}
}
return Py_BuildValue("(iiissii)", fd, d.dom_family,
s.so_type, unix_laddr_str, unix_raddr_str, PSUTIL_CONN_NONE,
pid);
}
return NO_SOCKET;
}
PyObject *
psutil_net_connections(PyObject *self, PyObject *args) {
PyObject *py_retlist = PyList_New(0);
PyObject *py_tuple = NULL;
KA_T fp;
int Kd = -1;
int i, np;
struct procentry64 *p;
struct fdsinfo64 *fds = (struct fdsinfo64 *)NULL;
pid32_t requested_pid;
pid32_t pid;
struct procentry64 *processes = (struct procentry64 *)NULL;
/* the process table */
if (py_retlist == NULL)
goto error;
if (! PyArg_ParseTuple(args, "i", &requested_pid))
goto error;
Kd = open(KMEM, O_RDONLY, 0);
if (Kd < 0) {
PyErr_SetFromErrnoWithFilename(PyExc_OSError, KMEM);
goto error;
}
processes = psutil_read_process_table(&np);
if (!processes)
goto error;
/* Loop through processes */
for (p = processes; np > 0; np--, p++) {
pid = p->pi_pid;
if (requested_pid != -1 && requested_pid != pid)
continue;
if (p->pi_state == 0 || p->pi_state == SZOMB)
continue;
if (!fds) {
fds = (struct fdsinfo64 *)malloc((size_t)FDSINFOSIZE);
if (!fds) {
PyErr_NoMemory();
goto error;
}
}
if (getprocs64((struct procentry64 *)NULL, PROCSIZE, fds, FDSINFOSIZE,
&pid, 1)
!= 1)
continue;
/* loop over file descriptors */
for (i = 0; i < p->pi_maxofile; i++) {
fp = (KA_T)fds->pi_ufd[i].fp;
if (fp) {
py_tuple = process_file(Kd, p->pi_pid, i, fp);
if (py_tuple == NULL)
goto error;
if (py_tuple != NO_SOCKET) {
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_DECREF(py_tuple);
}
}
}
}
close(Kd);
free(processes);
if (fds != NULL)
free(fds);
return py_retlist;
error:
Py_XDECREF(py_tuple);
Py_DECREF(py_retlist);
if (Kd > 0)
close(Kd);
if (processes != NULL)
free(processes);
if (fds != NULL)
free(fds);
return NULL;
}
| 8,134 | 27.246528 | 78 | c |
psutil | psutil-master/psutil/arch/aix/net_kernel_structs.h | /*
* Copyright (c) 2017, Arnon Yaari
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
/* The kernel is always 64 bit but Python is usually compiled as a 32 bit
* process. We're reading the kernel memory to get the network connections,
* so we need the structs we read to be defined with 64 bit "pointers".
* Here are the partial definitions of the structs we use, taken from the
* header files, with data type sizes converted to their 64 bit counterparts,
* and unused data truncated. */
#ifdef __64BIT__
/* In case we're in a 64 bit process after all */
#include <sys/socketvar.h>
#include <sys/protosw.h>
#include <sys/unpcb.h>
#include <sys/mbuf_base.h>
#include <sys/mbuf_macro.h>
#include <netinet/ip_var.h>
#include <netinet/tcp.h>
#include <netinet/tcpip.h>
#include <netinet/tcp_timer.h>
#include <netinet/tcp_var.h>
#define file64 file
#define socket64 socket
#define protosw64 protosw
#define inpcb64 inpcb
#define tcpcb64 tcpcb
#define unpcb64 unpcb
#define mbuf64 mbuf
#else /* __64BIT__ */
struct file64 {
int f_flag;
int f_count;
int f_options;
int f_type;
u_longlong_t f_data;
};
struct socket64 {
short so_type; /* generic type, see socket.h */
short so_options; /* from socket call, see socket.h */
ushort so_linger; /* time to linger while closing */
short so_state; /* internal state flags SS_*, below */
u_longlong_t so_pcb; /* protocol control block */
u_longlong_t so_proto; /* protocol handle */
};
struct protosw64 {
short pr_type; /* socket type used for */
u_longlong_t pr_domain; /* domain protocol a member of */
short pr_protocol; /* protocol number */
short pr_flags; /* see below */
};
struct inpcb64 {
u_longlong_t inp_next,inp_prev;
/* pointers to other pcb's */
u_longlong_t inp_head; /* pointer back to chain of inpcb's
for this protocol */
u_int32_t inp_iflowinfo; /* input flow label */
u_short inp_fport; /* foreign port */
u_int16_t inp_fatype; /* foreign address type */
union in_addr_6 inp_faddr_6; /* foreign host table entry */
u_int32_t inp_oflowinfo; /* output flow label */
u_short inp_lport; /* local port */
u_int16_t inp_latype; /* local address type */
union in_addr_6 inp_laddr_6; /* local host table entry */
u_longlong_t inp_socket; /* back pointer to socket */
u_longlong_t inp_ppcb; /* pointer to per-protocol pcb */
u_longlong_t space_rt;
struct sockaddr_in6 spare_dst;
u_longlong_t inp_ifa; /* interface address to use */
int inp_flags; /* generic IP/datagram flags */
};
struct tcpcb64 {
u_longlong_t seg__next;
u_longlong_t seg__prev;
short t_state; /* state of this connection */
};
struct unpcb64 {
u_longlong_t unp_socket; /* pointer back to socket */
u_longlong_t unp_vnode; /* if associated with file */
ino_t unp_vno; /* fake vnode number */
u_longlong_t unp_conn; /* control block of connected socket */
u_longlong_t unp_refs; /* referencing socket linked list */
u_longlong_t unp_nextref; /* link in unp_refs list */
u_longlong_t unp_addr; /* bound address of socket */
};
struct m_hdr64
{
u_longlong_t mh_next; /* next buffer in chain */
u_longlong_t mh_nextpkt; /* next chain in queue/record */
long mh_len; /* amount of data in this mbuf */
u_longlong_t mh_data; /* location of data */
};
struct mbuf64
{
struct m_hdr64 m_hdr;
};
#define m_len m_hdr.mh_len
#endif /* __64BIT__ */
| 4,060 | 35.258929 | 77 | h |
psutil | psutil-master/psutil/arch/bsd/cpu.c | /*
* 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 <sys/sysctl.h>
#include <sys/resource.h>
#include <sys/sched.h>
PyObject *
psutil_cpu_count_logical(PyObject *self, PyObject *args) {
int mib[2];
int ncpu;
size_t len;
mib[0] = CTL_HW;
mib[1] = HW_NCPU;
len = sizeof(ncpu);
if (sysctl(mib, 2, &ncpu, &len, NULL, 0) == -1)
Py_RETURN_NONE; // mimic os.cpu_count()
else
return Py_BuildValue("i", ncpu);
}
PyObject *
psutil_cpu_times(PyObject *self, PyObject *args) {
#ifdef PSUTIL_NETBSD
u_int64_t cpu_time[CPUSTATES];
#else
long cpu_time[CPUSTATES];
#endif
size_t size = sizeof(cpu_time);
int ret;
#if defined(PSUTIL_FREEBSD) || defined(PSUTIL_NETBSD)
ret = sysctlbyname("kern.cp_time", &cpu_time, &size, NULL, 0);
#elif PSUTIL_OPENBSD
int mib[] = {CTL_KERN, KERN_CPTIME};
ret = sysctl(mib, 2, &cpu_time, &size, NULL, 0);
#endif
if (ret == -1)
return PyErr_SetFromErrno(PyExc_OSError);
return Py_BuildValue("(ddddd)",
(double)cpu_time[CP_USER] / CLOCKS_PER_SEC,
(double)cpu_time[CP_NICE] / CLOCKS_PER_SEC,
(double)cpu_time[CP_SYS] / CLOCKS_PER_SEC,
(double)cpu_time[CP_IDLE] / CLOCKS_PER_SEC,
(double)cpu_time[CP_INTR] / CLOCKS_PER_SEC
);
}
| 1,552 | 26.732143 | 73 | c |
psutil | psutil-master/psutil/arch/bsd/disk.c | /*
* 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 <sys/mount.h>
#if PSUTIL_NETBSD
// getvfsstat()
#include <sys/types.h>
#include <sys/statvfs.h>
#else
// getfsstat()
#include <sys/param.h>
#include <sys/ucred.h>
#include <sys/mount.h>
#endif
PyObject *
psutil_disk_partitions(PyObject *self, PyObject *args) {
int num;
int i;
long len;
uint64_t flags;
char opts[200];
#ifdef PSUTIL_NETBSD
struct statvfs *fs = NULL;
#else
struct statfs *fs = NULL;
#endif
PyObject *py_retlist = PyList_New(0);
PyObject *py_dev = NULL;
PyObject *py_mountp = NULL;
PyObject *py_tuple = NULL;
if (py_retlist == NULL)
return NULL;
// get the number of mount points
Py_BEGIN_ALLOW_THREADS
#ifdef PSUTIL_NETBSD
num = getvfsstat(NULL, 0, MNT_NOWAIT);
#else
num = getfsstat(NULL, 0, MNT_NOWAIT);
#endif
Py_END_ALLOW_THREADS
if (num == -1) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
len = sizeof(*fs) * num;
fs = malloc(len);
if (fs == NULL) {
PyErr_NoMemory();
goto error;
}
Py_BEGIN_ALLOW_THREADS
#ifdef PSUTIL_NETBSD
num = getvfsstat(fs, len, MNT_NOWAIT);
#else
num = getfsstat(fs, len, MNT_NOWAIT);
#endif
Py_END_ALLOW_THREADS
if (num == -1) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
for (i = 0; i < num; i++) {
py_tuple = NULL;
opts[0] = 0;
#ifdef PSUTIL_NETBSD
flags = fs[i].f_flag;
#else
flags = fs[i].f_flags;
#endif
// see sys/mount.h
if (flags & MNT_RDONLY)
strlcat(opts, "ro", sizeof(opts));
else
strlcat(opts, "rw", sizeof(opts));
if (flags & MNT_SYNCHRONOUS)
strlcat(opts, ",sync", sizeof(opts));
if (flags & MNT_NOEXEC)
strlcat(opts, ",noexec", sizeof(opts));
if (flags & MNT_NOSUID)
strlcat(opts, ",nosuid", sizeof(opts));
if (flags & MNT_ASYNC)
strlcat(opts, ",async", sizeof(opts));
if (flags & MNT_NOATIME)
strlcat(opts, ",noatime", sizeof(opts));
if (flags & MNT_SOFTDEP)
strlcat(opts, ",softdep", sizeof(opts));
#ifdef PSUTIL_FREEBSD
if (flags & MNT_UNION)
strlcat(opts, ",union", sizeof(opts));
if (flags & MNT_SUIDDIR)
strlcat(opts, ",suiddir", sizeof(opts));
if (flags & MNT_SOFTDEP)
strlcat(opts, ",softdep", sizeof(opts));
if (flags & MNT_NOSYMFOLLOW)
strlcat(opts, ",nosymfollow", sizeof(opts));
#ifdef MNT_GJOURNAL
if (flags & MNT_GJOURNAL)
strlcat(opts, ",gjournal", sizeof(opts));
#endif
if (flags & MNT_MULTILABEL)
strlcat(opts, ",multilabel", sizeof(opts));
if (flags & MNT_ACLS)
strlcat(opts, ",acls", sizeof(opts));
if (flags & MNT_NOCLUSTERR)
strlcat(opts, ",noclusterr", sizeof(opts));
if (flags & MNT_NOCLUSTERW)
strlcat(opts, ",noclusterw", sizeof(opts));
#ifdef MNT_NFS4ACLS
if (flags & MNT_NFS4ACLS)
strlcat(opts, ",nfs4acls", sizeof(opts));
#endif
#elif PSUTIL_NETBSD
if (flags & MNT_NODEV)
strlcat(opts, ",nodev", sizeof(opts));
if (flags & MNT_UNION)
strlcat(opts, ",union", sizeof(opts));
if (flags & MNT_NOCOREDUMP)
strlcat(opts, ",nocoredump", sizeof(opts));
#ifdef MNT_RELATIME
if (flags & MNT_RELATIME)
strlcat(opts, ",relatime", sizeof(opts));
#endif
if (flags & MNT_IGNORE)
strlcat(opts, ",ignore", sizeof(opts));
#ifdef MNT_DISCARD
if (flags & MNT_DISCARD)
strlcat(opts, ",discard", sizeof(opts));
#endif
#ifdef MNT_EXTATTR
if (flags & MNT_EXTATTR)
strlcat(opts, ",extattr", sizeof(opts));
#endif
if (flags & MNT_LOG)
strlcat(opts, ",log", sizeof(opts));
if (flags & MNT_SYMPERM)
strlcat(opts, ",symperm", sizeof(opts));
if (flags & MNT_NODEVMTIME)
strlcat(opts, ",nodevmtime", sizeof(opts));
#endif
py_dev = PyUnicode_DecodeFSDefault(fs[i].f_mntfromname);
if (! py_dev)
goto error;
py_mountp = PyUnicode_DecodeFSDefault(fs[i].f_mntonname);
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
if (!py_tuple)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_CLEAR(py_dev);
Py_CLEAR(py_mountp);
Py_CLEAR(py_tuple);
}
free(fs);
return py_retlist;
error:
Py_XDECREF(py_dev);
Py_XDECREF(py_mountp);
Py_XDECREF(py_tuple);
Py_DECREF(py_retlist);
if (fs != NULL)
free(fs);
return NULL;
}
| 5,271 | 27.652174 | 73 | c |
psutil | psutil-master/psutil/arch/bsd/net.c | /*
* 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 <sys/sysctl.h>
#include <string.h>
#include <net/if.h>
#include <net/if_dl.h>
#include <net/route.h>
PyObject *
psutil_net_io_counters(PyObject *self, PyObject *args) {
char *buf = NULL, *lim, *next;
struct if_msghdr *ifm;
int mib[6];
size_t len;
PyObject *py_retdict = PyDict_New();
PyObject *py_ifc_info = NULL;
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_IFLIST; // operation
mib[5] = 0;
if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
buf = malloc(len);
if (buf == NULL) {
PyErr_NoMemory();
goto error;
}
if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
lim = buf + len;
for (next = buf; next < lim; ) {
py_ifc_info = NULL;
ifm = (struct if_msghdr *)next;
next += ifm->ifm_msglen;
if (ifm->ifm_type == RTM_IFINFO) {
struct if_msghdr *if2m = (struct if_msghdr *)ifm;
struct sockaddr_dl *sdl = (struct sockaddr_dl *)(if2m + 1);
char ifc_name[32];
strncpy(ifc_name, sdl->sdl_data, sdl->sdl_nlen);
ifc_name[sdl->sdl_nlen] = 0;
// XXX: ignore usbus interfaces:
// http://lists.freebsd.org/pipermail/freebsd-current/
// 2011-October/028752.html
// 'ifconfig -a' doesn't show them, nor do we.
if (strncmp(ifc_name, "usbus", 5) == 0)
continue;
py_ifc_info = Py_BuildValue("(kkkkkkki)",
if2m->ifm_data.ifi_obytes,
if2m->ifm_data.ifi_ibytes,
if2m->ifm_data.ifi_opackets,
if2m->ifm_data.ifi_ipackets,
if2m->ifm_data.ifi_ierrors,
if2m->ifm_data.ifi_oerrors,
if2m->ifm_data.ifi_iqdrops,
#ifdef _IFI_OQDROPS
if2m->ifm_data.ifi_oqdrops
#else
0
#endif
);
if (!py_ifc_info)
goto error;
if (PyDict_SetItemString(py_retdict, ifc_name, py_ifc_info))
goto error;
Py_CLEAR(py_ifc_info);
}
else {
continue;
}
}
free(buf);
return py_retdict;
error:
Py_XDECREF(py_ifc_info);
Py_DECREF(py_retdict);
if (buf != NULL)
free(buf);
return NULL;
}
| 3,121 | 28.45283 | 73 | c |
psutil | psutil-master/psutil/arch/bsd/proc.c | /*
* 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 <kvm.h>
#include <sys/proc.h>
#include <sys/sysctl.h>
#include <sys/types.h>
#include <sys/file.h>
#include <sys/vnode.h> // VREG
#ifdef PSUTIL_FREEBSD
#include <sys/user.h> // kinfo_proc, kinfo_file, KF_*
#include <libutil.h> // kinfo_getfile()
#endif
#include "../../_psutil_common.h"
#include "../../_psutil_posix.h"
#ifdef PSUTIL_FREEBSD
#include "../../arch/freebsd/proc.h"
#elif PSUTIL_OPENBSD
#include "../../arch/openbsd/proc.h"
#elif PSUTIL_NETBSD
#include "../../arch/netbsd/proc.h"
#endif
// convert a timeval struct to a double
#define PSUTIL_TV2DOUBLE(t) ((t).tv_sec + (t).tv_usec / 1000000.0)
#if defined(PSUTIL_OPENBSD) || defined (PSUTIL_NETBSD)
#define PSUTIL_KPT2DOUBLE(t) (t ## _sec + t ## _usec / 1000000.0)
#endif
/*
* Return a Python list of all the PIDs running on the system.
*/
PyObject *
psutil_pids(PyObject *self, PyObject *args) {
kinfo_proc *proclist = NULL;
kinfo_proc *orig_address = NULL;
size_t num_processes;
size_t idx;
PyObject *py_retlist = PyList_New(0);
PyObject *py_pid = NULL;
if (py_retlist == NULL)
return NULL;
if (psutil_get_proc_list(&proclist, &num_processes) != 0)
goto error;
if (num_processes > 0) {
orig_address = proclist; // save so we can free it after we're done
for (idx = 0; idx < num_processes; idx++) {
#ifdef PSUTIL_FREEBSD
py_pid = PyLong_FromPid(proclist->ki_pid);
#elif defined(PSUTIL_OPENBSD) || defined(PSUTIL_NETBSD)
py_pid = PyLong_FromPid(proclist->p_pid);
#endif
if (!py_pid)
goto error;
if (PyList_Append(py_retlist, py_pid))
goto error;
Py_CLEAR(py_pid);
proclist++;
}
free(orig_address);
}
return py_retlist;
error:
Py_XDECREF(py_pid);
Py_DECREF(py_retlist);
if (orig_address != NULL)
free(orig_address);
return NULL;
}
/*
* Collect different info about a process in one shot and return
* them as a big Python tuple.
*/
PyObject *
psutil_proc_oneshot_info(PyObject *self, PyObject *args) {
pid_t pid;
long rss;
long vms;
long memtext;
long memdata;
long memstack;
int oncpu;
kinfo_proc kp;
long pagesize = psutil_getpagesize();
char str[1000];
PyObject *py_name;
PyObject *py_ppid;
PyObject *py_retlist;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
return NULL;
if (psutil_kinfo_proc(pid, &kp) == -1)
return NULL;
// Process
#ifdef PSUTIL_FREEBSD
sprintf(str, "%s", kp.ki_comm);
#elif defined(PSUTIL_OPENBSD) || defined(PSUTIL_NETBSD)
sprintf(str, "%s", kp.p_comm);
#endif
py_name = PyUnicode_DecodeFSDefault(str);
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();
py_name = Py_None;
}
// Py_INCREF(py_name);
// Calculate memory.
#ifdef PSUTIL_FREEBSD
rss = (long)kp.ki_rssize * pagesize;
vms = (long)kp.ki_size;
memtext = (long)kp.ki_tsize * pagesize;
memdata = (long)kp.ki_dsize * pagesize;
memstack = (long)kp.ki_ssize * pagesize;
#else
rss = (long)kp.p_vm_rssize * pagesize;
#ifdef PSUTIL_OPENBSD
// VMS, this is how ps determines it on OpenBSD:
// https://github.com/openbsd/src/blob/
// 588f7f8c69786211f2d16865c552afb91b1c7cba/bin/ps/print.c#L505
vms = (long)(kp.p_vm_dsize + kp.p_vm_ssize + kp.p_vm_tsize) * pagesize;
#elif PSUTIL_NETBSD
// VMS, this is how top determines it on NetBSD:
// https://github.com/IIJ-NetBSD/netbsd-src/blob/master/external/
// bsd/top/dist/machine/m_netbsd.c
vms = (long)kp.p_vm_msize * pagesize;
#endif
memtext = (long)kp.p_vm_tsize * pagesize;
memdata = (long)kp.p_vm_dsize * pagesize;
memstack = (long)kp.p_vm_ssize * pagesize;
#endif
#ifdef PSUTIL_FREEBSD
// what CPU we're on; top was used as an example:
// https://svnweb.freebsd.org/base/head/usr.bin/top/machine.c?
// view=markup&pathrev=273835
// XXX - note: for "intr" PID this is -1.
if (kp.ki_stat == SRUN && kp.ki_oncpu != NOCPU)
oncpu = kp.ki_oncpu;
else
oncpu = kp.ki_lastcpu;
#else
// On Net/OpenBSD we have kp.p_cpuid but it appears it's always
// set to KI_NOCPU. Even if it's not, ki_lastcpu does not exist
// so there's no way to determine where "sleeping" processes
// were. Not supported.
oncpu = -1;
#endif
#ifdef PSUTIL_FREEBSD
py_ppid = PyLong_FromPid(kp.ki_ppid);
#elif defined(PSUTIL_OPENBSD) || defined(PSUTIL_NETBSD)
py_ppid = PyLong_FromPid(kp.p_ppid);
#else
py_ppid = Py_BuildfValue(-1);
#endif
if (! py_ppid)
return NULL;
// Return a single big tuple with all process info.
py_retlist = Py_BuildValue(
#if defined(__FreeBSD_version) && __FreeBSD_version >= 1200031
"(OillllllLdllllddddlllllbO)",
#else
"(OillllllidllllddddlllllbO)",
#endif
#ifdef PSUTIL_FREEBSD
py_ppid, // (pid_t) ppid
(int)kp.ki_stat, // (int) status
// UIDs
(long)kp.ki_ruid, // (long) real uid
(long)kp.ki_uid, // (long) effective uid
(long)kp.ki_svuid, // (long) saved uid
// GIDs
(long)kp.ki_rgid, // (long) real gid
(long)kp.ki_groups[0], // (long) effective gid
(long)kp.ki_svuid, // (long) saved gid
//
kp.ki_tdev, // (int or long long) tty nr
PSUTIL_TV2DOUBLE(kp.ki_start), // (double) create time
// ctx switches
kp.ki_rusage.ru_nvcsw, // (long) ctx switches (voluntary)
kp.ki_rusage.ru_nivcsw, // (long) ctx switches (unvoluntary)
// IO count
kp.ki_rusage.ru_inblock, // (long) read io count
kp.ki_rusage.ru_oublock, // (long) write io count
// CPU times: convert from micro seconds to seconds.
PSUTIL_TV2DOUBLE(kp.ki_rusage.ru_utime), // (double) user time
PSUTIL_TV2DOUBLE(kp.ki_rusage.ru_stime), // (double) sys time
PSUTIL_TV2DOUBLE(kp.ki_rusage_ch.ru_utime), // (double) children utime
PSUTIL_TV2DOUBLE(kp.ki_rusage_ch.ru_stime), // (double) children stime
// memory
rss, // (long) rss
vms, // (long) vms
memtext, // (long) mem text
memdata, // (long) mem data
memstack, // (long) mem stack
// others
oncpu, // (int) the CPU we are on
#elif defined(PSUTIL_OPENBSD) || defined(PSUTIL_NETBSD)
py_ppid, // (pid_t) ppid
(int)kp.p_stat, // (int) status
// UIDs
(long)kp.p_ruid, // (long) real uid
(long)kp.p_uid, // (long) effective uid
(long)kp.p_svuid, // (long) saved uid
// GIDs
(long)kp.p_rgid, // (long) real gid
(long)kp.p_groups[0], // (long) effective gid
(long)kp.p_svuid, // (long) saved gid
//
kp.p_tdev, // (int) tty nr
PSUTIL_KPT2DOUBLE(kp.p_ustart), // (double) create time
// ctx switches
kp.p_uru_nvcsw, // (long) ctx switches (voluntary)
kp.p_uru_nivcsw, // (long) ctx switches (unvoluntary)
// IO count
kp.p_uru_inblock, // (long) read io count
kp.p_uru_oublock, // (long) write io count
// CPU times: convert from micro seconds to seconds.
PSUTIL_KPT2DOUBLE(kp.p_uutime), // (double) user time
PSUTIL_KPT2DOUBLE(kp.p_ustime), // (double) sys time
// OpenBSD and NetBSD provide children user + system times summed
// together (no distinction).
kp.p_uctime_sec + kp.p_uctime_usec / 1000000.0, // (double) ch utime
kp.p_uctime_sec + kp.p_uctime_usec / 1000000.0, // (double) ch stime
// memory
rss, // (long) rss
vms, // (long) vms
memtext, // (long) mem text
memdata, // (long) mem data
memstack, // (long) mem stack
// others
oncpu, // (int) the CPU we are on
#endif
py_name // (pystr) name
);
Py_DECREF(py_name);
Py_DECREF(py_ppid);
return py_retlist;
}
PyObject *
psutil_proc_name(PyObject *self, PyObject *args) {
pid_t pid;
kinfo_proc kp;
char str[1000];
if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
return NULL;
if (psutil_kinfo_proc(pid, &kp) == -1)
return NULL;
#ifdef PSUTIL_FREEBSD
sprintf(str, "%s", kp.ki_comm);
#elif defined(PSUTIL_OPENBSD) || defined(PSUTIL_NETBSD)
sprintf(str, "%s", kp.p_comm);
#endif
return PyUnicode_DecodeFSDefault(str);
}
PyObject *
psutil_proc_environ(PyObject *self, PyObject *args) {
int i, cnt = -1;
long pid;
char *s, **envs, errbuf[_POSIX2_LINE_MAX];
PyObject *py_value=NULL, *py_retdict=NULL;
kvm_t *kd;
#ifdef PSUTIL_NETBSD
struct kinfo_proc2 *p;
#else
struct kinfo_proc *p;
#endif
if (!PyArg_ParseTuple(args, "l", &pid))
return NULL;
#if defined(PSUTIL_FREEBSD)
kd = kvm_openfiles(NULL, "/dev/null", NULL, 0, errbuf);
#else
kd = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, errbuf);
#endif
if (!kd) {
convert_kvm_err("kvm_openfiles", errbuf);
return NULL;
}
py_retdict = PyDict_New();
if (!py_retdict)
goto error;
#if defined(PSUTIL_FREEBSD)
p = kvm_getprocs(kd, KERN_PROC_PID, pid, &cnt);
#elif defined(PSUTIL_OPENBSD)
p = kvm_getprocs(kd, KERN_PROC_PID, pid, sizeof(*p), &cnt);
#elif defined(PSUTIL_NETBSD)
p = kvm_getproc2(kd, KERN_PROC_PID, pid, sizeof(*p), &cnt);
#endif
if (!p) {
NoSuchProcess("kvm_getprocs");
goto error;
}
if (cnt <= 0) {
NoSuchProcess(cnt < 0 ? kvm_geterr(kd) : "kvm_getprocs: cnt==0");
goto error;
}
// On *BSD kernels there are a few kernel-only system processes without an
// environment (See e.g. "procstat -e 0 | 1 | 2 ..." on FreeBSD.)
// Some system process have no stats attached at all
// (they are marked with P_SYSTEM.)
// On FreeBSD, it's possible that the process is swapped or paged out,
// then there no access to the environ stored in the process' user area.
// On NetBSD, we cannot call kvm_getenvv2() for a zombie process.
// To make unittest suite happy, return an empty environment.
#if defined(PSUTIL_FREEBSD)
#if (defined(__FreeBSD_version) && __FreeBSD_version >= 700000)
if (!((p)->ki_flag & P_INMEM) || ((p)->ki_flag & P_SYSTEM)) {
#else
if ((p)->ki_flag & P_SYSTEM) {
#endif
#elif defined(PSUTIL_NETBSD)
if ((p)->p_stat == SZOMB) {
#elif defined(PSUTIL_OPENBSD)
if ((p)->p_flag & P_SYSTEM) {
#endif
kvm_close(kd);
return py_retdict;
}
#if defined(PSUTIL_NETBSD)
envs = kvm_getenvv2(kd, p, 0);
#else
envs = kvm_getenvv(kd, p, 0);
#endif
if (!envs) {
// Map to "psutil" general high-level exceptions
switch (errno) {
case 0:
// Process has cleared it's environment, return empty one
kvm_close(kd);
return py_retdict;
case EPERM:
AccessDenied("kvm_getenvv -> EPERM");
break;
case ESRCH:
NoSuchProcess("kvm_getenvv -> ESRCH");
break;
#if defined(PSUTIL_FREEBSD)
case ENOMEM:
// Unfortunately, under FreeBSD kvm_getenvv() returns
// failure for certain processes ( e.g. try
// "sudo procstat -e <pid of your XOrg server>".)
// Map the error condition to 'AccessDenied'.
sprintf(errbuf,
"kvm_getenvv(pid=%ld, ki_uid=%d) -> ENOMEM",
pid, p->ki_uid);
AccessDenied(errbuf);
break;
#endif
default:
sprintf(errbuf, "kvm_getenvv(pid=%ld)", pid);
PyErr_SetFromOSErrnoWithSyscall(errbuf);
break;
}
goto error;
}
for (i = 0; envs[i] != NULL; i++) {
s = strchr(envs[i], '=');
if (!s)
continue;
*s++ = 0;
py_value = PyUnicode_DecodeFSDefault(s);
if (!py_value)
goto error;
if (PyDict_SetItemString(py_retdict, envs[i], py_value)) {
goto error;
}
Py_DECREF(py_value);
}
kvm_close(kd);
return py_retdict;
error:
Py_XDECREF(py_value);
Py_XDECREF(py_retdict);
kvm_close(kd);
return NULL;
}
/*
* Return files opened by process as a list of (path, fd) tuples.
* TODO: this is broken as it may report empty paths. 'procstat'
* utility has the same problem see:
* https://github.com/giampaolo/psutil/issues/595
*/
#if (defined(__FreeBSD_version) && __FreeBSD_version >= 800000) || PSUTIL_OPENBSD || defined(PSUTIL_NETBSD)
PyObject *
psutil_proc_open_files(PyObject *self, PyObject *args) {
pid_t pid;
int i;
int cnt;
int regular;
int fd;
char *path;
struct kinfo_file *freep = NULL;
struct kinfo_file *kif;
kinfo_proc kipp;
PyObject *py_tuple = NULL;
PyObject *py_path = NULL;
PyObject *py_retlist = PyList_New(0);
if (py_retlist == NULL)
return NULL;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
goto error;
if (psutil_kinfo_proc(pid, &kipp) == -1)
goto error;
errno = 0;
freep = kinfo_getfile(pid, &cnt);
if (freep == NULL) {
#if !defined(PSUTIL_OPENBSD)
psutil_raise_for_pid(pid, "kinfo_getfile()");
#endif
goto error;
}
for (i = 0; i < cnt; i++) {
kif = &freep[i];
#ifdef PSUTIL_FREEBSD
regular = (kif->kf_type == KF_TYPE_VNODE) && \
(kif->kf_vnode_type == KF_VTYPE_VREG);
fd = kif->kf_fd;
path = kif->kf_path;
#elif PSUTIL_OPENBSD
regular = (kif->f_type == DTYPE_VNODE) && (kif->v_type == VREG);
fd = kif->fd_fd;
// XXX - it appears path is not exposed in the kinfo_file struct.
path = "";
#elif PSUTIL_NETBSD
regular = (kif->ki_ftype == DTYPE_VNODE) && (kif->ki_vtype == VREG);
fd = kif->ki_fd;
// XXX - it appears path is not exposed in the kinfo_file struct.
path = "";
#endif
if (regular == 1) {
py_path = PyUnicode_DecodeFSDefault(path);
if (! py_path)
goto error;
py_tuple = Py_BuildValue("(Oi)", py_path, fd);
if (py_tuple == NULL)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_CLEAR(py_path);
Py_CLEAR(py_tuple);
}
}
free(freep);
return py_retlist;
error:
Py_XDECREF(py_tuple);
Py_DECREF(py_retlist);
if (freep != NULL)
free(freep);
return NULL;
}
#endif
| 15,817 | 30.955556 | 107 | c |
psutil | psutil-master/psutil/arch/bsd/proc.h | /*
* 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>
PyObject *psutil_pids(PyObject *self, PyObject *args);
PyObject *psutil_proc_environ(PyObject *self, PyObject *args);
PyObject *psutil_proc_name(PyObject *self, PyObject *args);
PyObject *psutil_proc_oneshot_info(PyObject *self, PyObject *args);
PyObject *psutil_proc_open_files(PyObject *self, PyObject *args);
| 519 | 36.142857 | 73 | h |
psutil | psutil-master/psutil/arch/bsd/sys.c | /*
* 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 <sys/sysctl.h>
#include <stdio.h>
#include <sys/param.h> // OS version
#ifdef PSUTIL_FREEBSD
#if __FreeBSD_version < 900000
#include <utmp.h>
#else
#include <utmpx.h>
#endif
#elif PSUTIL_NETBSD
#include <utmpx.h>
#elif PSUTIL_OPENBSD
#include <utmp.h>
#endif
// Return a Python float indicating the system boot time expressed in
// seconds since the epoch.
PyObject *
psutil_boot_time(PyObject *self, PyObject *args) {
// fetch sysctl "kern.boottime"
static int request[2] = { CTL_KERN, KERN_BOOTTIME };
struct timeval boottime;
size_t len = sizeof(boottime);
if (sysctl(request, 2, &boottime, &len, NULL, 0) == -1)
return PyErr_SetFromErrno(PyExc_OSError);
return Py_BuildValue("d", (double)boottime.tv_sec);
}
PyObject *
psutil_users(PyObject *self, PyObject *args) {
PyObject *py_retlist = PyList_New(0);
PyObject *py_username = NULL;
PyObject *py_tty = NULL;
PyObject *py_hostname = NULL;
PyObject *py_tuple = NULL;
PyObject *py_pid = NULL;
if (py_retlist == NULL)
return NULL;
#if (defined(__FreeBSD_version) && (__FreeBSD_version < 900000)) || PSUTIL_OPENBSD
struct utmp ut;
FILE *fp;
Py_BEGIN_ALLOW_THREADS
fp = fopen(_PATH_UTMP, "r");
Py_END_ALLOW_THREADS
if (fp == NULL) {
PyErr_SetFromErrnoWithFilename(PyExc_OSError, _PATH_UTMP);
goto error;
}
while (fread(&ut, sizeof(ut), 1, fp) == 1) {
if (*ut.ut_name == '\0')
continue;
py_username = PyUnicode_DecodeFSDefault(ut.ut_name);
if (! py_username)
goto error;
py_tty = PyUnicode_DecodeFSDefault(ut.ut_line);
if (! py_tty)
goto error;
py_hostname = PyUnicode_DecodeFSDefault(ut.ut_host);
if (! py_hostname)
goto error;
py_tuple = Py_BuildValue(
"(OOOdi)",
py_username, // username
py_tty, // tty
py_hostname, // hostname
(double)ut.ut_time, // start time
#if defined(PSUTIL_OPENBSD) || (defined(__FreeBSD_version) && __FreeBSD_version < 900000)
-1 // process id (set to None later)
#else
ut.ut_pid // TODO: use PyLong_FromPid
#endif
);
if (!py_tuple) {
fclose(fp);
goto error;
}
if (PyList_Append(py_retlist, py_tuple)) {
fclose(fp);
goto error;
}
Py_CLEAR(py_username);
Py_CLEAR(py_tty);
Py_CLEAR(py_hostname);
Py_CLEAR(py_tuple);
}
fclose(fp);
#else
struct utmpx *utx;
setutxent();
while ((utx = getutxent()) != NULL) {
if (utx->ut_type != USER_PROCESS)
continue;
py_username = PyUnicode_DecodeFSDefault(utx->ut_user);
if (! py_username)
goto error;
py_tty = PyUnicode_DecodeFSDefault(utx->ut_line);
if (! py_tty)
goto error;
py_hostname = PyUnicode_DecodeFSDefault(utx->ut_host);
if (! py_hostname)
goto error;
#ifdef PSUTIL_OPENBSD
py_pid = Py_BuildValue("i", -1); // set to None later
#else
py_pid = PyLong_FromPid(utx->ut_pid);
#endif
if (! py_pid)
goto error;
py_tuple = Py_BuildValue(
"(OOOdO)",
py_username, // username
py_tty, // tty
py_hostname, // hostname
(double)utx->ut_tv.tv_sec, // start time
py_pid // process id
);
if (!py_tuple) {
endutxent();
goto error;
}
if (PyList_Append(py_retlist, py_tuple)) {
endutxent();
goto error;
}
Py_CLEAR(py_username);
Py_CLEAR(py_tty);
Py_CLEAR(py_hostname);
Py_CLEAR(py_tuple);
Py_CLEAR(py_pid);
}
endutxent();
#endif
return py_retlist;
error:
Py_XDECREF(py_username);
Py_XDECREF(py_tty);
Py_XDECREF(py_hostname);
Py_XDECREF(py_tuple);
Py_XDECREF(py_pid);
Py_DECREF(py_retlist);
return NULL;
}
| 4,387 | 26.08642 | 89 | c |
psutil | psutil-master/psutil/arch/freebsd/cpu.c | /*
* 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.
*/
/*
System-wide CPU related functions.
Original code was refactored and moved from psutil/arch/freebsd/specific.c
in 2020 (and was moved in there previously already) from cset.
a4c0a0eb0d2a872ab7a45e47fcf37ef1fde5b012
For reference, here's the git history with original(ish) implementations:
- CPU stats: fb0154ef164d0e5942ac85102ab660b8d2938fbb
- CPU freq: 459556dd1e2979cdee22177339ced0761caf4c83
- CPU cores: e0d6d7865df84dc9a1d123ae452fd311f79b1dde
*/
#include <Python.h>
#include <sys/sysctl.h>
#include <devstat.h>
#include "../../_psutil_common.h"
#include "../../_psutil_posix.h"
PyObject *
psutil_per_cpu_times(PyObject *self, PyObject *args) {
static int maxcpus;
int mib[2];
int ncpu;
size_t len;
size_t size;
int i;
PyObject *py_retlist = PyList_New(0);
PyObject *py_cputime = NULL;
if (py_retlist == NULL)
return NULL;
// retrieve maxcpus value
size = sizeof(maxcpus);
if (sysctlbyname("kern.smp.maxcpus", &maxcpus, &size, NULL, 0) < 0) {
Py_DECREF(py_retlist);
return PyErr_SetFromOSErrnoWithSyscall(
"sysctlbyname('kern.smp.maxcpus')");
}
long cpu_time[maxcpus][CPUSTATES];
// retrieve the number of cpus
mib[0] = CTL_HW;
mib[1] = HW_NCPU;
len = sizeof(ncpu);
if (sysctl(mib, 2, &ncpu, &len, NULL, 0) == -1) {
PyErr_SetFromOSErrnoWithSyscall("sysctl(HW_NCPU)");
goto error;
}
// per-cpu info
size = sizeof(cpu_time);
if (sysctlbyname("kern.cp_times", &cpu_time, &size, NULL, 0) == -1) {
PyErr_SetFromOSErrnoWithSyscall("sysctlbyname('kern.smp.maxcpus')");
goto error;
}
for (i = 0; i < ncpu; i++) {
py_cputime = Py_BuildValue(
"(ddddd)",
(double)cpu_time[i][CP_USER] / CLOCKS_PER_SEC,
(double)cpu_time[i][CP_NICE] / CLOCKS_PER_SEC,
(double)cpu_time[i][CP_SYS] / CLOCKS_PER_SEC,
(double)cpu_time[i][CP_IDLE] / CLOCKS_PER_SEC,
(double)cpu_time[i][CP_INTR] / CLOCKS_PER_SEC);
if (!py_cputime)
goto error;
if (PyList_Append(py_retlist, py_cputime))
goto error;
Py_DECREF(py_cputime);
}
return py_retlist;
error:
Py_XDECREF(py_cputime);
Py_DECREF(py_retlist);
return NULL;
}
PyObject *
psutil_cpu_topology(PyObject *self, PyObject *args) {
void *topology = NULL;
size_t size = 0;
PyObject *py_str;
if (sysctlbyname("kern.sched.topology_spec", NULL, &size, NULL, 0))
goto error;
topology = malloc(size);
if (!topology) {
PyErr_NoMemory();
return NULL;
}
if (sysctlbyname("kern.sched.topology_spec", topology, &size, NULL, 0))
goto error;
py_str = Py_BuildValue("s", topology);
free(topology);
return py_str;
error:
if (topology != NULL)
free(topology);
Py_RETURN_NONE;
}
PyObject *
psutil_cpu_stats(PyObject *self, PyObject *args) {
unsigned int v_soft;
unsigned int v_intr;
unsigned int v_syscall;
unsigned int v_trap;
unsigned int v_swtch;
size_t size = sizeof(v_soft);
if (sysctlbyname("vm.stats.sys.v_soft", &v_soft, &size, NULL, 0)) {
return PyErr_SetFromOSErrnoWithSyscall(
"sysctlbyname('vm.stats.sys.v_soft')");
}
if (sysctlbyname("vm.stats.sys.v_intr", &v_intr, &size, NULL, 0)) {
return PyErr_SetFromOSErrnoWithSyscall(
"sysctlbyname('vm.stats.sys.v_intr')");
}
if (sysctlbyname("vm.stats.sys.v_syscall", &v_syscall, &size, NULL, 0)) {
return PyErr_SetFromOSErrnoWithSyscall(
"sysctlbyname('vm.stats.sys.v_syscall')");
}
if (sysctlbyname("vm.stats.sys.v_trap", &v_trap, &size, NULL, 0)) {
return PyErr_SetFromOSErrnoWithSyscall(
"sysctlbyname('vm.stats.sys.v_trap')");
}
if (sysctlbyname("vm.stats.sys.v_swtch", &v_swtch, &size, NULL, 0)) {
return PyErr_SetFromOSErrnoWithSyscall(
"sysctlbyname('vm.stats.sys.v_swtch')");
}
return Py_BuildValue(
"IIIII",
v_swtch, // ctx switches
v_intr, // interrupts
v_soft, // software interrupts
v_syscall, // syscalls
v_trap // traps
);
}
/*
* Return frequency information of a given CPU.
* As of Dec 2018 only CPU 0 appears to be supported and all other
* cores match the frequency of CPU 0.
*/
PyObject *
psutil_cpu_freq(PyObject *self, PyObject *args) {
int current;
int core;
char sensor[26];
char available_freq_levels[1000];
size_t size = sizeof(current);
if (! PyArg_ParseTuple(args, "i", &core))
return NULL;
// https://www.unix.com/man-page/FreeBSD/4/cpufreq/
sprintf(sensor, "dev.cpu.%d.freq", core);
if (sysctlbyname(sensor, ¤t, &size, NULL, 0))
goto error;
size = sizeof(available_freq_levels);
// https://www.unix.com/man-page/FreeBSD/4/cpufreq/
// In case of failure, an empty string is returned.
sprintf(sensor, "dev.cpu.%d.freq_levels", core);
sysctlbyname(sensor, &available_freq_levels, &size, NULL, 0);
return Py_BuildValue("is", current, available_freq_levels);
error:
if (errno == ENOENT)
PyErr_SetString(PyExc_NotImplementedError, "unable to read frequency");
else
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
| 5,555 | 27.492308 | 79 | c |
psutil | psutil-master/psutil/arch/freebsd/disk.c | /*
* 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 <sys/sysctl.h>
#include <devstat.h>
#include "../../_psutil_common.h"
#include "../../_psutil_posix.h"
// convert a bintime struct to milliseconds
#define PSUTIL_BT2MSEC(bt) (bt.sec * 1000 + (((uint64_t) 1000000000 * (uint32_t) \
(bt.frac >> 32) ) >> 32 ) / 1000000)
PyObject *
psutil_disk_io_counters(PyObject *self, PyObject *args) {
int i;
struct statinfo stats;
PyObject *py_retdict = PyDict_New();
PyObject *py_disk_info = NULL;
if (py_retdict == NULL)
return NULL;
if (devstat_checkversion(NULL) < 0) {
PyErr_Format(PyExc_RuntimeError,
"devstat_checkversion() syscall failed");
goto error;
}
stats.dinfo = (struct devinfo *)malloc(sizeof(struct devinfo));
if (stats.dinfo == NULL) {
PyErr_NoMemory();
goto error;
}
bzero(stats.dinfo, sizeof(struct devinfo));
if (devstat_getdevs(NULL, &stats) == -1) {
PyErr_Format(PyExc_RuntimeError, "devstat_getdevs() syscall failed");
goto error;
}
for (i = 0; i < stats.dinfo->numdevs; i++) {
py_disk_info = NULL;
struct devstat current;
char disk_name[128];
current = stats.dinfo->devices[i];
snprintf(disk_name, sizeof(disk_name), "%s%d",
current.device_name,
current.unit_number);
py_disk_info = Py_BuildValue(
"(KKKKLLL)",
current.operations[DEVSTAT_READ], // no reads
current.operations[DEVSTAT_WRITE], // no writes
current.bytes[DEVSTAT_READ], // bytes read
current.bytes[DEVSTAT_WRITE], // bytes written
(long long) PSUTIL_BT2MSEC(current.duration[DEVSTAT_READ]), // r time
(long long) PSUTIL_BT2MSEC(current.duration[DEVSTAT_WRITE]), // w time
(long long) PSUTIL_BT2MSEC(current.busy_time) // busy time
); // finished transactions
if (!py_disk_info)
goto error;
if (PyDict_SetItemString(py_retdict, disk_name, py_disk_info))
goto error;
Py_DECREF(py_disk_info);
}
if (stats.dinfo->mem_ptr)
free(stats.dinfo->mem_ptr);
free(stats.dinfo);
return py_retdict;
error:
Py_XDECREF(py_disk_info);
Py_DECREF(py_retdict);
if (stats.dinfo != NULL)
free(stats.dinfo);
return NULL;
}
| 2,599 | 28.885057 | 83 | c |
psutil | psutil-master/psutil/arch/freebsd/mem.c | /*
* 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 <sys/param.h>
#include <sys/sysctl.h>
#include <sys/vmmeter.h>
#include <vm/vm_param.h>
#include <devstat.h>
#include <paths.h>
#include <fcntl.h>
#include "../../_psutil_common.h"
#include "../../_psutil_posix.h"
#ifndef _PATH_DEVNULL
#define _PATH_DEVNULL "/dev/null"
#endif
PyObject *
psutil_virtual_mem(PyObject *self, PyObject *args) {
unsigned long total;
unsigned int active, inactive, wired, cached, free;
size_t size = sizeof(total);
struct vmtotal vm;
int mib[] = {CTL_VM, VM_METER};
long pagesize = psutil_getpagesize();
#if __FreeBSD_version > 702101
long buffers;
#else
int buffers;
#endif
size_t buffers_size = sizeof(buffers);
if (sysctlbyname("hw.physmem", &total, &size, NULL, 0)) {
return PyErr_SetFromOSErrnoWithSyscall("sysctlbyname('hw.physmem')");
}
if (sysctlbyname("vm.stats.vm.v_active_count", &active, &size, NULL, 0)) {
return PyErr_SetFromOSErrnoWithSyscall(
"sysctlbyname('vm.stats.vm.v_active_count')");
}
if (sysctlbyname("vm.stats.vm.v_inactive_count", &inactive, &size, NULL, 0))
{
return PyErr_SetFromOSErrnoWithSyscall(
"sysctlbyname('vm.stats.vm.v_inactive_count')");
}
if (sysctlbyname("vm.stats.vm.v_wire_count", &wired, &size, NULL, 0)) {
return PyErr_SetFromOSErrnoWithSyscall(
"sysctlbyname('vm.stats.vm.v_wire_count')");
}
// https://github.com/giampaolo/psutil/issues/997
if (sysctlbyname("vm.stats.vm.v_cache_count", &cached, &size, NULL, 0)) {
cached = 0;
}
if (sysctlbyname("vm.stats.vm.v_free_count", &free, &size, NULL, 0)) {
return PyErr_SetFromOSErrnoWithSyscall(
"sysctlbyname('vm.stats.vm.v_free_count')");
}
if (sysctlbyname("vfs.bufspace", &buffers, &buffers_size, NULL, 0)) {
return PyErr_SetFromOSErrnoWithSyscall("sysctlbyname('vfs.bufspace')");
}
size = sizeof(vm);
if (sysctl(mib, 2, &vm, &size, NULL, 0) != 0) {
return PyErr_SetFromOSErrnoWithSyscall("sysctl(CTL_VM | VM_METER)");
}
return Py_BuildValue("KKKKKKKK",
(unsigned long long) total,
(unsigned long long) free * pagesize,
(unsigned long long) active * pagesize,
(unsigned long long) inactive * pagesize,
(unsigned long long) wired * pagesize,
(unsigned long long) cached * pagesize,
(unsigned long long) buffers,
(unsigned long long) (vm.t_vmshr + vm.t_rmshr) * pagesize // shared
);
}
PyObject *
psutil_swap_mem(PyObject *self, PyObject *args) {
// Return swap memory stats (see 'swapinfo' cmdline tool)
kvm_t *kd;
struct kvm_swap kvmsw[1];
unsigned int swapin, swapout, nodein, nodeout;
size_t size = sizeof(unsigned int);
long pagesize = psutil_getpagesize();
kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open failed");
if (kd == NULL) {
PyErr_SetString(PyExc_RuntimeError, "kvm_open() syscall failed");
return NULL;
}
if (kvm_getswapinfo(kd, kvmsw, 1, 0) < 0) {
kvm_close(kd);
PyErr_SetString(PyExc_RuntimeError,
"kvm_getswapinfo() syscall failed");
return NULL;
}
kvm_close(kd);
if (sysctlbyname("vm.stats.vm.v_swapin", &swapin, &size, NULL, 0) == -1) {
return PyErr_SetFromOSErrnoWithSyscall(
"sysctlbyname('vm.stats.vm.v_swapin)'");
}
if (sysctlbyname("vm.stats.vm.v_swapout", &swapout, &size, NULL, 0) == -1){
return PyErr_SetFromOSErrnoWithSyscall(
"sysctlbyname('vm.stats.vm.v_swapout)'");
}
if (sysctlbyname("vm.stats.vm.v_vnodein", &nodein, &size, NULL, 0) == -1) {
return PyErr_SetFromOSErrnoWithSyscall(
"sysctlbyname('vm.stats.vm.v_vnodein)'");
}
if (sysctlbyname("vm.stats.vm.v_vnodeout", &nodeout, &size, NULL, 0) == -1) {
return PyErr_SetFromOSErrnoWithSyscall(
"sysctlbyname('vm.stats.vm.v_vnodeout)'");
}
return Py_BuildValue(
"(KKKII)",
(unsigned long long)kvmsw[0].ksw_total * pagesize, // total
(unsigned long long)kvmsw[0].ksw_used * pagesize, // used
(unsigned long long)kvmsw[0].ksw_total * pagesize - // free
kvmsw[0].ksw_used * pagesize,
swapin + swapout, // swap in
nodein + nodeout // swap out
);
}
| 4,652 | 32.47482 | 81 | c |
psutil | psutil-master/psutil/arch/freebsd/proc.c | /*
* 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 <assert.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/sysctl.h>
#include <sys/param.h>
#include <sys/user.h>
#include <sys/proc.h>
#include <signal.h>
#include <fcntl.h>
#include <devstat.h>
#include <libutil.h> // process open files, shared libs (kinfo_getvmmap), cwd
#include <sys/cpuset.h>
#include "../../_psutil_common.h"
#include "../../_psutil_posix.h"
#define PSUTIL_TV2DOUBLE(t) ((t).tv_sec + (t).tv_usec / 1000000.0)
// ============================================================================
// Utility functions
// ============================================================================
int
psutil_kinfo_proc(pid_t pid, struct kinfo_proc *proc) {
// Fills a kinfo_proc struct based on process pid.
int mib[4];
size_t size;
mib[0] = CTL_KERN;
mib[1] = KERN_PROC;
mib[2] = KERN_PROC_PID;
mib[3] = pid;
size = sizeof(struct kinfo_proc);
if (sysctl((int *)mib, 4, proc, &size, NULL, 0) == -1) {
PyErr_SetFromOSErrnoWithSyscall("sysctl(KERN_PROC_PID)");
return -1;
}
// sysctl stores 0 in the size if we can't find the process information.
if (size == 0) {
NoSuchProcess("sysctl (size = 0)");
return -1;
}
return 0;
}
// remove spaces from string
static void psutil_remove_spaces(char *str) {
char *p1 = str;
char *p2 = str;
do
while (*p2 == ' ')
p2++;
while ((*p1++ = *p2++));
}
// ============================================================================
// APIS
// ============================================================================
int
psutil_get_proc_list(struct kinfo_proc **procList, size_t *procCount) {
// Returns a list of all BSD processes on the system. This routine
// allocates the list and puts it in *procList and a count of the
// number of entries in *procCount. You are responsible for freeing
// this list. On success returns 0, else 1 with exception set.
int err;
struct kinfo_proc *buf = NULL;
int name[] = { CTL_KERN, KERN_PROC, KERN_PROC_PROC, 0 };
size_t length = 0;
size_t max_length = 12 * 1024 * 1024; // 12MB
assert(procList != NULL);
assert(*procList == NULL);
assert(procCount != NULL);
// Call sysctl with a NULL buffer in order to get buffer length.
err = sysctl(name, 3, NULL, &length, NULL, 0);
if (err == -1) {
PyErr_SetFromOSErrnoWithSyscall("sysctl (null buffer)");
return 1;
}
while (1) {
// Allocate an appropriately sized buffer based on the results
// from the previous call.
buf = malloc(length);
if (buf == NULL) {
PyErr_NoMemory();
return 1;
}
// Call sysctl again with the new buffer.
err = sysctl(name, 3, buf, &length, NULL, 0);
if (err == -1) {
free(buf);
if (errno == ENOMEM) {
// Sometimes the first sysctl() suggested size is not enough,
// so we dynamically increase it until it's big enough :
// https://github.com/giampaolo/psutil/issues/2093
psutil_debug("errno=ENOMEM, length=%zu; retrying", length);
length *= 2;
if (length < max_length) {
continue;
}
}
PyErr_SetFromOSErrnoWithSyscall("sysctl()");
return 1;
}
else {
break;
}
}
*procList = buf;
*procCount = length / sizeof(struct kinfo_proc);
return 0;
}
/*
* Borrowed from psi Python System Information project
* Based on code from ps.
*/
PyObject *
psutil_proc_cmdline(PyObject *self, PyObject *args) {
pid_t pid;
int mib[4];
int argmax;
size_t size = sizeof(argmax);
char *procargs = NULL;
size_t pos = 0;
PyObject *py_retlist = PyList_New(0);
PyObject *py_arg = NULL;
if (py_retlist == NULL)
return NULL;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
goto error;
// Get the maximum process arguments size.
mib[0] = CTL_KERN;
mib[1] = KERN_ARGMAX;
size = sizeof(argmax);
if (sysctl(mib, 2, &argmax, &size, NULL, 0) == -1)
goto error;
// Allocate space for the arguments.
procargs = (char *)malloc(argmax);
if (procargs == NULL) {
PyErr_NoMemory();
goto error;
}
// Make a sysctl() call to get the raw argument space of the process.
mib[0] = CTL_KERN;
mib[1] = KERN_PROC;
mib[2] = KERN_PROC_ARGS;
mib[3] = pid;
size = argmax;
if (sysctl(mib, 4, procargs, &size, NULL, 0) == -1) {
PyErr_SetFromOSErrnoWithSyscall("sysctl(KERN_PROC_ARGS)");
goto error;
}
// args are returned as a flattened string with \0 separators between
// arguments add each string to the list then step forward to the next
// separator
if (size > 0) {
while (pos < size) {
py_arg = PyUnicode_DecodeFSDefault(&procargs[pos]);
if (!py_arg)
goto error;
if (PyList_Append(py_retlist, py_arg))
goto error;
Py_DECREF(py_arg);
pos = pos + strlen(&procargs[pos]) + 1;
}
}
free(procargs);
return py_retlist;
error:
Py_XDECREF(py_arg);
Py_DECREF(py_retlist);
if (procargs != NULL)
free(procargs);
return NULL;
}
/*
* Return process pathname executable.
* Thanks to Robert N. M. Watson:
* http://fxr.googlebit.com/source/usr.bin/procstat/procstat_bin.c?v=8-CURRENT
*/
PyObject *
psutil_proc_exe(PyObject *self, PyObject *args) {
pid_t pid;
char pathname[PATH_MAX];
int error;
int mib[4];
int ret;
size_t size;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
return NULL;
mib[0] = CTL_KERN;
mib[1] = KERN_PROC;
mib[2] = KERN_PROC_PATHNAME;
mib[3] = pid;
size = sizeof(pathname);
error = sysctl(mib, 4, pathname, &size, NULL, 0);
if (error == -1) {
// see: https://github.com/giampaolo/psutil/issues/907
if (errno == ENOENT) {
return PyUnicode_DecodeFSDefault("");
}
else {
return \
PyErr_SetFromOSErrnoWithSyscall("sysctl(KERN_PROC_PATHNAME)");
}
}
if (size == 0 || strlen(pathname) == 0) {
ret = psutil_pid_exists(pid);
if (ret == -1)
return NULL;
else if (ret == 0)
return NoSuchProcess("psutil_pid_exists -> 0");
else
strcpy(pathname, "");
}
return PyUnicode_DecodeFSDefault(pathname);
}
PyObject *
psutil_proc_num_threads(PyObject *self, PyObject *args) {
// Return number of threads used by process as a Python integer.
pid_t pid;
struct kinfo_proc kp;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
return NULL;
if (psutil_kinfo_proc(pid, &kp) == -1)
return NULL;
return Py_BuildValue("l", (long)kp.ki_numthreads);
}
PyObject *
psutil_proc_threads(PyObject *self, PyObject *args) {
// Retrieves all threads used by process returning a list of tuples
// including thread id, user time and system time.
// Thanks to Robert N. M. Watson:
// http://code.metager.de/source/xref/freebsd/usr.bin/procstat/
// procstat_threads.c
pid_t pid;
int mib[4];
struct kinfo_proc *kip = NULL;
struct kinfo_proc *kipp = NULL;
int error;
unsigned int i;
size_t size;
PyObject *py_retlist = PyList_New(0);
PyObject *py_tuple = NULL;
if (py_retlist == NULL)
return NULL;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
goto error;
// we need to re-query for thread information, so don't use *kipp
mib[0] = CTL_KERN;
mib[1] = KERN_PROC;
mib[2] = KERN_PROC_PID | KERN_PROC_INC_THREAD;
mib[3] = pid;
size = 0;
error = sysctl(mib, 4, NULL, &size, NULL, 0);
if (error == -1) {
PyErr_SetFromOSErrnoWithSyscall("sysctl(KERN_PROC_INC_THREAD)");
goto error;
}
if (size == 0) {
NoSuchProcess("sysctl (size = 0)");
goto error;
}
kip = malloc(size);
if (kip == NULL) {
PyErr_NoMemory();
goto error;
}
error = sysctl(mib, 4, kip, &size, NULL, 0);
if (error == -1) {
PyErr_SetFromOSErrnoWithSyscall("sysctl(KERN_PROC_INC_THREAD)");
goto error;
}
if (size == 0) {
NoSuchProcess("sysctl (size = 0)");
goto error;
}
for (i = 0; i < size / sizeof(*kipp); i++) {
kipp = &kip[i];
py_tuple = Py_BuildValue("Idd",
kipp->ki_tid,
PSUTIL_TV2DOUBLE(kipp->ki_rusage.ru_utime),
PSUTIL_TV2DOUBLE(kipp->ki_rusage.ru_stime));
if (py_tuple == NULL)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_DECREF(py_tuple);
}
free(kip);
return py_retlist;
error:
Py_XDECREF(py_tuple);
Py_DECREF(py_retlist);
if (kip != NULL)
free(kip);
return NULL;
}
#if defined(__FreeBSD_version) && __FreeBSD_version >= 701000
PyObject *
psutil_proc_cwd(PyObject *self, PyObject *args) {
pid_t pid;
struct kinfo_file *freep = NULL;
struct kinfo_file *kif;
struct kinfo_proc kipp;
PyObject *py_path = NULL;
int i, cnt;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
goto error;
if (psutil_kinfo_proc(pid, &kipp) == -1)
goto error;
errno = 0;
freep = kinfo_getfile(pid, &cnt);
if (freep == NULL) {
psutil_raise_for_pid(pid, "kinfo_getfile()");
goto error;
}
for (i = 0; i < cnt; i++) {
kif = &freep[i];
if (kif->kf_fd == KF_FD_TYPE_CWD) {
py_path = PyUnicode_DecodeFSDefault(kif->kf_path);
if (!py_path)
goto error;
break;
}
}
/*
* For lower pids it seems we can't retrieve any information
* (lsof can't do that it either). Since this happens even
* as root we return an empty string instead of AccessDenied.
*/
if (py_path == NULL)
py_path = PyUnicode_DecodeFSDefault("");
free(freep);
return py_path;
error:
Py_XDECREF(py_path);
if (freep != NULL)
free(freep);
return NULL;
}
#endif
#if defined(__FreeBSD_version) && __FreeBSD_version >= 800000
PyObject *
psutil_proc_num_fds(PyObject *self, PyObject *args) {
pid_t pid;
int cnt;
struct kinfo_file *freep;
struct kinfo_proc kipp;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
return NULL;
if (psutil_kinfo_proc(pid, &kipp) == -1)
return NULL;
errno = 0;
freep = kinfo_getfile(pid, &cnt);
if (freep == NULL) {
psutil_raise_for_pid(pid, "kinfo_getfile()");
return NULL;
}
free(freep);
return Py_BuildValue("i", cnt);
}
#endif
PyObject *
psutil_proc_memory_maps(PyObject *self, PyObject *args) {
// Return a list of tuples for every process memory maps.
// 'procstat' cmdline utility has been used as an example.
pid_t pid;
int ptrwidth;
int i, cnt;
char addr[1000];
char perms[4];
char *path;
struct kinfo_proc kp;
struct kinfo_vmentry *freep = NULL;
struct kinfo_vmentry *kve;
ptrwidth = 2 * sizeof(void *);
PyObject *py_tuple = NULL;
PyObject *py_path = NULL;
PyObject *py_retlist = PyList_New(0);
if (py_retlist == NULL)
return NULL;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
goto error;
if (psutil_kinfo_proc(pid, &kp) == -1)
goto error;
errno = 0;
freep = kinfo_getvmmap(pid, &cnt);
if (freep == NULL) {
psutil_raise_for_pid(pid, "kinfo_getvmmap()");
goto error;
}
for (i = 0; i < cnt; i++) {
py_tuple = NULL;
kve = &freep[i];
addr[0] = '\0';
perms[0] = '\0';
sprintf(addr, "%#*jx-%#*jx", ptrwidth, (uintmax_t)kve->kve_start,
ptrwidth, (uintmax_t)kve->kve_end);
psutil_remove_spaces(addr);
strlcat(perms, kve->kve_protection & KVME_PROT_READ ? "r" : "-",
sizeof(perms));
strlcat(perms, kve->kve_protection & KVME_PROT_WRITE ? "w" : "-",
sizeof(perms));
strlcat(perms, kve->kve_protection & KVME_PROT_EXEC ? "x" : "-",
sizeof(perms));
if (strlen(kve->kve_path) == 0) {
switch (kve->kve_type) {
case KVME_TYPE_NONE:
path = "[none]";
break;
case KVME_TYPE_DEFAULT:
path = "[default]";
break;
case KVME_TYPE_VNODE:
path = "[vnode]";
break;
case KVME_TYPE_SWAP:
path = "[swap]";
break;
case KVME_TYPE_DEVICE:
path = "[device]";
break;
case KVME_TYPE_PHYS:
path = "[phys]";
break;
case KVME_TYPE_DEAD:
path = "[dead]";
break;
#ifdef KVME_TYPE_SG
case KVME_TYPE_SG:
path = "[sg]";
break;
#endif
case KVME_TYPE_UNKNOWN:
path = "[unknown]";
break;
default:
path = "[?]";
break;
}
}
else {
path = kve->kve_path;
}
py_path = PyUnicode_DecodeFSDefault(path);
if (! py_path)
goto error;
py_tuple = Py_BuildValue("ssOiiii",
addr, // "start-end" address
perms, // "rwx" permissions
py_path, // path
kve->kve_resident, // rss
kve->kve_private_resident, // private
kve->kve_ref_count, // ref count
kve->kve_shadow_count); // shadow count
if (!py_tuple)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_DECREF(py_path);
Py_DECREF(py_tuple);
}
free(freep);
return py_retlist;
error:
Py_XDECREF(py_tuple);
Py_XDECREF(py_path);
Py_DECREF(py_retlist);
if (freep != NULL)
free(freep);
return NULL;
}
PyObject*
psutil_proc_cpu_affinity_get(PyObject* self, PyObject* args) {
// Get process CPU affinity.
// Reference:
// http://sources.freebsd.org/RELENG_9/src/usr.bin/cpuset/cpuset.c
pid_t pid;
int ret;
int i;
cpuset_t mask;
PyObject* py_retlist;
PyObject* py_cpu_num;
if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
return NULL;
ret = cpuset_getaffinity(CPU_LEVEL_WHICH, CPU_WHICH_PID, pid,
sizeof(mask), &mask);
if (ret != 0)
return PyErr_SetFromErrno(PyExc_OSError);
py_retlist = PyList_New(0);
if (py_retlist == NULL)
return NULL;
for (i = 0; i < CPU_SETSIZE; i++) {
if (CPU_ISSET(i, &mask)) {
py_cpu_num = Py_BuildValue("i", i);
if (py_cpu_num == NULL)
goto error;
if (PyList_Append(py_retlist, py_cpu_num))
goto error;
}
}
return py_retlist;
error:
Py_XDECREF(py_cpu_num);
Py_DECREF(py_retlist);
return NULL;
}
PyObject *
psutil_proc_cpu_affinity_set(PyObject *self, PyObject *args) {
// Set process CPU affinity.
// Reference:
// http://sources.freebsd.org/RELENG_9/src/usr.bin/cpuset/cpuset.c
pid_t pid;
int i;
int seq_len;
int ret;
cpuset_t cpu_set;
PyObject *py_cpu_set;
PyObject *py_cpu_seq = NULL;
if (!PyArg_ParseTuple(args, _Py_PARSE_PID "O", &pid, &py_cpu_set))
return NULL;
py_cpu_seq = PySequence_Fast(py_cpu_set, "expected a sequence or integer");
if (!py_cpu_seq)
return NULL;
seq_len = PySequence_Fast_GET_SIZE(py_cpu_seq);
// calculate the mask
CPU_ZERO(&cpu_set);
for (i = 0; i < seq_len; i++) {
PyObject *item = PySequence_Fast_GET_ITEM(py_cpu_seq, i);
#if PY_MAJOR_VERSION >= 3
long value = PyLong_AsLong(item);
#else
long value = PyInt_AsLong(item);
#endif
if (value == -1 || PyErr_Occurred())
goto error;
CPU_SET(value, &cpu_set);
}
// set affinity
ret = cpuset_setaffinity(CPU_LEVEL_WHICH, CPU_WHICH_PID, pid,
sizeof(cpu_set), &cpu_set);
if (ret != 0) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
Py_DECREF(py_cpu_seq);
Py_RETURN_NONE;
error:
if (py_cpu_seq != NULL)
Py_DECREF(py_cpu_seq);
return NULL;
}
/*
* An emulation of Linux prlimit(). Returns a (soft, hard) tuple.
*/
PyObject *
psutil_proc_getrlimit(PyObject *self, PyObject *args) {
pid_t pid;
int ret;
int resource;
size_t len;
int name[5];
struct rlimit rlp;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID "i", &pid, &resource))
return NULL;
name[0] = CTL_KERN;
name[1] = KERN_PROC;
name[2] = KERN_PROC_RLIMIT;
name[3] = pid;
name[4] = resource;
len = sizeof(rlp);
ret = sysctl(name, 5, &rlp, &len, NULL, 0);
if (ret == -1)
return PyErr_SetFromErrno(PyExc_OSError);
#if defined(HAVE_LONG_LONG)
return Py_BuildValue("LL",
(PY_LONG_LONG) rlp.rlim_cur,
(PY_LONG_LONG) rlp.rlim_max);
#else
return Py_BuildValue("ll",
(long) rlp.rlim_cur,
(long) rlp.rlim_max);
#endif
}
/*
* An emulation of Linux prlimit() (set).
*/
PyObject *
psutil_proc_setrlimit(PyObject *self, PyObject *args) {
pid_t pid;
int ret;
int resource;
int name[5];
struct rlimit new;
struct rlimit *newp = NULL;
PyObject *py_soft = NULL;
PyObject *py_hard = NULL;
if (! PyArg_ParseTuple(
args, _Py_PARSE_PID "iOO", &pid, &resource, &py_soft, &py_hard))
return NULL;
name[0] = CTL_KERN;
name[1] = KERN_PROC;
name[2] = KERN_PROC_RLIMIT;
name[3] = pid;
name[4] = resource;
#if defined(HAVE_LONG_LONG)
new.rlim_cur = PyLong_AsLongLong(py_soft);
if (new.rlim_cur == (rlim_t) - 1 && PyErr_Occurred())
return NULL;
new.rlim_max = PyLong_AsLongLong(py_hard);
if (new.rlim_max == (rlim_t) - 1 && PyErr_Occurred())
return NULL;
#else
new.rlim_cur = PyLong_AsLong(py_soft);
if (new.rlim_cur == (rlim_t) - 1 && PyErr_Occurred())
return NULL;
new.rlim_max = PyLong_AsLong(py_hard);
if (new.rlim_max == (rlim_t) - 1 && PyErr_Occurred())
return NULL;
#endif
newp = &new;
ret = sysctl(name, 5, NULL, 0, newp, sizeof(*newp));
if (ret == -1)
return PyErr_SetFromErrno(PyExc_OSError);
Py_RETURN_NONE;
}
| 19,437 | 25.848066 | 79 | c |
psutil | psutil-master/psutil/arch/freebsd/proc.h | /*
* 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>
typedef struct kinfo_proc kinfo_proc;
int psutil_get_proc_list(struct kinfo_proc **procList, size_t *procCount);
int psutil_kinfo_proc(const pid_t pid, struct kinfo_proc *proc);
PyObject* psutil_proc_cmdline(PyObject* self, PyObject* args);
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);
PyObject* psutil_proc_exe(PyObject* self, PyObject* args);
PyObject* psutil_proc_getrlimit(PyObject* self, PyObject* args);
PyObject* psutil_proc_memory_maps(PyObject* self, PyObject* args);
PyObject* psutil_proc_num_fds(PyObject* self, PyObject* args);
PyObject* psutil_proc_num_threads(PyObject* self, PyObject* args);
PyObject* psutil_proc_setrlimit(PyObject* self, PyObject* args);
PyObject* psutil_proc_threads(PyObject* self, PyObject* args);
| 1,102 | 43.12 | 74 | h |
psutil | psutil-master/psutil/arch/freebsd/proc_socks.c | /*
* 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.
*
* Retrieves per-process open socket connections.
*/
#include <Python.h>
#include <sys/param.h>
#include <sys/user.h>
#include <sys/socketvar.h> // for struct xsocket
#include <sys/un.h>
#include <sys/sysctl.h>
#include <netinet/in.h> // for xinpcb struct
#include <netinet/in_pcb.h>
#include <netinet/tcp_var.h> // for struct xtcpcb
#include <arpa/inet.h> // for inet_ntop()
#include <libutil.h>
#include "../../_psutil_common.h"
#include "../../_psutil_posix.h"
// The tcplist fetching and walking is borrowed from netstat/inet.c.
static char *
psutil_fetch_tcplist(void) {
char *buf;
size_t len;
for (;;) {
if (sysctlbyname("net.inet.tcp.pcblist", NULL, &len, NULL, 0) < 0) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
buf = malloc(len);
if (buf == NULL) {
PyErr_NoMemory();
return NULL;
}
if (sysctlbyname("net.inet.tcp.pcblist", buf, &len, NULL, 0) < 0) {
free(buf);
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
return buf;
}
}
static int
psutil_sockaddr_port(int family, struct sockaddr_storage *ss) {
struct sockaddr_in6 *sin6;
struct sockaddr_in *sin;
if (family == AF_INET) {
sin = (struct sockaddr_in *)ss;
return (sin->sin_port);
}
else {
sin6 = (struct sockaddr_in6 *)ss;
return (sin6->sin6_port);
}
}
static void *
psutil_sockaddr_addr(int family, struct sockaddr_storage *ss) {
struct sockaddr_in6 *sin6;
struct sockaddr_in *sin;
if (family == AF_INET) {
sin = (struct sockaddr_in *)ss;
return (&sin->sin_addr);
}
else {
sin6 = (struct sockaddr_in6 *)ss;
return (&sin6->sin6_addr);
}
}
static socklen_t
psutil_sockaddr_addrlen(int family) {
if (family == AF_INET)
return (sizeof(struct in_addr));
else
return (sizeof(struct in6_addr));
}
static int
psutil_sockaddr_matches(int family, int port, void *pcb_addr,
struct sockaddr_storage *ss) {
if (psutil_sockaddr_port(family, ss) != port)
return (0);
return (memcmp(psutil_sockaddr_addr(family, ss), pcb_addr,
psutil_sockaddr_addrlen(family)) == 0);
}
#if __FreeBSD_version >= 1200026
static struct xtcpcb *
psutil_search_tcplist(char *buf, struct kinfo_file *kif) {
struct xtcpcb *tp;
struct xinpcb *inp;
#else
static struct tcpcb *
psutil_search_tcplist(char *buf, struct kinfo_file *kif) {
struct tcpcb *tp;
struct inpcb *inp;
#endif
struct xinpgen *xig, *oxig;
struct xsocket *so;
oxig = xig = (struct xinpgen *)buf;
for (xig = (struct xinpgen *)((char *)xig + xig->xig_len);
xig->xig_len > sizeof(struct xinpgen);
xig = (struct xinpgen *)((char *)xig + xig->xig_len)) {
#if __FreeBSD_version >= 1200026
tp = (struct xtcpcb *)xig;
inp = &tp->xt_inp;
so = &inp->xi_socket;
#else
tp = &((struct xtcpcb *)xig)->xt_tp;
inp = &((struct xtcpcb *)xig)->xt_inp;
so = &((struct xtcpcb *)xig)->xt_socket;
#endif
if (so->so_type != kif->kf_sock_type ||
so->xso_family != kif->kf_sock_domain ||
so->xso_protocol != kif->kf_sock_protocol)
continue;
if (kif->kf_sock_domain == AF_INET) {
if (!psutil_sockaddr_matches(
AF_INET, inp->inp_lport, &inp->inp_laddr,
#if __FreeBSD_version < 1200031
&kif->kf_sa_local))
#else
&kif->kf_un.kf_sock.kf_sa_local))
#endif
continue;
if (!psutil_sockaddr_matches(
AF_INET, inp->inp_fport, &inp->inp_faddr,
#if __FreeBSD_version < 1200031
&kif->kf_sa_peer))
#else
&kif->kf_un.kf_sock.kf_sa_peer))
#endif
continue;
} else {
if (!psutil_sockaddr_matches(
AF_INET6, inp->inp_lport, &inp->in6p_laddr,
#if __FreeBSD_version < 1200031
&kif->kf_sa_local))
#else
&kif->kf_un.kf_sock.kf_sa_local))
#endif
continue;
if (!psutil_sockaddr_matches(
AF_INET6, inp->inp_fport, &inp->in6p_faddr,
#if __FreeBSD_version < 1200031
&kif->kf_sa_peer))
#else
&kif->kf_un.kf_sock.kf_sa_peer))
#endif
continue;
}
return (tp);
}
return NULL;
}
PyObject *
psutil_proc_connections(PyObject *self, PyObject *args) {
// Return connections opened by process.
pid_t pid;
int i;
int cnt;
struct kinfo_file *freep = NULL;
struct kinfo_file *kif;
char *tcplist = NULL;
#if __FreeBSD_version >= 1200026
struct xtcpcb *tcp;
#else
struct tcpcb *tcp;
#endif
PyObject *py_retlist = PyList_New(0);
PyObject *py_tuple = NULL;
PyObject *py_laddr = NULL;
PyObject *py_raddr = NULL;
PyObject *py_af_filter = NULL;
PyObject *py_type_filter = NULL;
PyObject *py_family = NULL;
PyObject *py_type = NULL;
if (py_retlist == NULL)
return NULL;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID "OO", &pid,
&py_af_filter, &py_type_filter))
{
goto error;
}
if (!PySequence_Check(py_af_filter) || !PySequence_Check(py_type_filter)) {
PyErr_SetString(PyExc_TypeError, "arg 2 or 3 is not a sequence");
goto error;
}
errno = 0;
freep = kinfo_getfile(pid, &cnt);
if (freep == NULL) {
psutil_raise_for_pid(pid, "kinfo_getfile()");
goto error;
}
tcplist = psutil_fetch_tcplist();
if (tcplist == NULL) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
for (i = 0; i < cnt; i++) {
int lport, rport, state;
char lip[200], rip[200];
char path[PATH_MAX];
int inseq;
py_tuple = NULL;
py_laddr = NULL;
py_raddr = NULL;
kif = &freep[i];
if (kif->kf_type == KF_TYPE_SOCKET) {
// apply filters
py_family = PyLong_FromLong((long)kif->kf_sock_domain);
inseq = PySequence_Contains(py_af_filter, py_family);
Py_DECREF(py_family);
if (inseq == 0)
continue;
py_type = PyLong_FromLong((long)kif->kf_sock_type);
inseq = PySequence_Contains(py_type_filter, py_type);
Py_DECREF(py_type);
if (inseq == 0)
continue;
// IPv4 / IPv6 socket
if ((kif->kf_sock_domain == AF_INET) ||
(kif->kf_sock_domain == AF_INET6)) {
// fill status
state = PSUTIL_CONN_NONE;
if (kif->kf_sock_type == SOCK_STREAM) {
tcp = psutil_search_tcplist(tcplist, kif);
if (tcp != NULL)
state = (int)tcp->t_state;
}
// build addr and port
inet_ntop(
kif->kf_sock_domain,
psutil_sockaddr_addr(kif->kf_sock_domain,
#if __FreeBSD_version < 1200031
&kif->kf_sa_local),
#else
&kif->kf_un.kf_sock.kf_sa_local),
#endif
lip,
sizeof(lip));
inet_ntop(
kif->kf_sock_domain,
psutil_sockaddr_addr(kif->kf_sock_domain,
#if __FreeBSD_version < 1200031
&kif->kf_sa_peer),
#else
&kif->kf_un.kf_sock.kf_sa_peer),
#endif
rip,
sizeof(rip));
lport = htons(psutil_sockaddr_port(kif->kf_sock_domain,
#if __FreeBSD_version < 1200031
&kif->kf_sa_local));
#else
&kif->kf_un.kf_sock.kf_sa_local));
#endif
rport = htons(psutil_sockaddr_port(kif->kf_sock_domain,
#if __FreeBSD_version < 1200031
&kif->kf_sa_peer));
#else
&kif->kf_un.kf_sock.kf_sa_peer));
#endif
// construct python tuple/list
py_laddr = Py_BuildValue("(si)", lip, lport);
if (!py_laddr)
goto error;
if (rport != 0)
py_raddr = Py_BuildValue("(si)", rip, rport);
else
py_raddr = Py_BuildValue("()");
if (!py_raddr)
goto error;
py_tuple = Py_BuildValue(
"(iiiNNi)",
kif->kf_fd,
kif->kf_sock_domain,
kif->kf_sock_type,
py_laddr,
py_raddr,
state
);
if (!py_tuple)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_DECREF(py_tuple);
}
// UNIX socket.
// Note: remote path cannot be determined.
else if (kif->kf_sock_domain == AF_UNIX) {
struct sockaddr_un *sun;
#if __FreeBSD_version < 1200031
sun = (struct sockaddr_un *)&kif->kf_sa_local;
#else
sun = (struct sockaddr_un *)&kif->kf_un.kf_sock.kf_sa_local;
#endif
snprintf(
path, sizeof(path), "%.*s",
(int)(sun->sun_len - (sizeof(*sun) - sizeof(sun->sun_path))),
sun->sun_path);
py_laddr = PyUnicode_DecodeFSDefault(path);
if (! py_laddr)
goto error;
py_tuple = Py_BuildValue(
"(iiiOsi)",
kif->kf_fd,
kif->kf_sock_domain,
kif->kf_sock_type,
py_laddr,
"", // raddr can't be determined
PSUTIL_CONN_NONE
);
if (!py_tuple)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_DECREF(py_tuple);
Py_DECREF(py_laddr);
}
}
}
free(freep);
free(tcplist);
return py_retlist;
error:
Py_XDECREF(py_tuple);
Py_XDECREF(py_laddr);
Py_XDECREF(py_raddr);
Py_DECREF(py_retlist);
if (freep != NULL)
free(freep);
if (tcplist != NULL)
free(tcplist);
return NULL;
}
| 11,001 | 28.495979 | 85 | c |
psutil | psutil-master/psutil/arch/freebsd/sensors.c | /*
* 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.
*/
/*
Original code was refactored and moved from psutil/arch/freebsd/specific.c
For reference, here's the git history with original(ish) implementations:
- sensors_battery(): 022cf0a05d34f4274269d4f8002ee95b9f3e32d2
- sensors_cpu_temperature(): bb5d032be76980a9e110f03f1203bd35fa85a793
(patch by Alex Manuskin)
*/
#include <Python.h>
#include <sys/sysctl.h>
#include "../../_psutil_common.h"
#include "../../_psutil_posix.h"
#define DECIKELVIN_2_CELSIUS(t) (t - 2731) / 10
PyObject *
psutil_sensors_battery(PyObject *self, PyObject *args) {
int percent;
int minsleft;
int power_plugged;
size_t size = sizeof(percent);
if (sysctlbyname("hw.acpi.battery.life", &percent, &size, NULL, 0))
goto error;
if (sysctlbyname("hw.acpi.battery.time", &minsleft, &size, NULL, 0))
goto error;
if (sysctlbyname("hw.acpi.acline", &power_plugged, &size, NULL, 0))
goto error;
return Py_BuildValue("iii", percent, minsleft, power_plugged);
error:
// see: https://github.com/giampaolo/psutil/issues/1074
if (errno == ENOENT)
PyErr_SetString(PyExc_NotImplementedError, "no battery");
else
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
// Return temperature information for a given CPU core number.
PyObject *
psutil_sensors_cpu_temperature(PyObject *self, PyObject *args) {
int current;
int tjmax;
int core;
char sensor[26];
size_t size = sizeof(current);
if (! PyArg_ParseTuple(args, "i", &core))
return NULL;
sprintf(sensor, "dev.cpu.%d.temperature", core);
if (sysctlbyname(sensor, ¤t, &size, NULL, 0))
goto error;
current = DECIKELVIN_2_CELSIUS(current);
// Return -273 in case of failure.
sprintf(sensor, "dev.cpu.%d.coretemp.tjmax", core);
if (sysctlbyname(sensor, &tjmax, &size, NULL, 0))
tjmax = 0;
tjmax = DECIKELVIN_2_CELSIUS(tjmax);
return Py_BuildValue("ii", current, tjmax);
error:
if (errno == ENOENT)
PyErr_SetString(PyExc_NotImplementedError, "no temperature sensors");
else
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
| 2,329 | 27.072289 | 77 | c |
psutil | psutil-master/psutil/arch/freebsd/sys_socks.c | /*
* 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.
*
* Retrieves system-wide open socket connections. This is based off of
* sockstat utility source code:
* https://github.com/freebsd/freebsd/blob/master/usr.bin/sockstat/sockstat.c
*/
#include <Python.h>
#include <sys/param.h>
#include <sys/user.h>
#include <sys/file.h>
#include <sys/socketvar.h> // for struct xsocket
#include <sys/un.h>
#include <sys/unpcb.h>
#include <sys/sysctl.h>
#if defined(__FreeBSD_version) && __FreeBSD_version < 800000
#include <netinet/in_systm.h>
#endif
#include <netinet/in.h> // for xinpcb struct
#include <netinet/ip.h>
#include <netinet/in_pcb.h>
#include <netinet/tcp_var.h> // for struct xtcpcb
#include <arpa/inet.h> // for inet_ntop()
#include "../../_psutil_common.h"
#include "../../_psutil_posix.h"
static struct xfile *psutil_xfiles;
static int psutil_nxfiles;
int
psutil_populate_xfiles(void) {
size_t len;
if ((psutil_xfiles = malloc(len = sizeof *psutil_xfiles)) == NULL) {
PyErr_NoMemory();
return 0;
}
while (sysctlbyname("kern.file", psutil_xfiles, &len, 0, 0) == -1) {
if (errno != ENOMEM) {
PyErr_SetFromErrno(0);
return 0;
}
len *= 2;
if ((psutil_xfiles = realloc(psutil_xfiles, len)) == NULL) {
PyErr_NoMemory();
return 0;
}
}
if (len > 0 && psutil_xfiles->xf_size != sizeof *psutil_xfiles) {
PyErr_Format(PyExc_RuntimeError, "struct xfile size mismatch");
return 0;
}
psutil_nxfiles = len / sizeof *psutil_xfiles;
return 1;
}
struct xfile *
psutil_get_file_from_sock(kvaddr_t sock) {
struct xfile *xf;
int n;
for (xf = psutil_xfiles, n = 0; n < psutil_nxfiles; ++n, ++xf) {
if (xf->xf_data == sock)
return xf;
}
return NULL;
}
// Reference:
// https://github.com/freebsd/freebsd/blob/master/usr.bin/sockstat/sockstat.c
int psutil_gather_inet(int proto, PyObject *py_retlist) {
struct xinpgen *xig, *exig;
struct xinpcb *xip;
struct xtcpcb *xtp;
#if __FreeBSD_version >= 1200026
struct xinpcb *inp;
#else
struct inpcb *inp;
#endif
struct xsocket *so;
const char *varname = NULL;
size_t len, bufsize;
void *buf;
int retry;
int type;
PyObject *py_tuple = NULL;
PyObject *py_laddr = NULL;
PyObject *py_raddr = NULL;
switch (proto) {
case IPPROTO_TCP:
varname = "net.inet.tcp.pcblist";
type = SOCK_STREAM;
break;
case IPPROTO_UDP:
varname = "net.inet.udp.pcblist";
type = SOCK_DGRAM;
break;
}
buf = NULL;
bufsize = 8192;
retry = 5;
do {
for (;;) {
buf = realloc(buf, bufsize);
if (buf == NULL)
continue; // XXX
len = bufsize;
if (sysctlbyname(varname, buf, &len, NULL, 0) == 0)
break;
if (errno != ENOMEM) {
PyErr_SetFromErrno(0);
goto error;
}
bufsize *= 2;
}
xig = (struct xinpgen *)buf;
exig = (struct xinpgen *)(void *)((char *)buf + len - sizeof *exig);
if (xig->xig_len != sizeof *xig || exig->xig_len != sizeof *exig) {
PyErr_Format(PyExc_RuntimeError, "struct xinpgen size mismatch");
goto error;
}
} while (xig->xig_gen != exig->xig_gen && retry--);
for (;;) {
struct xfile *xf;
int lport, rport, status, family;
xig = (struct xinpgen *)(void *)((char *)xig + xig->xig_len);
if (xig >= exig)
break;
switch (proto) {
case IPPROTO_TCP:
xtp = (struct xtcpcb *)xig;
if (xtp->xt_len != sizeof *xtp) {
PyErr_Format(PyExc_RuntimeError,
"struct xtcpcb size mismatch");
goto error;
}
inp = &xtp->xt_inp;
#if __FreeBSD_version >= 1200026
so = &inp->xi_socket;
status = xtp->t_state;
#else
so = &xtp->xt_socket;
status = xtp->xt_tp.t_state;
#endif
break;
case IPPROTO_UDP:
xip = (struct xinpcb *)xig;
if (xip->xi_len != sizeof *xip) {
PyErr_Format(PyExc_RuntimeError,
"struct xinpcb size mismatch");
goto error;
}
#if __FreeBSD_version >= 1200026
inp = xip;
#else
inp = &xip->xi_inp;
#endif
so = &xip->xi_socket;
status = PSUTIL_CONN_NONE;
break;
default:
PyErr_Format(PyExc_RuntimeError, "invalid proto");
goto error;
}
char lip[200], rip[200];
xf = psutil_get_file_from_sock(so->xso_so);
if (xf == NULL)
continue;
lport = ntohs(inp->inp_lport);
rport = ntohs(inp->inp_fport);
if (inp->inp_vflag & INP_IPV4) {
family = AF_INET;
inet_ntop(AF_INET, &inp->inp_laddr.s_addr, lip, sizeof(lip));
inet_ntop(AF_INET, &inp->inp_faddr.s_addr, rip, sizeof(rip));
}
else if (inp->inp_vflag & INP_IPV6) {
family = AF_INET6;
inet_ntop(AF_INET6, &inp->in6p_laddr.s6_addr, lip, sizeof(lip));
inet_ntop(AF_INET6, &inp->in6p_faddr.s6_addr, rip, sizeof(rip));
}
// construct python tuple/list
py_laddr = Py_BuildValue("(si)", lip, lport);
if (!py_laddr)
goto error;
if (rport != 0)
py_raddr = Py_BuildValue("(si)", rip, rport);
else
py_raddr = Py_BuildValue("()");
if (!py_raddr)
goto error;
py_tuple = Py_BuildValue(
"iiiNNi" _Py_PARSE_PID,
xf->xf_fd, // fd
family, // family
type, // type
py_laddr, // laddr
py_raddr, // raddr
status, // status
xf->xf_pid // pid
);
if (!py_tuple)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_CLEAR(py_tuple);
}
free(buf);
return 1;
error:
Py_XDECREF(py_tuple);
Py_XDECREF(py_laddr);
Py_XDECREF(py_raddr);
free(buf);
return 0;
}
int psutil_gather_unix(int proto, PyObject *py_retlist) {
struct xunpgen *xug, *exug;
struct xunpcb *xup;
const char *varname = NULL;
const char *protoname = NULL;
size_t len;
size_t bufsize;
void *buf;
int retry;
struct sockaddr_un *sun;
char path[PATH_MAX];
PyObject *py_tuple = NULL;
PyObject *py_lpath = NULL;
switch (proto) {
case SOCK_STREAM:
varname = "net.local.stream.pcblist";
protoname = "stream";
break;
case SOCK_DGRAM:
varname = "net.local.dgram.pcblist";
protoname = "dgram";
break;
}
buf = NULL;
bufsize = 8192;
retry = 5;
do {
for (;;) {
buf = realloc(buf, bufsize);
if (buf == NULL) {
PyErr_NoMemory();
goto error;
}
len = bufsize;
if (sysctlbyname(varname, buf, &len, NULL, 0) == 0)
break;
if (errno != ENOMEM) {
PyErr_SetFromErrno(0);
goto error;
}
bufsize *= 2;
}
xug = (struct xunpgen *)buf;
exug = (struct xunpgen *)(void *)
((char *)buf + len - sizeof *exug);
if (xug->xug_len != sizeof *xug || exug->xug_len != sizeof *exug) {
PyErr_Format(PyExc_RuntimeError, "struct xinpgen size mismatch");
goto error;
}
} while (xug->xug_gen != exug->xug_gen && retry--);
for (;;) {
struct xfile *xf;
xug = (struct xunpgen *)(void *)((char *)xug + xug->xug_len);
if (xug >= exug)
break;
xup = (struct xunpcb *)xug;
if (xup->xu_len != sizeof *xup)
goto error;
xf = psutil_get_file_from_sock(xup->xu_socket.xso_so);
if (xf == NULL)
continue;
sun = (struct sockaddr_un *)&xup->xu_addr;
snprintf(path, sizeof(path), "%.*s",
(int)(sun->sun_len - (sizeof(*sun) - sizeof(sun->sun_path))),
sun->sun_path);
py_lpath = PyUnicode_DecodeFSDefault(path);
if (! py_lpath)
goto error;
py_tuple = Py_BuildValue("(iiiOsii)",
xf->xf_fd, // fd
AF_UNIX, // family
proto, // type
py_lpath, // lpath
"", // rath
PSUTIL_CONN_NONE, // status
xf->xf_pid); // pid
if (!py_tuple)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_DECREF(py_lpath);
Py_DECREF(py_tuple);
}
free(buf);
return 1;
error:
Py_XDECREF(py_tuple);
Py_XDECREF(py_lpath);
free(buf);
return 0;
}
PyObject*
psutil_net_connections(PyObject* self, PyObject* args) {
// Return system-wide open connections.
PyObject *py_retlist = PyList_New(0);
if (py_retlist == NULL)
return NULL;
if (psutil_populate_xfiles() != 1)
goto error;
if (psutil_gather_inet(IPPROTO_TCP, py_retlist) == 0)
goto error;
if (psutil_gather_inet(IPPROTO_UDP, py_retlist) == 0)
goto error;
if (psutil_gather_unix(SOCK_STREAM, py_retlist) == 0)
goto error;
if (psutil_gather_unix(SOCK_DGRAM, py_retlist) == 0)
goto error;
free(psutil_xfiles);
return py_retlist;
error:
Py_DECREF(py_retlist);
free(psutil_xfiles);
return NULL;
}
| 10,147 | 26.576087 | 78 | c |
psutil | psutil-master/psutil/arch/netbsd/cpu.c | /*
* Copyright (c) 2009, Giampaolo Rodola', Landry Breuil.
* 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 <sys/sched.h>
#include <sys/sysctl.h>
#include <uvm/uvm_extern.h>
/*
CPU related functions. Original code was refactored and moved from
psutil/arch/netbsd/specific.c in 2023 (and was moved in there previously
already) from cset 84219ad. For reference, here's the git history with
original(ish) implementations:
- per CPU times: 312442ad2a5b5d0c608476c5ab3e267735c3bc59 (Jan 2016)
- CPU stats: a991494e4502e1235ebc62b5ba450287d0dedec0 (Jan 2016)
*/
PyObject *
psutil_cpu_stats(PyObject *self, PyObject *args) {
size_t size;
struct uvmexp_sysctl uv;
int uvmexp_mib[] = {CTL_VM, VM_UVMEXP2};
size = sizeof(uv);
if (sysctl(uvmexp_mib, 2, &uv, &size, NULL, 0) < 0) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
return Py_BuildValue(
"IIIIIII",
uv.swtch, // ctx switches
uv.intrs, // interrupts - XXX always 0, will be determined via /proc
uv.softs, // soft interrupts
uv.syscalls, // syscalls - XXX always 0
uv.traps, // traps
uv.faults, // faults
uv.forks // forks
);
}
PyObject *
psutil_per_cpu_times(PyObject *self, PyObject *args) {
int mib[3];
int ncpu;
size_t len;
size_t size;
int i;
PyObject *py_cputime = NULL;
PyObject *py_retlist = PyList_New(0);
if (py_retlist == NULL)
return NULL;
// retrieve the number of cpus
mib[0] = CTL_HW;
mib[1] = HW_NCPU;
len = sizeof(ncpu);
if (sysctl(mib, 2, &ncpu, &len, NULL, 0) == -1) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
uint64_t cpu_time[CPUSTATES];
for (i = 0; i < ncpu; i++) {
// per-cpu info
mib[0] = CTL_KERN;
mib[1] = KERN_CP_TIME;
mib[2] = i;
size = sizeof(cpu_time);
if (sysctl(mib, 3, &cpu_time, &size, NULL, 0) == -1) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
py_cputime = Py_BuildValue(
"(ddddd)",
(double)cpu_time[CP_USER] / CLOCKS_PER_SEC,
(double)cpu_time[CP_NICE] / CLOCKS_PER_SEC,
(double)cpu_time[CP_SYS] / CLOCKS_PER_SEC,
(double)cpu_time[CP_IDLE] / CLOCKS_PER_SEC,
(double)cpu_time[CP_INTR] / CLOCKS_PER_SEC
);
if (!py_cputime)
goto error;
if (PyList_Append(py_retlist, py_cputime))
goto error;
Py_DECREF(py_cputime);
}
return py_retlist;
error:
Py_XDECREF(py_cputime);
Py_DECREF(py_retlist);
return NULL;
}
| 2,775 | 25.692308 | 77 | c |
psutil | psutil-master/psutil/arch/netbsd/disk.c | /*
* Copyright (c) 2009, Giampaolo Rodola', Landry Breuil.
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
/*
Disk related functions. Original code was refactored and moved from
psutil/arch/netbsd/specific.c in 2023 (and was moved in there previously
already) from cset 84219ad. For reference, here's the git history with
original(ish) implementations:
- disk IO counters: 312442ad2a5b5d0c608476c5ab3e267735c3bc59 (Jan 2016)
*/
#include <Python.h>
#include <sys/sysctl.h>
#include <sys/disk.h>
PyObject *
psutil_disk_io_counters(PyObject *self, PyObject *args) {
int i, dk_ndrive, mib[3];
size_t len;
struct io_sysctl *stats = NULL;
PyObject *py_disk_info = NULL;
PyObject *py_retdict = PyDict_New();
if (py_retdict == NULL)
return NULL;
mib[0] = CTL_HW;
mib[1] = HW_IOSTATS;
mib[2] = sizeof(struct io_sysctl);
len = 0;
if (sysctl(mib, 3, NULL, &len, NULL, 0) < 0) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
dk_ndrive = (int)(len / sizeof(struct io_sysctl));
stats = malloc(len);
if (stats == NULL) {
PyErr_NoMemory();
goto error;
}
if (sysctl(mib, 3, stats, &len, NULL, 0) < 0 ) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
for (i = 0; i < dk_ndrive; i++) {
py_disk_info = Py_BuildValue(
"(KKKK)",
stats[i].rxfer,
stats[i].wxfer,
stats[i].rbytes,
stats[i].wbytes
);
if (!py_disk_info)
goto error;
if (PyDict_SetItemString(py_retdict, stats[i].name, py_disk_info))
goto error;
Py_DECREF(py_disk_info);
}
free(stats);
return py_retdict;
error:
Py_XDECREF(py_disk_info);
Py_DECREF(py_retdict);
if (stats != NULL)
free(stats);
return NULL;
}
| 1,939 | 24.526316 | 74 | c |
psutil | psutil-master/psutil/arch/netbsd/mem.c | /*
* Copyright (c) 2009, Giampaolo Rodola', Landry Breuil.
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
/*
Memory related functions. Original code was refactored and moved from
psutil/arch/netbsd/specific.c in 2023 (and was moved in there previously
already) from cset 84219ad. For reference, here's the git history with
original(ish) implementations:
- virtual memory: 0749a69c01b374ca3e2180aaafc3c95e3b2d91b9 (Oct 2016)
- swap memory: 312442ad2a5b5d0c608476c5ab3e267735c3bc59 (Jan 2016)
*/
#include <Python.h>
#include <sys/swap.h>
#include <sys/sysctl.h>
#include <uvm/uvm_extern.h>
#include "../../_psutil_common.h"
#include "../../_psutil_posix.h"
// Virtual memory stats, taken from:
// https://github.com/satterly/zabbix-stats/blob/master/src/libs/zbxsysinfo/
// netbsd/memory.c
PyObject *
psutil_virtual_mem(PyObject *self, PyObject *args) {
size_t size;
struct uvmexp_sysctl uv;
int mib[] = {CTL_VM, VM_UVMEXP2};
long long cached;
size = sizeof(uv);
if (sysctl(mib, 2, &uv, &size, NULL, 0) < 0) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
// Note: zabbix does not include anonpages, but that doesn't match the
// "Cached" value in /proc/meminfo.
// https://github.com/zabbix/zabbix/blob/af5e0f8/src/libs/zbxsysinfo/netbsd/memory.c#L182
cached = (uv.filepages + uv.execpages + uv.anonpages) << uv.pageshift;
return Py_BuildValue(
"LLLLLL",
(long long) uv.npages << uv.pageshift, // total
(long long) uv.free << uv.pageshift, // free
(long long) uv.active << uv.pageshift, // active
(long long) uv.inactive << uv.pageshift, // inactive
(long long) uv.wired << uv.pageshift, // wired
cached // cached
);
}
PyObject *
psutil_swap_mem(PyObject *self, PyObject *args) {
uint64_t swap_total, swap_free;
struct swapent *swdev;
int nswap, i;
long pagesize = psutil_getpagesize();
nswap = swapctl(SWAP_NSWAP, 0, 0);
if (nswap == 0) {
// This means there's no swap partition.
return Py_BuildValue("(iiiii)", 0, 0, 0, 0, 0);
}
swdev = calloc(nswap, sizeof(*swdev));
if (swdev == NULL) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
if (swapctl(SWAP_STATS, swdev, nswap) == -1) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
// Total things up.
swap_total = swap_free = 0;
for (i = 0; i < nswap; i++) {
if (swdev[i].se_flags & SWF_ENABLE) {
swap_total += (uint64_t)swdev[i].se_nblks * DEV_BSIZE;
swap_free += (uint64_t)(swdev[i].se_nblks - swdev[i].se_inuse) * DEV_BSIZE;
}
}
free(swdev);
// Get swap in/out
unsigned int total;
size_t size = sizeof(total);
struct uvmexp_sysctl uv;
int mib[] = {CTL_VM, VM_UVMEXP2};
size = sizeof(uv);
if (sysctl(mib, 2, &uv, &size, NULL, 0) < 0) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
return Py_BuildValue("(LLLll)",
swap_total,
(swap_total - swap_free),
swap_free,
(long) uv.pgswapin * pagesize, // swap in
(long) uv.pgswapout * pagesize); // swap out
error:
free(swdev);
return NULL;
}
| 3,428 | 29.078947 | 93 | c |
psutil | psutil-master/psutil/arch/netbsd/proc.c | /*
* Copyright (c) 2009, Giampaolo Rodola', Landry Breuil.
* All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*
* Platform-specific module methods for NetBSD.
*/
#include <Python.h>
#include <sys/sysctl.h>
#include <kvm.h>
#include "../../_psutil_common.h"
#include "../../_psutil_posix.h"
#include "proc.h"
#define PSUTIL_KPT2DOUBLE(t) (t ## _sec + t ## _usec / 1000000.0)
#define PSUTIL_TV2DOUBLE(t) ((t).tv_sec + (t).tv_usec / 1000000.0)
// ============================================================================
// Utility functions
// ============================================================================
int
psutil_kinfo_proc(pid_t pid, kinfo_proc *proc) {
// Fills a kinfo_proc struct based on process pid.
int ret;
int mib[6];
size_t size = sizeof(kinfo_proc);
mib[0] = CTL_KERN;
mib[1] = KERN_PROC2;
mib[2] = KERN_PROC_PID;
mib[3] = pid;
mib[4] = size;
mib[5] = 1;
ret = sysctl((int*)mib, 6, proc, &size, NULL, 0);
if (ret == -1) {
PyErr_SetFromErrno(PyExc_OSError);
return -1;
}
// sysctl stores 0 in the size if we can't find the process information.
if (size == 0) {
NoSuchProcess("sysctl (size = 0)");
return -1;
}
return 0;
}
struct kinfo_file *
kinfo_getfile(pid_t pid, int* cnt) {
// Mimic's FreeBSD kinfo_file call, taking a pid and a ptr to an
// int as arg and returns an array with cnt struct kinfo_file.
int mib[6];
size_t len;
struct kinfo_file* kf;
mib[0] = CTL_KERN;
mib[1] = KERN_FILE2;
mib[2] = KERN_FILE_BYPID;
mib[3] = (int) pid;
mib[4] = sizeof(struct kinfo_file);
mib[5] = 0;
// get the size of what would be returned
if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
if ((kf = malloc(len)) == NULL) {
PyErr_NoMemory();
return NULL;
}
mib[5] = (int)(len / sizeof(struct kinfo_file));
if (sysctl(mib, 6, kf, &len, NULL, 0) < 0) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
*cnt = (int)(len / sizeof(struct kinfo_file));
return kf;
}
PyObject *
psutil_proc_cwd(PyObject *self, PyObject *args) {
long pid;
char path[MAXPATHLEN];
size_t pathlen = sizeof path;
if (! PyArg_ParseTuple(args, "l", &pid))
return NULL;
#ifdef KERN_PROC_CWD
int name[] = { CTL_KERN, KERN_PROC_ARGS, pid, KERN_PROC_CWD};
if (sysctl(name, 4, path, &pathlen, NULL, 0) != 0) {
if (errno == ENOENT)
NoSuchProcess("sysctl -> ENOENT");
else
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
#else
char *buf;
if (asprintf(&buf, "/proc/%d/cwd", (int)pid) < 0) {
PyErr_NoMemory();
return NULL;
}
ssize_t len = readlink(buf, path, sizeof(path) - 1);
free(buf);
if (len == -1) {
if (errno == ENOENT) {
psutil_debug("sysctl(KERN_PROC_CWD) -> ENOENT converted to ''");
return Py_BuildValue("s", "");
}
else {
PyErr_SetFromErrno(PyExc_OSError);
}
return NULL;
}
path[len] = '\0';
#endif
return PyUnicode_DecodeFSDefault(path);
}
// XXX: This is no longer used as per
// https://github.com/giampaolo/psutil/pull/557#issuecomment-171912820
// Current implementation uses /proc instead.
// Left here just in case.
/*
PyObject *
psutil_proc_exe(PyObject *self, PyObject *args) {
#if __NetBSD_Version__ >= 799000000
pid_t pid;
char pathname[MAXPATHLEN];
int error;
int mib[4];
int ret;
size_t size;
if (! PyArg_ParseTuple(args, "l", &pid))
return NULL;
if (pid == 0) {
// else returns ENOENT
return Py_BuildValue("s", "");
}
mib[0] = CTL_KERN;
mib[1] = KERN_PROC_ARGS;
mib[2] = pid;
mib[3] = KERN_PROC_PATHNAME;
size = sizeof(pathname);
error = sysctl(mib, 4, NULL, &size, NULL, 0);
if (error == -1) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
error = sysctl(mib, 4, pathname, &size, NULL, 0);
if (error == -1) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
if (size == 0 || strlen(pathname) == 0) {
ret = psutil_pid_exists(pid);
if (ret == -1)
return NULL;
else if (ret == 0)
return NoSuchProcess("psutil_pid_exists -> 0");
else
strcpy(pathname, "");
}
return PyUnicode_DecodeFSDefault(pathname);
#else
return Py_BuildValue("s", "");
#endif
}
*/
PyObject *
psutil_proc_num_threads(PyObject *self, PyObject *args) {
// Return number of threads used by process as a Python integer.
long pid;
kinfo_proc kp;
if (! PyArg_ParseTuple(args, "l", &pid))
return NULL;
if (psutil_kinfo_proc(pid, &kp) == -1)
return NULL;
return Py_BuildValue("l", (long)kp.p_nlwps);
}
PyObject *
psutil_proc_threads(PyObject *self, PyObject *args) {
pid_t pid;
int mib[5];
int i, nlwps;
ssize_t st;
size_t size;
struct kinfo_lwp *kl = NULL;
PyObject *py_retlist = PyList_New(0);
PyObject *py_tuple = NULL;
if (py_retlist == NULL)
return NULL;
if (! PyArg_ParseTuple(args, "l", &pid))
goto error;
mib[0] = CTL_KERN;
mib[1] = KERN_LWP;
mib[2] = pid;
mib[3] = sizeof(struct kinfo_lwp);
mib[4] = 0;
st = sysctl(mib, 5, NULL, &size, NULL, 0);
if (st == -1) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
if (size == 0) {
NoSuchProcess("sysctl (size = 0)");
goto error;
}
mib[4] = size / sizeof(size_t);
kl = malloc(size);
if (kl == NULL) {
PyErr_NoMemory();
goto error;
}
st = sysctl(mib, 5, kl, &size, NULL, 0);
if (st == -1) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
if (size == 0) {
NoSuchProcess("sysctl (size = 0)");
goto error;
}
nlwps = (int)(size / sizeof(struct kinfo_lwp));
for (i = 0; i < nlwps; i++) {
if ((&kl[i])->l_stat == LSIDL || (&kl[i])->l_stat == LSZOMB)
continue;
// XXX: we return 2 "user" times because the struct does not provide
// any "system" time.
py_tuple = Py_BuildValue("idd",
(&kl[i])->l_lid,
PSUTIL_KPT2DOUBLE((&kl[i])->l_rtime),
PSUTIL_KPT2DOUBLE((&kl[i])->l_rtime));
if (py_tuple == NULL)
goto error;
if (PyList_Append(py_retlist, py_tuple))
goto error;
Py_DECREF(py_tuple);
}
free(kl);
return py_retlist;
error:
Py_XDECREF(py_tuple);
Py_DECREF(py_retlist);
if (kl != NULL)
free(kl);
return NULL;
}
int
psutil_get_proc_list(kinfo_proc **procList, size_t *procCount) {
// Returns a list of all BSD processes on the system. This routine
// allocates the list and puts it in *procList and a count of the
// number of entries in *procCount. You are responsible for freeing
// this list (use "free" from System framework).
// On success, the function returns 0.
// On error, the function returns a BSD errno value.
kinfo_proc *result;
// Declaring name as const requires us to cast it when passing it to
// sysctl because the prototype doesn't include the const modifier.
char errbuf[_POSIX2_LINE_MAX];
int cnt;
kvm_t *kd;
assert( procList != NULL);
assert(*procList == NULL);
assert(procCount != NULL);
kd = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, errbuf);
if (kd == NULL) {
PyErr_Format(
PyExc_RuntimeError, "kvm_openfiles() syscall failed: %s", errbuf);
return 1;
}
result = kvm_getproc2(kd, KERN_PROC_ALL, 0, sizeof(kinfo_proc), &cnt);
if (result == NULL) {
PyErr_Format(PyExc_RuntimeError, "kvm_getproc2() syscall failed");
kvm_close(kd);
return 1;
}
*procCount = (size_t)cnt;
size_t mlen = cnt * sizeof(kinfo_proc);
if ((*procList = malloc(mlen)) == NULL) {
PyErr_NoMemory();
kvm_close(kd);
return 1;
}
memcpy(*procList, result, mlen);
assert(*procList != NULL);
kvm_close(kd);
return 0;
}
PyObject *
psutil_proc_cmdline(PyObject *self, PyObject *args) {
pid_t pid;
int mib[4];
int st;
size_t len = 0;
size_t pos = 0;
char *procargs = NULL;
PyObject *py_retlist = PyList_New(0);
PyObject *py_arg = NULL;
if (py_retlist == NULL)
return NULL;
if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
goto error;
mib[0] = CTL_KERN;
mib[1] = KERN_PROC_ARGS;
mib[2] = pid;
mib[3] = KERN_PROC_ARGV;
st = sysctl(mib, __arraycount(mib), NULL, &len, NULL, 0);
if (st == -1) {
PyErr_SetFromOSErrnoWithSyscall("sysctl(KERN_PROC_ARGV) get size");
goto error;
}
procargs = (char *)malloc(len);
if (procargs == NULL) {
PyErr_NoMemory();
goto error;
}
st = sysctl(mib, __arraycount(mib), procargs, &len, NULL, 0);
if (st == -1) {
PyErr_SetFromOSErrnoWithSyscall("sysctl(KERN_PROC_ARGV)");
goto error;
}
if (len > 0) {
while (pos < len) {
py_arg = PyUnicode_DecodeFSDefault(&procargs[pos]);
if (!py_arg)
goto error;
if (PyList_Append(py_retlist, py_arg))
goto error;
Py_DECREF(py_arg);
pos = pos + strlen(&procargs[pos]) + 1;
}
}
free(procargs);
return py_retlist;
error:
Py_XDECREF(py_arg);
Py_DECREF(py_retlist);
if (procargs != NULL)
free(procargs);
return NULL;
}
PyObject *
psutil_proc_num_fds(PyObject *self, PyObject *args) {
long pid;
int cnt;
struct kinfo_file *freep;
if (! PyArg_ParseTuple(args, "l", &pid))
return NULL;
errno = 0;
freep = kinfo_getfile(pid, &cnt);
if (freep == NULL) {
psutil_raise_for_pid(pid, "kinfo_getfile()");
return NULL;
}
free(freep);
return Py_BuildValue("i", cnt);
}
| 10,328 | 23.889157 | 79 | c |
psutil | psutil-master/psutil/arch/netbsd/proc.h | /*
* Copyright (c) 2009, Giampaolo Rodola', Landry Breuil.
* 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>
typedef struct kinfo_proc2 kinfo_proc;
int psutil_kinfo_proc(pid_t pid, kinfo_proc *proc);
struct kinfo_file * kinfo_getfile(pid_t pid, int* cnt);
int psutil_get_proc_list(kinfo_proc **procList, size_t *procCount);
char *psutil_get_cmd_args(pid_t pid, size_t *argsize);
PyObject *psutil_proc_cmdline(PyObject *self, PyObject *args);
PyObject *psutil_proc_connections(PyObject *self, PyObject *args);
PyObject *psutil_proc_cwd(PyObject *self, PyObject *args);
PyObject *psutil_proc_num_fds(PyObject *self, PyObject *args);
PyObject *psutil_proc_threads(PyObject *self, PyObject *args);
PyObject* psutil_proc_exe(PyObject* self, PyObject* args);
PyObject* psutil_proc_num_threads(PyObject* self, PyObject* args);
| 927 | 37.666667 | 73 | h |
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
- Downloads last month
- 8