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