Debian Codegraph @

src/libsysprof/sysprof-elf-loader.c

raw
1 /* sysprof-elf-loader.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 <fcntl.h>
24 #include <unistd.h>
25 #include <sys/stat.h>
26
27 #include "sysprof-elf-private.h"
28 #include "sysprof-elf-loader-private.h"
29 #include "sysprof-strings-private.h"
30
31 #define DEFAULT_DEBUG_DIRS SYSPROF_STRV_INIT("/usr/lib/debug", "/app/lib/debug")
32
33 struct _SysprofElfLoader
34 {
35 GObject parent_instance;
36 GHashTable *cache;
37 char **debug_dirs;
38 char **external_debug_dirs;
39 };
40
41 enum {
42 PROP_0,
43 PROP_DEBUG_DIRS,
44 PROP_EXTERNAL_DEBUG_DIRS,
45 N_PROPS
46 };
47
48 G_DEFINE_FINAL_TYPE (SysprofElfLoader, sysprof_elf_loader, G_TYPE_OBJECT)
49
50 static GParamSpec *properties [N_PROPS];
51 static gboolean in_flatpak;
52 static gboolean in_podman;
53
54 SysprofElfLoader *
55 sysprof_elf_loader_new (void)
56 {
57 return g_object_new (SYSPROF_TYPE_ELF_LOADER, NULL);
58 }
59
60 static void
61 _g_object_xunref (gpointer data)
62 {
63 if (data != NULL)
64 g_object_unref (data);
65 }
66
67 static void
68 sysprof_elf_loader_finalize (GObject *object)
69 {
70 SysprofElfLoader *self = (SysprofElfLoader *)object;
71
72 g_clear_pointer (&self->debug_dirs, g_strfreev);
73 g_clear_pointer (&self->external_debug_dirs, g_strfreev);
74 g_clear_pointer (&self->cache, g_hash_table_unref);
75
76 G_OBJECT_CLASS (sysprof_elf_loader_parent_class)->finalize (object);
77 }
78
79 static void
80 sysprof_elf_loader_get_property (GObject *object,
81 guint prop_id,
82 GValue *value,
83 GParamSpec *pspec)
84 {
85 SysprofElfLoader *self = SYSPROF_ELF_LOADER (object);
86
87 switch (prop_id)
88 {
89 case PROP_DEBUG_DIRS:
90 g_value_set_boxed (value, sysprof_elf_loader_get_debug_dirs (self));
91 break;
92
93 case PROP_EXTERNAL_DEBUG_DIRS:
94 g_value_set_boxed (value, sysprof_elf_loader_get_external_debug_dirs (self));
95 break;
96
97 default:
98 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
99 }
100 }
101
102 static void
103 sysprof_elf_loader_set_property (GObject *object,
104 guint prop_id,
105 const GValue *value,
106 GParamSpec *pspec)
107 {
108 SysprofElfLoader *self = SYSPROF_ELF_LOADER (object);
109
110 switch (prop_id)
111 {
112 case PROP_DEBUG_DIRS:
113 sysprof_elf_loader_set_debug_dirs (self, g_value_get_boxed (value));
114 break;
115
116 case PROP_EXTERNAL_DEBUG_DIRS:
117 sysprof_elf_loader_set_external_debug_dirs (self, g_value_get_boxed (value));
118 break;
119
120 default:
121 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
122 }
123 }
124
125 static void
126 sysprof_elf_loader_class_init (SysprofElfLoaderClass *klass)
127 {
128 GObjectClass *object_class = G_OBJECT_CLASS (klass);
129
130 object_class->finalize = sysprof_elf_loader_finalize;
131 object_class->get_property = sysprof_elf_loader_get_property;
132 object_class->set_property = sysprof_elf_loader_set_property;
133
134 properties [PROP_DEBUG_DIRS] =
135 g_param_spec_boxed ("debug-dirs", NULL, NULL,
136 G_TYPE_STRV,
137 (G_PARAM_READWRITE | G_PARAM_EXPLICIT_NOTIFY | G_PARAM_STATIC_STRINGS));
138
139 properties [PROP_EXTERNAL_DEBUG_DIRS] =
140 g_param_spec_boxed ("external-debug-dirs", NULL, NULL,
141 G_TYPE_STRV,
142 (G_PARAM_READWRITE | G_PARAM_EXPLICIT_NOTIFY | G_PARAM_STATIC_STRINGS));
143
144 g_object_class_install_properties (object_class, N_PROPS, properties);
145
146 in_flatpak = g_file_test ("/.flatpak-info", G_FILE_TEST_EXISTS);
147 in_podman = g_file_test ("/run/.containerenv", G_FILE_TEST_EXISTS);
148 }
149
150 static void
151 sysprof_elf_loader_init (SysprofElfLoader *self)
152 {
153 self->debug_dirs = g_strdupv ((char **)DEFAULT_DEBUG_DIRS);
154 self->cache = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, _g_object_xunref);
155 }
156
157 /**
158 * sysprof_elf_loader_get_debug_dirs:
159 * @self: a #SysprofElfLoader
160 *
161 * Gets the #SysprofElfLoader:debug-dirs property.
162 *
163 * See sysprof_elf_loader_set_debug_dirs() for information on how
164 * these directories are used.
165 *
166 * Returns: (nullable): an array of debug directories, or %NULL
167 */
168 const char * const *
169 sysprof_elf_loader_get_debug_dirs (SysprofElfLoader *self)
170 {
171 g_return_val_if_fail (SYSPROF_IS_ELF_LOADER (self), NULL);
172
173 return (const char * const *)self->debug_dirs;
174 }
175
176 /**
177 * sysprof_elf_loader_set_debug_dirs:
178 * @self: a #SysprofElfLoader
179 * @debug_dirs: the new debug directories to use
180 *
181 * Sets the #SysprofElfLoader:debug-dirs prpoerty.
182 *
183 * If @debug_dirs is %NULL, the default debug directories will
184 * be used.
185 *
186 * These directories will be used to resolve debug symbols within
187 * the mount namespace of the process whose symbols are being
188 * resolved.
189 *
190 * To set a global directory that may contain debug symbols, use
191 * sysprof_elf_loader_set_external_debug_dirs() which can be searched
192 * regardless of what mount namespace the resolving process was in.
193 */
194 void
195 sysprof_elf_loader_set_debug_dirs (SysprofElfLoader *self,
196 const char * const *debug_dirs)
197 {
198 g_return_if_fail (SYSPROF_IS_ELF_LOADER (self));
199 g_return_if_fail (self->debug_dirs != NULL);
200
201 if (sysprof_set_strv (&self->debug_dirs, debug_dirs))
202 g_object_notify_by_pspec (G_OBJECT (self), properties [PROP_DEBUG_DIRS]);
203 }
204
205 /**
206 * sysprof_elf_loader_get_external_debug_dirs:
207 * @self: a #SysprofElfLoader
208 *
209 * Gets the #SysprofElfLoader:external-debug-dirs property.
210 *
211 * See sysprof_elf_loader_set_external_debug_dirs() for how this
212 * property is used to locate ELF files.
213 *
214 * Returns: (nullable): an array of external debug directories, or %NULL
215 */
216 const char * const *
217 sysprof_elf_loader_get_external_debug_dirs (SysprofElfLoader *self)
218 {
219 g_return_val_if_fail (SYSPROF_IS_ELF_LOADER (self), NULL);
220
221 return (const char * const *)self->external_debug_dirs;
222 }
223
224 /**
225 * sysprof_elf_loader_set_external_debug_dirs:
226 * @self: a #SysprofElfLoader
227 * @external_debug_dirs: (nullable): array of debug directories to resolve
228 * `.gnu_debuglink` references in ELF files.
229 *
230 * Sets the #SysprofElfLoader:external-debug-dirs property.
231 *
232 * This is used to resolve `.gnu_debuglink` files across any process that is
233 * loading ELF files with this #SysprofElfLoader. That allows for symbolizing
234 * a capture file that was recording on a different system for which the
235 * debug symbols only exist locally.
236 *
237 * Note that this has no effect on stack trace unwinding, that must occur
238 * independently of this, when the samples are recorded by the specific
239 * unwinder in use.
240 */
241 void
242 sysprof_elf_loader_set_external_debug_dirs (SysprofElfLoader *self,
243 const char * const *external_debug_dirs)
244 {
245 g_return_if_fail (SYSPROF_IS_ELF_LOADER (self));
246
247 if (sysprof_set_strv (&self->external_debug_dirs, external_debug_dirs))
248 g_object_notify_by_pspec (G_OBJECT (self), properties [PROP_EXTERNAL_DEBUG_DIRS]);
249 }
250
251 static char *
252 access_path_from_container (const char *path)
253 {
254 if ((in_flatpak && !g_str_has_prefix (path, "/home/")) || in_podman)
255 return g_build_filename ("/var/run/host", path, NULL);
256
257 return NULL;
258 }
259
260 static SysprofElf *
261 get_deepest_debuglink (SysprofElf *elf)
262 {
263 SysprofElf *debug_link = sysprof_elf_get_debug_link_elf (elf);
264 return debug_link ? get_deepest_debuglink (debug_link) : elf;
265 }
266
267 static gboolean
268 try_load_build_id (SysprofElfLoader *self,
269 SysprofMountNamespace *mount_namespace,
270 SysprofElf *elf,
271 const char *build_id,
272 const char *debug_dir)
273 {
274 g_assert (SYSPROF_IS_ELF_LOADER (self));
275 g_assert (!mount_namespace || SYSPROF_IS_MOUNT_NAMESPACE (mount_namespace));
276 g_assert (SYSPROF_IS_ELF (elf));
277
278 if (build_id && build_id[0] && build_id[1])
279 {
280 char prefix[3] = {build_id[0], build_id[1], 0};
281 g_autofree char *build_id_path = g_build_filename (debug_dir, ".build-id", prefix, build_id, NULL);
282 g_autoptr(SysprofElf) debug_link_elf = sysprof_elf_loader_load (self, mount_namespace, build_id_path, build_id, 0, NULL);
283
284 if (debug_link_elf != NULL)
285 {
286 sysprof_elf_set_debug_link_elf (elf, debug_link_elf);
287 return TRUE;
288 }
289 }
290
291 return FALSE;
292 }
293
294 static const char *
295 skip_common_prefix (const char *path,
296 const char *other)
297 {
298 const char *committed = path;
299
300 /* If @path is "/app/bin/foo" and @other is "/app/lib/debug", we want
301 * to return "bin/foo", otherwise "/app/bin/foo".
302 */
303
304 while (*path && *other)
305 {
306 if (*path != *other)
307 break;
308
309 if (*path == '/')
310 committed = path;
311
312 path++;
313 other++;
314 }
315
316 return committed;
317 }
318
319 static void
320 sysprof_elf_loader_annotate (SysprofElfLoader *self,
321 SysprofMountNamespace *mount_namespace,
322 const char *orig_file,
323 SysprofElf *elf,
324 const char *debug_link)
325 {
326 g_assert (SYSPROF_IS_ELF_LOADER (self));
327 g_assert (SYSPROF_IS_MOUNT_NAMESPACE (mount_namespace));
328 g_assert (SYSPROF_IS_ELF (elf));
329 g_assert (debug_link != NULL);
330
331 if (self->debug_dirs != NULL)
332 {
333 for (guint i = 0; self->debug_dirs[i]; i++)
334 {
335 g_autoptr(SysprofElf) debug_link_elf = NULL;
336 g_autofree char *directory_name = NULL;
337 g_autofree char *debug_path = NULL;
338 g_autofree char *short_debug_path = NULL;
339 g_autofree char *shorter_debug_path = NULL;
340 const char *short_directory_name;
341 const char *debug_dir = self->debug_dirs[i];
342 const char *build_id;
343
344 directory_name = g_path_get_dirname (orig_file);
345 build_id = sysprof_elf_get_build_id (elf);
346
347 if (try_load_build_id (self, mount_namespace, elf, build_id, debug_dir))
348 return;
349
350 debug_path = g_build_filename (debug_dir, directory_name, debug_link, NULL);
351 if ((debug_link_elf = sysprof_elf_loader_load (self, mount_namespace, debug_path, build_id, 0, NULL)))
352 {
353 sysprof_elf_set_debug_link_elf (elf, get_deepest_debuglink (debug_link_elf));
354 return;
355 }
356
357 short_directory_name = skip_common_prefix (directory_name, debug_dir);
358 short_debug_path = g_build_filename (debug_dir, short_directory_name, debug_link, NULL);
359 if ((debug_link_elf = sysprof_elf_loader_load (self, mount_namespace, short_debug_path, build_id, 0, NULL)))
360 {
361 sysprof_elf_set_debug_link_elf (elf, get_deepest_debuglink (debug_link_elf));
362 return;
363 }
364 shorter_debug_path = g_build_filename (directory_name, ".debug", debug_link, NULL);
365 if ((debug_link_elf = sysprof_elf_loader_load (self, mount_namespace, shorter_debug_path, build_id, 0, NULL)))
366 {
367 sysprof_elf_set_debug_link_elf (elf, get_deepest_debuglink (debug_link_elf));
368 return;
369 }
370 }
371 }
372
373 if (self->external_debug_dirs != NULL)
374 {
375 for (guint i = 0; self->external_debug_dirs[i]; i++)
376 {
377 g_autoptr(SysprofElf) debug_link_elf = NULL;
378 g_autofree char *directory_name = NULL;
379 g_autofree char *debug_path = NULL;
380 const char *debug_dir = self->external_debug_dirs[i];
381 const char *build_id;
382
383 directory_name = g_path_get_dirname (orig_file);
384 debug_path = g_build_filename (debug_dir, directory_name, debug_link, NULL);
385 build_id = sysprof_elf_get_build_id (elf);
386
387 if (try_load_build_id (self, NULL, elf, build_id, debug_dir))
388 return;
389
390 if ((debug_link_elf = sysprof_elf_loader_load (self, NULL, debug_path, build_id, 0, NULL)))
391 {
392 sysprof_elf_set_debug_link_elf (elf, get_deepest_debuglink (debug_link_elf));
393 return;
394 }
395 }
396 }
397 }
398
399 static gboolean
400 get_file_and_inode (const char *path,
401 GMappedFile **mapped_file,
402 guint64 *file_inode)
403 {
404 struct stat stbuf;
405 int fd;
406
407 g_assert (path != NULL);
408 g_assert (mapped_file != NULL);
409 g_assert (file_inode != NULL);
410
411 *mapped_file = NULL;
412 *file_inode = 0;
413
414 fd = open (path, O_RDONLY|O_CLOEXEC, 0);
415 if (fd == -1)
416 return FALSE;
417
418 if (fstat (fd, &stbuf) == 0)
419 *file_inode = (guint64)stbuf.st_ino;
420 *mapped_file = g_mapped_file_new_from_fd (fd, FALSE, NULL);
421 close (fd);
422
423 return *mapped_file != NULL;
424 }
425
426 /**
427 * sysprof_elf_loader_load:
428 * @self: a #SysprofElfLoader
429 * @mount_namespace: a #SysprofMountNamespace for path resolving
430 * @file: the path of the file to load within the mount namespace
431 * @build_id: (nullable): an optional build-id that can be used to resolve
432 * the file alternatively to the file path
433 * @file_inode: expected inode for @file
434 * @error: a location for a #GError, or %NULL
435 *
436 * Attempts to load a #SysprofElf for @file (or optionally by @build_id).
437 *
438 * This attempts to follow `.gnu_debuglink` ELF section headers and attach
439 * them to the resulting #SysprofElf so that additional symbol information
440 * is available.
441 *
442 * Returns: (transfer full): a #SysprofElf, or %NULL if the file could
443 * not be resolved.
444 */
445 SysprofElf *
446 sysprof_elf_loader_load (SysprofElfLoader *self,
447 SysprofMountNamespace *mount_namespace,
448 const char *file,
449 const char *build_id,
450 guint64 file_inode,
451 GError **error)
452 {
453 const char * const fallback_paths[2] = { file, NULL };
454 g_auto(GStrv) paths = NULL;
455
456 g_return_val_if_fail (SYSPROF_IS_ELF_LOADER (self), NULL);
457 g_return_val_if_fail (!mount_namespace || SYSPROF_IS_MOUNT_NAMESPACE (mount_namespace), NULL);
458
459 /* We must translate the file into a number of paths that may possibly
460 * locate the file in the case that there are overlays in the mount
461 * namespace. Each of the paths could be in a lower overlay layer.
462 *
463 * To allow for zero-translation, we allow a NULL mount namespace.
464 * sysprof_elf_loader_annotate() will use that to load from external
465 * directories for which on additional translation is necessary.
466 */
467 if (mount_namespace == NULL)
468 paths = g_strdupv ((char **)fallback_paths);
469 else
470 paths = sysprof_mount_namespace_translate (mount_namespace, file);
471
472 if (paths == NULL)
473 goto failure;
474
475 for (guint i = 0; paths[i]; i++)
476 {
477 g_autoptr(GMappedFile) mapped_file = NULL;
478 g_autoptr(SysprofElf) elf = NULL;
479 g_autoptr(GError) local_error = NULL;
480 g_autofree char *container_path = NULL;
481 SysprofElf *cached_elf = NULL;
482 const char *path = paths[i];
483 const char *debug_link;
484 guint64 mapped_file_inode;
485
486 if (path[0] == 0)
487 continue;
488
489 if (in_flatpak || in_podman)
490 {
491 if ((container_path = access_path_from_container (path)))
492 path = container_path;
493 }
494
495 /* Lookup to see if we've already parsed this ELF and handle cases where
496 * we've failed to load it too. In the case we failed to load a key is
497 * stored in the cache with a NULL value.
498 */
499 if (g_hash_table_lookup_extended (self->cache, path, NULL, (gpointer *)&cached_elf))
500 {
501 if (cached_elf != NULL)
502 {
503 if (sysprof_elf_matches (cached_elf, file_inode, build_id))
504 return g_object_ref (cached_elf);
505 }
506
507 continue;
508 }
509
510 /* Try to mmap the file and parse it. If the parser fails to parse the
511 * section headers, then this probably isn't an ELF file and we should
512 * store a failure record in the cache so that we don't attempt to load
513 * it again.
514 */
515 if (get_file_and_inode (path, &mapped_file, &mapped_file_inode))
516 elf = sysprof_elf_new (path, g_steal_pointer (&mapped_file), mapped_file_inode, &local_error);
517
518 g_hash_table_insert (self->cache,
519 g_strdup (path),
520 elf ? g_object_ref (elf) : NULL);
521
522 if (elf != NULL)
523 {
524 if (mount_namespace && (debug_link = sysprof_elf_get_debug_link (elf)))
525 sysprof_elf_loader_annotate (self, mount_namespace, file, elf, debug_link);
526
527 /* If we loaded the ELF, but it doesn't match what this request is looking
528 * for in terms of inode/build-id, then we need to bail and not return it.
529 * We can, however, leave it in the cache in-case another process/sample
530 * will need the ELF.
531 */
532 if (!sysprof_elf_matches (elf, file_inode, build_id))
533 g_clear_object (&elf);
534 }
535
536 if (elf != NULL)
537 return g_steal_pointer (&elf);
538 }
539
540 failure:
541 if (error != NULL)
542 g_set_error_literal (error,
543 G_FILE_ERROR,
544 G_FILE_ERROR_NOENT,
545 "Failed to locate file");
546
547 return NULL;
548 }