Debian Codegraph @

psutil/arch/osx/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 // Process related functions. Original code was moved in here from
8 // psutil/_psutil_osx.c and psutil/arc/osx/process_info.c in 2023.
9 // For reference, here's the GIT blame history before the move:
10 // https://github.com/giampaolo/psutil/blame/59504a5/psutil/_psutil_osx.c
11 // https://github.com/giampaolo/psutil/blame/efd7ed3/psutil/arch/osx/process_info.c
12
13 #include <Python.h>
14 #include <assert.h>
15 #include <errno.h>
16 #include <stdbool.h>
17 #include <stdlib.h>
18 #include <stdio.h>
19 #include <sys/sysctl.h>
20 #include <libproc.h>
21 #include <sys/proc_info.h>
22 #include <sys/sysctl.h>
23 #include <netinet/tcp_fsm.h>
24 #include <arpa/inet.h>
25 #include <pwd.h>
26 #include <unistd.h>
27 #include <mach/mach.h>
28 #include <mach/mach_vm.h>
29 #include <mach/shared_region.h>
30 #include <mach-o/loader.h>
31
32 #include "../../arch/all/init.h"
33
34
35 #define PSUTIL_TV2DOUBLE(t) ((t).tv_sec + (t).tv_usec / 1000000.0)
36 typedef struct kinfo_proc kinfo_proc;
37
38
39 // ====================================================================
40 // --- utils
41 // ====================================================================
42
43
44 static int
45 psutil_get_proc_list(struct kinfo_proc **procList, size_t *procCount) {
46 int mib[3];
47 size_t len = 0;
48 char *buf = NULL;
49
50 mib[0] = CTL_KERN;
51 mib[1] = KERN_PROC;
52 mib[2] = KERN_PROC_ALL;
53 *procList = NULL;
54 *procCount = 0;
55
56 if (psutil_sysctl_malloc(mib, 3, &buf, &len) != 0)
57 return 1;
58
59 *procList = (struct kinfo_proc *)buf;
60 *procCount = len / sizeof(struct kinfo_proc);
61
62 if (*procCount == 0) {
63 free(buf);
64 PyErr_Format(PyExc_RuntimeError, "no PIDs found");
65 return 1;
66 }
67
68 return 0;
69 }
70
71 // Read process argument space.
72 static int
73 psutil_sysctl_procargs(pid_t pid, char *procargs, size_t *argmax) {
74 int mib[3];
75
76 mib[0] = CTL_KERN;
77 mib[1] = KERN_PROCARGS2;
78 mib[2] = pid;
79
80 if (sysctl(mib, 3, procargs, argmax, NULL, 0) < 0) {
81 if (psutil_pid_exists(pid) == 0) {
82 NoSuchProcess("psutil_pid_exists -> 0");
83 return 1;
84 }
85 // In case of zombie process we'll get EINVAL. We translate it
86 // to NSP and _psosx.py will translate it to ZP.
87 if (errno == EINVAL) {
88 psutil_debug("sysctl(KERN_PROCARGS2) -> EINVAL translated to NSP");
89 NoSuchProcess("sysctl(KERN_PROCARGS2) -> EINVAL");
90 return 1;
91 }
92 // There's nothing we can do other than raising AD.
93 if (errno == EIO) {
94 psutil_debug("sysctl(KERN_PROCARGS2) -> EIO translated to AD");
95 AccessDenied("sysctl(KERN_PROCARGS2) -> EIO");
96 return 1;
97 }
98 psutil_PyErr_SetFromOSErrnoWithSyscall("sysctl(KERN_PROCARGS2)");
99 return 1;
100 }
101 return 0;
102 }
103
104
105 static int
106 psutil_get_kinfo_proc(pid_t pid, struct kinfo_proc *kp) {
107 int mib[4];
108 size_t len;
109 mib[0] = CTL_KERN;
110 mib[1] = KERN_PROC;
111 mib[2] = KERN_PROC_PID;
112 mib[3] = pid;
113
114 // fetch the info with sysctl()
115 len = sizeof(struct kinfo_proc);
116
117 // now read the data from sysctl
118 if (sysctl(mib, 4, kp, &len, NULL, 0) == -1) {
119 // raise an exception and throw errno as the error
120 psutil_PyErr_SetFromOSErrnoWithSyscall("sysctl");
121 return -1;
122 }
123
124 // sysctl succeeds but len is zero, happens when process has gone away
125 if (len == 0) {
126 NoSuchProcess("sysctl(kinfo_proc), len == 0");
127 return -1;
128 }
129 return 0;
130 }
131
132
133 /*
134 * A wrapper around proc_pidinfo().
135 * https://opensource.apple.com/source/xnu/xnu-2050.7.9/bsd/kern/proc_info.c
136 * Returns 0 on failure.
137 */
138 static int
139 psutil_proc_pidinfo(pid_t pid, int flavor, uint64_t arg, void *pti, int size) {
140 errno = 0;
141 int ret;
142
143 ret = proc_pidinfo(pid, flavor, arg, pti, size);
144 if (ret <= 0) {
145 psutil_raise_for_pid(pid, "proc_pidinfo()");
146 return 0;
147 }
148 if ((unsigned long)ret < sizeof(pti)) {
149 psutil_raise_for_pid(
150 pid, "proc_pidinfo() return size < sizeof(struct_pointer)");
151 return 0;
152 }
153 return ret;
154 }
155
156
157 /*
158 * A wrapper around task_for_pid() which sucks big time:
159 * - it's not documented
160 * - errno is set only sometimes
161 * - sometimes errno is ENOENT (?!?)
162 * - for PIDs != getpid() or PIDs which are not members of the procmod
163 * it requires root
164 * As such we can only guess what the heck went wrong and fail either
165 * with NoSuchProcess or giveup with AccessDenied.
166 * Here's some history:
167 * https://github.com/giampaolo/psutil/issues/1181
168 * https://github.com/giampaolo/psutil/issues/1209
169 * https://github.com/giampaolo/psutil/issues/1291#issuecomment-396062519
170 */
171 static int
172 psutil_task_for_pid(pid_t pid, mach_port_t *task)
173 {
174 // See: https://github.com/giampaolo/psutil/issues/1181
175 kern_return_t err = KERN_SUCCESS;
176
177 err = task_for_pid(mach_task_self(), pid, task);
178 if (err != KERN_SUCCESS) {
179 if (psutil_pid_exists(pid) == 0)
180 NoSuchProcess("task_for_pid");
181 // Now done in Python.
182 // else if (psutil_is_zombie(pid) == 1)
183 // PyErr_SetString(ZombieProcessError,
184 // "task_for_pid -> psutil_is_zombie -> 1");
185 else {
186 psutil_debug(
187 "task_for_pid() failed (pid=%ld, err=%i, errno=%i, msg='%s'); "
188 "setting AccessDenied()",
189 (long)pid, err, errno, mach_error_string(err));
190 AccessDenied("task_for_pid");
191 }
192 return 1;
193 }
194 return 0;
195 }
196
197
198 /*
199 * A wrapper around proc_pidinfo(PROC_PIDLISTFDS), which dynamically sets
200 * the buffer size.
201 */
202 static struct proc_fdinfo*
203 psutil_proc_list_fds(pid_t pid, int *num_fds) {
204 int ret;
205 int fds_size = 0;
206 int max_size = 24 * 1024 * 1024; // 24M
207 struct proc_fdinfo *fds_pointer = NULL;
208
209 errno = 0;
210 ret = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, NULL, 0);
211 if (ret <= 0) {
212 psutil_raise_for_pid(pid, "proc_pidinfo(PROC_PIDLISTFDS) 1/2");
213 goto error;
214 }
215
216 while (1) {
217 if (ret > fds_size) {
218 while (ret > fds_size) {
219 fds_size += PROC_PIDLISTFD_SIZE * 32;
220 if (fds_size > max_size) {
221 PyErr_Format(PyExc_RuntimeError,
222 "prevent malloc() to allocate > 24M");
223 goto error;
224 }
225 }
226
227 if (fds_pointer != NULL) {
228 free(fds_pointer);
229 }
230 fds_pointer = malloc(fds_size);
231
232 if (fds_pointer == NULL) {
233 PyErr_NoMemory();
234 goto error;
235 }
236 }
237
238 errno = 0;
239 ret = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, fds_pointer, fds_size);
240 if (ret <= 0) {
241 psutil_raise_for_pid(pid, "proc_pidinfo(PROC_PIDLISTFDS) 2/2");
242 goto error;
243 }
244
245 if (ret + (int)PROC_PIDLISTFD_SIZE >= fds_size) {
246 psutil_debug("PROC_PIDLISTFDS: make room for 1 extra fd");
247 ret = fds_size + (int)PROC_PIDLISTFD_SIZE;
248 continue;
249 }
250
251 break;
252 }
253
254 *num_fds = (ret / (int)PROC_PIDLISTFD_SIZE);
255 return fds_pointer;
256
257 error:
258 if (fds_pointer != NULL)
259 free(fds_pointer);
260 return NULL;
261 }
262
263
264 // ====================================================================
265 // --- Python APIs
266 // ====================================================================
267
268
269 /*
270 * Return a Python list of all the PIDs running on the system.
271 */
272 PyObject *
273 psutil_pids(PyObject *self, PyObject *args) {
274 kinfo_proc *proclist = NULL;
275 kinfo_proc *orig_address = NULL;
276 size_t num_processes;
277 size_t idx;
278 PyObject *py_pid = NULL;
279 PyObject *py_retlist = PyList_New(0);
280
281 if (py_retlist == NULL)
282 return NULL;
283
284 if (psutil_get_proc_list(&proclist, &num_processes) != 0)
285 goto error;
286
287 // save the address of proclist so we can free it later
288 orig_address = proclist;
289 for (idx = 0; idx < num_processes; idx++) {
290 py_pid = PyLong_FromPid(proclist->kp_proc.p_pid);
291 if (! py_pid)
292 goto error;
293 if (PyList_Append(py_retlist, py_pid))
294 goto error;
295 Py_CLEAR(py_pid);
296 proclist++;
297 }
298 free(orig_address);
299
300 return py_retlist;
301
302 error:
303 Py_XDECREF(py_pid);
304 Py_DECREF(py_retlist);
305 if (orig_address != NULL)
306 free(orig_address);
307 return NULL;
308 }
309
310
311 /*
312 * Return multiple process info as a Python tuple in one shot by
313 * using sysctl() and filling up a kinfo_proc struct.
314 * It should be possible to do this for all processes without
315 * incurring into permission (EPERM) errors.
316 * This will also succeed for zombie processes returning correct
317 * information.
318 */
319 PyObject *
320 psutil_proc_kinfo_oneshot(PyObject *self, PyObject *args) {
321 pid_t pid;
322 struct kinfo_proc kp;
323 PyObject *py_name;
324 PyObject *py_retlist;
325
326 if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
327 return NULL;
328 if (psutil_get_kinfo_proc(pid, &kp) == -1)
329 return NULL;
330
331 py_name = PyUnicode_DecodeFSDefault(kp.kp_proc.p_comm);
332 if (! py_name) {
333 // Likely a decoding error. We don't want to fail the whole
334 // operation. The python module may retry with proc_name().
335 PyErr_Clear();
336 py_name = Py_None;
337 }
338
339 py_retlist = Py_BuildValue(
340 _Py_PARSE_PID "llllllidiO",
341 kp.kp_eproc.e_ppid, // (pid_t) ppid
342 (long)kp.kp_eproc.e_pcred.p_ruid, // (long) real uid
343 (long)kp.kp_eproc.e_ucred.cr_uid, // (long) effective uid
344 (long)kp.kp_eproc.e_pcred.p_svuid, // (long) saved uid
345 (long)kp.kp_eproc.e_pcred.p_rgid, // (long) real gid
346 (long)kp.kp_eproc.e_ucred.cr_groups[0], // (long) effective gid
347 (long)kp.kp_eproc.e_pcred.p_svgid, // (long) saved gid
348 kp.kp_eproc.e_tdev, // (int) tty nr
349 PSUTIL_TV2DOUBLE(kp.kp_proc.p_starttime), // (double) create time
350 (int)kp.kp_proc.p_stat, // (int) status
351 py_name // (pystr) name
352 );
353
354 if (py_retlist != NULL) {
355 // XXX shall we decref() also in case of Py_BuildValue() error?
356 Py_DECREF(py_name);
357 }
358 return py_retlist;
359 }
360
361
362 /*
363 * Return multiple process info as a Python tuple in one shot by
364 * using proc_pidinfo(PROC_PIDTASKINFO) and filling a proc_taskinfo
365 * struct.
366 * Contrarily from proc_kinfo above this function will fail with
367 * EACCES for PIDs owned by another user and with ESRCH for zombie
368 * processes.
369 */
370 PyObject *
371 psutil_proc_pidtaskinfo_oneshot(PyObject *self, PyObject *args) {
372 pid_t pid;
373 struct proc_taskinfo pti;
374 uint64_t total_user;
375 uint64_t total_system;
376
377 if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
378 return NULL;
379 if (psutil_proc_pidinfo(pid, PROC_PIDTASKINFO, 0, &pti, sizeof(pti)) <= 0)
380 return NULL;
381
382 total_user = pti.pti_total_user * PSUTIL_MACH_TIMEBASE_INFO.numer;
383 total_user /= PSUTIL_MACH_TIMEBASE_INFO.denom;
384 total_system = pti.pti_total_system * PSUTIL_MACH_TIMEBASE_INFO.numer;
385 total_system /= PSUTIL_MACH_TIMEBASE_INFO.denom;
386
387 return Py_BuildValue(
388 "(ddKKkkkk)",
389 (float)total_user / 1000000000.0, // (float) cpu user time
390 (float)total_system / 1000000000.0, // (float) cpu sys time
391 // Note about memory: determining other mem stats on macOS is a mess:
392 // http://www.opensource.apple.com/source/top/top-67/libtop.c?txt
393 // I just give up.
394 // struct proc_regioninfo pri;
395 // psutil_proc_pidinfo(pid, PROC_PIDREGIONINFO, 0, &pri, sizeof(pri))
396 pti.pti_resident_size, // (uns long long) rss
397 pti.pti_virtual_size, // (uns long long) vms
398 pti.pti_faults, // (uns long) number of page faults (pages)
399 pti.pti_pageins, // (uns long) number of actual pageins (pages)
400 pti.pti_threadnum, // (uns long) num threads
401 // Unvoluntary value seems not to be available;
402 // pti.pti_csw probably refers to the sum of the two;
403 // getrusage() numbers seems to confirm this theory.
404 pti.pti_csw // (uns long) voluntary ctx switches
405 );
406 }
407
408
409 /*
410 * Return process name from kinfo_proc as a Python string.
411 */
412 PyObject *
413 psutil_proc_name(PyObject *self, PyObject *args) {
414 pid_t pid;
415 struct kinfo_proc kp;
416
417 if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
418 return NULL;
419 if (psutil_get_kinfo_proc(pid, &kp) == -1)
420 return NULL;
421 return PyUnicode_DecodeFSDefault(kp.kp_proc.p_comm);
422 }
423
424
425 /*
426 * Return process current working directory.
427 * Raises NSP in case of zombie process.
428 */
429 PyObject *
430 psutil_proc_cwd(PyObject *self, PyObject *args) {
431 pid_t pid;
432 struct proc_vnodepathinfo pathinfo;
433
434 if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
435 return NULL;
436
437 if (psutil_proc_pidinfo(
438 pid, PROC_PIDVNODEPATHINFO, 0, &pathinfo, sizeof(pathinfo)) <= 0)
439 {
440 return NULL;
441 }
442
443 return PyUnicode_DecodeFSDefault(pathinfo.pvi_cdir.vip_path);
444 }
445
446
447 /*
448 * Return path of the process executable.
449 */
450 PyObject *
451 psutil_proc_exe(PyObject *self, PyObject *args) {
452 pid_t pid;
453 char buf[PATH_MAX];
454 int ret;
455
456 if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
457 return NULL;
458 errno = 0;
459 ret = proc_pidpath(pid, &buf, sizeof(buf));
460 if (ret == 0) {
461 if (pid == 0) {
462 AccessDenied("automatically set for PID 0");
463 return NULL;
464 }
465 else if (errno == ENOENT) {
466 // It may happen (file not found error) if the process is
467 // still alive but the executable which launched it got
468 // deleted, see:
469 // https://github.com/giampaolo/psutil/issues/1738
470 return Py_BuildValue("s", "");
471 }
472 else {
473 psutil_raise_for_pid(pid, "proc_pidpath()");
474 return NULL;
475 }
476 }
477 return PyUnicode_DecodeFSDefault(buf);
478 }
479
480
481 /*
482 * Indicates if the given virtual address on the given architecture is in the
483 * shared VM region.
484 */
485 static bool
486 psutil_in_shared_region(mach_vm_address_t addr, cpu_type_t type) {
487 mach_vm_address_t base;
488 mach_vm_address_t size;
489
490 switch (type) {
491 case CPU_TYPE_ARM:
492 base = SHARED_REGION_BASE_ARM;
493 size = SHARED_REGION_SIZE_ARM;
494 break;
495 case CPU_TYPE_I386:
496 base = SHARED_REGION_BASE_I386;
497 size = SHARED_REGION_SIZE_I386;
498 break;
499 case CPU_TYPE_X86_64:
500 base = SHARED_REGION_BASE_X86_64;
501 size = SHARED_REGION_SIZE_X86_64;
502 break;
503 default:
504 return false;
505 }
506
507 return base <= addr && addr < (base + size);
508 }
509
510
511 /*
512 * Returns the USS (unique set size) of the process. Reference:
513 * https://dxr.mozilla.org/mozilla-central/source/xpcom/base/
514 * nsMemoryReporterManager.cpp
515 */
516 PyObject *
517 psutil_proc_memory_uss(PyObject *self, PyObject *args) {
518 pid_t pid;
519 cpu_type_t cpu_type;
520 size_t private_pages = 0;
521 mach_vm_size_t size = 0;
522 mach_msg_type_number_t info_count = VM_REGION_TOP_INFO_COUNT;
523 kern_return_t kr;
524 long pagesize = psutil_getpagesize();
525 mach_vm_address_t addr = MACH_VM_MIN_ADDRESS;
526 mach_port_t task = MACH_PORT_NULL;
527 vm_region_top_info_data_t info;
528 mach_port_t object_name;
529
530 if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
531 return NULL;
532
533 if (psutil_task_for_pid(pid, &task) != 0)
534 return NULL;
535
536 if (psutil_sysctlbyname(
537 "sysctl.proc_cputype", &cpu_type, sizeof(cpu_type)) != 0)
538 {
539 return NULL;
540 }
541
542 // Roughly based on libtop_update_vm_regions in
543 // http://www.opensource.apple.com/source/top/top-100.1.2/libtop.c
544 for (addr = 0; ; addr += size) {
545 kr = mach_vm_region(
546 task, &addr, &size, VM_REGION_TOP_INFO, (vm_region_info_t)&info,
547 &info_count, &object_name);
548 if (kr == KERN_INVALID_ADDRESS) {
549 // Done iterating VM regions.
550 break;
551 }
552 else if (kr != KERN_SUCCESS) {
553 PyErr_Format(
554 PyExc_RuntimeError,
555 "mach_vm_region(VM_REGION_TOP_INFO) syscall failed");
556 return NULL;
557 }
558
559 if (psutil_in_shared_region(addr, cpu_type) &&
560 info.share_mode != SM_PRIVATE) {
561 continue;
562 }
563
564 switch (info.share_mode) {
565 #ifdef SM_LARGE_PAGE
566 case SM_LARGE_PAGE:
567 // NB: Large pages are not shareable and always resident.
568 #endif
569 case SM_PRIVATE:
570 private_pages += info.private_pages_resident;
571 private_pages += info.shared_pages_resident;
572 break;
573 case SM_COW:
574 private_pages += info.private_pages_resident;
575 if (info.ref_count == 1) {
576 // Treat copy-on-write pages as private if they only
577 // have one reference.
578 private_pages += info.shared_pages_resident;
579 }
580 break;
581 case SM_SHARED:
582 default:
583 break;
584 }
585 }
586
587 mach_port_deallocate(mach_task_self(), task);
588 return Py_BuildValue("K", private_pages * pagesize);
589 }
590
591
592 /*
593 * Return process threads
594 */
595 PyObject *
596 psutil_proc_threads(PyObject *self, PyObject *args) {
597 pid_t pid;
598 int err, ret;
599 kern_return_t kr;
600 unsigned int info_count = TASK_BASIC_INFO_COUNT;
601 mach_port_t task = MACH_PORT_NULL;
602 struct task_basic_info tasks_info;
603 thread_act_port_array_t thread_list = NULL;
604 thread_info_data_t thinfo_basic;
605 thread_basic_info_t basic_info_th;
606 mach_msg_type_number_t thread_count, thread_info_count, j;
607
608 PyObject *py_tuple = NULL;
609 PyObject *py_retlist = PyList_New(0);
610
611 if (py_retlist == NULL)
612 return NULL;
613
614 if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
615 goto error;
616
617 if (psutil_task_for_pid(pid, &task) != 0)
618 goto error;
619
620 info_count = TASK_BASIC_INFO_COUNT;
621 err = task_info(task, TASK_BASIC_INFO, (task_info_t)&tasks_info,
622 &info_count);
623 if (err != KERN_SUCCESS) {
624 // errcode 4 is "invalid argument" (access denied)
625 if (err == 4) {
626 AccessDenied("task_info(TASK_BASIC_INFO)");
627 }
628 else {
629 // otherwise throw a runtime error with appropriate error code
630 PyErr_Format(PyExc_RuntimeError,
631 "task_info(TASK_BASIC_INFO) syscall failed");
632 }
633 goto error;
634 }
635
636 err = task_threads(task, &thread_list, &thread_count);
637 if (err != KERN_SUCCESS) {
638 PyErr_Format(PyExc_RuntimeError, "task_threads() syscall failed");
639 goto error;
640 }
641
642 for (j = 0; j < thread_count; j++) {
643 thread_info_count = THREAD_INFO_MAX;
644 kr = thread_info(thread_list[j], THREAD_BASIC_INFO,
645 (thread_info_t)thinfo_basic, &thread_info_count);
646 if (kr != KERN_SUCCESS) {
647 PyErr_Format(PyExc_RuntimeError,
648 "thread_info(THREAD_BASIC_INFO) syscall failed");
649 goto error;
650 }
651
652 basic_info_th = (thread_basic_info_t)thinfo_basic;
653 py_tuple = Py_BuildValue(
654 "Iff",
655 j + 1,
656 basic_info_th->user_time.seconds + \
657 (float)basic_info_th->user_time.microseconds / 1000000.0,
658 basic_info_th->system_time.seconds + \
659 (float)basic_info_th->system_time.microseconds / 1000000.0
660 );
661 if (!py_tuple)
662 goto error;
663 if (PyList_Append(py_retlist, py_tuple))
664 goto error;
665 Py_CLEAR(py_tuple);
666 }
667
668 ret = vm_deallocate(
669 task, (vm_address_t)thread_list, thread_count * sizeof(thread_act_t)
670 );
671
672 if (ret != KERN_SUCCESS)
673 PyErr_WarnEx(PyExc_RuntimeWarning, "vm_deallocate() failed", 2);
674
675 mach_port_deallocate(mach_task_self(), task);
676
677 return py_retlist;
678
679 error:
680 if (task != MACH_PORT_NULL)
681 mach_port_deallocate(mach_task_self(), task);
682 Py_XDECREF(py_tuple);
683 Py_DECREF(py_retlist);
684 if (thread_list != NULL) {
685 ret = vm_deallocate(
686 task, (vm_address_t)thread_list, thread_count * sizeof(thread_act_t)
687 );
688
689 if (ret != KERN_SUCCESS)
690 PyErr_WarnEx(PyExc_RuntimeWarning, "vm_deallocate() failed", 2);
691 }
692 return NULL;
693 }
694
695
696 /*
697 * Return process open files as a Python tuple.
698 * References:
699 * - lsof source code: https://github.com/apple-opensource/lsof/blob/28/lsof/dialects/darwin/libproc/dproc.c#L342
700 * - /usr/include/sys/proc_info.h
701 */
702 PyObject *
703 psutil_proc_open_files(PyObject *self, PyObject *args) {
704 pid_t pid;
705 int num_fds;
706 int i;
707 unsigned long nb;
708 struct proc_fdinfo *fds_pointer = NULL;
709 struct proc_fdinfo *fdp_pointer;
710 struct vnode_fdinfowithpath vi;
711 PyObject *py_retlist = PyList_New(0);
712 PyObject *py_tuple = NULL;
713 PyObject *py_path = NULL;
714
715 if (py_retlist == NULL)
716 return NULL;
717
718 if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
719 goto error;
720
721 // see: https://github.com/giampaolo/psutil/issues/2116
722 if (pid == 0)
723 return py_retlist;
724
725 fds_pointer = psutil_proc_list_fds(pid, &num_fds);
726 if (fds_pointer == NULL)
727 goto error;
728
729 for (i = 0; i < num_fds; i++) {
730 fdp_pointer = &fds_pointer[i];
731
732 if (fdp_pointer->proc_fdtype == PROX_FDTYPE_VNODE) {
733 errno = 0;
734 nb = proc_pidfdinfo((pid_t)pid,
735 fdp_pointer->proc_fd,
736 PROC_PIDFDVNODEPATHINFO,
737 &vi,
738 sizeof(vi));
739
740 // --- errors checking
741 if ((nb <= 0) || nb < sizeof(vi)) {
742 if ((errno == ENOENT) || (errno == EBADF)) {
743 // no such file or directory or bad file descriptor;
744 // let's assume the file has been closed or removed
745 continue;
746 }
747 else {
748 psutil_raise_for_pid(
749 pid, "proc_pidinfo(PROC_PIDFDVNODEPATHINFO)");
750 goto error;
751 }
752 }
753 // --- /errors checking
754
755 // --- construct python list
756 py_path = PyUnicode_DecodeFSDefault(vi.pvip.vip_path);
757 if (! py_path)
758 goto error;
759 py_tuple = Py_BuildValue(
760 "(Oi)",
761 py_path,
762 (int)fdp_pointer->proc_fd);
763 if (!py_tuple)
764 goto error;
765 if (PyList_Append(py_retlist, py_tuple))
766 goto error;
767 Py_CLEAR(py_tuple);
768 Py_CLEAR(py_path);
769 // --- /construct python list
770 }
771 }
772
773 free(fds_pointer);
774 return py_retlist;
775
776 error:
777 Py_XDECREF(py_tuple);
778 Py_XDECREF(py_path);
779 Py_DECREF(py_retlist);
780 if (fds_pointer != NULL)
781 free(fds_pointer);
782 return NULL; // exception has already been set earlier
783 }
784
785
786 /*
787 * Return process TCP and UDP connections as a list of tuples.
788 * Raises NSP in case of zombie process.
789 * References:
790 * - lsof source code: https://github.com/apple-opensource/lsof/blob/28/lsof/dialects/darwin/libproc/dproc.c#L342
791 * - /usr/include/sys/proc_info.h
792 */
793 PyObject *
794 psutil_proc_net_connections(PyObject *self, PyObject *args) {
795 pid_t pid;
796 int num_fds;
797 int i;
798 unsigned long nb;
799 struct proc_fdinfo *fds_pointer = NULL;
800 struct proc_fdinfo *fdp_pointer;
801 struct socket_fdinfo si;
802 PyObject *py_retlist = PyList_New(0);
803 PyObject *py_tuple = NULL;
804 PyObject *py_laddr = NULL;
805 PyObject *py_raddr = NULL;
806 PyObject *py_af_filter = NULL;
807 PyObject *py_type_filter = NULL;
808
809 if (py_retlist == NULL)
810 return NULL;
811
812 if (! PyArg_ParseTuple(args, _Py_PARSE_PID "OO", &pid, &py_af_filter,
813 &py_type_filter)) {
814 goto error;
815 }
816
817 // see: https://github.com/giampaolo/psutil/issues/2116
818 if (pid == 0)
819 return py_retlist;
820
821 if (!PySequence_Check(py_af_filter) || !PySequence_Check(py_type_filter)) {
822 PyErr_SetString(PyExc_TypeError, "arg 2 or 3 is not a sequence");
823 goto error;
824 }
825
826 fds_pointer = psutil_proc_list_fds(pid, &num_fds);
827 if (fds_pointer == NULL)
828 goto error;
829
830 for (i = 0; i < num_fds; i++) {
831 py_tuple = NULL;
832 py_laddr = NULL;
833 py_raddr = NULL;
834 fdp_pointer = &fds_pointer[i];
835
836 if (fdp_pointer->proc_fdtype == PROX_FDTYPE_SOCKET) {
837 errno = 0;
838 nb = proc_pidfdinfo(pid, fdp_pointer->proc_fd,
839 PROC_PIDFDSOCKETINFO, &si, sizeof(si));
840
841 // --- errors checking
842 if ((nb <= 0) || (nb < sizeof(si)) || (errno != 0)) {
843 if (errno == EBADF) {
844 // let's assume socket has been closed
845 psutil_debug("proc_pidfdinfo(PROC_PIDFDSOCKETINFO) -> "
846 "EBADF (ignored)");
847 continue;
848 }
849 else if (errno == EOPNOTSUPP) {
850 // may happen sometimes, see:
851 // https://github.com/giampaolo/psutil/issues/1512
852 psutil_debug("proc_pidfdinfo(PROC_PIDFDSOCKETINFO) -> "
853 "EOPNOTSUPP (ignored)");
854 continue;
855 }
856 else {
857 psutil_raise_for_pid(
858 pid, "proc_pidinfo(PROC_PIDFDSOCKETINFO)");
859 goto error;
860 }
861 }
862 // --- /errors checking
863
864 //
865 int fd, family, type, lport, rport, state;
866 // TODO: use INET6_ADDRSTRLEN instead of 200
867 char lip[200], rip[200];
868 int inseq;
869 PyObject *py_family;
870 PyObject *py_type;
871
872 fd = (int)fdp_pointer->proc_fd;
873 family = si.psi.soi_family;
874 type = si.psi.soi_type;
875
876 // apply filters
877 py_family = PyLong_FromLong((long)family);
878 inseq = PySequence_Contains(py_af_filter, py_family);
879 Py_DECREF(py_family);
880 if (inseq == 0)
881 continue;
882 py_type = PyLong_FromLong((long)type);
883 inseq = PySequence_Contains(py_type_filter, py_type);
884 Py_DECREF(py_type);
885 if (inseq == 0)
886 continue;
887
888 if ((family == AF_INET) || (family == AF_INET6)) {
889 if (family == AF_INET) {
890 inet_ntop(AF_INET,
891 &si.psi.soi_proto.pri_tcp.tcpsi_ini. \
892 insi_laddr.ina_46.i46a_addr4,
893 lip,
894 sizeof(lip));
895 inet_ntop(AF_INET,
896 &si.psi.soi_proto.pri_tcp.tcpsi_ini.insi_faddr. \
897 ina_46.i46a_addr4,
898 rip,
899 sizeof(rip));
900 }
901 else {
902 inet_ntop(AF_INET6,
903 &si.psi.soi_proto.pri_tcp.tcpsi_ini. \
904 insi_laddr.ina_6,
905 lip, sizeof(lip));
906 inet_ntop(AF_INET6,
907 &si.psi.soi_proto.pri_tcp.tcpsi_ini. \
908 insi_faddr.ina_6,
909 rip, sizeof(rip));
910 }
911
912 // check for inet_ntop failures
913 if (errno != 0) {
914 psutil_PyErr_SetFromOSErrnoWithSyscall("inet_ntop()");
915 goto error;
916 }
917
918 lport = ntohs(si.psi.soi_proto.pri_tcp.tcpsi_ini.insi_lport);
919 rport = ntohs(si.psi.soi_proto.pri_tcp.tcpsi_ini.insi_fport);
920 if (type == SOCK_STREAM)
921 state = (int)si.psi.soi_proto.pri_tcp.tcpsi_state;
922 else
923 state = PSUTIL_CONN_NONE;
924
925 py_laddr = Py_BuildValue("(si)", lip, lport);
926 if (!py_laddr)
927 goto error;
928 if (rport != 0)
929 py_raddr = Py_BuildValue("(si)", rip, rport);
930 else
931 py_raddr = Py_BuildValue("()");
932 if (!py_raddr)
933 goto error;
934
935 // construct the python list
936 py_tuple = Py_BuildValue(
937 "(iiiNNi)", fd, family, type, py_laddr, py_raddr, state);
938 if (!py_tuple)
939 goto error;
940 if (PyList_Append(py_retlist, py_tuple))
941 goto error;
942 Py_CLEAR(py_tuple);
943 }
944 else if (family == AF_UNIX) {
945 py_laddr = PyUnicode_DecodeFSDefault(
946 si.psi.soi_proto.pri_un.unsi_addr.ua_sun.sun_path);
947 if (!py_laddr)
948 goto error;
949 py_raddr = PyUnicode_DecodeFSDefault(
950 si.psi.soi_proto.pri_un.unsi_caddr.ua_sun.sun_path);
951 if (!py_raddr)
952 goto error;
953 // construct the python list
954 py_tuple = Py_BuildValue(
955 "(iiiOOi)",
956 fd, family, type,
957 py_laddr,
958 py_raddr,
959 PSUTIL_CONN_NONE);
960 if (!py_tuple)
961 goto error;
962 if (PyList_Append(py_retlist, py_tuple))
963 goto error;
964 Py_CLEAR(py_tuple);
965 Py_CLEAR(py_laddr);
966 Py_CLEAR(py_raddr);
967 }
968 }
969 }
970
971 free(fds_pointer);
972 return py_retlist;
973
974 error:
975 Py_XDECREF(py_tuple);
976 Py_XDECREF(py_laddr);
977 Py_XDECREF(py_raddr);
978 Py_DECREF(py_retlist);
979 if (fds_pointer != NULL)
980 free(fds_pointer);
981 return NULL;
982 }
983
984
985 /*
986 * Return number of file descriptors opened by process.
987 * Raises NSP in case of zombie process.
988 */
989 PyObject *
990 psutil_proc_num_fds(PyObject *self, PyObject *args) {
991 pid_t pid;
992 int num_fds;
993 struct proc_fdinfo *fds_pointer;
994
995 if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
996 return NULL;
997
998 fds_pointer = psutil_proc_list_fds(pid, &num_fds);
999 if (fds_pointer == NULL)
1000 return NULL;
1001
1002 free(fds_pointer);
1003 return Py_BuildValue("i", num_fds);
1004 }
1005
1006
1007 // return process args as a python list
1008 PyObject *
1009 psutil_proc_cmdline(PyObject *self, PyObject *args) {
1010 pid_t pid;
1011 int nargs;
1012 size_t len;
1013 char *procargs = NULL;
1014 char *arg_ptr;
1015 char *arg_end;
1016 char *curr_arg;
1017 size_t argmax;
1018 PyObject *py_retlist = PyList_New(0);
1019 PyObject *py_arg = NULL;
1020
1021 if (py_retlist == NULL)
1022 return NULL;
1023 if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
1024 goto error;
1025
1026 // special case for PID 0 (kernel_task) where cmdline cannot be fetched
1027 if (pid == 0)
1028 return py_retlist;
1029
1030 // read argmax and allocate memory for argument space.
1031 argmax = psutil_sysctl_argmax();
1032 if (! argmax)
1033 goto error;
1034
1035 procargs = (char *)malloc(argmax);
1036 if (NULL == procargs) {
1037 PyErr_NoMemory();
1038 goto error;
1039 }
1040
1041 if (psutil_sysctl_procargs(pid, procargs, &argmax) != 0)
1042 goto error;
1043
1044 arg_end = &procargs[argmax];
1045 // copy the number of arguments to nargs
1046 memcpy(&nargs, procargs, sizeof(nargs));
1047
1048 arg_ptr = procargs + sizeof(nargs);
1049 len = strlen(arg_ptr);
1050 arg_ptr += len + 1;
1051
1052 if (arg_ptr == arg_end) {
1053 free(procargs);
1054 return py_retlist;
1055 }
1056
1057 // skip ahead to the first argument
1058 for (; arg_ptr < arg_end; arg_ptr++) {
1059 if (*arg_ptr != '\0')
1060 break;
1061 }
1062
1063 // iterate through arguments
1064 curr_arg = arg_ptr;
1065 while (arg_ptr < arg_end && nargs > 0) {
1066 if (*arg_ptr++ == '\0') {
1067 py_arg = PyUnicode_DecodeFSDefault(curr_arg);
1068 if (! py_arg)
1069 goto error;
1070 if (PyList_Append(py_retlist, py_arg))
1071 goto error;
1072 Py_DECREF(py_arg);
1073 // iterate to next arg and decrement # of args
1074 curr_arg = arg_ptr;
1075 nargs--;
1076 }
1077 }
1078
1079 free(procargs);
1080 return py_retlist;
1081
1082 error:
1083 Py_XDECREF(py_arg);
1084 Py_XDECREF(py_retlist);
1085 if (procargs != NULL)
1086 free(procargs);
1087 return NULL;
1088 }
1089
1090
1091 // Return process environment as a python string.
1092 // On Big Sur this function returns an empty string unless:
1093 // * kernel is DEVELOPMENT || DEBUG
1094 // * target process is same as current_proc()
1095 // * target process is not cs_restricted
1096 // * SIP is off
1097 // * caller has an entitlement
1098 // See: https://github.com/apple/darwin-xnu/blob/2ff845c2e033bd0ff64b5b6aa6063a1f8f65aa32/bsd/kern/kern_sysctl.c#L1315-L1321
1099 PyObject *
1100 psutil_proc_environ(PyObject *self, PyObject *args) {
1101 pid_t pid;
1102 int nargs;
1103 char *procargs = NULL;
1104 char *procenv = NULL;
1105 char *arg_ptr;
1106 char *arg_end;
1107 char *env_start;
1108 size_t argmax;
1109 PyObject *py_ret = NULL;
1110
1111 if (! PyArg_ParseTuple(args, _Py_PARSE_PID, &pid))
1112 return NULL;
1113
1114 // special case for PID 0 (kernel_task) where cmdline cannot be fetched
1115 if (pid == 0)
1116 goto empty;
1117
1118 // read argmax and allocate memory for argument space.
1119 argmax = psutil_sysctl_argmax();
1120 if (! argmax)
1121 goto error;
1122
1123 procargs = (char *)malloc(argmax);
1124 if (NULL == procargs) {
1125 PyErr_NoMemory();
1126 goto error;
1127 }
1128
1129 if (psutil_sysctl_procargs(pid, procargs, &argmax) != 0)
1130 goto error;
1131
1132 arg_end = &procargs[argmax];
1133 // copy the number of arguments to nargs
1134 memcpy(&nargs, procargs, sizeof(nargs));
1135
1136 // skip executable path
1137 arg_ptr = procargs + sizeof(nargs);
1138 arg_ptr = memchr(arg_ptr, '\0', arg_end - arg_ptr);
1139
1140 if (arg_ptr == NULL || arg_ptr == arg_end) {
1141 psutil_debug(
1142 "(arg_ptr == NULL || arg_ptr == arg_end); set environ to empty");
1143 goto empty;
1144 }
1145
1146 // skip ahead to the first argument
1147 for (; arg_ptr < arg_end; arg_ptr++) {
1148 if (*arg_ptr != '\0')
1149 break;
1150 }
1151
1152 // iterate through arguments
1153 while (arg_ptr < arg_end && nargs > 0) {
1154 if (*arg_ptr++ == '\0')
1155 nargs--;
1156 }
1157
1158 // build an environment variable block
1159 env_start = arg_ptr;
1160
1161 procenv = calloc(1, arg_end - arg_ptr);
1162 if (procenv == NULL) {
1163 PyErr_NoMemory();
1164 goto error;
1165 }
1166
1167 while (*arg_ptr != '\0' && arg_ptr < arg_end) {
1168 char *s = memchr(arg_ptr + 1, '\0', arg_end - arg_ptr);
1169 if (s == NULL)
1170 break;
1171 memcpy(procenv + (arg_ptr - env_start), arg_ptr, s - arg_ptr);
1172 arg_ptr = s + 1;
1173 }
1174
1175 py_ret = PyUnicode_DecodeFSDefaultAndSize(
1176 procenv, arg_ptr - env_start + 1);
1177 if (!py_ret) {
1178 // XXX: don't want to free() this as per:
1179 // https://github.com/giampaolo/psutil/issues/926
1180 // It sucks but not sure what else to do.
1181 procargs = NULL;
1182 goto error;
1183 }
1184
1185 free(procargs);
1186 free(procenv);
1187 return py_ret;
1188
1189 empty:
1190 if (procargs != NULL)
1191 free(procargs);
1192 return Py_BuildValue("s", "");
1193
1194 error:
1195 Py_XDECREF(py_ret);
1196 if (procargs != NULL)
1197 free(procargs);
1198 if (procenv != NULL)
1199 free(procargs);
1200 return NULL;
1201 }