Debian Codegraph @

psutil/arch/bsd/proc.c

raw
1 /*
2 * Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
3 * Use of this source code is governed by a BSD-style license that can be
4 * found in the LICENSE file.
5 */
6
7 #include <Python.h>
8 #include <kvm.h>
9 #include <sys/proc.h>
10 #include <sys/sysctl.h>
11 #include <sys/types.h>
12 #include <sys/file.h>
13 #include <sys/vnode.h> // VREG
14 #ifdef PSUTIL_FREEBSD
15 #include <sys/user.h> // kinfo_proc, kinfo_file, KF_*
16 #include <libutil.h> // kinfo_getfile()
17 #endif
18
19 #include "../../arch/all/init.h"
20 #ifdef PSUTIL_FREEBSD
21 #include "../../arch/freebsd/init.h" // TODO: refactor this
22 #elif PSUTIL_OPENBSD
23 #include "../../arch/openbsd/init.h" // TODO: refactor this
24 #elif PSUTIL_NETBSD
25 #include "../../arch/netbsd/init.h" // TODO: refactor this
26 #endif
27
28
29 // convert a timeval struct to a double
30 #define PSUTIL_TV2DOUBLE(t) ((t).tv_sec + (t).tv_usec / 1000000.0)
31
32 #if defined(PSUTIL_OPENBSD) || defined (PSUTIL_NETBSD)
33 #define PSUTIL_KPT2DOUBLE(t) (t ## _sec + t ## _usec / 1000000.0)
34 #endif
35
36
37 // Mimic's FreeBSD kinfo_file call, taking a pid and a ptr to an
38 // int as arg and returns an array with cnt struct kinfo_file.
39 #ifdef PSUTIL_HASNT_KINFO_GETFILE
40 struct kinfo_file *
41 kinfo_getfile(pid_t pid, int *cnt) {
42 int mib[6];
43 size_t len;
44 struct kinfo_file *kf = NULL;
45
46 mib[0] = CTL_KERN;
47 mib[1] = KERN_FILE;
48 mib[2] = KERN_FILE_BYPID;
49 mib[3] = pid;
50 mib[4] = sizeof(struct kinfo_file);
51 mib[5] = 0;
52
53 if (psutil_sysctl_malloc(mib, 6, (char **)&kf, &len) != 0) {
54 return NULL;
55 }
56
57 *cnt = (int)(len / sizeof(struct kinfo_file));
58 return kf;
59 }
60 #endif // PSUTIL_HASNT_KINFO_GETFILE
61
62
63 /*
64 * Return a Python list of all the PIDs running on the system.
65 */
66 PyObject *
67 psutil_pids(PyObject *self, PyObject *args) {
68 kinfo_proc *proclist = NULL;
69 kinfo_proc *orig_address = NULL;
70 size_t num_processes;
71 size_t idx;
72 PyObject *py_retlist = PyList_New(0);
73 PyObject *py_pid = NULL;
74
75 if (py_retlist == NULL)
76 return NULL;
77
78 if (psutil_get_proc_list(&proclist, &num_processes) != 0)
79 goto error;
80
81 if (num_processes > 0) {
82 orig_address = proclist; // save so we can free it after we're done
83 for (idx = 0; idx < num_processes; idx++) {
84 #ifdef PSUTIL_FREEBSD
85 py_pid = PyLong_FromPid(proclist->ki_pid);
86 #elif defined(PSUTIL_OPENBSD) || defined(PSUTIL_NETBSD)
87 py_pid = PyLong_FromPid(proclist->p_pid);
88 #endif
89 if (!py_pid)
90 goto error;
91 if (PyList_Append(py_retlist, py_pid))
92 goto error;
93 Py_CLEAR(py_pid);
94 proclist++;
95 }
96 free(orig_address);
97 }
98
99 return py_retlist;
100
101 error:
102 Py_XDECREF(py_pid);
103 Py_DECREF(py_retlist);
104 if (orig_address != NULL)
105 free(orig_address);
106 return NULL;
107 }
108
109
110 /*
111 * Collect different info about a process in one shot and return
112 * them as a big Python tuple.
113 */
114 PyObject *
115 psutil_proc_oneshot_info(PyObject *self, PyObject *args) {
116 pid_t pid;
117 long rss;
118 long vms;
119 long memtext;
120 long memdata;
121 long memstack;
122 int oncpu;
123 kinfo_proc kp;
124 long pagesize = psutil_getpagesize();
125 char str[1000];
126 PyObject *py_name;
127 PyObject *py_ppid;
128 PyObject *py_retlist;
129
130 if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
131 return NULL;
132 if (psutil_kinfo_proc(pid, &kp) == -1)
133 return NULL;
134
135 // Process
136 #ifdef PSUTIL_FREEBSD
137 sprintf(str, "%s", kp.ki_comm);
138 #elif defined(PSUTIL_OPENBSD) || defined(PSUTIL_NETBSD)
139 sprintf(str, "%s", kp.p_comm);
140 #endif
141 py_name = PyUnicode_DecodeFSDefault(str);
142 if (! py_name) {
143 // Likely a decoding error. We don't want to fail the whole
144 // operation. The python module may retry with proc_name().
145 PyErr_Clear();
146 py_name = Py_None;
147 }
148 // Py_INCREF(py_name);
149
150 // Calculate memory.
151 #ifdef PSUTIL_FREEBSD
152 rss = (long)kp.ki_rssize * pagesize;
153 vms = (long)kp.ki_size;
154 memtext = (long)kp.ki_tsize * pagesize;
155 memdata = (long)kp.ki_dsize * pagesize;
156 memstack = (long)kp.ki_ssize * pagesize;
157 #else
158 rss = (long)kp.p_vm_rssize * pagesize;
159 #ifdef PSUTIL_OPENBSD
160 // VMS, this is how ps determines it on OpenBSD:
161 // https://github.com/openbsd/src/blob/
162 // 588f7f8c69786211f2d16865c552afb91b1c7cba/bin/ps/print.c#L505
163 vms = (long)(kp.p_vm_dsize + kp.p_vm_ssize + kp.p_vm_tsize) * pagesize;
164 #elif PSUTIL_NETBSD
165 // VMS, this is how top determines it on NetBSD:
166 // https://github.com/IIJ-NetBSD/netbsd-src/blob/master/external/
167 // bsd/top/dist/machine/m_netbsd.c
168 vms = (long)kp.p_vm_msize * pagesize;
169 #endif
170 memtext = (long)kp.p_vm_tsize * pagesize;
171 memdata = (long)kp.p_vm_dsize * pagesize;
172 memstack = (long)kp.p_vm_ssize * pagesize;
173 #endif
174
175 #ifdef PSUTIL_FREEBSD
176 // what CPU we're on; top was used as an example:
177 // https://svnweb.freebsd.org/base/head/usr.bin/top/machine.c?
178 // view=markup&pathrev=273835
179 // XXX - note: for "intr" PID this is -1.
180 if (kp.ki_stat == SRUN && kp.ki_oncpu != NOCPU)
181 oncpu = kp.ki_oncpu;
182 else
183 oncpu = kp.ki_lastcpu;
184 #else
185 // On Net/OpenBSD we have kp.p_cpuid but it appears it's always
186 // set to KI_NOCPU. Even if it's not, ki_lastcpu does not exist
187 // so there's no way to determine where "sleeping" processes
188 // were. Not supported.
189 oncpu = -1;
190 #endif
191
192 #ifdef PSUTIL_FREEBSD
193 py_ppid = PyLong_FromPid(kp.ki_ppid);
194 #elif defined(PSUTIL_OPENBSD) || defined(PSUTIL_NETBSD)
195 py_ppid = PyLong_FromPid(kp.p_ppid);
196 #else
197 py_ppid = Py_BuildfValue(-1);
198 #endif
199 if (! py_ppid)
200 return NULL;
201
202 // Return a single big tuple with all process info.
203 py_retlist = Py_BuildValue(
204 #if defined(__FreeBSD_version) && __FreeBSD_version >= 1200031
205 "(OillllllLdllllddddlllllbO)",
206 #else
207 "(OillllllidllllddddlllllbO)",
208 #endif
209 #ifdef PSUTIL_FREEBSD
210 py_ppid, // (pid_t) ppid
211 (int)kp.ki_stat, // (int) status
212 // UIDs
213 (long)kp.ki_ruid, // (long) real uid
214 (long)kp.ki_uid, // (long) effective uid
215 (long)kp.ki_svuid, // (long) saved uid
216 // GIDs
217 (long)kp.ki_rgid, // (long) real gid
218 (long)kp.ki_groups[0], // (long) effective gid
219 (long)kp.ki_svuid, // (long) saved gid
220 //
221 kp.ki_tdev, // (int or long long) tty nr
222 PSUTIL_TV2DOUBLE(kp.ki_start), // (double) create time
223 // ctx switches
224 kp.ki_rusage.ru_nvcsw, // (long) ctx switches (voluntary)
225 kp.ki_rusage.ru_nivcsw, // (long) ctx switches (unvoluntary)
226 // IO count
227 kp.ki_rusage.ru_inblock, // (long) read io count
228 kp.ki_rusage.ru_oublock, // (long) write io count
229 // CPU times: convert from micro seconds to seconds.
230 PSUTIL_TV2DOUBLE(kp.ki_rusage.ru_utime), // (double) user time
231 PSUTIL_TV2DOUBLE(kp.ki_rusage.ru_stime), // (double) sys time
232 PSUTIL_TV2DOUBLE(kp.ki_rusage_ch.ru_utime), // (double) children utime
233 PSUTIL_TV2DOUBLE(kp.ki_rusage_ch.ru_stime), // (double) children stime
234 // memory
235 rss, // (long) rss
236 vms, // (long) vms
237 memtext, // (long) mem text
238 memdata, // (long) mem data
239 memstack, // (long) mem stack
240 // others
241 oncpu, // (int) the CPU we are on
242 #elif defined(PSUTIL_OPENBSD) || defined(PSUTIL_NETBSD)
243 py_ppid, // (pid_t) ppid
244 (int)kp.p_stat, // (int) status
245 // UIDs
246 (long)kp.p_ruid, // (long) real uid
247 (long)kp.p_uid, // (long) effective uid
248 (long)kp.p_svuid, // (long) saved uid
249 // GIDs
250 (long)kp.p_rgid, // (long) real gid
251 (long)kp.p_groups[0], // (long) effective gid
252 (long)kp.p_svuid, // (long) saved gid
253 //
254 kp.p_tdev, // (int) tty nr
255 PSUTIL_KPT2DOUBLE(kp.p_ustart), // (double) create time
256 // ctx switches
257 kp.p_uru_nvcsw, // (long) ctx switches (voluntary)
258 kp.p_uru_nivcsw, // (long) ctx switches (unvoluntary)
259 // IO count
260 kp.p_uru_inblock, // (long) read io count
261 kp.p_uru_oublock, // (long) write io count
262 // CPU times: convert from micro seconds to seconds.
263 PSUTIL_KPT2DOUBLE(kp.p_uutime), // (double) user time
264 PSUTIL_KPT2DOUBLE(kp.p_ustime), // (double) sys time
265 // OpenBSD and NetBSD provide children user + system times summed
266 // together (no distinction).
267 kp.p_uctime_sec + kp.p_uctime_usec / 1000000.0, // (double) ch utime
268 kp.p_uctime_sec + kp.p_uctime_usec / 1000000.0, // (double) ch stime
269 // memory
270 rss, // (long) rss
271 vms, // (long) vms
272 memtext, // (long) mem text
273 memdata, // (long) mem data
274 memstack, // (long) mem stack
275 // others
276 oncpu, // (int) the CPU we are on
277 #endif
278 py_name // (pystr) name
279 );
280
281 Py_DECREF(py_name);
282 Py_DECREF(py_ppid);
283 return py_retlist;
284 }
285
286
287 PyObject *
288 psutil_proc_name(PyObject *self, PyObject *args) {
289 pid_t pid;
290 kinfo_proc kp;
291 char str[1000];
292
293 if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
294 return NULL;
295 if (psutil_kinfo_proc(pid, &kp) == -1)
296 return NULL;
297
298 #ifdef PSUTIL_FREEBSD
299 sprintf(str, "%s", kp.ki_comm);
300 #elif defined(PSUTIL_OPENBSD) || defined(PSUTIL_NETBSD)
301 sprintf(str, "%s", kp.p_comm);
302 #endif
303 return PyUnicode_DecodeFSDefault(str);
304 }
305
306
307 PyObject *
308 psutil_proc_environ(PyObject *self, PyObject *args) {
309 int i, cnt = -1;
310 long pid;
311 char *s, **envs, errbuf[_POSIX2_LINE_MAX];
312 PyObject *py_value=NULL, *py_retdict=NULL;
313 kvm_t *kd;
314 #ifdef PSUTIL_NETBSD
315 struct kinfo_proc2 *p;
316 #else
317 struct kinfo_proc *p;
318 #endif
319
320 if (!PyArg_ParseTuple(args, "l", &pid))
321 return NULL;
322
323 #if defined(PSUTIL_FREEBSD)
324 kd = kvm_openfiles(NULL, "/dev/null", NULL, 0, errbuf);
325 #else
326 kd = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, errbuf);
327 #endif
328 if (!kd) {
329 convert_kvm_err("kvm_openfiles", errbuf);
330 return NULL;
331 }
332
333 py_retdict = PyDict_New();
334 if (!py_retdict)
335 goto error;
336
337 #if defined(PSUTIL_FREEBSD)
338 p = kvm_getprocs(kd, KERN_PROC_PID, pid, &cnt);
339 #elif defined(PSUTIL_OPENBSD)
340 p = kvm_getprocs(kd, KERN_PROC_PID, pid, sizeof(*p), &cnt);
341 #elif defined(PSUTIL_NETBSD)
342 p = kvm_getproc2(kd, KERN_PROC_PID, pid, sizeof(*p), &cnt);
343 #endif
344 if (!p) {
345 NoSuchProcess("kvm_getprocs");
346 goto error;
347 }
348 if (cnt <= 0) {
349 NoSuchProcess(cnt < 0 ? kvm_geterr(kd) : "kvm_getprocs: cnt==0");
350 goto error;
351 }
352
353 // On *BSD kernels there are a few kernel-only system processes without an
354 // environment (See e.g. "procstat -e 0 | 1 | 2 ..." on FreeBSD.)
355 // Some system process have no stats attached at all
356 // (they are marked with P_SYSTEM.)
357 // On FreeBSD, it's possible that the process is swapped or paged out,
358 // then there no access to the environ stored in the process' user area.
359 // On NetBSD, we cannot call kvm_getenvv2() for a zombie process.
360 // To make unittest suite happy, return an empty environment.
361 #if defined(PSUTIL_FREEBSD)
362 if (!((p)->ki_flag & P_INMEM) || ((p)->ki_flag & P_SYSTEM)) {
363 #elif defined(PSUTIL_NETBSD)
364 if ((p)->p_stat == SZOMB) {
365 #elif defined(PSUTIL_OPENBSD)
366 if ((p)->p_flag & P_SYSTEM) {
367 #endif
368 kvm_close(kd);
369 return py_retdict;
370 }
371
372 #if defined(PSUTIL_NETBSD)
373 envs = kvm_getenvv2(kd, p, 0);
374 #else
375 envs = kvm_getenvv(kd, p, 0);
376 #endif
377 if (!envs) {
378 // Map to "psutil" general high-level exceptions
379 switch (errno) {
380 case 0:
381 // Process has cleared it's environment, return empty one
382 kvm_close(kd);
383 return py_retdict;
384 case EPERM:
385 AccessDenied("kvm_getenvv -> EPERM");
386 break;
387 case ESRCH:
388 NoSuchProcess("kvm_getenvv -> ESRCH");
389 break;
390 #if defined(PSUTIL_FREEBSD)
391 case ENOMEM:
392 // Unfortunately, under FreeBSD kvm_getenvv() returns
393 // failure for certain processes ( e.g. try
394 // "sudo procstat -e <pid of your XOrg server>".)
395 // Map the error condition to 'AccessDenied'.
396 sprintf(errbuf,
397 "kvm_getenvv(pid=%ld, ki_uid=%d) -> ENOMEM",
398 pid, p->ki_uid);
399 AccessDenied(errbuf);
400 break;
401 #endif
402 default:
403 sprintf(errbuf, "kvm_getenvv(pid=%ld)", pid);
404 psutil_PyErr_SetFromOSErrnoWithSyscall(errbuf);
405 break;
406 }
407 goto error;
408 }
409
410 for (i = 0; envs[i] != NULL; i++) {
411 s = strchr(envs[i], '=');
412 if (!s)
413 continue;
414 *s++ = 0;
415 py_value = PyUnicode_DecodeFSDefault(s);
416 if (!py_value)
417 goto error;
418 if (PyDict_SetItemString(py_retdict, envs[i], py_value)) {
419 goto error;
420 }
421 Py_DECREF(py_value);
422 }
423
424 kvm_close(kd);
425 return py_retdict;
426
427 error:
428 Py_XDECREF(py_value);
429 Py_XDECREF(py_retdict);
430 kvm_close(kd);
431 return NULL;
432 }
433
434
435 /*
436 * Return files opened by process as a list of (path, fd) tuples.
437 * TODO: this is broken as it may report empty paths. 'procstat'
438 * utility has the same problem see:
439 * https://github.com/giampaolo/psutil/issues/595
440 */
441 PyObject *
442 psutil_proc_open_files(PyObject *self, PyObject *args) {
443 pid_t pid;
444 int i;
445 int cnt;
446 int regular;
447 int fd;
448 char *path;
449 struct kinfo_file *freep = NULL;
450 struct kinfo_file *kif;
451 kinfo_proc kipp;
452 PyObject *py_tuple = NULL;
453 PyObject *py_path = NULL;
454 PyObject *py_retlist = PyList_New(0);
455
456 if (py_retlist == NULL)
457 return NULL;
458 if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
459 goto error;
460 if (psutil_kinfo_proc(pid, &kipp) == -1)
461 goto error;
462
463 errno = 0;
464 freep = kinfo_getfile(pid, &cnt);
465
466 if (freep == NULL) {
467 #if defined(PSUTIL_OPENBSD)
468 if ((pid == 0) && (errno == ESRCH)) {
469 psutil_debug(
470 "open_files() returned ESRCH for PID 0; forcing `return []`"
471 );
472 PyErr_Clear();
473 return py_retlist;
474 }
475 #else
476 psutil_raise_for_pid(pid, "kinfo_getfile()");
477 #endif
478 goto error;
479 }
480
481 for (i = 0; i < cnt; i++) {
482 kif = &freep[i];
483
484 #ifdef PSUTIL_FREEBSD
485 regular = (kif->kf_type == KF_TYPE_VNODE) && \
486 (kif->kf_vnode_type == KF_VTYPE_VREG);
487 fd = kif->kf_fd;
488 path = kif->kf_path;
489 #elif PSUTIL_OPENBSD
490 regular = (kif->f_type == DTYPE_VNODE) && (kif->v_type == VREG);
491 fd = kif->fd_fd;
492 // XXX - it appears path is not exposed in the kinfo_file struct.
493 path = "";
494 #elif PSUTIL_NETBSD
495 regular = (kif->ki_ftype == DTYPE_VNODE) && (kif->ki_vtype == VREG);
496 fd = kif->ki_fd;
497 // XXX - it appears path is not exposed in the kinfo_file struct.
498 path = "";
499 #endif
500 if (regular == 1) {
501 py_path = PyUnicode_DecodeFSDefault(path);
502 if (! py_path)
503 goto error;
504 py_tuple = Py_BuildValue("(Oi)", py_path, fd);
505 if (py_tuple == NULL)
506 goto error;
507 if (PyList_Append(py_retlist, py_tuple))
508 goto error;
509 Py_CLEAR(py_path);
510 Py_CLEAR(py_tuple);
511 }
512 }
513 free(freep);
514 return py_retlist;
515
516 error:
517 Py_XDECREF(py_tuple);
518 Py_DECREF(py_retlist);
519 if (freep != NULL)
520 free(freep);
521 return NULL;
522 }