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