Debian Codegraph @

psutil/arch/freebsd/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 <assert.h>
9 #include <errno.h>
10 #include <stdlib.h>
11 #include <stdio.h>
12 #include <string.h>
13 #include <sys/types.h>
14 #include <sys/sysctl.h>
15 #include <sys/param.h>
16 #include <sys/user.h>
17 #include <sys/proc.h>
18 #include <signal.h>
19 #include <fcntl.h>
20 #include <devstat.h>
21 #include <libutil.h> // process open files, shared libs (kinfo_getvmmap), cwd
22 #include <sys/cpuset.h>
23
24 #include "../../arch/all/init.h"
25
26
27 #define PSUTIL_TV2DOUBLE(t) ((t).tv_sec + (t).tv_usec / 1000000.0)
28
29
30 // ============================================================================
31 // Utility functions
32 // ============================================================================
33
34
35 int
36 psutil_kinfo_proc(pid_t pid, struct kinfo_proc *proc) {
37 // Fills a kinfo_proc struct based on process pid.
38 int mib[4];
39 size_t size;
40 mib[0] = CTL_KERN;
41 mib[1] = KERN_PROC;
42 mib[2] = KERN_PROC_PID;
43 mib[3] = pid;
44
45 size = sizeof(struct kinfo_proc);
46 if (sysctl((int *)mib, 4, proc, &size, NULL, 0) == -1) {
47 psutil_PyErr_SetFromOSErrnoWithSyscall("sysctl(KERN_PROC_PID)");
48 return -1;
49 }
50
51 // sysctl stores 0 in the size if we can't find the process information.
52 if (size == 0) {
53 NoSuchProcess("sysctl (size = 0)");
54 return -1;
55 }
56 return 0;
57 }
58
59
60 // remove spaces from string
61 static void psutil_remove_spaces(char *str) {
62 char *p1 = str;
63 char *p2 = str;
64 do
65 while (*p2 == ' ')
66 p2++;
67 while ((*p1++ = *p2++));
68 }
69
70
71 // ============================================================================
72 // APIS
73 // ============================================================================
74
75
76 int psutil_get_proc_list(struct kinfo_proc **procList, size_t *procCount) {
77 int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PROC, 0 };
78 size_t length = 0;
79 char *buf = NULL;
80
81 assert(procList != NULL);
82 assert(*procList == NULL);
83 assert(procCount != NULL);
84
85 if (psutil_sysctl_malloc(mib, 4, &buf, &length) != 0) {
86 return 1;
87 }
88
89 *procList = (struct kinfo_proc *)buf;
90 *procCount = length / sizeof(struct kinfo_proc);
91 return 0;
92 }
93
94 /*
95 * Borrowed from psi Python System Information project
96 * Based on code from ps.
97 */
98 PyObject *
99 psutil_proc_cmdline(PyObject *self, PyObject *args) {
100 pid_t pid;
101 int mib[4];
102 char *procargs = NULL;
103 size_t size = 0;
104 size_t pos = 0;
105 PyObject *py_retlist = PyList_New(0);
106 PyObject *py_arg = NULL;
107
108 if (py_retlist == NULL)
109 return NULL;
110 if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
111 goto error;
112
113 mib[0] = CTL_KERN;
114 mib[1] = KERN_PROC;
115 mib[2] = KERN_PROC_ARGS;
116 mib[3] = pid;
117
118 if (psutil_sysctl_malloc(mib, 4, &procargs, &size) != 0)
119 goto error;
120
121 // args are returned as a flattened string with \0 separators between
122 // arguments add each string to the list then step forward to the next
123 // separator
124 if (size > 0) {
125 while (pos < size) {
126 py_arg = PyUnicode_DecodeFSDefault(&procargs[pos]);
127 if (!py_arg)
128 goto error;
129 if (PyList_Append(py_retlist, py_arg))
130 goto error;
131 Py_DECREF(py_arg);
132 py_arg = NULL;
133 pos += strlen(&procargs[pos]) + 1;
134 }
135 }
136
137 free(procargs);
138 return py_retlist;
139
140 error:
141 Py_XDECREF(py_arg);
142 Py_XDECREF(py_retlist);
143 if (procargs != NULL)
144 free(procargs);
145 return NULL;
146 }
147
148 /*
149 * Return process pathname executable.
150 * Thanks to Robert N. M. Watson:
151 * http://fxr.googlebit.com/source/usr.bin/procstat/procstat_bin.c?v=8-CURRENT
152 */
153 PyObject *
154 psutil_proc_exe(PyObject *self, PyObject *args) {
155 pid_t pid;
156 char pathname[PATH_MAX];
157 int error;
158 int mib[4];
159 int ret;
160 size_t size;
161
162 if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
163 return NULL;
164
165 mib[0] = CTL_KERN;
166 mib[1] = KERN_PROC;
167 mib[2] = KERN_PROC_PATHNAME;
168 mib[3] = pid;
169
170 size = sizeof(pathname);
171 error = sysctl(mib, 4, pathname, &size, NULL, 0);
172 if (error == -1) {
173 // see: https://github.com/giampaolo/psutil/issues/907
174 if (errno == ENOENT) {
175 return PyUnicode_DecodeFSDefault("");
176 }
177 else {
178 return psutil_PyErr_SetFromOSErrnoWithSyscall(
179 "sysctl(KERN_PROC_PATHNAME)"
180 );
181 }
182 }
183 if (size == 0 || strlen(pathname) == 0) {
184 ret = psutil_pid_exists(pid);
185 if (ret == -1)
186 return NULL;
187 else if (ret == 0)
188 return NoSuchProcess("psutil_pid_exists -> 0");
189 else
190 strcpy(pathname, "");
191 }
192
193 return PyUnicode_DecodeFSDefault(pathname);
194 }
195
196
197 PyObject *
198 psutil_proc_num_threads(PyObject *self, PyObject *args) {
199 // Return number of threads used by process as a Python integer.
200 pid_t pid;
201 struct kinfo_proc kp;
202 if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
203 return NULL;
204 if (psutil_kinfo_proc(pid, &kp) == -1)
205 return NULL;
206 return Py_BuildValue("l", (long)kp.ki_numthreads);
207 }
208
209
210 PyObject *
211 psutil_proc_threads(PyObject *self, PyObject *args) {
212 // Retrieves all threads used by process returning a list of tuples
213 // including thread id, user time and system time.
214 // Thanks to Robert N. M. Watson:
215 // http://code.metager.de/source/xref/freebsd/usr.bin/procstat/
216 // procstat_threads.c
217 pid_t pid;
218 int mib[4];
219 struct kinfo_proc *kip = NULL;
220 struct kinfo_proc *kipp = NULL;
221 unsigned int i;
222 size_t size = 0;
223 PyObject *py_retlist = PyList_New(0);
224 PyObject *py_tuple = NULL;
225
226 if (py_retlist == NULL)
227 return NULL;
228 if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
229 goto error;
230
231 // we need to re-query for thread information, so don't use *kipp
232 mib[0] = CTL_KERN;
233 mib[1] = KERN_PROC;
234 mib[2] = KERN_PROC_PID | KERN_PROC_INC_THREAD;
235 mib[3] = pid;
236
237 if (psutil_sysctl_malloc(mib, 4, (char **)&kip, &size) != 0)
238 goto error;
239
240 // subtle check: size == 0 means no such process
241 if (size == 0) {
242 NoSuchProcess("sysctl (size = 0)");
243 goto error;
244 }
245
246 for (i = 0; i < size / sizeof(*kip); i++) {
247 kipp = &kip[i];
248 py_tuple = Py_BuildValue("Idd",
249 kipp->ki_tid,
250 PSUTIL_TV2DOUBLE(kipp->ki_rusage.ru_utime),
251 PSUTIL_TV2DOUBLE(kipp->ki_rusage.ru_stime));
252 if (py_tuple == NULL)
253 goto error;
254 if (PyList_Append(py_retlist, py_tuple))
255 goto error;
256 Py_DECREF(py_tuple);
257 }
258
259 free(kip);
260 return py_retlist;
261
262 error:
263 Py_XDECREF(py_tuple);
264 Py_DECREF(py_retlist);
265 free(kip);
266 return NULL;
267 }
268
269 PyObject *
270 psutil_proc_cwd(PyObject *self, PyObject *args) {
271 pid_t pid;
272 struct kinfo_file *freep = NULL;
273 struct kinfo_file *kif;
274 struct kinfo_proc kipp;
275 PyObject *py_path = NULL;
276
277 int i, cnt;
278
279 if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
280 goto error;
281 if (psutil_kinfo_proc(pid, &kipp) == -1)
282 goto error;
283
284 errno = 0;
285 freep = kinfo_getfile(pid, &cnt);
286 if (freep == NULL) {
287 psutil_raise_for_pid(pid, "kinfo_getfile()");
288 goto error;
289 }
290
291 for (i = 0; i < cnt; i++) {
292 kif = &freep[i];
293 if (kif->kf_fd == KF_FD_TYPE_CWD) {
294 py_path = PyUnicode_DecodeFSDefault(kif->kf_path);
295 if (!py_path)
296 goto error;
297 break;
298 }
299 }
300 /*
301 * For lower pids it seems we can't retrieve any information
302 * (lsof can't do that it either). Since this happens even
303 * as root we return an empty string instead of AccessDenied.
304 */
305 if (py_path == NULL)
306 py_path = PyUnicode_DecodeFSDefault("");
307 free(freep);
308 return py_path;
309
310 error:
311 Py_XDECREF(py_path);
312 if (freep != NULL)
313 free(freep);
314 return NULL;
315 }
316
317
318 PyObject *
319 psutil_proc_num_fds(PyObject *self, PyObject *args) {
320 pid_t pid;
321 int cnt;
322
323 struct kinfo_file *freep;
324 struct kinfo_proc kipp;
325
326 if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
327 return NULL;
328 if (psutil_kinfo_proc(pid, &kipp) == -1)
329 return NULL;
330
331 errno = 0;
332 freep = kinfo_getfile(pid, &cnt);
333 if (freep == NULL) {
334 psutil_raise_for_pid(pid, "kinfo_getfile()");
335 return NULL;
336 }
337 free(freep);
338
339 return Py_BuildValue("i", cnt);
340 }
341
342
343 PyObject *
344 psutil_proc_memory_maps(PyObject *self, PyObject *args) {
345 // Return a list of tuples for every process memory maps.
346 // 'procstat' cmdline utility has been used as an example.
347 pid_t pid;
348 int ptrwidth;
349 int i, cnt;
350 char addr[1000];
351 char perms[4];
352 char *path;
353 struct kinfo_proc kp;
354 struct kinfo_vmentry *freep = NULL;
355 struct kinfo_vmentry *kve;
356 ptrwidth = 2 * sizeof(void *);
357 PyObject *py_tuple = NULL;
358 PyObject *py_path = NULL;
359 PyObject *py_retlist = PyList_New(0);
360
361 if (py_retlist == NULL)
362 return NULL;
363 if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
364 goto error;
365 if (psutil_kinfo_proc(pid, &kp) == -1)
366 goto error;
367
368 errno = 0;
369 freep = kinfo_getvmmap(pid, &cnt);
370 if (freep == NULL) {
371 psutil_raise_for_pid(pid, "kinfo_getvmmap()");
372 goto error;
373 }
374 for (i = 0; i < cnt; i++) {
375 py_tuple = NULL;
376 kve = &freep[i];
377 addr[0] = '\0';
378 perms[0] = '\0';
379 sprintf(addr, "%#*jx-%#*jx", ptrwidth, (uintmax_t)kve->kve_start,
380 ptrwidth, (uintmax_t)kve->kve_end);
381 psutil_remove_spaces(addr);
382 strlcat(perms, kve->kve_protection & KVME_PROT_READ ? "r" : "-",
383 sizeof(perms));
384 strlcat(perms, kve->kve_protection & KVME_PROT_WRITE ? "w" : "-",
385 sizeof(perms));
386 strlcat(perms, kve->kve_protection & KVME_PROT_EXEC ? "x" : "-",
387 sizeof(perms));
388
389 if (strlen(kve->kve_path) == 0) {
390 switch (kve->kve_type) {
391 case KVME_TYPE_NONE:
392 path = "[none]";
393 break;
394 case KVME_TYPE_DEFAULT:
395 path = "[default]";
396 break;
397 case KVME_TYPE_VNODE:
398 path = "[vnode]";
399 break;
400 case KVME_TYPE_SWAP:
401 path = "[swap]";
402 break;
403 case KVME_TYPE_DEVICE:
404 path = "[device]";
405 break;
406 case KVME_TYPE_PHYS:
407 path = "[phys]";
408 break;
409 case KVME_TYPE_DEAD:
410 path = "[dead]";
411 break;
412 #ifdef KVME_TYPE_SG
413 case KVME_TYPE_SG:
414 path = "[sg]";
415 break;
416 #endif
417 case KVME_TYPE_UNKNOWN:
418 path = "[unknown]";
419 break;
420 default:
421 path = "[?]";
422 break;
423 }
424 }
425 else {
426 path = kve->kve_path;
427 }
428
429 py_path = PyUnicode_DecodeFSDefault(path);
430 if (! py_path)
431 goto error;
432 py_tuple = Py_BuildValue("ssOiiii",
433 addr, // "start-end" address
434 perms, // "rwx" permissions
435 py_path, // path
436 kve->kve_resident, // rss
437 kve->kve_private_resident, // private
438 kve->kve_ref_count, // ref count
439 kve->kve_shadow_count); // shadow count
440 if (!py_tuple)
441 goto error;
442 if (PyList_Append(py_retlist, py_tuple))
443 goto error;
444 Py_DECREF(py_path);
445 Py_DECREF(py_tuple);
446 }
447 free(freep);
448 return py_retlist;
449
450 error:
451 Py_XDECREF(py_tuple);
452 Py_XDECREF(py_path);
453 Py_DECREF(py_retlist);
454 if (freep != NULL)
455 free(freep);
456 return NULL;
457 }
458
459
460 PyObject*
461 psutil_proc_cpu_affinity_get(PyObject* self, PyObject* args) {
462 // Get process CPU affinity.
463 // Reference:
464 // http://sources.freebsd.org/RELENG_9/src/usr.bin/cpuset/cpuset.c
465 pid_t pid;
466 int ret;
467 int i;
468 cpuset_t mask;
469 PyObject* py_retlist;
470 PyObject* py_cpu_num;
471
472 if (!PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
473 return NULL;
474 ret = cpuset_getaffinity(CPU_LEVEL_WHICH, CPU_WHICH_PID, pid,
475 sizeof(mask), &mask);
476 if (ret != 0)
477 return PyErr_SetFromErrno(PyExc_OSError);
478
479 py_retlist = PyList_New(0);
480 if (py_retlist == NULL)
481 return NULL;
482
483 for (i = 0; i < CPU_SETSIZE; i++) {
484 if (CPU_ISSET(i, &mask)) {
485 py_cpu_num = Py_BuildValue("i", i);
486 if (py_cpu_num == NULL)
487 goto error;
488 if (PyList_Append(py_retlist, py_cpu_num))
489 goto error;
490 }
491 }
492
493 return py_retlist;
494
495 error:
496 Py_XDECREF(py_cpu_num);
497 Py_DECREF(py_retlist);
498 return NULL;
499 }
500
501
502 PyObject *
503 psutil_proc_cpu_affinity_set(PyObject *self, PyObject *args) {
504 // Set process CPU affinity.
505 // Reference:
506 // http://sources.freebsd.org/RELENG_9/src/usr.bin/cpuset/cpuset.c
507 pid_t pid;
508 int i;
509 int seq_len;
510 int ret;
511 cpuset_t cpu_set;
512 PyObject *py_cpu_set;
513 PyObject *py_cpu_seq = NULL;
514
515 if (!PyArg_ParseTuple(args, _Py_PARSE_PID "O", &pid, &py_cpu_set))
516 return NULL;
517
518 py_cpu_seq = PySequence_Fast(py_cpu_set, "expected a sequence or integer");
519 if (!py_cpu_seq)
520 return NULL;
521 seq_len = PySequence_Fast_GET_SIZE(py_cpu_seq);
522
523 // calculate the mask
524 CPU_ZERO(&cpu_set);
525 for (i = 0; i < seq_len; i++) {
526 PyObject *item = PySequence_Fast_GET_ITEM(py_cpu_seq, i);
527 long value = PyLong_AsLong(item);
528 if (value == -1 || PyErr_Occurred())
529 goto error;
530 CPU_SET(value, &cpu_set);
531 }
532
533 // set affinity
534 ret = cpuset_setaffinity(CPU_LEVEL_WHICH, CPU_WHICH_PID, pid,
535 sizeof(cpu_set), &cpu_set);
536 if (ret != 0) {
537 PyErr_SetFromErrno(PyExc_OSError);
538 goto error;
539 }
540
541 Py_DECREF(py_cpu_seq);
542 Py_RETURN_NONE;
543
544 error:
545 if (py_cpu_seq != NULL)
546 Py_DECREF(py_cpu_seq);
547 return NULL;
548 }
549
550
551 /*
552 * An emulation of Linux prlimit(). Returns a (soft, hard) tuple.
553 */
554 PyObject *
555 psutil_proc_getrlimit(PyObject *self, PyObject *args) {
556 pid_t pid;
557 int resource;
558 int name[5];
559 struct rlimit rlp;
560
561 if (! PyArg_ParseTuple(args, _Py_PARSE_PID "i", &pid, &resource))
562 return NULL;
563
564 name[0] = CTL_KERN;
565 name[1] = KERN_PROC;
566 name[2] = KERN_PROC_RLIMIT;
567 name[3] = pid;
568 name[4] = resource;
569
570 if (psutil_sysctl(name, 5, &rlp, sizeof(rlp)) != 0)
571 return NULL;
572
573 #if defined(HAVE_LONG_LONG)
574 return Py_BuildValue("LL",
575 (PY_LONG_LONG) rlp.rlim_cur,
576 (PY_LONG_LONG) rlp.rlim_max);
577 #else
578 return Py_BuildValue("ll",
579 (long) rlp.rlim_cur,
580 (long) rlp.rlim_max);
581 #endif
582 }
583
584
585 /*
586 * An emulation of Linux prlimit() (set).
587 */
588 PyObject *
589 psutil_proc_setrlimit(PyObject *self, PyObject *args) {
590 pid_t pid;
591 int ret;
592 int resource;
593 int name[5];
594 struct rlimit new;
595 struct rlimit *newp = NULL;
596 PyObject *py_soft = NULL;
597 PyObject *py_hard = NULL;
598
599 if (! PyArg_ParseTuple(
600 args, _Py_PARSE_PID "iOO", &pid, &resource, &py_soft, &py_hard))
601 return NULL;
602
603 name[0] = CTL_KERN;
604 name[1] = KERN_PROC;
605 name[2] = KERN_PROC_RLIMIT;
606 name[3] = pid;
607 name[4] = resource;
608
609 #if defined(HAVE_LONG_LONG)
610 new.rlim_cur = PyLong_AsLongLong(py_soft);
611 if (new.rlim_cur == (rlim_t) - 1 && PyErr_Occurred())
612 return NULL;
613 new.rlim_max = PyLong_AsLongLong(py_hard);
614 if (new.rlim_max == (rlim_t) - 1 && PyErr_Occurred())
615 return NULL;
616 #else
617 new.rlim_cur = PyLong_AsLong(py_soft);
618 if (new.rlim_cur == (rlim_t) - 1 && PyErr_Occurred())
619 return NULL;
620 new.rlim_max = PyLong_AsLong(py_hard);
621 if (new.rlim_max == (rlim_t) - 1 && PyErr_Occurred())
622 return NULL;
623 #endif
624 newp = &new;
625 ret = sysctl(name, 5, NULL, 0, newp, sizeof(*newp));
626 if (ret == -1)
627 return PyErr_SetFromErrno(PyExc_OSError);
628 Py_RETURN_NONE;
629 }