xref: /linux/tools/perf/util/unwind-libdw.c (revision d8fd56321d7bb5df31cdf33e9acbd62f4606b483)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <assert.h>
3 #include <linux/compiler.h>
4 #include <elfutils/libdw.h>
5 #include <elfutils/libdwfl.h>
6 #include <inttypes.h>
7 #include <byteswap.h>
8 #include <errno.h>
9 #include "debug.h"
10 #include "dso.h"
11 #include <dwarf-regs.h>
12 #include "unwind.h"
13 #include "unwind-libdw.h"
14 #include "machine.h"
15 #include "map.h"
16 #include "symbol.h"
17 #include "thread.h"
18 #include <linux/types.h>
19 #include <linux/zalloc.h>
20 #include "event.h"
21 #include "evsel.h"
22 #include "memswap.h"
23 #include "perf_regs.h"
24 #include "callchain.h"
25 #include "util/env.h"
26 
27 /*
28  * The dwfl thread argument passed to functions like memory_read. Memory has to
29  * be allocated to persist of multiple uses of the dwfl.
30  */
31 struct dwfl_ui_thread_info {
32 	/* Back link to the dwfl. */
33 	Dwfl *dwfl;
34 	/* The current unwind info, only 1 is supported. */
35 	struct unwind_info *ui;
36 };
37 
38 static char *debuginfo_path;
39 
40 static int __find_debuginfo(Dwfl_Module *mod __maybe_unused, void **userdata,
41 			    const char *modname __maybe_unused, Dwarf_Addr base __maybe_unused,
42 			    const char *file_name, const char *debuglink_file __maybe_unused,
43 			    GElf_Word debuglink_crc __maybe_unused, char **debuginfo_file_name)
44 {
45 	const struct dso *dso = *userdata;
46 
47 	assert(dso);
48 	mutex_lock(dso__lock((struct dso *)dso));
49 	if (dso__symsrc_filename(dso) && strcmp(file_name, dso__symsrc_filename(dso)))
50 		*debuginfo_file_name = strdup(dso__symsrc_filename(dso));
51 	mutex_unlock(dso__lock((struct dso *)dso));
52 	return -1;
53 }
54 
55 void libdw__invalidate_dwfl(struct maps *maps, void *arg)
56 {
57 	struct dwfl_ui_thread_info *dwfl_ui_ti = arg;
58 
59 	if (!dwfl_ui_ti)
60 		return;
61 
62 	assert(dwfl_ui_ti->ui == NULL);
63 	maps__set_libdw_addr_space_dwfl(maps, NULL);
64 	dwfl_end(dwfl_ui_ti->dwfl);
65 	free(dwfl_ui_ti);
66 }
67 
68 static const Dwfl_Callbacks offline_callbacks = {
69 	.find_debuginfo		= __find_debuginfo,
70 	.debuginfo_path		= &debuginfo_path,
71 	.section_address	= dwfl_offline_section_address,
72 	// .find_elf is not set as we use dwfl_report_elf() instead.
73 };
74 
75 static int __report_module(struct addr_location *al, u64 ip,
76 			    struct unwind_info *ui)
77 {
78 	Dwfl_Module *mod;
79 	struct dso *dso = NULL;
80 	Dwarf_Addr base;
81 	/*
82 	 * Some callers will use al->sym, so we can't just use the
83 	 * cheaper thread__find_map() here.
84 	 */
85 	thread__find_symbol(ui->thread, PERF_RECORD_MISC_USER, ip, al);
86 
87 	if (al->map)
88 		dso = map__dso(al->map);
89 
90 	if (!dso)
91 		return 0;
92 
93 	/*
94 	 * The generated JIT DSO files only map the code segment without
95 	 * ELF headers.  Since JIT codes used to be packed in a memory
96 	 * segment, calculating the base address using pgoff falls into
97 	 * a different code in another DSO.  So just use the map->start
98 	 * directly to pick the correct one.
99 	 */
100 	if (!strncmp(dso__long_name(dso), "/tmp/jitted-", 12))
101 		base = map__start(al->map);
102 	else
103 		base = map__start(al->map) - map__pgoff(al->map);
104 
105 	mod = dwfl_addrmodule(ui->dwfl, ip);
106 	if (mod) {
107 		Dwarf_Addr s;
108 
109 		dwfl_module_info(mod, NULL, &s, NULL, NULL, NULL, NULL, NULL);
110 		if (s != base)
111 			mod = NULL;
112 	}
113 
114 	if (!mod) {
115 		char filename[PATH_MAX];
116 
117 		__symbol__join_symfs(filename, sizeof(filename), dso__long_name(dso));
118 		/* Don't hang up on device files like /dev/dri/renderD128. */
119 		if (is_regular_file(filename)) {
120 			mod = dwfl_report_elf(ui->dwfl, dso__short_name(dso), filename, -1,
121 					      base, false);
122 		}
123 	}
124 	if (!mod) {
125 		char filename[PATH_MAX];
126 
127 		if (dso__build_id_filename(dso, filename, sizeof(filename), false))
128 			mod = dwfl_report_elf(ui->dwfl, dso__short_name(dso), filename, -1,
129 					      base, false);
130 	}
131 
132 	if (mod) {
133 		void **userdatap;
134 
135 		dwfl_module_info(mod, &userdatap, NULL, NULL, NULL, NULL, NULL, NULL);
136 		*userdatap = dso;
137 	}
138 
139 	return mod && dwfl_addrmodule(ui->dwfl, ip) == mod ? 0 : -1;
140 }
141 
142 static int report_module(u64 ip, struct unwind_info *ui)
143 {
144 	struct addr_location al;
145 	int res;
146 
147 	addr_location__init(&al);
148 	res = __report_module(&al, ip, ui);
149 	addr_location__exit(&al);
150 	return res;
151 }
152 
153 /*
154  * Store all entries within entries array,
155  * we will process it after we finish unwind.
156  */
157 static int entry(u64 ip, struct unwind_info *ui)
158 
159 {
160 	struct unwind_entry *e = &ui->entries[ui->idx++];
161 	struct addr_location al;
162 
163 	addr_location__init(&al);
164 	if (__report_module(&al, ip, ui)) {
165 		addr_location__exit(&al);
166 		return -1;
167 	}
168 
169 	e->ip	  = ip;
170 	e->ms.thread = thread__get(al.thread);
171 	e->ms.map = map__get(al.map);
172 	e->ms.sym = al.sym;
173 
174 	pr_debug("unwind: %s:ip = 0x%" PRIx64 " (0x%" PRIx64 ")\n",
175 		 al.sym ? al.sym->name : "''",
176 		 ip,
177 		 al.map ? map__map_ip(al.map, ip) : (u64) 0);
178 	addr_location__exit(&al);
179 	return 0;
180 }
181 
182 static pid_t next_thread(Dwfl *dwfl __maybe_unused, void *arg, void **thread_argp)
183 {
184 	struct dwfl_ui_thread_info *dwfl_ui_ti = arg;
185 
186 	/* We want only single thread to be processed. */
187 	if (*thread_argp != NULL)
188 		return 0;
189 
190 	assert(dwfl_ui_ti->ui != NULL);
191 	*thread_argp = arg;
192 	return thread__tid(dwfl_ui_ti->ui->thread);
193 }
194 
195 static bool get_thread(Dwfl *dwfl __maybe_unused, pid_t tid, void *arg,
196 		       void **thread_argp)
197 {
198 	struct dwfl_ui_thread_info *dwfl_ui_ti = arg;
199 
200 	assert(dwfl_ui_ti->ui != NULL);
201 	if (tid != thread__tid(dwfl_ui_ti->ui->thread))
202 		return false;
203 
204 	*thread_argp = arg;
205 	return true;
206 }
207 
208 static int access_dso_mem(struct unwind_info *ui, Dwarf_Addr addr,
209 			  Dwarf_Word *data, size_t len)
210 {
211 	struct addr_location al;
212 	union u64_swap u;
213 	ssize_t size;
214 	struct dso *dso;
215 
216 	addr_location__init(&al);
217 	if (!thread__find_map(ui->thread, PERF_RECORD_MISC_USER, addr, &al)) {
218 		pr_debug("unwind: no map for %lx\n", (unsigned long)addr);
219 		goto out_fail;
220 	}
221 	dso = map__dso(al.map);
222 	if (!dso)
223 		goto out_fail;
224 
225 	size = dso__data_read_addr(dso, al.map, ui->machine, addr, (u8 *)&u, len);
226 
227 	addr_location__exit(&al);
228 	if (size != (ssize_t)len)
229 		return 1;
230 	*data = len == sizeof(u32) ? u.val32[0] : u.val64;
231 	return 0;
232 out_fail:
233 	addr_location__exit(&al);
234 	return -1;
235 }
236 
237 /*
238  * libdw expects a 32-bit task's words zero-extended.  A recording of the
239  * other byte order was swapped in 8-byte units when it was read (see
240  * perf_event__all64_swap()), so a 4-byte word is picked out of its unit with
241  * that swap undone, as for PERF_SAMPLE_CPU in __evsel__parse_sample().
242  */
243 static Dwarf_Word stack_word(struct stack_dump *stack, int offset, size_t len,
244 			     bool swapped)
245 {
246 	union u64_swap u;
247 
248 	if (len == sizeof(u64))
249 		return *(Dwarf_Word *)&stack->data[offset];
250 	if (!swapped)
251 		return *(u32 *)&stack->data[offset];
252 
253 	u.val64 = bswap_64(*(u64 *)&stack->data[offset & ~7]);
254 	return bswap_32(u.val32[(offset & 4) / 4]);
255 }
256 
257 static bool memory_read(Dwfl *dwfl __maybe_unused, Dwarf_Addr addr, Dwarf_Word *result,
258 			void *arg)
259 {
260 	struct dwfl_ui_thread_info *dwfl_ui_ti = arg;
261 	struct unwind_info *ui = dwfl_ui_ti->ui;
262 	struct stack_dump *stack = &ui->sample->user_stack;
263 	u64 start, end;
264 	bool swapped;
265 	size_t len;
266 	int offset;
267 	int ret;
268 
269 	if (!ui->sample->user_regs)
270 		return false;
271 	len = ui->sample->user_regs->abi == PERF_SAMPLE_REGS_ABI_32 ?
272 	      sizeof(u32) : sizeof(u64);
273 	swapped = ui->sample->evsel && ui->sample->evsel->needs_swap;
274 
275 	ret = perf_reg_value(&start, ui->sample->user_regs,
276 			     perf_arch_reg_sp(ui->e_machine));
277 	if (ret)
278 		return false;
279 
280 	end = start + stack->size;
281 
282 	/* Check overflow. */
283 	if (addr + len < addr)
284 		return false;
285 
286 	if (addr < start || addr + len > end) {
287 		ret = access_dso_mem(ui, addr, result, len);
288 		if (ret) {
289 			pr_debug("unwind: access_mem 0x%" PRIx64 " not inside range"
290 				 " 0x%" PRIx64 "-0x%" PRIx64 "\n",
291 				addr, start, end);
292 			return false;
293 		}
294 		return true;
295 	}
296 
297 	offset  = addr - start;
298 	*result = stack_word(stack, offset, len, swapped);
299 	pr_debug("unwind: access_mem addr 0x%" PRIx64 ", val %lx, offset %d\n",
300 		 addr, (unsigned long)*result, offset);
301 	return true;
302 }
303 
304 static bool libdw_set_initial_registers(Dwfl_Thread *thread, void *arg)
305 {
306 	struct dwfl_ui_thread_info *dwfl_ui_ti = arg;
307 	struct unwind_info *ui = dwfl_ui_ti->ui;
308 	struct regs_dump *user_regs = perf_sample__user_regs(ui->sample);
309 	Dwarf_Word *dwarf_regs;
310 	int max_dwarf_reg = 0;
311 	bool ret;
312 	uint16_t e_machine = ui->e_machine;
313 	int e_flags = ui->e_flags;
314 	uint64_t ip_perf_reg = perf_arch_reg_ip(e_machine);
315 	Dwarf_Word val = 0;
316 
317 
318 	/*
319 	 * For every possible perf register in the bitmap determine the dwarf
320 	 * register and use to compute the max.
321 	 */
322 	for (int perf_reg = 0; perf_reg < 64; perf_reg++) {
323 		if (user_regs->mask & (1ULL << perf_reg)) {
324 			int dwarf_reg =
325 				get_dwarf_regnum_for_perf_regnum(perf_reg, e_machine,
326 								 e_flags,
327 								 /*only_libdw_supported=*/true,
328 								 user_regs->abi);
329 			if (dwarf_reg > max_dwarf_reg)
330 				max_dwarf_reg = dwarf_reg;
331 		}
332 	}
333 
334 	dwarf_regs = calloc(max_dwarf_reg + 1, sizeof(*dwarf_regs));
335 	if (!dwarf_regs)
336 		return false;
337 
338 	for (int perf_reg = 0; perf_reg < 64; perf_reg++) {
339 		if (user_regs->mask & (1ULL << perf_reg)) {
340 			int dwarf_reg =
341 				get_dwarf_regnum_for_perf_regnum(perf_reg, e_machine,
342 								 e_flags,
343 								 /*only_libdw_supported=*/true,
344 								 user_regs->abi);
345 			if (dwarf_reg >= 0) {
346 				val = 0;
347 				if (perf_reg_value(&val, user_regs, perf_reg) == 0)
348 					dwarf_regs[dwarf_reg] = val;
349 			}
350 		}
351 	}
352 	if (perf_reg_value(&val, user_regs, ip_perf_reg) == 0)
353 		dwfl_thread_state_register_pc(thread, val);
354 
355 	ret = dwfl_thread_state_registers(thread, 0, max_dwarf_reg + 1, dwarf_regs);
356 	free(dwarf_regs);
357 	return ret;
358 }
359 
360 static const Dwfl_Thread_Callbacks callbacks = {
361 	.next_thread           = next_thread,
362 	.get_thread            = get_thread,
363 	.memory_read           = memory_read,
364 	.set_initial_registers = libdw_set_initial_registers,
365 };
366 
367 static int
368 frame_callback(Dwfl_Frame *state, void *arg)
369 {
370 	struct unwind_info *ui = arg;
371 	Dwarf_Addr pc;
372 	bool isactivation;
373 
374 	if (!dwfl_frame_pc(state, &pc, NULL)) {
375 		if (!ui->best_effort)
376 			pr_err("%s", dwfl_errmsg(-1));
377 		return DWARF_CB_ABORT;
378 	}
379 
380 	// report the module before we query for isactivation
381 	report_module(pc, ui);
382 
383 	if (!dwfl_frame_pc(state, &pc, &isactivation)) {
384 		if (!ui->best_effort)
385 			pr_err("%s", dwfl_errmsg(-1));
386 		return DWARF_CB_ABORT;
387 	}
388 
389 	if (!isactivation)
390 		--pc;
391 
392 	return entry(pc, ui) || !(--ui->max_stack) ?
393 	       DWARF_CB_ABORT : DWARF_CB_OK;
394 }
395 
396 int libdw__get_entries(unwind_entry_cb_t cb, void *arg,
397 			struct thread *thread,
398 			struct perf_sample *data,
399 			int max_stack,
400 			bool best_effort)
401 {
402 	struct maps *maps = thread__maps(thread);
403 	struct machine *machine = maps__machine(maps);
404 	uint32_t e_flags = 0;
405 	uint16_t e_machine = thread__e_machine(thread, machine, &e_flags);
406 	struct dwfl_ui_thread_info *dwfl_ui_ti;
407 	static struct unwind_info *ui;
408 	Dwfl *dwfl;
409 	Dwarf_Word ip;
410 	int err = -EINVAL, i, entries;
411 
412 	if (!data->user_regs || !data->user_regs->regs)
413 		return 0;
414 
415 	ui = zalloc(sizeof(*ui) + sizeof(ui->entries[0]) * max_stack);
416 	if (!ui)
417 		return -ENOMEM;
418 
419 	*ui = (struct unwind_info){
420 		.sample		= data,
421 		.thread		= thread,
422 		.machine	= machine,
423 		.cb		= cb,
424 		.arg		= arg,
425 		.max_stack	= max_stack,
426 		.e_machine	= e_machine,
427 		.e_flags	= e_flags,
428 		.best_effort    = best_effort
429 	};
430 
431 	dwfl_ui_ti = maps__libdw_addr_space_dwfl(maps);
432 	if (dwfl_ui_ti) {
433 		dwfl = dwfl_ui_ti->dwfl;
434 	} else {
435 		dwfl_ui_ti = zalloc(sizeof(*dwfl_ui_ti));
436 		if (!dwfl_ui_ti) {
437 			free(ui);
438 			return -ENOMEM;
439 		}
440 
441 		dwfl = dwfl_begin(&offline_callbacks);
442 		if (!dwfl)
443 			goto out;
444 
445 		dwfl_ui_ti->dwfl = dwfl;
446 		maps__set_libdw_addr_space_dwfl(maps, dwfl_ui_ti);
447 	}
448 	assert(dwfl_ui_ti->ui == NULL);
449 	assert(dwfl_ui_ti->dwfl == dwfl);
450 	assert(dwfl_ui_ti == maps__libdw_addr_space_dwfl(maps));
451 	dwfl_ui_ti->ui = ui;
452 	ui->dwfl = dwfl;
453 
454 	err = perf_reg_value(&ip, data->user_regs, perf_arch_reg_ip(e_machine));
455 	if (err)
456 		goto out;
457 
458 	err = report_module(ip, ui);
459 	if (err)
460 		goto out;
461 
462 	dwfl_attach_state(dwfl, /*elf=*/NULL, thread__pid(thread), &callbacks,
463 			  /* Dwfl thread function argument*/dwfl_ui_ti);
464 	// Ignore thread already attached error.
465 
466 	err = dwfl_getthread_frames(dwfl, thread__tid(thread), frame_callback,
467 				    /* Dwfl frame function argument*/ui);
468 
469 	if (err && ui->max_stack != max_stack)
470 		err = 0;
471 
472 	/*
473 	 * Display what we got based on the order setup.
474 	 */
475 	for (i = 0; i < ui->idx && !err; i++) {
476 		int j = i;
477 
478 		if (callchain_param.order == ORDER_CALLER)
479 			j = ui->idx - i - 1;
480 
481 		err = ui->entries[j].ip ? ui->cb(&ui->entries[j], ui->arg) : 0;
482 	}
483 
484  out:
485 	if (err)
486 		pr_debug("unwind: failed with '%s'\n", dwfl_errmsg(-1));
487 
488 	for (i = 0; i < ui->idx; i++)
489 		map_symbol__exit(&ui->entries[i].ms);
490 
491 	dwfl_ui_ti->ui = NULL;
492 	entries = (int)ui->idx;
493 	free(ui);
494 	/*
495 	 * Unwinder return contract:
496 	 *  > 0 : unwinding succeeded (stops fallback). If we found frames but hit an error
497 	 *        (e.g. truncated stack), report success to preserve existing frames.
498 	 *    0 : unwinding failed without yielding frames. Ignore non-fatal errors
499 	 *        (e.g. missing debug info, DWARF corruption) to allow fallback unwinder or
500 	 *        kernel callchain resolution to proceed.
501 	 *  < 0 : fatal error (e.g. -ENOMEM). Aborts unwinding entirely.
502 	 */
503 	if (err)
504 		return (err == -ENOMEM) ? -ENOMEM : (entries > 0 ? 1 : 0);
505 	return entries;
506 }
507