Debian Codegraph @

src/sysprofd/helpers.c

raw
1 /* helpers.c
2 *
3 * Copyright 2019 Christian Hergert <[email protected]>
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 *
18 * SPDX-License-Identifier: GPL-3.0-or-later
19 */
20
21 #define G_LOG_DOMAIN "helpers"
22
23 #include "config.h"
24
25 #include <fcntl.h>
26 #include <gio/gio.h>
27 #include <errno.h>
28 #ifdef __linux__
29 # include <linux/perf_event.h>
30 # include <sys/syscall.h>
31 #endif
32 #include <string.h>
33 #include <unistd.h>
34
35 #include "helpers.h"
36
37 #ifdef __linux__
38 static gboolean
39 linux_list_processes (gint32 **processes,
40 gsize *n_processes)
41 {
42 g_autoptr(GDir) dir = NULL;
43 g_autoptr(GArray) pids = NULL;
44 const gchar *name;
45
46 if (!(dir = g_dir_open ("/proc/", 0, NULL)))
47 return FALSE;
48
49 pids = g_array_new (FALSE, FALSE, sizeof (gint32));
50
51 while ((name = g_dir_read_name (dir)))
52 {
53 if (g_ascii_isalnum (*name))
54 {
55 gchar *endptr = NULL;
56 gint64 val = g_ascii_strtoll (name, &endptr, 10);
57
58 if (endptr != NULL && *endptr == 0 && val < G_MAXINT && val >= 0)
59 {
60 gint32 v32 = val;
61 g_array_append_val (pids, v32);
62 }
63 }
64 }
65
66 *n_processes = pids->len;
67 *processes = (gint32 *)(gpointer)g_array_free (g_steal_pointer (&pids), FALSE);
68
69 return TRUE;
70 }
71 #endif
72
73 gboolean
74 helpers_list_processes (gint32 **processes,
75 gsize *n_processes)
76 {
77 g_return_val_if_fail (processes != NULL, FALSE);
78 g_return_val_if_fail (n_processes != NULL, FALSE);
79
80 *processes = NULL;
81 *n_processes = 0;
82
83 #ifdef __linux__
84 return linux_list_processes (processes, n_processes);
85 #else
86 return FALSE;
87 #endif
88 }
89
90 #ifdef __linux__
91 static int
92 _perf_event_open (struct perf_event_attr *attr,
93 pid_t pid,
94 int cpu,
95 int group_fd,
96 unsigned long flags)
97 {
98 g_assert (attr != NULL);
99
100 /* Quick sanity check */
101 if (attr->sample_period < 100000 && attr->type != PERF_TYPE_TRACEPOINT)
102 return -EINVAL;
103
104 return syscall (__NR_perf_event_open, attr, pid, cpu, group_fd, flags);
105 }
106 #endif
107
108 gboolean
109 helpers_perf_event_open (GVariant *options,
110 gint32 pid,
111 gint32 cpu,
112 gint group_fd,
113 guint64 flags,
114 gint *out_fd)
115 {
116 #ifndef __linux__
117 *out_fd = -1;
118 return FALSE;
119 #else
120 struct perf_event_attr attr = {0};
121 GVariantIter iter;
122 GVariant *value;
123 char *key;
124 gint32 disabled = 0;
125 gint32 wakeup_events = 149;
126 gint32 type = 0;
127 guint64 sample_period = 0;
128 guint64 sample_type = 0;
129 guint64 config = 0;
130 guint64 sample_regs_user = 0;
131 guint sample_stack_user = 0;
132 int clockid = CLOCK_MONOTONIC;
133 int comm = 0;
134 int mmap_ = 0;
135 int mmap2 = 0;
136 int build_id = 0;
137 int task = 0;
138 int exclude_idle = 0;
139 int use_clockid = 0;
140 int sample_id_all = 0;
141
142 g_assert (out_fd != NULL);
143
144 *out_fd = -1;
145
146 g_variant_iter_init (&iter, options);
147
148 while (g_variant_iter_loop (&iter, "{sv}", &key, &value))
149 {
150 if (FALSE) {}
151 else if (strcmp (key, "disabled") == 0)
152 {
153 if (!g_variant_is_of_type (value, G_VARIANT_TYPE_BOOLEAN))
154 goto bad_arg;
155 disabled = g_variant_get_boolean (value);
156 }
157 else if (strcmp (key, "wakeup_events") == 0)
158 {
159 if (!g_variant_is_of_type (value, G_VARIANT_TYPE_UINT32))
160 goto bad_arg;
161 wakeup_events = g_variant_get_uint32 (value);
162 }
163 else if (strcmp (key, "sample_id_all") == 0)
164 {
165 if (!g_variant_is_of_type (value, G_VARIANT_TYPE_BOOLEAN))
166 goto bad_arg;
167 sample_id_all = g_variant_get_boolean (value);
168 }
169 else if (strcmp (key, "build_id") == 0)
170 {
171 if (!g_variant_is_of_type (value, G_VARIANT_TYPE_BOOLEAN))
172 goto bad_arg;
173 build_id = g_variant_get_boolean (value);
174 }
175 else if (strcmp (key, "clockid") == 0)
176 {
177 if (!g_variant_is_of_type (value, G_VARIANT_TYPE_INT32))
178 goto bad_arg;
179 clockid = g_variant_get_int32 (value);
180 }
181 else if (strcmp (key, "comm") == 0)
182 {
183 if (!g_variant_is_of_type (value, G_VARIANT_TYPE_BOOLEAN))
184 goto bad_arg;
185 comm = g_variant_get_boolean (value);
186 }
187 else if (strcmp (key, "exclude_idle") == 0)
188 {
189 if (!g_variant_is_of_type (value, G_VARIANT_TYPE_BOOLEAN))
190 goto bad_arg;
191 exclude_idle = g_variant_get_boolean (value);
192 }
193 else if (strcmp (key, "mmap") == 0)
194 {
195 if (!g_variant_is_of_type (value, G_VARIANT_TYPE_BOOLEAN))
196 goto bad_arg;
197 mmap_ = g_variant_get_boolean (value);
198 }
199 else if (strcmp (key, "mmap2") == 0)
200 {
201 if (!g_variant_is_of_type (value, G_VARIANT_TYPE_BOOLEAN))
202 goto bad_arg;
203 mmap2 = g_variant_get_boolean (value);
204 }
205 else if (strcmp (key, "config") == 0)
206 {
207 if (!g_variant_is_of_type (value, G_VARIANT_TYPE_UINT64))
208 goto bad_arg;
209 config = g_variant_get_uint64 (value);
210 }
211 else if (strcmp (key, "sample_period") == 0)
212 {
213 if (!g_variant_is_of_type (value, G_VARIANT_TYPE_UINT64))
214 goto bad_arg;
215 sample_period = g_variant_get_uint64 (value);
216 }
217 else if (strcmp (key, "sample_type") == 0)
218 {
219 if (!g_variant_is_of_type (value, G_VARIANT_TYPE_UINT64))
220 goto bad_arg;
221 sample_type = g_variant_get_uint64 (value);
222 }
223 else if (strcmp (key, "task") == 0)
224 {
225 if (!g_variant_is_of_type (value, G_VARIANT_TYPE_BOOLEAN))
226 goto bad_arg;
227 task = g_variant_get_boolean (value);
228 }
229 else if (strcmp (key, "type") == 0)
230 {
231 if (!g_variant_is_of_type (value, G_VARIANT_TYPE_UINT32))
232 goto bad_arg;
233 type = g_variant_get_uint32 (value);
234 }
235 else if (strcmp (key, "use_clockid") == 0)
236 {
237 if (!g_variant_is_of_type (value, G_VARIANT_TYPE_BOOLEAN))
238 goto bad_arg;
239 use_clockid = g_variant_get_boolean (value);
240 }
241 else if (strcmp (key, "sample_stack_user") == 0)
242 {
243 if (!g_variant_is_of_type (value, G_VARIANT_TYPE_UINT32))
244 goto bad_arg;
245 sample_stack_user = g_variant_get_uint32 (value);
246 }
247 else if (strcmp (key, "sample_regs_user") == 0)
248 {
249 if (!g_variant_is_of_type (value, G_VARIANT_TYPE_UINT64))
250 goto bad_arg;
251 sample_regs_user = g_variant_get_uint64 (value);
252 }
253
254 continue;
255
256 bad_arg:
257 errno = EINVAL;
258 return FALSE;
259 }
260
261 attr.comm = !!comm;
262 attr.config = config;
263 attr.disabled = disabled;
264 attr.exclude_idle = !!exclude_idle;
265 attr.mmap = !!mmap_;
266 attr.mmap2 = !!mmap2;
267 attr.build_id = !!build_id;
268 attr.sample_id_all = sample_id_all;
269 attr.sample_period = sample_period;
270 attr.sample_type = sample_type;
271 attr.task = !!task;
272 attr.type = type;
273 attr.wakeup_events = wakeup_events;
274 attr.sample_regs_user = sample_regs_user;
275 attr.sample_stack_user = sample_stack_user;
276
277 #ifdef HAVE_PERF_CLOCKID
278 if (!use_clockid || clockid < 0)
279 attr.clockid = CLOCK_MONOTONIC;
280 else
281 attr.clockid = clockid;
282 attr.use_clockid = use_clockid;
283 #endif
284
285 attr.size = sizeof attr;
286
287 errno = 0;
288 *out_fd = _perf_event_open (&attr, pid, cpu, group_fd, flags);
289 return *out_fd >= 0;
290 #endif
291 }
292
293 gboolean
294 helpers_get_proc_file (const gchar *path,
295 gchar **contents,
296 gsize *len)
297 {
298 g_autofree gchar *canon = NULL;
299 g_autoptr(GFile) file = NULL;
300
301 g_assert (path != NULL);
302 g_assert (contents != NULL);
303 g_assert (len != NULL);
304
305 *contents = NULL;
306 *len = 0;
307
308 /* Canonicalize filename */
309 file = g_file_new_for_path (path);
310 canon = g_file_get_path (file);
311
312 return g_file_is_native (file) &&
313 (g_str_has_prefix (canon, "/proc/") || g_str_has_prefix (canon, "/sys/")) &&
314 g_file_get_contents (canon, contents, len, NULL);
315 }
316
317 gboolean
318 helpers_get_proc_fd (const gchar *path,
319 gint *out_fd)
320 {
321 g_autofree gchar *canon = NULL;
322 g_autoptr(GFile) file = NULL;
323
324 g_assert (path != NULL);
325 g_assert (out_fd != NULL);
326
327 /* Canonicalize filename */
328 file = g_file_new_for_path (path);
329 canon = g_file_get_path (file);
330
331 return g_file_is_native (file) &&
332 (g_str_has_prefix (canon, "/proc/") || g_str_has_prefix (canon, "/sys/")) &&
333 -1 != (*out_fd = open (canon, O_RDONLY | O_CLOEXEC));
334 }
335
336 gboolean
337 helpers_can_see_pids (void)
338 {
339 g_autofree gchar *contents = NULL;
340 gsize len = 0;
341
342 if (g_file_test ("/.flatpak-info", G_FILE_TEST_EXISTS))
343 return FALSE;
344
345 if (helpers_get_proc_file ("/proc/mounts", &contents, &len))
346 {
347 g_auto(GStrv) lines = g_strsplit (contents, "\n", 0);
348
349 for (guint i = 0; lines[i]; i++)
350 {
351 if (!g_str_has_prefix (lines[i], "proc /proc "))
352 continue;
353
354 if (strstr (lines[i], "hidepid=") && !strstr (lines[i], "hidepid=0"))
355 return FALSE;
356
357 return TRUE;
358 }
359 }
360
361 return TRUE;
362 }
363
364 static void
365 helpers_list_processes_worker (GTask *task,
366 gpointer source_object,
367 gpointer task_data,
368 GCancellable *cancellable)
369 {
370 g_autofree gint32 *processes = NULL;
371 gsize n_processes;
372
373 g_assert (G_IS_TASK (task));
374 g_assert (!cancellable || G_IS_CANCELLABLE (cancellable));
375
376 if (helpers_list_processes (&processes, &n_processes))
377 {
378 GArray *ar;
379
380 ar = g_array_new (FALSE, FALSE, sizeof (gint32));
381 g_array_append_vals (ar, processes, n_processes);
382 g_task_return_pointer (task,
383 g_steal_pointer (&ar),
384 (GDestroyNotify) g_array_unref);
385
386 return;
387 }
388
389 g_task_return_new_error (task,
390 G_IO_ERROR,
391 G_IO_ERROR_FAILED,
392 "Failed to list processes");
393 }
394
395 void
396 helpers_list_processes_async (GCancellable *cancellable,
397 GAsyncReadyCallback callback,
398 gpointer user_data)
399 {
400 g_autoptr(GTask) task = NULL;
401
402 g_return_if_fail (!cancellable || G_IS_CANCELLABLE (cancellable));
403
404 task = g_task_new (NULL, cancellable, callback, user_data);
405 g_task_set_source_tag (task, helpers_list_processes_async);
406 g_task_run_in_thread (task, helpers_list_processes_worker);
407 }
408
409 gboolean
410 helpers_list_processes_finish (GAsyncResult *result,
411 gint32 **processes,
412 gsize *n_processes,
413 GError **error)
414 {
415 g_autoptr(GArray) ret = NULL;
416
417 g_return_val_if_fail (G_IS_TASK (result), FALSE);
418
419 if ((ret = g_task_propagate_pointer (G_TASK (result), error)))
420 {
421 if (n_processes)
422 *n_processes = ret->len;
423
424 if (processes)
425 *processes = (gint32 *)(gpointer)g_array_free (ret, FALSE);
426
427 return TRUE;
428 }
429 else
430 {
431 if (processes)
432 *processes = NULL;
433 if (n_processes)
434 *n_processes = 0;
435 }
436
437 return FALSE;
438 }
439
440 static gboolean
441 needs_escape (const gchar *str)
442 {
443 for (; *str; str++)
444 {
445 if (g_ascii_isspace (*str) || *str == '\'' || *str == '"')
446 return TRUE;
447 }
448
449 return FALSE;
450 }
451
452 static void
453 postprocess_cmdline (gchar **str,
454 gsize len)
455 {
456 g_autoptr(GPtrArray) parts = g_ptr_array_new_with_free_func (g_free);
457 g_autofree gchar *instr = NULL;
458 const gchar *begin = NULL;
459
460 if (len == 0)
461 return;
462
463 instr = *str;
464
465 for (gsize i = 0; i < len; i++)
466 {
467 if (!begin && instr[i])
468 {
469 begin = &instr[i];
470 }
471 else if (begin && instr[i] == '\0')
472 {
473 if (needs_escape (begin))
474 g_ptr_array_add (parts, g_shell_quote (begin));
475 else
476 g_ptr_array_add (parts, g_strdup (begin));
477
478 begin = NULL;
479 }
480 }
481
482 /* If the last byte was not \0, as can happen with prctl(), then we need
483 * to add it here manually.
484 */
485 if (begin)
486 {
487 if (needs_escape (begin))
488 g_ptr_array_add (parts, g_shell_quote (begin));
489 else
490 g_ptr_array_add (parts, g_strdup (begin));
491 }
492
493 g_ptr_array_add (parts, NULL);
494
495 *str = g_strjoinv (" ", (gchar **)parts->pdata);
496 }
497
498 static void
499 postprocess_rstrip (gchar **str,
500 gsize len)
501 {
502 g_strchomp (*str);
503 }
504
505 static void
506 add_pid_proc_file_to (gint pid,
507 const gchar *name,
508 GVariantDict *dict,
509 void (*postprocess) (gchar **, gsize))
510 {
511 g_autofree gchar *path = NULL;
512 g_autofree gchar *contents = NULL;
513 gsize len;
514
515 g_assert (pid > -1);
516 g_assert (name != NULL);
517 g_assert (dict != NULL);
518
519 path = g_strdup_printf ("/proc/%d/%s", pid, name);
520
521 if (g_file_get_contents (path, &contents, &len, NULL))
522 {
523 if (postprocess)
524 postprocess (&contents, len);
525 g_variant_dict_insert (dict, name, "s", contents);
526 }
527 }
528
529
530 GVariant *
531 helpers_get_process_info (const gchar *attributes)
532 {
533 GVariantBuilder builder;
534 g_autofree gint *processes = NULL;
535 gsize n_processes = 0;
536 gboolean want_statm;
537 gboolean want_cmdline;
538 gboolean want_comm;
539 gboolean want_maps;
540 gboolean want_mountinfo;
541 gboolean want_cgroup;
542
543 if (attributes == NULL)
544 attributes = "";
545
546 want_statm = !!strstr (attributes, "statm");
547 want_cmdline = !!strstr (attributes, "cmdline");
548 want_maps = !!strstr (attributes, "maps");
549 want_mountinfo = !!strstr (attributes, "mountinfo");
550 want_comm = !!strstr (attributes, "comm");
551 want_cgroup = !!strstr (attributes, "cgroup");
552
553 g_variant_builder_init (&builder, G_VARIANT_TYPE ("aa{sv}"));
554
555 if (helpers_list_processes (&processes, &n_processes))
556 {
557 for (guint i = 0; i < n_processes; i++)
558 {
559 gint pid = processes[i];
560 GVariantDict dict;
561
562 g_variant_dict_init (&dict, NULL);
563 g_variant_dict_insert (&dict, "pid", "i", pid, NULL);
564
565 if (want_statm)
566 add_pid_proc_file_to (pid, "statm", &dict, postprocess_rstrip);
567
568 if (want_cmdline)
569 add_pid_proc_file_to (pid, "cmdline", &dict, postprocess_cmdline);
570
571 if (want_comm)
572 add_pid_proc_file_to (pid, "comm", &dict, postprocess_rstrip);
573
574 if (want_maps)
575 add_pid_proc_file_to (pid, "maps", &dict, postprocess_rstrip);
576
577 if (want_mountinfo)
578 add_pid_proc_file_to (pid, "mountinfo", &dict, postprocess_rstrip);
579
580 if (want_cgroup)
581 add_pid_proc_file_to (pid, "cgroup", &dict, postprocess_rstrip);
582
583 g_variant_builder_add_value (&builder, g_variant_dict_end (&dict));
584 }
585 }
586
587 return g_variant_take_ref (g_variant_builder_end (&builder));
588 }