xref: /openbmc/linux/tools/perf/util/probe-finder.c (revision 547840bd)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * probe-finder.c : C expression to kprobe event converter
4  *
5  * Written by Masami Hiramatsu <mhiramat@redhat.com>
6  */
7 
8 #include <inttypes.h>
9 #include <sys/utsname.h>
10 #include <sys/types.h>
11 #include <sys/stat.h>
12 #include <fcntl.h>
13 #include <errno.h>
14 #include <stdio.h>
15 #include <unistd.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #include <stdarg.h>
19 #include <dwarf-regs.h>
20 
21 #include <linux/bitops.h>
22 #include <linux/zalloc.h>
23 #include "event.h"
24 #include "dso.h"
25 #include "debug.h"
26 #include "intlist.h"
27 #include "strbuf.h"
28 #include "strlist.h"
29 #include "symbol.h"
30 #include "probe-finder.h"
31 #include "probe-file.h"
32 #include "string2.h"
33 
34 /* Kprobe tracer basic type is up to u64 */
35 #define MAX_BASIC_TYPE_BITS	64
36 
37 /* Dwarf FL wrappers */
38 static char *debuginfo_path;	/* Currently dummy */
39 
40 static const Dwfl_Callbacks offline_callbacks = {
41 	.find_debuginfo = dwfl_standard_find_debuginfo,
42 	.debuginfo_path = &debuginfo_path,
43 
44 	.section_address = dwfl_offline_section_address,
45 
46 	/* We use this table for core files too.  */
47 	.find_elf = dwfl_build_id_find_elf,
48 };
49 
50 /* Get a Dwarf from offline image */
51 static int debuginfo__init_offline_dwarf(struct debuginfo *dbg,
52 					 const char *path)
53 {
54 	int fd;
55 
56 	fd = open(path, O_RDONLY);
57 	if (fd < 0)
58 		return fd;
59 
60 	dbg->dwfl = dwfl_begin(&offline_callbacks);
61 	if (!dbg->dwfl)
62 		goto error;
63 
64 	dwfl_report_begin(dbg->dwfl);
65 	dbg->mod = dwfl_report_offline(dbg->dwfl, "", "", fd);
66 	if (!dbg->mod)
67 		goto error;
68 
69 	dbg->dbg = dwfl_module_getdwarf(dbg->mod, &dbg->bias);
70 	if (!dbg->dbg)
71 		goto error;
72 
73 	dwfl_report_end(dbg->dwfl, NULL, NULL);
74 
75 	return 0;
76 error:
77 	if (dbg->dwfl)
78 		dwfl_end(dbg->dwfl);
79 	else
80 		close(fd);
81 	memset(dbg, 0, sizeof(*dbg));
82 
83 	return -ENOENT;
84 }
85 
86 static struct debuginfo *__debuginfo__new(const char *path)
87 {
88 	struct debuginfo *dbg = zalloc(sizeof(*dbg));
89 	if (!dbg)
90 		return NULL;
91 
92 	if (debuginfo__init_offline_dwarf(dbg, path) < 0)
93 		zfree(&dbg);
94 	if (dbg)
95 		pr_debug("Open Debuginfo file: %s\n", path);
96 	return dbg;
97 }
98 
99 enum dso_binary_type distro_dwarf_types[] = {
100 	DSO_BINARY_TYPE__FEDORA_DEBUGINFO,
101 	DSO_BINARY_TYPE__UBUNTU_DEBUGINFO,
102 	DSO_BINARY_TYPE__OPENEMBEDDED_DEBUGINFO,
103 	DSO_BINARY_TYPE__BUILDID_DEBUGINFO,
104 	DSO_BINARY_TYPE__MIXEDUP_UBUNTU_DEBUGINFO,
105 	DSO_BINARY_TYPE__NOT_FOUND,
106 };
107 
108 struct debuginfo *debuginfo__new(const char *path)
109 {
110 	enum dso_binary_type *type;
111 	char buf[PATH_MAX], nil = '\0';
112 	struct dso *dso;
113 	struct debuginfo *dinfo = NULL;
114 
115 	/* Try to open distro debuginfo files */
116 	dso = dso__new(path);
117 	if (!dso)
118 		goto out;
119 
120 	for (type = distro_dwarf_types;
121 	     !dinfo && *type != DSO_BINARY_TYPE__NOT_FOUND;
122 	     type++) {
123 		if (dso__read_binary_type_filename(dso, *type, &nil,
124 						   buf, PATH_MAX) < 0)
125 			continue;
126 		dinfo = __debuginfo__new(buf);
127 	}
128 	dso__put(dso);
129 
130 out:
131 	/* if failed to open all distro debuginfo, open given binary */
132 	return dinfo ? : __debuginfo__new(path);
133 }
134 
135 void debuginfo__delete(struct debuginfo *dbg)
136 {
137 	if (dbg) {
138 		if (dbg->dwfl)
139 			dwfl_end(dbg->dwfl);
140 		free(dbg);
141 	}
142 }
143 
144 /*
145  * Probe finder related functions
146  */
147 
148 static struct probe_trace_arg_ref *alloc_trace_arg_ref(long offs)
149 {
150 	struct probe_trace_arg_ref *ref;
151 	ref = zalloc(sizeof(struct probe_trace_arg_ref));
152 	if (ref != NULL)
153 		ref->offset = offs;
154 	return ref;
155 }
156 
157 /*
158  * Convert a location into trace_arg.
159  * If tvar == NULL, this just checks variable can be converted.
160  * If fentry == true and vr_die is a parameter, do huristic search
161  * for the location fuzzed by function entry mcount.
162  */
163 static int convert_variable_location(Dwarf_Die *vr_die, Dwarf_Addr addr,
164 				     Dwarf_Op *fb_ops, Dwarf_Die *sp_die,
165 				     unsigned int machine,
166 				     struct probe_trace_arg *tvar)
167 {
168 	Dwarf_Attribute attr;
169 	Dwarf_Addr tmp = 0;
170 	Dwarf_Op *op;
171 	size_t nops;
172 	unsigned int regn;
173 	Dwarf_Word offs = 0;
174 	bool ref = false;
175 	const char *regs;
176 	int ret, ret2 = 0;
177 
178 	if (dwarf_attr(vr_die, DW_AT_external, &attr) != NULL)
179 		goto static_var;
180 
181 	/* Constant value */
182 	if (dwarf_attr(vr_die, DW_AT_const_value, &attr) &&
183 	    immediate_value_is_supported()) {
184 		Dwarf_Sword snum;
185 
186 		dwarf_formsdata(&attr, &snum);
187 		ret = asprintf(&tvar->value, "\\%ld", (long)snum);
188 
189 		return ret < 0 ? -ENOMEM : 0;
190 	}
191 
192 	/* TODO: handle more than 1 exprs */
193 	if (dwarf_attr(vr_die, DW_AT_location, &attr) == NULL)
194 		return -EINVAL;	/* Broken DIE ? */
195 	if (dwarf_getlocation_addr(&attr, addr, &op, &nops, 1) <= 0) {
196 		ret = dwarf_entrypc(sp_die, &tmp);
197 		if (ret)
198 			return -ENOENT;
199 
200 		if (probe_conf.show_location_range &&
201 			(dwarf_tag(vr_die) == DW_TAG_variable)) {
202 			ret2 = -ERANGE;
203 		} else if (addr != tmp ||
204 			dwarf_tag(vr_die) != DW_TAG_formal_parameter) {
205 			return -ENOENT;
206 		}
207 
208 		ret = dwarf_highpc(sp_die, &tmp);
209 		if (ret)
210 			return -ENOENT;
211 		/*
212 		 * This is fuzzed by fentry mcount. We try to find the
213 		 * parameter location at the earliest address.
214 		 */
215 		for (addr += 1; addr <= tmp; addr++) {
216 			if (dwarf_getlocation_addr(&attr, addr, &op,
217 						   &nops, 1) > 0)
218 				goto found;
219 		}
220 		return -ENOENT;
221 	}
222 found:
223 	if (nops == 0)
224 		/* TODO: Support const_value */
225 		return -ENOENT;
226 
227 	if (op->atom == DW_OP_addr) {
228 static_var:
229 		if (!tvar)
230 			return ret2;
231 		/* Static variables on memory (not stack), make @varname */
232 		ret = strlen(dwarf_diename(vr_die));
233 		tvar->value = zalloc(ret + 2);
234 		if (tvar->value == NULL)
235 			return -ENOMEM;
236 		snprintf(tvar->value, ret + 2, "@%s", dwarf_diename(vr_die));
237 		tvar->ref = alloc_trace_arg_ref((long)offs);
238 		if (tvar->ref == NULL)
239 			return -ENOMEM;
240 		return ret2;
241 	}
242 
243 	/* If this is based on frame buffer, set the offset */
244 	if (op->atom == DW_OP_fbreg) {
245 		if (fb_ops == NULL)
246 			return -ENOTSUP;
247 		ref = true;
248 		offs = op->number;
249 		op = &fb_ops[0];
250 	}
251 
252 	if (op->atom >= DW_OP_breg0 && op->atom <= DW_OP_breg31) {
253 		regn = op->atom - DW_OP_breg0;
254 		offs += op->number;
255 		ref = true;
256 	} else if (op->atom >= DW_OP_reg0 && op->atom <= DW_OP_reg31) {
257 		regn = op->atom - DW_OP_reg0;
258 	} else if (op->atom == DW_OP_bregx) {
259 		regn = op->number;
260 		offs += op->number2;
261 		ref = true;
262 	} else if (op->atom == DW_OP_regx) {
263 		regn = op->number;
264 	} else {
265 		pr_debug("DW_OP %x is not supported.\n", op->atom);
266 		return -ENOTSUP;
267 	}
268 
269 	if (!tvar)
270 		return ret2;
271 
272 	regs = get_dwarf_regstr(regn, machine);
273 	if (!regs) {
274 		/* This should be a bug in DWARF or this tool */
275 		pr_warning("Mapping for the register number %u "
276 			   "missing on this architecture.\n", regn);
277 		return -ENOTSUP;
278 	}
279 
280 	tvar->value = strdup(regs);
281 	if (tvar->value == NULL)
282 		return -ENOMEM;
283 
284 	if (ref) {
285 		tvar->ref = alloc_trace_arg_ref((long)offs);
286 		if (tvar->ref == NULL)
287 			return -ENOMEM;
288 	}
289 	return ret2;
290 }
291 
292 #define BYTES_TO_BITS(nb)	((nb) * BITS_PER_LONG / sizeof(long))
293 
294 static int convert_variable_type(Dwarf_Die *vr_die,
295 				 struct probe_trace_arg *tvar,
296 				 const char *cast, bool user_access)
297 {
298 	struct probe_trace_arg_ref **ref_ptr = &tvar->ref;
299 	Dwarf_Die type;
300 	char buf[16];
301 	char sbuf[STRERR_BUFSIZE];
302 	int bsize, boffs, total;
303 	int ret;
304 	char prefix;
305 
306 	/* TODO: check all types */
307 	if (cast && strcmp(cast, "string") != 0 && strcmp(cast, "ustring") &&
308 	    strcmp(cast, "x") != 0 &&
309 	    strcmp(cast, "s") != 0 && strcmp(cast, "u") != 0) {
310 		/* Non string type is OK */
311 		/* and respect signedness/hexadecimal cast */
312 		tvar->type = strdup(cast);
313 		return (tvar->type == NULL) ? -ENOMEM : 0;
314 	}
315 
316 	bsize = dwarf_bitsize(vr_die);
317 	if (bsize > 0) {
318 		/* This is a bitfield */
319 		boffs = dwarf_bitoffset(vr_die);
320 		total = dwarf_bytesize(vr_die);
321 		if (boffs < 0 || total < 0)
322 			return -ENOENT;
323 		ret = snprintf(buf, 16, "b%d@%d/%zd", bsize, boffs,
324 				BYTES_TO_BITS(total));
325 		goto formatted;
326 	}
327 
328 	if (die_get_real_type(vr_die, &type) == NULL) {
329 		pr_warning("Failed to get a type information of %s.\n",
330 			   dwarf_diename(vr_die));
331 		return -ENOENT;
332 	}
333 
334 	pr_debug("%s type is %s.\n",
335 		 dwarf_diename(vr_die), dwarf_diename(&type));
336 
337 	if (cast && (!strcmp(cast, "string") || !strcmp(cast, "ustring"))) {
338 		/* String type */
339 		ret = dwarf_tag(&type);
340 		if (ret != DW_TAG_pointer_type &&
341 		    ret != DW_TAG_array_type) {
342 			pr_warning("Failed to cast into string: "
343 				   "%s(%s) is not a pointer nor array.\n",
344 				   dwarf_diename(vr_die), dwarf_diename(&type));
345 			return -EINVAL;
346 		}
347 		if (die_get_real_type(&type, &type) == NULL) {
348 			pr_warning("Failed to get a type"
349 				   " information.\n");
350 			return -ENOENT;
351 		}
352 		if (ret == DW_TAG_pointer_type) {
353 			while (*ref_ptr)
354 				ref_ptr = &(*ref_ptr)->next;
355 			/* Add new reference with offset +0 */
356 			*ref_ptr = zalloc(sizeof(struct probe_trace_arg_ref));
357 			if (*ref_ptr == NULL) {
358 				pr_warning("Out of memory error\n");
359 				return -ENOMEM;
360 			}
361 			(*ref_ptr)->user_access = user_access;
362 		}
363 		if (!die_compare_name(&type, "char") &&
364 		    !die_compare_name(&type, "unsigned char")) {
365 			pr_warning("Failed to cast into string: "
366 				   "%s is not (unsigned) char *.\n",
367 				   dwarf_diename(vr_die));
368 			return -EINVAL;
369 		}
370 		tvar->type = strdup(cast);
371 		return (tvar->type == NULL) ? -ENOMEM : 0;
372 	}
373 
374 	if (cast && (strcmp(cast, "u") == 0))
375 		prefix = 'u';
376 	else if (cast && (strcmp(cast, "s") == 0))
377 		prefix = 's';
378 	else if (cast && (strcmp(cast, "x") == 0) &&
379 		 probe_type_is_available(PROBE_TYPE_X))
380 		prefix = 'x';
381 	else
382 		prefix = die_is_signed_type(&type) ? 's' :
383 			 probe_type_is_available(PROBE_TYPE_X) ? 'x' : 'u';
384 
385 	ret = dwarf_bytesize(&type);
386 	if (ret <= 0)
387 		/* No size ... try to use default type */
388 		return 0;
389 	ret = BYTES_TO_BITS(ret);
390 
391 	/* Check the bitwidth */
392 	if (ret > MAX_BASIC_TYPE_BITS) {
393 		pr_info("%s exceeds max-bitwidth. Cut down to %d bits.\n",
394 			dwarf_diename(&type), MAX_BASIC_TYPE_BITS);
395 		ret = MAX_BASIC_TYPE_BITS;
396 	}
397 	ret = snprintf(buf, 16, "%c%d", prefix, ret);
398 
399 formatted:
400 	if (ret < 0 || ret >= 16) {
401 		if (ret >= 16)
402 			ret = -E2BIG;
403 		pr_warning("Failed to convert variable type: %s\n",
404 			   str_error_r(-ret, sbuf, sizeof(sbuf)));
405 		return ret;
406 	}
407 	tvar->type = strdup(buf);
408 	if (tvar->type == NULL)
409 		return -ENOMEM;
410 	return 0;
411 }
412 
413 static int convert_variable_fields(Dwarf_Die *vr_die, const char *varname,
414 				    struct perf_probe_arg_field *field,
415 				    struct probe_trace_arg_ref **ref_ptr,
416 				    Dwarf_Die *die_mem, bool user_access)
417 {
418 	struct probe_trace_arg_ref *ref = *ref_ptr;
419 	Dwarf_Die type;
420 	Dwarf_Word offs;
421 	int ret, tag;
422 
423 	pr_debug("converting %s in %s\n", field->name, varname);
424 	if (die_get_real_type(vr_die, &type) == NULL) {
425 		pr_warning("Failed to get the type of %s.\n", varname);
426 		return -ENOENT;
427 	}
428 	pr_debug2("Var real type: %s (%x)\n", dwarf_diename(&type),
429 		  (unsigned)dwarf_dieoffset(&type));
430 	tag = dwarf_tag(&type);
431 
432 	if (field->name[0] == '[' &&
433 	    (tag == DW_TAG_array_type || tag == DW_TAG_pointer_type)) {
434 		/* Save original type for next field or type */
435 		memcpy(die_mem, &type, sizeof(*die_mem));
436 		/* Get the type of this array */
437 		if (die_get_real_type(&type, &type) == NULL) {
438 			pr_warning("Failed to get the type of %s.\n", varname);
439 			return -ENOENT;
440 		}
441 		pr_debug2("Array real type: %s (%x)\n", dwarf_diename(&type),
442 			 (unsigned)dwarf_dieoffset(&type));
443 		if (tag == DW_TAG_pointer_type) {
444 			ref = zalloc(sizeof(struct probe_trace_arg_ref));
445 			if (ref == NULL)
446 				return -ENOMEM;
447 			if (*ref_ptr)
448 				(*ref_ptr)->next = ref;
449 			else
450 				*ref_ptr = ref;
451 		}
452 		ref->offset += dwarf_bytesize(&type) * field->index;
453 		ref->user_access = user_access;
454 		goto next;
455 	} else if (tag == DW_TAG_pointer_type) {
456 		/* Check the pointer and dereference */
457 		if (!field->ref) {
458 			pr_err("Semantic error: %s must be referred by '->'\n",
459 			       field->name);
460 			return -EINVAL;
461 		}
462 		/* Get the type pointed by this pointer */
463 		if (die_get_real_type(&type, &type) == NULL) {
464 			pr_warning("Failed to get the type of %s.\n", varname);
465 			return -ENOENT;
466 		}
467 		/* Verify it is a data structure  */
468 		tag = dwarf_tag(&type);
469 		if (tag != DW_TAG_structure_type && tag != DW_TAG_union_type) {
470 			pr_warning("%s is not a data structure nor a union.\n",
471 				   varname);
472 			return -EINVAL;
473 		}
474 
475 		ref = zalloc(sizeof(struct probe_trace_arg_ref));
476 		if (ref == NULL)
477 			return -ENOMEM;
478 		if (*ref_ptr)
479 			(*ref_ptr)->next = ref;
480 		else
481 			*ref_ptr = ref;
482 	} else {
483 		/* Verify it is a data structure  */
484 		if (tag != DW_TAG_structure_type && tag != DW_TAG_union_type) {
485 			pr_warning("%s is not a data structure nor a union.\n",
486 				   varname);
487 			return -EINVAL;
488 		}
489 		if (field->name[0] == '[') {
490 			pr_err("Semantic error: %s is not a pointer"
491 			       " nor array.\n", varname);
492 			return -EINVAL;
493 		}
494 		/* While prcessing unnamed field, we don't care about this */
495 		if (field->ref && dwarf_diename(vr_die)) {
496 			pr_err("Semantic error: %s must be referred by '.'\n",
497 			       field->name);
498 			return -EINVAL;
499 		}
500 		if (!ref) {
501 			pr_warning("Structure on a register is not "
502 				   "supported yet.\n");
503 			return -ENOTSUP;
504 		}
505 	}
506 
507 	if (die_find_member(&type, field->name, die_mem) == NULL) {
508 		pr_warning("%s(type:%s) has no member %s.\n", varname,
509 			   dwarf_diename(&type), field->name);
510 		return -EINVAL;
511 	}
512 
513 	/* Get the offset of the field */
514 	if (tag == DW_TAG_union_type) {
515 		offs = 0;
516 	} else {
517 		ret = die_get_data_member_location(die_mem, &offs);
518 		if (ret < 0) {
519 			pr_warning("Failed to get the offset of %s.\n",
520 				   field->name);
521 			return ret;
522 		}
523 	}
524 	ref->offset += (long)offs;
525 	ref->user_access = user_access;
526 
527 	/* If this member is unnamed, we need to reuse this field */
528 	if (!dwarf_diename(die_mem))
529 		return convert_variable_fields(die_mem, varname, field,
530 						&ref, die_mem, user_access);
531 
532 next:
533 	/* Converting next field */
534 	if (field->next)
535 		return convert_variable_fields(die_mem, field->name,
536 				field->next, &ref, die_mem, user_access);
537 	else
538 		return 0;
539 }
540 
541 static void print_var_not_found(const char *varname)
542 {
543 	pr_err("Failed to find the location of the '%s' variable at this address.\n"
544 	       " Perhaps it has been optimized out.\n"
545 	       " Use -V with the --range option to show '%s' location range.\n",
546 		varname, varname);
547 }
548 
549 /* Show a variables in kprobe event format */
550 static int convert_variable(Dwarf_Die *vr_die, struct probe_finder *pf)
551 {
552 	Dwarf_Die die_mem;
553 	int ret;
554 
555 	pr_debug("Converting variable %s into trace event.\n",
556 		 dwarf_diename(vr_die));
557 
558 	ret = convert_variable_location(vr_die, pf->addr, pf->fb_ops,
559 					&pf->sp_die, pf->machine, pf->tvar);
560 	if (ret == -ENOENT && pf->skip_empty_arg)
561 		/* This can be found in other place. skip it */
562 		return 0;
563 	if (ret == -ENOENT || ret == -EINVAL) {
564 		print_var_not_found(pf->pvar->var);
565 	} else if (ret == -ENOTSUP)
566 		pr_err("Sorry, we don't support this variable location yet.\n");
567 	else if (ret == 0 && pf->pvar->field) {
568 		ret = convert_variable_fields(vr_die, pf->pvar->var,
569 					      pf->pvar->field, &pf->tvar->ref,
570 					      &die_mem, pf->pvar->user_access);
571 		vr_die = &die_mem;
572 	}
573 	if (ret == 0)
574 		ret = convert_variable_type(vr_die, pf->tvar, pf->pvar->type,
575 					    pf->pvar->user_access);
576 	/* *expr will be cached in libdw. Don't free it. */
577 	return ret;
578 }
579 
580 /* Find a variable in a scope DIE */
581 static int find_variable(Dwarf_Die *sc_die, struct probe_finder *pf)
582 {
583 	Dwarf_Die vr_die;
584 	char *buf, *ptr;
585 	int ret = 0;
586 
587 	/* Copy raw parameters */
588 	if (!is_c_varname(pf->pvar->var))
589 		return copy_to_probe_trace_arg(pf->tvar, pf->pvar);
590 
591 	if (pf->pvar->name)
592 		pf->tvar->name = strdup(pf->pvar->name);
593 	else {
594 		buf = synthesize_perf_probe_arg(pf->pvar);
595 		if (!buf)
596 			return -ENOMEM;
597 		ptr = strchr(buf, ':');	/* Change type separator to _ */
598 		if (ptr)
599 			*ptr = '_';
600 		pf->tvar->name = buf;
601 	}
602 	if (pf->tvar->name == NULL)
603 		return -ENOMEM;
604 
605 	pr_debug("Searching '%s' variable in context.\n", pf->pvar->var);
606 	/* Search child die for local variables and parameters. */
607 	if (!die_find_variable_at(sc_die, pf->pvar->var, pf->addr, &vr_die)) {
608 		/* Search again in global variables */
609 		if (!die_find_variable_at(&pf->cu_die, pf->pvar->var,
610 						0, &vr_die)) {
611 			if (pf->skip_empty_arg)
612 				return 0;
613 			pr_warning("Failed to find '%s' in this function.\n",
614 				   pf->pvar->var);
615 			ret = -ENOENT;
616 		}
617 	}
618 	if (ret >= 0)
619 		ret = convert_variable(&vr_die, pf);
620 
621 	return ret;
622 }
623 
624 /* Convert subprogram DIE to trace point */
625 static int convert_to_trace_point(Dwarf_Die *sp_die, Dwfl_Module *mod,
626 				  Dwarf_Addr paddr, bool retprobe,
627 				  const char *function,
628 				  struct probe_trace_point *tp)
629 {
630 	Dwarf_Addr eaddr;
631 	GElf_Sym sym;
632 	const char *symbol;
633 
634 	/* Verify the address is correct */
635 	if (!dwarf_haspc(sp_die, paddr)) {
636 		pr_warning("Specified offset is out of %s\n",
637 			   dwarf_diename(sp_die));
638 		return -EINVAL;
639 	}
640 
641 	if (dwarf_entrypc(sp_die, &eaddr) == 0) {
642 		/* If the DIE has entrypc, use it. */
643 		symbol = dwarf_diename(sp_die);
644 	} else {
645 		/* Try to get actual symbol name and address from symtab */
646 		symbol = dwfl_module_addrsym(mod, paddr, &sym, NULL);
647 		eaddr = sym.st_value;
648 	}
649 	if (!symbol) {
650 		pr_warning("Failed to find symbol at 0x%lx\n",
651 			   (unsigned long)paddr);
652 		return -ENOENT;
653 	}
654 
655 	tp->offset = (unsigned long)(paddr - eaddr);
656 	tp->address = (unsigned long)paddr;
657 	tp->symbol = strdup(symbol);
658 	if (!tp->symbol)
659 		return -ENOMEM;
660 
661 	/* Return probe must be on the head of a subprogram */
662 	if (retprobe) {
663 		if (eaddr != paddr) {
664 			pr_warning("Failed to find \"%s%%return\",\n"
665 				   " because %s is an inlined function and"
666 				   " has no return point.\n", function,
667 				   function);
668 			return -EINVAL;
669 		}
670 		tp->retprobe = true;
671 	}
672 
673 	return 0;
674 }
675 
676 /* Call probe_finder callback with scope DIE */
677 static int call_probe_finder(Dwarf_Die *sc_die, struct probe_finder *pf)
678 {
679 	Dwarf_Attribute fb_attr;
680 	Dwarf_Frame *frame = NULL;
681 	size_t nops;
682 	int ret;
683 
684 	if (!sc_die) {
685 		pr_err("Caller must pass a scope DIE. Program error.\n");
686 		return -EINVAL;
687 	}
688 
689 	/* If not a real subprogram, find a real one */
690 	if (!die_is_func_def(sc_die)) {
691 		if (!die_find_realfunc(&pf->cu_die, pf->addr, &pf->sp_die)) {
692 			if (die_find_tailfunc(&pf->cu_die, pf->addr, &pf->sp_die)) {
693 				pr_warning("Ignoring tail call from %s\n",
694 						dwarf_diename(&pf->sp_die));
695 				return 0;
696 			} else {
697 				pr_warning("Failed to find probe point in any "
698 					   "functions.\n");
699 				return -ENOENT;
700 			}
701 		}
702 	} else
703 		memcpy(&pf->sp_die, sc_die, sizeof(Dwarf_Die));
704 
705 	/* Get the frame base attribute/ops from subprogram */
706 	dwarf_attr(&pf->sp_die, DW_AT_frame_base, &fb_attr);
707 	ret = dwarf_getlocation_addr(&fb_attr, pf->addr, &pf->fb_ops, &nops, 1);
708 	if (ret <= 0 || nops == 0) {
709 		pf->fb_ops = NULL;
710 #if _ELFUTILS_PREREQ(0, 142)
711 	} else if (nops == 1 && pf->fb_ops[0].atom == DW_OP_call_frame_cfa &&
712 		   (pf->cfi_eh != NULL || pf->cfi_dbg != NULL)) {
713 		if ((dwarf_cfi_addrframe(pf->cfi_eh, pf->addr, &frame) != 0 &&
714 		     (dwarf_cfi_addrframe(pf->cfi_dbg, pf->addr, &frame) != 0)) ||
715 		    dwarf_frame_cfa(frame, &pf->fb_ops, &nops) != 0) {
716 			pr_warning("Failed to get call frame on 0x%jx\n",
717 				   (uintmax_t)pf->addr);
718 			free(frame);
719 			return -ENOENT;
720 		}
721 #endif
722 	}
723 
724 	/* Call finder's callback handler */
725 	ret = pf->callback(sc_die, pf);
726 
727 	/* Since *pf->fb_ops can be a part of frame. we should free it here. */
728 	free(frame);
729 	pf->fb_ops = NULL;
730 
731 	return ret;
732 }
733 
734 struct find_scope_param {
735 	const char *function;
736 	const char *file;
737 	int line;
738 	int diff;
739 	Dwarf_Die *die_mem;
740 	bool found;
741 };
742 
743 static int find_best_scope_cb(Dwarf_Die *fn_die, void *data)
744 {
745 	struct find_scope_param *fsp = data;
746 	const char *file;
747 	int lno;
748 
749 	/* Skip if declared file name does not match */
750 	if (fsp->file) {
751 		file = dwarf_decl_file(fn_die);
752 		if (!file || strcmp(fsp->file, file) != 0)
753 			return 0;
754 	}
755 	/* If the function name is given, that's what user expects */
756 	if (fsp->function) {
757 		if (die_match_name(fn_die, fsp->function)) {
758 			memcpy(fsp->die_mem, fn_die, sizeof(Dwarf_Die));
759 			fsp->found = true;
760 			return 1;
761 		}
762 	} else {
763 		/* With the line number, find the nearest declared DIE */
764 		dwarf_decl_line(fn_die, &lno);
765 		if (lno < fsp->line && fsp->diff > fsp->line - lno) {
766 			/* Keep a candidate and continue */
767 			fsp->diff = fsp->line - lno;
768 			memcpy(fsp->die_mem, fn_die, sizeof(Dwarf_Die));
769 			fsp->found = true;
770 		}
771 	}
772 	return 0;
773 }
774 
775 /* Return innermost DIE */
776 static int find_inner_scope_cb(Dwarf_Die *fn_die, void *data)
777 {
778 	struct find_scope_param *fsp = data;
779 
780 	memcpy(fsp->die_mem, fn_die, sizeof(Dwarf_Die));
781 	fsp->found = true;
782 	return 1;
783 }
784 
785 /* Find an appropriate scope fits to given conditions */
786 static Dwarf_Die *find_best_scope(struct probe_finder *pf, Dwarf_Die *die_mem)
787 {
788 	struct find_scope_param fsp = {
789 		.function = pf->pev->point.function,
790 		.file = pf->fname,
791 		.line = pf->lno,
792 		.diff = INT_MAX,
793 		.die_mem = die_mem,
794 		.found = false,
795 	};
796 	int ret;
797 
798 	ret = cu_walk_functions_at(&pf->cu_die, pf->addr, find_best_scope_cb,
799 				   &fsp);
800 	if (!ret && !fsp.found)
801 		cu_walk_functions_at(&pf->cu_die, pf->addr,
802 				     find_inner_scope_cb, &fsp);
803 
804 	return fsp.found ? die_mem : NULL;
805 }
806 
807 static int verify_representive_line(struct probe_finder *pf, const char *fname,
808 				int lineno, Dwarf_Addr addr)
809 {
810 	const char *__fname, *__func = NULL;
811 	Dwarf_Die die_mem;
812 	int __lineno;
813 
814 	/* Verify line number and address by reverse search */
815 	if (cu_find_lineinfo(&pf->cu_die, addr, &__fname, &__lineno) < 0)
816 		return 0;
817 
818 	pr_debug2("Reversed line: %s:%d\n", __fname, __lineno);
819 	if (strcmp(fname, __fname) || lineno == __lineno)
820 		return 0;
821 
822 	pr_warning("This line is sharing the address with other lines.\n");
823 
824 	if (pf->pev->point.function) {
825 		/* Find best match function name and lines */
826 		pf->addr = addr;
827 		if (find_best_scope(pf, &die_mem)
828 		    && die_match_name(&die_mem, pf->pev->point.function)
829 		    && dwarf_decl_line(&die_mem, &lineno) == 0) {
830 			__func = dwarf_diename(&die_mem);
831 			__lineno -= lineno;
832 		}
833 	}
834 	pr_warning("Please try to probe at %s:%d instead.\n",
835 		   __func ? : __fname, __lineno);
836 
837 	return -ENOENT;
838 }
839 
840 static int probe_point_line_walker(const char *fname, int lineno,
841 				   Dwarf_Addr addr, void *data)
842 {
843 	struct probe_finder *pf = data;
844 	Dwarf_Die *sc_die, die_mem;
845 	int ret;
846 
847 	if (lineno != pf->lno || strtailcmp(fname, pf->fname) != 0)
848 		return 0;
849 
850 	if (verify_representive_line(pf, fname, lineno, addr))
851 		return -ENOENT;
852 
853 	pf->addr = addr;
854 	sc_die = find_best_scope(pf, &die_mem);
855 	if (!sc_die) {
856 		pr_warning("Failed to find scope of probe point.\n");
857 		return -ENOENT;
858 	}
859 
860 	ret = call_probe_finder(sc_die, pf);
861 
862 	/* Continue if no error, because the line will be in inline function */
863 	return ret < 0 ? ret : 0;
864 }
865 
866 /* Find probe point from its line number */
867 static int find_probe_point_by_line(struct probe_finder *pf)
868 {
869 	return die_walk_lines(&pf->cu_die, probe_point_line_walker, pf);
870 }
871 
872 /* Find lines which match lazy pattern */
873 static int find_lazy_match_lines(struct intlist *list,
874 				 const char *fname, const char *pat)
875 {
876 	FILE *fp;
877 	char *line = NULL;
878 	size_t line_len;
879 	ssize_t len;
880 	int count = 0, linenum = 1;
881 	char sbuf[STRERR_BUFSIZE];
882 
883 	fp = fopen(fname, "r");
884 	if (!fp) {
885 		pr_warning("Failed to open %s: %s\n", fname,
886 			   str_error_r(errno, sbuf, sizeof(sbuf)));
887 		return -errno;
888 	}
889 
890 	while ((len = getline(&line, &line_len, fp)) > 0) {
891 
892 		if (line[len - 1] == '\n')
893 			line[len - 1] = '\0';
894 
895 		if (strlazymatch(line, pat)) {
896 			intlist__add(list, linenum);
897 			count++;
898 		}
899 		linenum++;
900 	}
901 
902 	if (ferror(fp))
903 		count = -errno;
904 	free(line);
905 	fclose(fp);
906 
907 	if (count == 0)
908 		pr_debug("No matched lines found in %s.\n", fname);
909 	return count;
910 }
911 
912 static int probe_point_lazy_walker(const char *fname, int lineno,
913 				   Dwarf_Addr addr, void *data)
914 {
915 	struct probe_finder *pf = data;
916 	Dwarf_Die *sc_die, die_mem;
917 	int ret;
918 
919 	if (!intlist__has_entry(pf->lcache, lineno) ||
920 	    strtailcmp(fname, pf->fname) != 0)
921 		return 0;
922 
923 	pr_debug("Probe line found: line:%d addr:0x%llx\n",
924 		 lineno, (unsigned long long)addr);
925 	pf->addr = addr;
926 	pf->lno = lineno;
927 	sc_die = find_best_scope(pf, &die_mem);
928 	if (!sc_die) {
929 		pr_warning("Failed to find scope of probe point.\n");
930 		return -ENOENT;
931 	}
932 
933 	ret = call_probe_finder(sc_die, pf);
934 
935 	/*
936 	 * Continue if no error, because the lazy pattern will match
937 	 * to other lines
938 	 */
939 	return ret < 0 ? ret : 0;
940 }
941 
942 /* Find probe points from lazy pattern  */
943 static int find_probe_point_lazy(Dwarf_Die *sp_die, struct probe_finder *pf)
944 {
945 	int ret = 0;
946 	char *fpath;
947 
948 	if (intlist__empty(pf->lcache)) {
949 		const char *comp_dir;
950 
951 		comp_dir = cu_get_comp_dir(&pf->cu_die);
952 		ret = get_real_path(pf->fname, comp_dir, &fpath);
953 		if (ret < 0) {
954 			pr_warning("Failed to find source file path.\n");
955 			return ret;
956 		}
957 
958 		/* Matching lazy line pattern */
959 		ret = find_lazy_match_lines(pf->lcache, fpath,
960 					    pf->pev->point.lazy_line);
961 		free(fpath);
962 		if (ret <= 0)
963 			return ret;
964 	}
965 
966 	return die_walk_lines(sp_die, probe_point_lazy_walker, pf);
967 }
968 
969 static void skip_prologue(Dwarf_Die *sp_die, struct probe_finder *pf)
970 {
971 	struct perf_probe_point *pp = &pf->pev->point;
972 
973 	/* Not uprobe? */
974 	if (!pf->pev->uprobes)
975 		return;
976 
977 	/* Compiled with optimization? */
978 	if (die_is_optimized_target(&pf->cu_die))
979 		return;
980 
981 	/* Don't know entrypc? */
982 	if (!pf->addr)
983 		return;
984 
985 	/* Only FUNC and FUNC@SRC are eligible. */
986 	if (!pp->function || pp->line || pp->retprobe || pp->lazy_line ||
987 	    pp->offset || pp->abs_address)
988 		return;
989 
990 	/* Not interested in func parameter? */
991 	if (!perf_probe_with_var(pf->pev))
992 		return;
993 
994 	pr_info("Target program is compiled without optimization. Skipping prologue.\n"
995 		"Probe on address 0x%" PRIx64 " to force probing at the function entry.\n\n",
996 		pf->addr);
997 
998 	die_skip_prologue(sp_die, &pf->cu_die, &pf->addr);
999 }
1000 
1001 static int probe_point_inline_cb(Dwarf_Die *in_die, void *data)
1002 {
1003 	struct probe_finder *pf = data;
1004 	struct perf_probe_point *pp = &pf->pev->point;
1005 	Dwarf_Addr addr;
1006 	int ret;
1007 
1008 	if (pp->lazy_line)
1009 		ret = find_probe_point_lazy(in_die, pf);
1010 	else {
1011 		/* Get probe address */
1012 		if (die_entrypc(in_die, &addr) != 0) {
1013 			pr_warning("Failed to get entry address of %s.\n",
1014 				   dwarf_diename(in_die));
1015 			return -ENOENT;
1016 		}
1017 		if (addr == 0) {
1018 			pr_debug("%s has no valid entry address. skipped.\n",
1019 				 dwarf_diename(in_die));
1020 			return -ENOENT;
1021 		}
1022 		pf->addr = addr;
1023 		pf->addr += pp->offset;
1024 		pr_debug("found inline addr: 0x%jx\n",
1025 			 (uintmax_t)pf->addr);
1026 
1027 		ret = call_probe_finder(in_die, pf);
1028 	}
1029 
1030 	return ret;
1031 }
1032 
1033 /* Callback parameter with return value for libdw */
1034 struct dwarf_callback_param {
1035 	void *data;
1036 	int retval;
1037 };
1038 
1039 /* Search function from function name */
1040 static int probe_point_search_cb(Dwarf_Die *sp_die, void *data)
1041 {
1042 	struct dwarf_callback_param *param = data;
1043 	struct probe_finder *pf = param->data;
1044 	struct perf_probe_point *pp = &pf->pev->point;
1045 
1046 	/* Check tag and diename */
1047 	if (!die_is_func_def(sp_die) ||
1048 	    !die_match_name(sp_die, pp->function))
1049 		return DWARF_CB_OK;
1050 
1051 	/* Check declared file */
1052 	if (pp->file && strtailcmp(pp->file, dwarf_decl_file(sp_die)))
1053 		return DWARF_CB_OK;
1054 
1055 	pr_debug("Matched function: %s [%lx]\n", dwarf_diename(sp_die),
1056 		 (unsigned long)dwarf_dieoffset(sp_die));
1057 	pf->fname = dwarf_decl_file(sp_die);
1058 	if (pp->line) { /* Function relative line */
1059 		dwarf_decl_line(sp_die, &pf->lno);
1060 		pf->lno += pp->line;
1061 		param->retval = find_probe_point_by_line(pf);
1062 	} else if (die_is_func_instance(sp_die)) {
1063 		/* Instances always have the entry address */
1064 		die_entrypc(sp_die, &pf->addr);
1065 		/* But in some case the entry address is 0 */
1066 		if (pf->addr == 0) {
1067 			pr_debug("%s has no entry PC. Skipped\n",
1068 				 dwarf_diename(sp_die));
1069 			param->retval = 0;
1070 		/* Real function */
1071 		} else if (pp->lazy_line)
1072 			param->retval = find_probe_point_lazy(sp_die, pf);
1073 		else {
1074 			skip_prologue(sp_die, pf);
1075 			pf->addr += pp->offset;
1076 			/* TODO: Check the address in this function */
1077 			param->retval = call_probe_finder(sp_die, pf);
1078 		}
1079 	} else if (!probe_conf.no_inlines) {
1080 		/* Inlined function: search instances */
1081 		param->retval = die_walk_instances(sp_die,
1082 					probe_point_inline_cb, (void *)pf);
1083 		/* This could be a non-existed inline definition */
1084 		if (param->retval == -ENOENT)
1085 			param->retval = 0;
1086 	}
1087 
1088 	/* We need to find other candidates */
1089 	if (strisglob(pp->function) && param->retval >= 0) {
1090 		param->retval = 0;	/* We have to clear the result */
1091 		return DWARF_CB_OK;
1092 	}
1093 
1094 	return DWARF_CB_ABORT; /* Exit; no same symbol in this CU. */
1095 }
1096 
1097 static int find_probe_point_by_func(struct probe_finder *pf)
1098 {
1099 	struct dwarf_callback_param _param = {.data = (void *)pf,
1100 					      .retval = 0};
1101 	dwarf_getfuncs(&pf->cu_die, probe_point_search_cb, &_param, 0);
1102 	return _param.retval;
1103 }
1104 
1105 struct pubname_callback_param {
1106 	char *function;
1107 	char *file;
1108 	Dwarf_Die *cu_die;
1109 	Dwarf_Die *sp_die;
1110 	int found;
1111 };
1112 
1113 static int pubname_search_cb(Dwarf *dbg, Dwarf_Global *gl, void *data)
1114 {
1115 	struct pubname_callback_param *param = data;
1116 
1117 	if (dwarf_offdie(dbg, gl->die_offset, param->sp_die)) {
1118 		if (dwarf_tag(param->sp_die) != DW_TAG_subprogram)
1119 			return DWARF_CB_OK;
1120 
1121 		if (die_match_name(param->sp_die, param->function)) {
1122 			if (!dwarf_offdie(dbg, gl->cu_offset, param->cu_die))
1123 				return DWARF_CB_OK;
1124 
1125 			if (param->file &&
1126 			    strtailcmp(param->file, dwarf_decl_file(param->sp_die)))
1127 				return DWARF_CB_OK;
1128 
1129 			param->found = 1;
1130 			return DWARF_CB_ABORT;
1131 		}
1132 	}
1133 
1134 	return DWARF_CB_OK;
1135 }
1136 
1137 static int debuginfo__find_probe_location(struct debuginfo *dbg,
1138 				  struct probe_finder *pf)
1139 {
1140 	struct perf_probe_point *pp = &pf->pev->point;
1141 	Dwarf_Off off, noff;
1142 	size_t cuhl;
1143 	Dwarf_Die *diep;
1144 	int ret = 0;
1145 
1146 	off = 0;
1147 	pf->lcache = intlist__new(NULL);
1148 	if (!pf->lcache)
1149 		return -ENOMEM;
1150 
1151 	/* Fastpath: lookup by function name from .debug_pubnames section */
1152 	if (pp->function && !strisglob(pp->function)) {
1153 		struct pubname_callback_param pubname_param = {
1154 			.function = pp->function,
1155 			.file	  = pp->file,
1156 			.cu_die	  = &pf->cu_die,
1157 			.sp_die	  = &pf->sp_die,
1158 			.found	  = 0,
1159 		};
1160 		struct dwarf_callback_param probe_param = {
1161 			.data = pf,
1162 		};
1163 
1164 		dwarf_getpubnames(dbg->dbg, pubname_search_cb,
1165 				  &pubname_param, 0);
1166 		if (pubname_param.found) {
1167 			ret = probe_point_search_cb(&pf->sp_die, &probe_param);
1168 			if (ret)
1169 				goto found;
1170 		}
1171 	}
1172 
1173 	/* Loop on CUs (Compilation Unit) */
1174 	while (!dwarf_nextcu(dbg->dbg, off, &noff, &cuhl, NULL, NULL, NULL)) {
1175 		/* Get the DIE(Debugging Information Entry) of this CU */
1176 		diep = dwarf_offdie(dbg->dbg, off + cuhl, &pf->cu_die);
1177 		if (!diep)
1178 			continue;
1179 
1180 		/* Check if target file is included. */
1181 		if (pp->file)
1182 			pf->fname = cu_find_realpath(&pf->cu_die, pp->file);
1183 		else
1184 			pf->fname = NULL;
1185 
1186 		if (!pp->file || pf->fname) {
1187 			if (pp->function)
1188 				ret = find_probe_point_by_func(pf);
1189 			else if (pp->lazy_line)
1190 				ret = find_probe_point_lazy(&pf->cu_die, pf);
1191 			else {
1192 				pf->lno = pp->line;
1193 				ret = find_probe_point_by_line(pf);
1194 			}
1195 			if (ret < 0)
1196 				break;
1197 		}
1198 		off = noff;
1199 	}
1200 
1201 found:
1202 	intlist__delete(pf->lcache);
1203 	pf->lcache = NULL;
1204 
1205 	return ret;
1206 }
1207 
1208 /* Find probe points from debuginfo */
1209 static int debuginfo__find_probes(struct debuginfo *dbg,
1210 				  struct probe_finder *pf)
1211 {
1212 	int ret = 0;
1213 	Elf *elf;
1214 	GElf_Ehdr ehdr;
1215 
1216 	if (pf->cfi_eh || pf->cfi_dbg)
1217 		return debuginfo__find_probe_location(dbg, pf);
1218 
1219 	/* Get the call frame information from this dwarf */
1220 	elf = dwarf_getelf(dbg->dbg);
1221 	if (elf == NULL)
1222 		return -EINVAL;
1223 
1224 	if (gelf_getehdr(elf, &ehdr) == NULL)
1225 		return -EINVAL;
1226 
1227 	pf->machine = ehdr.e_machine;
1228 
1229 #if _ELFUTILS_PREREQ(0, 142)
1230 	do {
1231 		GElf_Shdr shdr;
1232 
1233 		if (elf_section_by_name(elf, &ehdr, &shdr, ".eh_frame", NULL) &&
1234 		    shdr.sh_type == SHT_PROGBITS)
1235 			pf->cfi_eh = dwarf_getcfi_elf(elf);
1236 
1237 		pf->cfi_dbg = dwarf_getcfi(dbg->dbg);
1238 	} while (0);
1239 #endif
1240 
1241 	ret = debuginfo__find_probe_location(dbg, pf);
1242 	return ret;
1243 }
1244 
1245 struct local_vars_finder {
1246 	struct probe_finder *pf;
1247 	struct perf_probe_arg *args;
1248 	bool vars;
1249 	int max_args;
1250 	int nargs;
1251 	int ret;
1252 };
1253 
1254 /* Collect available variables in this scope */
1255 static int copy_variables_cb(Dwarf_Die *die_mem, void *data)
1256 {
1257 	struct local_vars_finder *vf = data;
1258 	struct probe_finder *pf = vf->pf;
1259 	int tag;
1260 
1261 	tag = dwarf_tag(die_mem);
1262 	if (tag == DW_TAG_formal_parameter ||
1263 	    (tag == DW_TAG_variable && vf->vars)) {
1264 		if (convert_variable_location(die_mem, vf->pf->addr,
1265 					      vf->pf->fb_ops, &pf->sp_die,
1266 					      pf->machine, NULL) == 0) {
1267 			vf->args[vf->nargs].var = (char *)dwarf_diename(die_mem);
1268 			if (vf->args[vf->nargs].var == NULL) {
1269 				vf->ret = -ENOMEM;
1270 				return DIE_FIND_CB_END;
1271 			}
1272 			pr_debug(" %s", vf->args[vf->nargs].var);
1273 			vf->nargs++;
1274 		}
1275 	}
1276 
1277 	if (dwarf_haspc(die_mem, vf->pf->addr))
1278 		return DIE_FIND_CB_CONTINUE;
1279 	else
1280 		return DIE_FIND_CB_SIBLING;
1281 }
1282 
1283 static int expand_probe_args(Dwarf_Die *sc_die, struct probe_finder *pf,
1284 			     struct perf_probe_arg *args)
1285 {
1286 	Dwarf_Die die_mem;
1287 	int i;
1288 	int n = 0;
1289 	struct local_vars_finder vf = {.pf = pf, .args = args, .vars = false,
1290 				.max_args = MAX_PROBE_ARGS, .ret = 0};
1291 
1292 	for (i = 0; i < pf->pev->nargs; i++) {
1293 		/* var never be NULL */
1294 		if (strcmp(pf->pev->args[i].var, PROBE_ARG_VARS) == 0)
1295 			vf.vars = true;
1296 		else if (strcmp(pf->pev->args[i].var, PROBE_ARG_PARAMS) != 0) {
1297 			/* Copy normal argument */
1298 			args[n] = pf->pev->args[i];
1299 			n++;
1300 			continue;
1301 		}
1302 		pr_debug("Expanding %s into:", pf->pev->args[i].var);
1303 		vf.nargs = n;
1304 		/* Special local variables */
1305 		die_find_child(sc_die, copy_variables_cb, (void *)&vf,
1306 			       &die_mem);
1307 		pr_debug(" (%d)\n", vf.nargs - n);
1308 		if (vf.ret < 0)
1309 			return vf.ret;
1310 		n = vf.nargs;
1311 	}
1312 	return n;
1313 }
1314 
1315 static bool trace_event_finder_overlap(struct trace_event_finder *tf)
1316 {
1317 	int i;
1318 
1319 	for (i = 0; i < tf->ntevs; i++) {
1320 		if (tf->pf.addr == tf->tevs[i].point.address)
1321 			return true;
1322 	}
1323 	return false;
1324 }
1325 
1326 /* Add a found probe point into trace event list */
1327 static int add_probe_trace_event(Dwarf_Die *sc_die, struct probe_finder *pf)
1328 {
1329 	struct trace_event_finder *tf =
1330 			container_of(pf, struct trace_event_finder, pf);
1331 	struct perf_probe_point *pp = &pf->pev->point;
1332 	struct probe_trace_event *tev;
1333 	struct perf_probe_arg *args = NULL;
1334 	int ret, i;
1335 
1336 	/*
1337 	 * For some reason (e.g. different column assigned to same address)
1338 	 * This callback can be called with the address which already passed.
1339 	 * Ignore it first.
1340 	 */
1341 	if (trace_event_finder_overlap(tf))
1342 		return 0;
1343 
1344 	/* Check number of tevs */
1345 	if (tf->ntevs == tf->max_tevs) {
1346 		pr_warning("Too many( > %d) probe point found.\n",
1347 			   tf->max_tevs);
1348 		return -ERANGE;
1349 	}
1350 	tev = &tf->tevs[tf->ntevs++];
1351 
1352 	/* Trace point should be converted from subprogram DIE */
1353 	ret = convert_to_trace_point(&pf->sp_die, tf->mod, pf->addr,
1354 				     pp->retprobe, pp->function, &tev->point);
1355 	if (ret < 0)
1356 		goto end;
1357 
1358 	tev->point.realname = strdup(dwarf_diename(sc_die));
1359 	if (!tev->point.realname) {
1360 		ret = -ENOMEM;
1361 		goto end;
1362 	}
1363 
1364 	pr_debug("Probe point found: %s+%lu\n", tev->point.symbol,
1365 		 tev->point.offset);
1366 
1367 	/* Expand special probe argument if exist */
1368 	args = zalloc(sizeof(struct perf_probe_arg) * MAX_PROBE_ARGS);
1369 	if (args == NULL) {
1370 		ret = -ENOMEM;
1371 		goto end;
1372 	}
1373 
1374 	ret = expand_probe_args(sc_die, pf, args);
1375 	if (ret < 0)
1376 		goto end;
1377 
1378 	tev->nargs = ret;
1379 	tev->args = zalloc(sizeof(struct probe_trace_arg) * tev->nargs);
1380 	if (tev->args == NULL) {
1381 		ret = -ENOMEM;
1382 		goto end;
1383 	}
1384 
1385 	/* Find each argument */
1386 	for (i = 0; i < tev->nargs; i++) {
1387 		pf->pvar = &args[i];
1388 		pf->tvar = &tev->args[i];
1389 		/* Variable should be found from scope DIE */
1390 		ret = find_variable(sc_die, pf);
1391 		if (ret != 0)
1392 			break;
1393 	}
1394 
1395 end:
1396 	if (ret) {
1397 		clear_probe_trace_event(tev);
1398 		tf->ntevs--;
1399 	}
1400 	free(args);
1401 	return ret;
1402 }
1403 
1404 static int fill_empty_trace_arg(struct perf_probe_event *pev,
1405 				struct probe_trace_event *tevs, int ntevs)
1406 {
1407 	char **valp;
1408 	char *type;
1409 	int i, j, ret;
1410 
1411 	for (i = 0; i < pev->nargs; i++) {
1412 		type = NULL;
1413 		for (j = 0; j < ntevs; j++) {
1414 			if (tevs[j].args[i].value) {
1415 				type = tevs[j].args[i].type;
1416 				break;
1417 			}
1418 		}
1419 		if (j == ntevs) {
1420 			print_var_not_found(pev->args[i].var);
1421 			return -ENOENT;
1422 		}
1423 		for (j = 0; j < ntevs; j++) {
1424 			valp = &tevs[j].args[i].value;
1425 			if (*valp)
1426 				continue;
1427 
1428 			ret = asprintf(valp, "\\%lx", probe_conf.magic_num);
1429 			if (ret < 0)
1430 				return -ENOMEM;
1431 			/* Note that type can be NULL */
1432 			if (type) {
1433 				tevs[j].args[i].type = strdup(type);
1434 				if (!tevs[j].args[i].type)
1435 					return -ENOMEM;
1436 			}
1437 		}
1438 	}
1439 	return 0;
1440 }
1441 
1442 /* Find probe_trace_events specified by perf_probe_event from debuginfo */
1443 int debuginfo__find_trace_events(struct debuginfo *dbg,
1444 				 struct perf_probe_event *pev,
1445 				 struct probe_trace_event **tevs)
1446 {
1447 	struct trace_event_finder tf = {
1448 			.pf = {.pev = pev, .callback = add_probe_trace_event},
1449 			.max_tevs = probe_conf.max_probes, .mod = dbg->mod};
1450 	int ret, i;
1451 
1452 	/* Allocate result tevs array */
1453 	*tevs = zalloc(sizeof(struct probe_trace_event) * tf.max_tevs);
1454 	if (*tevs == NULL)
1455 		return -ENOMEM;
1456 
1457 	tf.tevs = *tevs;
1458 	tf.ntevs = 0;
1459 
1460 	if (pev->nargs != 0 && immediate_value_is_supported())
1461 		tf.pf.skip_empty_arg = true;
1462 
1463 	ret = debuginfo__find_probes(dbg, &tf.pf);
1464 	if (ret >= 0 && tf.pf.skip_empty_arg)
1465 		ret = fill_empty_trace_arg(pev, tf.tevs, tf.ntevs);
1466 
1467 	if (ret < 0) {
1468 		for (i = 0; i < tf.ntevs; i++)
1469 			clear_probe_trace_event(&tf.tevs[i]);
1470 		zfree(tevs);
1471 		return ret;
1472 	}
1473 
1474 	return (ret < 0) ? ret : tf.ntevs;
1475 }
1476 
1477 /* Collect available variables in this scope */
1478 static int collect_variables_cb(Dwarf_Die *die_mem, void *data)
1479 {
1480 	struct available_var_finder *af = data;
1481 	struct variable_list *vl;
1482 	struct strbuf buf = STRBUF_INIT;
1483 	int tag, ret;
1484 
1485 	vl = &af->vls[af->nvls - 1];
1486 
1487 	tag = dwarf_tag(die_mem);
1488 	if (tag == DW_TAG_formal_parameter ||
1489 	    tag == DW_TAG_variable) {
1490 		ret = convert_variable_location(die_mem, af->pf.addr,
1491 						af->pf.fb_ops, &af->pf.sp_die,
1492 						af->pf.machine, NULL);
1493 		if (ret == 0 || ret == -ERANGE) {
1494 			int ret2;
1495 			bool externs = !af->child;
1496 
1497 			if (strbuf_init(&buf, 64) < 0)
1498 				goto error;
1499 
1500 			if (probe_conf.show_location_range) {
1501 				if (!externs)
1502 					ret2 = strbuf_add(&buf,
1503 						ret ? "[INV]\t" : "[VAL]\t", 6);
1504 				else
1505 					ret2 = strbuf_add(&buf, "[EXT]\t", 6);
1506 				if (ret2)
1507 					goto error;
1508 			}
1509 
1510 			ret2 = die_get_varname(die_mem, &buf);
1511 
1512 			if (!ret2 && probe_conf.show_location_range &&
1513 				!externs) {
1514 				if (strbuf_addch(&buf, '\t') < 0)
1515 					goto error;
1516 				ret2 = die_get_var_range(&af->pf.sp_die,
1517 							die_mem, &buf);
1518 			}
1519 
1520 			pr_debug("Add new var: %s\n", buf.buf);
1521 			if (ret2 == 0) {
1522 				strlist__add(vl->vars,
1523 					strbuf_detach(&buf, NULL));
1524 			}
1525 			strbuf_release(&buf);
1526 		}
1527 	}
1528 
1529 	if (af->child && dwarf_haspc(die_mem, af->pf.addr))
1530 		return DIE_FIND_CB_CONTINUE;
1531 	else
1532 		return DIE_FIND_CB_SIBLING;
1533 error:
1534 	strbuf_release(&buf);
1535 	pr_debug("Error in strbuf\n");
1536 	return DIE_FIND_CB_END;
1537 }
1538 
1539 static bool available_var_finder_overlap(struct available_var_finder *af)
1540 {
1541 	int i;
1542 
1543 	for (i = 0; i < af->nvls; i++) {
1544 		if (af->pf.addr == af->vls[i].point.address)
1545 			return true;
1546 	}
1547 	return false;
1548 
1549 }
1550 
1551 /* Add a found vars into available variables list */
1552 static int add_available_vars(Dwarf_Die *sc_die, struct probe_finder *pf)
1553 {
1554 	struct available_var_finder *af =
1555 			container_of(pf, struct available_var_finder, pf);
1556 	struct perf_probe_point *pp = &pf->pev->point;
1557 	struct variable_list *vl;
1558 	Dwarf_Die die_mem;
1559 	int ret;
1560 
1561 	/*
1562 	 * For some reason (e.g. different column assigned to same address),
1563 	 * this callback can be called with the address which already passed.
1564 	 * Ignore it first.
1565 	 */
1566 	if (available_var_finder_overlap(af))
1567 		return 0;
1568 
1569 	/* Check number of tevs */
1570 	if (af->nvls == af->max_vls) {
1571 		pr_warning("Too many( > %d) probe point found.\n", af->max_vls);
1572 		return -ERANGE;
1573 	}
1574 	vl = &af->vls[af->nvls++];
1575 
1576 	/* Trace point should be converted from subprogram DIE */
1577 	ret = convert_to_trace_point(&pf->sp_die, af->mod, pf->addr,
1578 				     pp->retprobe, pp->function, &vl->point);
1579 	if (ret < 0)
1580 		return ret;
1581 
1582 	pr_debug("Probe point found: %s+%lu\n", vl->point.symbol,
1583 		 vl->point.offset);
1584 
1585 	/* Find local variables */
1586 	vl->vars = strlist__new(NULL, NULL);
1587 	if (vl->vars == NULL)
1588 		return -ENOMEM;
1589 	af->child = true;
1590 	die_find_child(sc_die, collect_variables_cb, (void *)af, &die_mem);
1591 
1592 	/* Find external variables */
1593 	if (!probe_conf.show_ext_vars)
1594 		goto out;
1595 	/* Don't need to search child DIE for external vars. */
1596 	af->child = false;
1597 	die_find_child(&pf->cu_die, collect_variables_cb, (void *)af, &die_mem);
1598 
1599 out:
1600 	if (strlist__empty(vl->vars)) {
1601 		strlist__delete(vl->vars);
1602 		vl->vars = NULL;
1603 	}
1604 
1605 	return ret;
1606 }
1607 
1608 /*
1609  * Find available variables at given probe point
1610  * Return the number of found probe points. Return 0 if there is no
1611  * matched probe point. Return <0 if an error occurs.
1612  */
1613 int debuginfo__find_available_vars_at(struct debuginfo *dbg,
1614 				      struct perf_probe_event *pev,
1615 				      struct variable_list **vls)
1616 {
1617 	struct available_var_finder af = {
1618 			.pf = {.pev = pev, .callback = add_available_vars},
1619 			.mod = dbg->mod,
1620 			.max_vls = probe_conf.max_probes};
1621 	int ret;
1622 
1623 	/* Allocate result vls array */
1624 	*vls = zalloc(sizeof(struct variable_list) * af.max_vls);
1625 	if (*vls == NULL)
1626 		return -ENOMEM;
1627 
1628 	af.vls = *vls;
1629 	af.nvls = 0;
1630 
1631 	ret = debuginfo__find_probes(dbg, &af.pf);
1632 	if (ret < 0) {
1633 		/* Free vlist for error */
1634 		while (af.nvls--) {
1635 			zfree(&af.vls[af.nvls].point.symbol);
1636 			strlist__delete(af.vls[af.nvls].vars);
1637 		}
1638 		zfree(vls);
1639 		return ret;
1640 	}
1641 
1642 	return (ret < 0) ? ret : af.nvls;
1643 }
1644 
1645 /* For the kernel module, we need a special code to get a DIE */
1646 int debuginfo__get_text_offset(struct debuginfo *dbg, Dwarf_Addr *offs,
1647 				bool adjust_offset)
1648 {
1649 	int n, i;
1650 	Elf32_Word shndx;
1651 	Elf_Scn *scn;
1652 	Elf *elf;
1653 	GElf_Shdr mem, *shdr;
1654 	const char *p;
1655 
1656 	elf = dwfl_module_getelf(dbg->mod, &dbg->bias);
1657 	if (!elf)
1658 		return -EINVAL;
1659 
1660 	/* Get the number of relocations */
1661 	n = dwfl_module_relocations(dbg->mod);
1662 	if (n < 0)
1663 		return -ENOENT;
1664 	/* Search the relocation related .text section */
1665 	for (i = 0; i < n; i++) {
1666 		p = dwfl_module_relocation_info(dbg->mod, i, &shndx);
1667 		if (strcmp(p, ".text") == 0) {
1668 			/* OK, get the section header */
1669 			scn = elf_getscn(elf, shndx);
1670 			if (!scn)
1671 				return -ENOENT;
1672 			shdr = gelf_getshdr(scn, &mem);
1673 			if (!shdr)
1674 				return -ENOENT;
1675 			*offs = shdr->sh_addr;
1676 			if (adjust_offset)
1677 				*offs -= shdr->sh_offset;
1678 		}
1679 	}
1680 	return 0;
1681 }
1682 
1683 /* Reverse search */
1684 int debuginfo__find_probe_point(struct debuginfo *dbg, unsigned long addr,
1685 				struct perf_probe_point *ppt)
1686 {
1687 	Dwarf_Die cudie, spdie, indie;
1688 	Dwarf_Addr _addr = 0, baseaddr = 0;
1689 	const char *fname = NULL, *func = NULL, *basefunc = NULL, *tmp;
1690 	int baseline = 0, lineno = 0, ret = 0;
1691 
1692 	/* We always need to relocate the address for aranges */
1693 	if (debuginfo__get_text_offset(dbg, &baseaddr, false) == 0)
1694 		addr += baseaddr;
1695 	/* Find cu die */
1696 	if (!dwarf_addrdie(dbg->dbg, (Dwarf_Addr)addr, &cudie)) {
1697 		pr_warning("Failed to find debug information for address %lx\n",
1698 			   addr);
1699 		ret = -EINVAL;
1700 		goto end;
1701 	}
1702 
1703 	/* Find a corresponding line (filename and lineno) */
1704 	cu_find_lineinfo(&cudie, addr, &fname, &lineno);
1705 	/* Don't care whether it failed or not */
1706 
1707 	/* Find a corresponding function (name, baseline and baseaddr) */
1708 	if (die_find_realfunc(&cudie, (Dwarf_Addr)addr, &spdie)) {
1709 		/* Get function entry information */
1710 		func = basefunc = dwarf_diename(&spdie);
1711 		if (!func ||
1712 		    die_entrypc(&spdie, &baseaddr) != 0 ||
1713 		    dwarf_decl_line(&spdie, &baseline) != 0) {
1714 			lineno = 0;
1715 			goto post;
1716 		}
1717 
1718 		fname = dwarf_decl_file(&spdie);
1719 		if (addr == (unsigned long)baseaddr) {
1720 			/* Function entry - Relative line number is 0 */
1721 			lineno = baseline;
1722 			goto post;
1723 		}
1724 
1725 		/* Track down the inline functions step by step */
1726 		while (die_find_top_inlinefunc(&spdie, (Dwarf_Addr)addr,
1727 						&indie)) {
1728 			/* There is an inline function */
1729 			if (die_entrypc(&indie, &_addr) == 0 &&
1730 			    _addr == addr) {
1731 				/*
1732 				 * addr is at an inline function entry.
1733 				 * In this case, lineno should be the call-site
1734 				 * line number. (overwrite lineinfo)
1735 				 */
1736 				lineno = die_get_call_lineno(&indie);
1737 				fname = die_get_call_file(&indie);
1738 				break;
1739 			} else {
1740 				/*
1741 				 * addr is in an inline function body.
1742 				 * Since lineno points one of the lines
1743 				 * of the inline function, baseline should
1744 				 * be the entry line of the inline function.
1745 				 */
1746 				tmp = dwarf_diename(&indie);
1747 				if (!tmp ||
1748 				    dwarf_decl_line(&indie, &baseline) != 0)
1749 					break;
1750 				func = tmp;
1751 				spdie = indie;
1752 			}
1753 		}
1754 		/* Verify the lineno and baseline are in a same file */
1755 		tmp = dwarf_decl_file(&spdie);
1756 		if (!tmp || strcmp(tmp, fname) != 0)
1757 			lineno = 0;
1758 	}
1759 
1760 post:
1761 	/* Make a relative line number or an offset */
1762 	if (lineno)
1763 		ppt->line = lineno - baseline;
1764 	else if (basefunc) {
1765 		ppt->offset = addr - (unsigned long)baseaddr;
1766 		func = basefunc;
1767 	}
1768 
1769 	/* Duplicate strings */
1770 	if (func) {
1771 		ppt->function = strdup(func);
1772 		if (ppt->function == NULL) {
1773 			ret = -ENOMEM;
1774 			goto end;
1775 		}
1776 	}
1777 	if (fname) {
1778 		ppt->file = strdup(fname);
1779 		if (ppt->file == NULL) {
1780 			zfree(&ppt->function);
1781 			ret = -ENOMEM;
1782 			goto end;
1783 		}
1784 	}
1785 end:
1786 	if (ret == 0 && (fname || func))
1787 		ret = 1;	/* Found a point */
1788 	return ret;
1789 }
1790 
1791 /* Add a line and store the src path */
1792 static int line_range_add_line(const char *src, unsigned int lineno,
1793 			       struct line_range *lr)
1794 {
1795 	/* Copy source path */
1796 	if (!lr->path) {
1797 		lr->path = strdup(src);
1798 		if (lr->path == NULL)
1799 			return -ENOMEM;
1800 	}
1801 	return intlist__add(lr->line_list, lineno);
1802 }
1803 
1804 static int line_range_walk_cb(const char *fname, int lineno,
1805 			      Dwarf_Addr addr __maybe_unused,
1806 			      void *data)
1807 {
1808 	struct line_finder *lf = data;
1809 	const char *__fname;
1810 	int __lineno;
1811 	int err;
1812 
1813 	if ((strtailcmp(fname, lf->fname) != 0) ||
1814 	    (lf->lno_s > lineno || lf->lno_e < lineno))
1815 		return 0;
1816 
1817 	/* Make sure this line can be reversable */
1818 	if (cu_find_lineinfo(&lf->cu_die, addr, &__fname, &__lineno) > 0
1819 	    && (lineno != __lineno || strcmp(fname, __fname)))
1820 		return 0;
1821 
1822 	err = line_range_add_line(fname, lineno, lf->lr);
1823 	if (err < 0 && err != -EEXIST)
1824 		return err;
1825 
1826 	return 0;
1827 }
1828 
1829 /* Find line range from its line number */
1830 static int find_line_range_by_line(Dwarf_Die *sp_die, struct line_finder *lf)
1831 {
1832 	int ret;
1833 
1834 	ret = die_walk_lines(sp_die ?: &lf->cu_die, line_range_walk_cb, lf);
1835 
1836 	/* Update status */
1837 	if (ret >= 0)
1838 		if (!intlist__empty(lf->lr->line_list))
1839 			ret = lf->found = 1;
1840 		else
1841 			ret = 0;	/* Lines are not found */
1842 	else {
1843 		zfree(&lf->lr->path);
1844 	}
1845 	return ret;
1846 }
1847 
1848 static int line_range_inline_cb(Dwarf_Die *in_die, void *data)
1849 {
1850 	int ret = find_line_range_by_line(in_die, data);
1851 
1852 	/*
1853 	 * We have to check all instances of inlined function, because
1854 	 * some execution paths can be optimized out depends on the
1855 	 * function argument of instances. However, if an error occurs,
1856 	 * it should be handled by the caller.
1857 	 */
1858 	return ret < 0 ? ret : 0;
1859 }
1860 
1861 /* Search function definition from function name */
1862 static int line_range_search_cb(Dwarf_Die *sp_die, void *data)
1863 {
1864 	struct dwarf_callback_param *param = data;
1865 	struct line_finder *lf = param->data;
1866 	struct line_range *lr = lf->lr;
1867 
1868 	/* Check declared file */
1869 	if (lr->file && strtailcmp(lr->file, dwarf_decl_file(sp_die)))
1870 		return DWARF_CB_OK;
1871 
1872 	if (die_is_func_def(sp_die) &&
1873 	    die_match_name(sp_die, lr->function)) {
1874 		lf->fname = dwarf_decl_file(sp_die);
1875 		dwarf_decl_line(sp_die, &lr->offset);
1876 		pr_debug("fname: %s, lineno:%d\n", lf->fname, lr->offset);
1877 		lf->lno_s = lr->offset + lr->start;
1878 		if (lf->lno_s < 0)	/* Overflow */
1879 			lf->lno_s = INT_MAX;
1880 		lf->lno_e = lr->offset + lr->end;
1881 		if (lf->lno_e < 0)	/* Overflow */
1882 			lf->lno_e = INT_MAX;
1883 		pr_debug("New line range: %d to %d\n", lf->lno_s, lf->lno_e);
1884 		lr->start = lf->lno_s;
1885 		lr->end = lf->lno_e;
1886 		if (!die_is_func_instance(sp_die))
1887 			param->retval = die_walk_instances(sp_die,
1888 						line_range_inline_cb, lf);
1889 		else
1890 			param->retval = find_line_range_by_line(sp_die, lf);
1891 		return DWARF_CB_ABORT;
1892 	}
1893 	return DWARF_CB_OK;
1894 }
1895 
1896 static int find_line_range_by_func(struct line_finder *lf)
1897 {
1898 	struct dwarf_callback_param param = {.data = (void *)lf, .retval = 0};
1899 	dwarf_getfuncs(&lf->cu_die, line_range_search_cb, &param, 0);
1900 	return param.retval;
1901 }
1902 
1903 int debuginfo__find_line_range(struct debuginfo *dbg, struct line_range *lr)
1904 {
1905 	struct line_finder lf = {.lr = lr, .found = 0};
1906 	int ret = 0;
1907 	Dwarf_Off off = 0, noff;
1908 	size_t cuhl;
1909 	Dwarf_Die *diep;
1910 	const char *comp_dir;
1911 
1912 	/* Fastpath: lookup by function name from .debug_pubnames section */
1913 	if (lr->function) {
1914 		struct pubname_callback_param pubname_param = {
1915 			.function = lr->function, .file = lr->file,
1916 			.cu_die = &lf.cu_die, .sp_die = &lf.sp_die, .found = 0};
1917 		struct dwarf_callback_param line_range_param = {
1918 			.data = (void *)&lf, .retval = 0};
1919 
1920 		dwarf_getpubnames(dbg->dbg, pubname_search_cb,
1921 				  &pubname_param, 0);
1922 		if (pubname_param.found) {
1923 			line_range_search_cb(&lf.sp_die, &line_range_param);
1924 			if (lf.found)
1925 				goto found;
1926 		}
1927 	}
1928 
1929 	/* Loop on CUs (Compilation Unit) */
1930 	while (!lf.found && ret >= 0) {
1931 		if (dwarf_nextcu(dbg->dbg, off, &noff, &cuhl,
1932 				 NULL, NULL, NULL) != 0)
1933 			break;
1934 
1935 		/* Get the DIE(Debugging Information Entry) of this CU */
1936 		diep = dwarf_offdie(dbg->dbg, off + cuhl, &lf.cu_die);
1937 		if (!diep)
1938 			continue;
1939 
1940 		/* Check if target file is included. */
1941 		if (lr->file)
1942 			lf.fname = cu_find_realpath(&lf.cu_die, lr->file);
1943 		else
1944 			lf.fname = 0;
1945 
1946 		if (!lr->file || lf.fname) {
1947 			if (lr->function)
1948 				ret = find_line_range_by_func(&lf);
1949 			else {
1950 				lf.lno_s = lr->start;
1951 				lf.lno_e = lr->end;
1952 				ret = find_line_range_by_line(NULL, &lf);
1953 			}
1954 		}
1955 		off = noff;
1956 	}
1957 
1958 found:
1959 	/* Store comp_dir */
1960 	if (lf.found) {
1961 		comp_dir = cu_get_comp_dir(&lf.cu_die);
1962 		if (comp_dir) {
1963 			lr->comp_dir = strdup(comp_dir);
1964 			if (!lr->comp_dir)
1965 				ret = -ENOMEM;
1966 		}
1967 	}
1968 
1969 	pr_debug("path: %s\n", lr->path);
1970 	return (ret < 0) ? ret : lf.found;
1971 }
1972 
1973 /*
1974  * Find a src file from a DWARF tag path. Prepend optional source path prefix
1975  * and chop off leading directories that do not exist. Result is passed back as
1976  * a newly allocated path on success.
1977  * Return 0 if file was found and readable, -errno otherwise.
1978  */
1979 int get_real_path(const char *raw_path, const char *comp_dir,
1980 			 char **new_path)
1981 {
1982 	const char *prefix = symbol_conf.source_prefix;
1983 
1984 	if (!prefix) {
1985 		if (raw_path[0] != '/' && comp_dir)
1986 			/* If not an absolute path, try to use comp_dir */
1987 			prefix = comp_dir;
1988 		else {
1989 			if (access(raw_path, R_OK) == 0) {
1990 				*new_path = strdup(raw_path);
1991 				return *new_path ? 0 : -ENOMEM;
1992 			} else
1993 				return -errno;
1994 		}
1995 	}
1996 
1997 	*new_path = malloc((strlen(prefix) + strlen(raw_path) + 2));
1998 	if (!*new_path)
1999 		return -ENOMEM;
2000 
2001 	for (;;) {
2002 		sprintf(*new_path, "%s/%s", prefix, raw_path);
2003 
2004 		if (access(*new_path, R_OK) == 0)
2005 			return 0;
2006 
2007 		if (!symbol_conf.source_prefix) {
2008 			/* In case of searching comp_dir, don't retry */
2009 			zfree(new_path);
2010 			return -errno;
2011 		}
2012 
2013 		switch (errno) {
2014 		case ENAMETOOLONG:
2015 		case ENOENT:
2016 		case EROFS:
2017 		case EFAULT:
2018 			raw_path = strchr(++raw_path, '/');
2019 			if (!raw_path) {
2020 				zfree(new_path);
2021 				return -ENOENT;
2022 			}
2023 			continue;
2024 
2025 		default:
2026 			zfree(new_path);
2027 			return -errno;
2028 		}
2029 	}
2030 }
2031