robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

Justin M. KeyesMerge #36500 ci: update clang to version 2187b5062f94

master
7.2 KiB286 linesraw
1/// OS process functions
2///
3/// psutil is a good reference for cross-platform syscall voodoo:
4/// https://github.com/giampaolo/psutil/tree/master/psutil/arch
5
6// IWYU pragma: no_include <sys/param.h>
7
8#include <assert.h>
9#include <signal.h>
10#include <stdbool.h>
11#include <stddef.h>
12#include <uv.h>
13
14#ifdef MSWIN
15# include <tlhelp32.h>
16#endif
17
18#ifdef __FreeBSD__
19# include <string.h>
20# include <sys/types.h>
21# include <sys/user.h>
22#endif
23
24#if defined(__NetBSD__) || defined(__OpenBSD__)
25# include <sys/param.h>
26#endif
27
28// Exclude GNU Hurd since glibc defines BSD but lacks sysctl.h
29#if defined(__APPLE__) || (defined(BSD) && !defined(__gnu_hurd__))
30# include <sys/sysctl.h>
31
32# include "nvim/macros_defs.h"
33#endif
34
35// Group Hurd with Linux, as both use glibc and standard POSIX interfaces here
36#if defined(__linux__) || defined(__gnu_hurd__)
37# include <stdio.h>
38#endif
39
40#include "nvim/log.h"
41#include "nvim/memory.h"
42#include "nvim/os/proc.h"
43
44#ifdef MSWIN
45# include "nvim/api/private/helpers.h"
46#endif
47
48#include "os/proc.c.generated.h"
49
50#ifdef MSWIN
51static bool os_proc_tree_kill_rec(void *proc, int sig)
52{
53  if (proc == NULL) {
54    return false;
55  }
56  PROCESSENTRY32 pe;
57  DWORD pid = GetProcessId(proc);
58
59  if (pid != 0) {
60    HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
61    if (h != INVALID_HANDLE_VALUE) {
62      pe.dwSize = sizeof(PROCESSENTRY32);
63      if (!Process32First(h, &pe)) {
64        goto theend;
65      }
66      do {
67        if (pe.th32ParentProcessID == pid) {
68          HANDLE ph = OpenProcess(PROCESS_ALL_ACCESS, false, pe.th32ProcessID);
69          if (ph != NULL) {
70            os_proc_tree_kill_rec(ph, sig);
71            CloseHandle(ph);
72          }
73        }
74      } while (Process32Next(h, &pe));
75      CloseHandle(h);
76    }
77  }
78
79theend:
80  return (bool)TerminateProcess(proc, (unsigned)sig);
81}
82/// Kills process `pid` and its descendants recursively.
83bool os_proc_tree_kill(int pid, int sig)
84{
85  assert(sig >= 0);
86  assert(sig == SIGTERM || sig == SIGKILL);
87  if (pid > 0) {
88    ILOG("terminating process tree: %d", pid);
89    HANDLE h = OpenProcess(PROCESS_ALL_ACCESS, false, (DWORD)pid);
90    return os_proc_tree_kill_rec(h, sig);
91  } else {
92    ELOG("invalid pid: %d", pid);
93  }
94  return false;
95}
96#else
97/// Kills process group where `pid` is the process group leader.
98bool os_proc_tree_kill(int pid, int sig)
99{
100  assert(sig == SIGTERM || sig == SIGKILL);
101  if (pid == 0) {
102    // Never kill self (pid=0).
103    return false;
104  }
105  ILOG("sending %s to PID %d", sig == SIGTERM ? "SIGTERM" : "SIGKILL", -pid);
106  return uv_kill(-pid, sig) == 0;
107}
108#endif
109
110/// Gets the process ids of the immediate children of process `ppid`.
111///
112/// @param ppid Process to inspect.
113/// @param[out,allocated] proc_list Child process ids.
114/// @param[out] proc_count Number of child processes.
115/// @return 0 on success, 1 if process not found, 2 on other error.
116int os_proc_children(int ppid, int **proc_list, size_t *proc_count)
117  FUNC_ATTR_NONNULL_ALL
118{
119  if (ppid < 0) {
120    return 2;
121  }
122
123  int *temp = NULL;
124  *proc_list = NULL;
125  *proc_count = 0;
126
127#ifdef MSWIN
128  PROCESSENTRY32 pe;
129
130  // Snapshot of all processes.
131  HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
132  if (h == INVALID_HANDLE_VALUE) {
133    return 2;
134  }
135
136  pe.dwSize = sizeof(PROCESSENTRY32);
137  // Get root process.
138  if (!Process32First(h, &pe)) {
139    CloseHandle(h);
140    return 2;
141  }
142  // Collect processes whose parent matches `ppid`.
143  do {
144    if (pe.th32ParentProcessID == (DWORD)ppid) {
145      temp = xrealloc(temp, (*proc_count + 1) * sizeof(*temp));
146      temp[*proc_count] = (int)pe.th32ProcessID;
147      (*proc_count)++;
148    }
149  } while (Process32Next(h, &pe));
150  CloseHandle(h);
151
152#elif defined(__APPLE__) || (defined(BSD) && !defined(__gnu_hurd__))
153# if defined(__APPLE__)
154#  define KP_PID(o) o.kp_proc.p_pid
155#  define KP_PPID(o) o.kp_eproc.e_ppid
156# elif defined(__FreeBSD__)
157#  define KP_PID(o) o.ki_pid
158#  define KP_PPID(o) o.ki_ppid
159# else
160#  define KP_PID(o) o.p_pid
161#  define KP_PPID(o) o.p_ppid
162# endif
163# ifdef __NetBSD__
164  static int name[] = {
165    CTL_KERN, KERN_PROC2, KERN_PROC_ALL, 0, (int)(sizeof(struct kinfo_proc2)), 0
166  };
167# else
168  static int name[] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0 };
169# endif
170
171  // Get total process count.
172  size_t len = 0;
173  int rv = sysctl(name, ARRAY_SIZE(name) - 1, NULL, &len, NULL, 0);
174  if (rv) {
175    return 2;
176  }
177
178  // Get ALL processes.
179# ifdef __NetBSD__
180  struct kinfo_proc2 *p_list = xmalloc(len);
181# else
182  struct kinfo_proc *p_list = xmalloc(len);
183# endif
184  rv = sysctl(name, ARRAY_SIZE(name) - 1, p_list, &len, NULL, 0);
185  if (rv) {
186    xfree(p_list);
187    return 2;
188  }
189
190  // Collect processes whose parent matches `ppid`.
191  bool exists = false;
192  size_t p_count = len / sizeof(*p_list);
193  for (size_t i = 0; i < p_count; i++) {
194    exists = exists || KP_PID(p_list[i]) == ppid;
195    if (KP_PPID(p_list[i]) == ppid) {
196      temp = xrealloc(temp, (*proc_count + 1) * sizeof(*temp));
197      temp[*proc_count] = KP_PID(p_list[i]);
198      (*proc_count)++;
199    }
200  }
201  xfree(p_list);
202  if (!exists) {
203    return 1;  // Process not found.
204  }
205
206#elif defined(__linux__) || defined(__gnu_hurd__)
207  char proc_p[256] = { 0 };
208  // Collect processes whose parent matches `ppid`.
209  // Rationale: children are defined in thread with same ID of process.
210  snprintf(proc_p, sizeof(proc_p), "/proc/%d/task/%d/children", ppid, ppid);
211  FILE *fp = fopen(proc_p, "r");
212  if (fp == NULL) {
213    return 2;  // Process not found, or /proc/…/children not supported.
214  }
215  int match_pid;
216  while (fscanf(fp, "%d", &match_pid) > 0) {
217    temp = xrealloc(temp, (*proc_count + 1) * sizeof(*temp));
218    temp[*proc_count] = match_pid;
219    (*proc_count)++;
220  }
221  fclose(fp);
222#endif
223
224  *proc_list = temp;
225  return 0;
226}
227
228#ifdef MSWIN
229/// Gets various properties of the process identified by `pid`.
230///
231/// @param pid Process to inspect.
232/// @return Map of process properties, empty on error.
233Dict os_proc_info(int pid, Arena *arena)
234{
235  Dict pinfo = ARRAY_DICT_INIT;
236  PROCESSENTRY32 pe;
237
238  // Snapshot of all processes.  This is used instead of:
239  //    OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, …)
240  // to avoid ERROR_PARTIAL_COPY.  https://stackoverflow.com/a/29942376
241  HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
242  if (h == INVALID_HANDLE_VALUE) {
243    return pinfo;  // Return empty.
244  }
245
246  pe.dwSize = sizeof(PROCESSENTRY32);
247  // Get root process.
248  if (!Process32First(h, &pe)) {
249    CloseHandle(h);
250    return pinfo;  // Return empty.
251  }
252  // Find the process.
253  do {
254    if (pe.th32ProcessID == (DWORD)pid) {
255      break;
256    }
257  } while (Process32Next(h, &pe));
258  CloseHandle(h);
259
260  if (pe.th32ProcessID == (DWORD)pid) {
261    pinfo = arena_dict(arena, 3);
262    PUT_C(pinfo, "pid", INTEGER_OBJ(pid));
263    PUT_C(pinfo, "ppid", INTEGER_OBJ((int)pe.th32ParentProcessID));
264    PUT_C(pinfo, "name", CSTR_TO_ARENA_OBJ(arena, pe.szExeFile));
265  }
266
267  return pinfo;
268}
269#endif
270
271/// Return true if process `pid` is running.
272bool os_proc_running(int pid)
273{
274  int err = uv_kill(pid, 0);
275  // If there is no error the process must be running.
276  if (err == 0) {
277    return true;
278  }
279  // If the error is ESRCH then the process is not running.
280  if (err == UV_ESRCH) {
281    return false;
282  }
283  // If the process is running and owned by another user we get EPERM.  With
284  // other errors the process might be running, assuming it is then.
285  return true;
286}