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