Debian Codegraph @

src/libsysprof/sysprof-linux-instrument.c

raw
1 /* sysprof-linux-instrument.c
2 *
3 * Copyright 2023 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 #include "config.h"
22
23 #include <stdio.h>
24
25 #include "sysprof-linux-instrument-private.h"
26 #include "sysprof-maps-parser-private.h"
27 #include "sysprof-podman-private.h"
28 #include "sysprof-recording-private.h"
29
30 #include "line-reader-private.h"
31
32 #include "../sysprofd/helpers.h"
33
34 #define PROCESS_INFO_KEYS "pid,maps,mountinfo,cmdline,comm,cgroup"
35
36 struct _SysprofLinuxInstrument
37 {
38 SysprofInstrument parent_instance;
39 GDBusConnection *connection;
40 SysprofRecording *recording;
41 GHashTable *seen;
42 };
43
44 G_DEFINE_FINAL_TYPE (SysprofLinuxInstrument, sysprof_linux_instrument, SYSPROF_TYPE_INSTRUMENT)
45
46 static char **
47 sysprof_linux_instrument_list_required_policy (SysprofInstrument *instrument)
48 {
49 static const char *policy[] = {"org.gnome.sysprof3.profile", NULL};
50
51 return g_strdupv ((char **)policy);
52 }
53
54 static void
55 sysprof_linux_instrument_set_connection (SysprofInstrument *instrument,
56 GDBusConnection *connection)
57 {
58 SysprofLinuxInstrument *self = SYSPROF_LINUX_INSTRUMENT (instrument);
59
60 g_set_object (&self->connection, connection);
61 }
62
63 static void
64 add_mmaps (SysprofRecording *recording,
65 GPid pid,
66 const char *mapsstr,
67 gboolean ignore_inode,
68 gint64 at_time)
69 {
70 SysprofCaptureWriter *writer;
71 SysprofMapsParser parser;
72 guint64 begin, end, offset, inode;
73 char *file;
74
75 g_assert (SYSPROF_IS_RECORDING (recording));
76 g_assert (mapsstr != NULL);
77 g_assert (pid > 0);
78
79 writer = _sysprof_recording_writer (recording);
80
81 sysprof_maps_parser_init (&parser, mapsstr, -1);
82 while (sysprof_maps_parser_next (&parser, &begin, &end, &offset, &inode, &file))
83 {
84 if (ignore_inode)
85 inode = 0;
86
87 sysprof_capture_writer_add_map (writer, at_time, -1, pid,
88 begin, end, offset, inode,
89 file);
90 g_free (file);
91 }
92 }
93
94 static DexFuture *
95 populate_overlays (SysprofRecording *recording,
96 SysprofPodman *podman,
97 int pid,
98 const char *cgroup,
99 gint64 at_time)
100 {
101 static GRegex *flatpak_regex;
102 static GRegex *podman_regex;
103
104 g_autoptr(GMatchInfo) flatpak_match = NULL;
105 g_autoptr(GMatchInfo) podman_match = NULL;
106 SysprofCaptureWriter *writer;
107
108 g_assert (SYSPROF_IS_RECORDING (recording));
109 g_assert (cgroup != NULL);
110
111 if (strcmp (cgroup, "") == 0)
112 return dex_future_new_for_boolean (TRUE);
113
114 writer = _sysprof_recording_writer (recording);
115
116 /* This function tries to discover the podman container that contains the
117 * process identified on the host as @pid. We can only do anything with this
118 * if the pids are in containers that the running user controls (so that we
119 * can actually access the overlays).
120 *
121 * This stuff, and I want to emphasize, is a giant hack. Just like containers
122 * are on Linux. But if we are really careful, we can make this work for the
123 * one particular use case I care about, which is podman/toolbox on Fedora
124 * Workstation/Silverblue.
125 *
126 * -- Christian
127 */
128 if G_UNLIKELY (podman_regex == NULL)
129 {
130 podman_regex = g_regex_new ("libpod-([a-z0-9]{64})\\.scope", G_REGEX_OPTIMIZE, 0, NULL);
131 g_assert (podman_regex != NULL);
132 }
133
134 if (flatpak_regex == NULL)
135 {
136 flatpak_regex = g_regex_new ("app-flatpak-([a-zA-Z_\\-\\.]+)-[0-9]+\\.scope", G_REGEX_OPTIMIZE, 0, NULL);
137 g_assert (flatpak_regex != NULL);
138 }
139
140 if (g_regex_match (podman_regex, cgroup, 0, &podman_match))
141 {
142 g_autofree char *word = g_match_info_fetch (podman_match, 1);
143 g_autofree char *path = g_strdup_printf ("/proc/%d/root/run/.containerenv", pid);
144 g_auto(GStrv) layers = NULL;
145
146 if ((layers = sysprof_podman_get_layers (podman, word)))
147 {
148 for (guint i = 0; layers[i]; i++)
149 sysprof_capture_writer_add_overlay (writer, at_time, -1, pid,
150 i, layers[i], "/");
151 }
152
153 return _sysprof_recording_add_file (recording, path, FALSE);
154 }
155 else if (g_regex_match (flatpak_regex, cgroup, 0, &flatpak_match))
156 {
157 g_autofree char *path = g_strdup_printf ("/proc/%d/root/.flatpak-info", pid);
158
159 return _sysprof_recording_add_file (recording, path, FALSE);
160 }
161
162 return dex_future_new_for_boolean (TRUE);
163 }
164
165 static DexFuture *
166 add_process_info (SysprofLinuxInstrument *self,
167 SysprofRecording *recording,
168 GVariant *process_info,
169 gint64 at_time)
170 {
171 g_autoptr(SysprofPodman) podman = NULL;
172 g_autoptr(GPtrArray) futures = NULL;
173 SysprofCaptureWriter *writer;
174 GVariantIter iter;
175 GVariant *pidinfo;
176
177 g_assert (SYSPROF_IS_LINUX_INSTRUMENT (self));
178 g_assert (SYSPROF_IS_RECORDING (recording));
179 g_assert (process_info != NULL);
180 g_assert (g_variant_is_of_type (process_info, G_VARIANT_TYPE ("aa{sv}")));
181
182 writer = _sysprof_recording_writer (recording);
183 podman = sysprof_podman_snapshot_current_user ();
184 futures = g_ptr_array_new_with_free_func (dex_unref);
185
186 /* Loop through all the PIDs the server notified us about */
187 g_variant_iter_init (&iter, process_info);
188 while (g_variant_iter_loop (&iter, "@a{sv}", &pidinfo))
189 {
190 g_autofree char *mount_path = NULL;
191 GVariantDict dict;
192 const char *cmdline;
193 const char *comm;
194 const char *mountinfo;
195 const char *maps;
196 const char *cgroup;
197 gboolean ignore_inode;
198 gint32 pid;
199
200 g_variant_dict_init (&dict, pidinfo);
201
202 if (!g_variant_dict_lookup (&dict, "pid", "i", &pid))
203 goto skip;
204
205 g_hash_table_add (self->seen, GINT_TO_POINTER (pid));
206
207 if (!g_variant_dict_lookup (&dict, "cmdline", "&s", &cmdline))
208 cmdline = "";
209
210 if (!g_variant_dict_lookup (&dict, "comm", "&s", &comm))
211 comm = "";
212
213 if (!g_variant_dict_lookup (&dict, "mountinfo", "&s", &mountinfo))
214 mountinfo = "";
215
216 if (!g_variant_dict_lookup (&dict, "maps", "&s", &maps))
217 maps = "";
218
219 if (!g_variant_dict_lookup (&dict, "cgroup", "&s", &cgroup))
220 cgroup = "";
221
222 /* Notify the capture that a process was spawned */
223 sysprof_capture_writer_add_process (writer, at_time, -1, pid,
224 *cmdline ? cmdline : comm);
225
226 /* Give the capture access to the mountinfo of that process to aid
227 * in resolving symbols later on.
228 */
229 mount_path = g_strdup_printf ("/proc/%u/mountinfo", pid);
230 _sysprof_recording_add_file_data (recording, mount_path, mountinfo, -1, TRUE);
231
232 /* Ignore inodes from podman/toolbox because they appear to always be
233 * wrong. We'll have to rely on CRC/build-id instead.
234 */
235 ignore_inode = strstr (cgroup, "/libpod-") != NULL;
236 add_mmaps (recording, pid, maps, ignore_inode, at_time);
237
238 /* We might have overlays that need to be applied to the process
239 * which can be rather combursome for old-style Podman using
240 * FUSE overlayfs.
241 */
242 g_ptr_array_add (futures, populate_overlays (recording, podman, pid, cgroup, at_time));
243
244 skip:
245 g_variant_dict_clear (&dict);
246 }
247
248 if (futures->len > 0)
249 return dex_future_allv ((DexFuture **)futures->pdata, futures->len);
250
251 return dex_future_new_for_boolean (TRUE);
252 }
253
254 static void
255 get_process_info_task (gpointer data)
256 {
257 g_autoptr(DexPromise) promise = data;
258 g_autoptr(GVariant) info = NULL;
259
260 if (!(info = helpers_get_process_info (PROCESS_INFO_KEYS)))
261 dex_promise_reject (promise,
262 g_error_new (G_IO_ERROR,
263 G_IO_ERROR_PERMISSION_DENIED,
264 "Failed to load process info"));
265 else
266 dex_promise_resolve_variant (promise, g_steal_pointer (&info));
267 }
268
269 static DexFuture *
270 get_process_info (void)
271 {
272 DexPromise *promise = dex_promise_new ();
273 dex_scheduler_push (dex_thread_pool_scheduler_get_default (),
274 get_process_info_task,
275 dex_ref (promise));
276 return DEX_FUTURE (g_steal_pointer (&promise));
277 }
278
279 static DexFuture *
280 sysprof_linux_instrument_prepare_fiber (gpointer user_data)
281 {
282 SysprofLinuxInstrument *self = user_data;
283 g_autoptr(GVariant) process_info_reply = NULL;
284 g_autoptr(GVariant) process_info = NULL;
285 g_autoptr(GError) error = NULL;
286 gint64 at_time;
287
288 g_assert (SYSPROF_IS_LINUX_INSTRUMENT (self));
289 g_assert (SYSPROF_IS_RECORDING (self->recording));
290
291 /* First get some basic information about the system into the capture. We can
292 * get the contents for all of these concurrently.
293 */
294 if (!dex_await (dex_future_all (_sysprof_recording_add_file (self->recording, "/proc/cpuinfo", TRUE),
295 _sysprof_recording_add_file (self->recording, "/proc/mounts", TRUE),
296 NULL),
297 &error))
298 return dex_future_new_for_error (g_steal_pointer (&error));
299
300 at_time = SYSPROF_CAPTURE_CURRENT_TIME;
301
302 if (self->connection != NULL)
303 {
304 /* We also want to get a bunch of info on user processes so that we can add
305 * records about them to the recording.
306 */
307 if (!(process_info_reply = dex_await_variant (dex_dbus_connection_call (self->connection,
308 "org.gnome.Sysprof3",
309 "/org/gnome/Sysprof3",
310 "org.gnome.Sysprof3.Service",
311 "GetProcessInfo",
312 g_variant_new ("(s)", PROCESS_INFO_KEYS),
313 G_VARIANT_TYPE ("(aa{sv})"),
314 G_DBUS_CALL_FLAGS_ALLOW_INTERACTIVE_AUTHORIZATION,
315 G_MAXINT),
316 &error)))
317 return dex_future_new_for_error (g_steal_pointer (&error));
318
319 /* Add process records for each of the processes discovered */
320 process_info = g_variant_get_child_value (process_info_reply, 0);
321 }
322 else
323 {
324 /* Load process info using same mechanism as sysprofd */
325 if (!(process_info = dex_await_variant (get_process_info (), &error)))
326 return dex_future_new_for_error (g_steal_pointer (&error));
327 }
328
329 g_assert (process_info != NULL);
330
331 dex_await (add_process_info (self, self->recording, process_info, at_time), NULL);
332
333 return dex_future_new_for_boolean (TRUE);
334 }
335
336 static DexFuture *
337 sysprof_linux_instrument_prepare (SysprofInstrument *instrument,
338 SysprofRecording *recording)
339 {
340 SysprofLinuxInstrument *self = (SysprofLinuxInstrument *)instrument;
341
342 g_assert (SYSPROF_IS_INSTRUMENT (self));
343 g_assert (SYSPROF_IS_RECORDING (recording));
344
345 g_set_object (&self->recording, recording);
346
347 return dex_scheduler_spawn (NULL, 0,
348 sysprof_linux_instrument_prepare_fiber,
349 g_object_ref (self),
350 g_object_unref);
351 }
352
353 typedef struct
354 {
355 SysprofRecording *recording;
356 GPtrArray *paths;
357 int pid;
358 } ProcessStarted;
359
360 static void
361 process_started_free (gpointer data)
362 {
363 ProcessStarted *state = data;
364
365 g_clear_object (&state->recording);
366 g_clear_pointer (&state->paths, g_ptr_array_unref);
367 g_free (state);
368 }
369
370 static DexFuture *
371 process_started_cb (DexFuture *completed,
372 gpointer user_data)
373 {
374 ProcessStarted *state = user_data;
375 guint size;
376
377 g_assert (DEX_IS_FUTURE_SET (completed));
378 g_assert (state != NULL);
379 g_assert (SYSPROF_IS_RECORDING (state->recording));
380 g_assert (state->pid > 0);
381 g_assert (state->paths != NULL);
382
383 size = dex_future_set_get_size (DEX_FUTURE_SET (completed));
384
385 g_assert (state->paths->len == size);
386
387 for (guint i = 0; i < size; i++)
388 {
389 g_autoptr(GError) error = NULL;
390 const GValue *value = NULL;
391 GVariant *variant = NULL;
392 const char *path = g_ptr_array_index (state->paths, i);
393 const char *bytestring = NULL;
394
395 if (!(value = dex_future_set_get_value_at (DEX_FUTURE_SET (completed), i, &error)))
396 continue;
397
398 if (!(variant = g_value_get_variant (value)) ||
399 !g_variant_is_of_type (variant, G_VARIANT_TYPE ("(ay)")))
400 g_return_val_if_reached (NULL);
401
402 g_variant_get (variant, "(^&ay)", &bytestring);
403
404 if (bytestring == NULL)
405 g_return_val_if_reached (NULL);
406
407 _sysprof_recording_add_file_data (state->recording, path, bytestring, -1, TRUE);
408 }
409
410 return dex_future_new_for_boolean (TRUE);
411 }
412
413 static DexFuture *
414 sysprof_linux_instrument_process_started (SysprofInstrument *instrument,
415 SysprofRecording *recording,
416 int pid,
417 const char *comm)
418 {
419 SysprofLinuxInstrument *self = (SysprofLinuxInstrument *)instrument;
420 g_autoptr(GDBusConnection) bus = NULL;
421 g_autoptr(GError) error = NULL;
422 g_autofree char *mountinfo_path = NULL;
423 g_autofree char *flatpak_info_path = NULL;
424 DexFuture *mountinfo;
425 DexFuture *flatpak_info;
426 ProcessStarted *state;
427
428 g_assert (SYSPROF_IS_LINUX_INSTRUMENT (self));
429 g_assert (SYSPROF_IS_RECORDING (recording));
430
431 /* Most information for new processes we'll get inline, like the address
432 * layout for memory mappings. But we still want to get information about
433 * flatpak and mountinfo.
434 */
435
436 /* Avoid spawn amplification by monitoring processes which are spawned in
437 * reaction to the requests we make of sysprofd. This in particular sucks
438 * because it means we are not very good at profiling these processes (at
439 * least the ones spawned while recording). However, if we did try to get
440 * information on them, we'd end up just chaising our tail.
441 */
442 if (comm != NULL)
443 {
444 /* Only check up to 15 chars because that is what we can get from Perf
445 * via PERF_RECORD_COMM messages.
446 */
447 if (g_str_has_prefix (comm, "systemd-userwor") ||
448 g_str_has_prefix (comm, "pkla-check-auth"))
449 return dex_future_new_for_boolean (TRUE);
450 }
451
452 /* Shortcut if we've already seen this */
453 if (g_hash_table_contains (self->seen, GINT_TO_POINTER (pid)))
454 return dex_future_new_for_boolean (TRUE);
455 g_hash_table_add (self->seen, GINT_TO_POINTER (pid));
456
457 /* Get the bus synchronously so we don't have to suspend the fiber. This
458 * will always return immediately anyway.
459 */
460 if (!(bus = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, &error)))
461 return dex_future_new_for_error (g_steal_pointer (&error));
462
463 mountinfo_path = g_strdup_printf ("/proc/%d/mountinfo", pid);
464 mountinfo = dex_dbus_connection_call (bus,
465 "org.gnome.Sysprof3",
466 "/org/gnome/Sysprof3",
467 "org.gnome.Sysprof3.Service",
468 "GetProcFile",
469 g_variant_new ("(^ay)", mountinfo_path),
470 G_VARIANT_TYPE ("(ay)"),
471 G_DBUS_CALL_FLAGS_NONE,
472 -1);
473
474 flatpak_info_path = g_strdup_printf ("/proc/%d/root/.flatpak-info", pid);
475 flatpak_info = dex_dbus_connection_call (bus,
476 "org.gnome.Sysprof3",
477 "/org/gnome/Sysprof3",
478 "org.gnome.Sysprof3.Service",
479 "GetProcFile",
480 g_variant_new ("(^ay)", flatpak_info_path),
481 G_VARIANT_TYPE ("(ay)"),
482 G_DBUS_CALL_FLAGS_NONE,
483 -1);
484
485 state = g_new0 (ProcessStarted, 1);
486 state->pid = pid;
487 state->recording = g_object_ref (recording);
488 state->paths = g_ptr_array_new_with_free_func (g_free);
489
490 g_ptr_array_add (state->paths, g_steal_pointer (&mountinfo_path));
491 g_ptr_array_add (state->paths, g_steal_pointer (&flatpak_info_path));
492
493 return dex_future_finally (dex_future_all (mountinfo, flatpak_info, NULL),
494 process_started_cb,
495 state,
496 process_started_free);
497 }
498
499 static void
500 sysprof_linux_instrument_dispose (GObject *object)
501 {
502 SysprofLinuxInstrument *self = (SysprofLinuxInstrument *)object;
503
504 g_clear_object (&self->connection);
505 g_clear_object (&self->recording);
506 g_hash_table_remove_all (self->seen);
507
508 G_OBJECT_CLASS (sysprof_linux_instrument_parent_class)->dispose (object);
509 }
510
511 static void
512 sysprof_linux_instrument_finalize (GObject *object)
513 {
514 SysprofLinuxInstrument *self = (SysprofLinuxInstrument *)object;
515
516 g_clear_pointer (&self->seen, g_hash_table_unref);
517
518 G_OBJECT_CLASS (sysprof_linux_instrument_parent_class)->finalize (object);
519 }
520
521 static void
522 sysprof_linux_instrument_class_init (SysprofLinuxInstrumentClass *klass)
523 {
524 GObjectClass *object_class = G_OBJECT_CLASS (klass);
525 SysprofInstrumentClass *instrument_class = SYSPROF_INSTRUMENT_CLASS (klass);
526
527 object_class->dispose = sysprof_linux_instrument_dispose;
528 object_class->finalize = sysprof_linux_instrument_finalize;
529
530 instrument_class->list_required_policy = sysprof_linux_instrument_list_required_policy;
531 instrument_class->prepare = sysprof_linux_instrument_prepare;
532 instrument_class->process_started = sysprof_linux_instrument_process_started;
533 instrument_class->set_connection = sysprof_linux_instrument_set_connection;
534 }
535
536 static void
537 sysprof_linux_instrument_init (SysprofLinuxInstrument *self)
538 {
539 self->seen = g_hash_table_new (NULL, NULL);
540 }
541
542 SysprofInstrument *
543 _sysprof_linux_instrument_new (void)
544 {
545 return g_object_new (SYSPROF_TYPE_LINUX_INSTRUMENT, NULL);
546 }