4b1890204e9962e3f3bdfd02a08a1fb01d632f13
[platform/kernel/linux-rpi.git] / tools / perf / util / dwarf-aux.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * dwarf-aux.c : libdw auxiliary interfaces
4  */
5
6 #include <errno.h>
7 #include <inttypes.h>
8 #include <stdbool.h>
9 #include <stdlib.h>
10 #include "debug.h"
11 #include "dwarf-aux.h"
12 #include "strbuf.h"
13 #include "string2.h"
14
15 /**
16  * cu_find_realpath - Find the realpath of the target file
17  * @cu_die: A DIE(dwarf information entry) of CU(compilation Unit)
18  * @fname:  The tail filename of the target file
19  *
20  * Find the real(long) path of @fname in @cu_die.
21  */
22 const char *cu_find_realpath(Dwarf_Die *cu_die, const char *fname)
23 {
24         Dwarf_Files *files;
25         size_t nfiles, i;
26         const char *src = NULL;
27         int ret;
28
29         if (!fname)
30                 return NULL;
31
32         ret = dwarf_getsrcfiles(cu_die, &files, &nfiles);
33         if (ret != 0)
34                 return NULL;
35
36         for (i = 0; i < nfiles; i++) {
37                 src = dwarf_filesrc(files, i, NULL, NULL);
38                 if (strtailcmp(src, fname) == 0)
39                         break;
40         }
41         if (i == nfiles)
42                 return NULL;
43         return src;
44 }
45
46 /**
47  * cu_get_comp_dir - Get the path of compilation directory
48  * @cu_die: a CU DIE
49  *
50  * Get the path of compilation directory of given @cu_die.
51  * Since this depends on DW_AT_comp_dir, older gcc will not
52  * embedded it. In that case, this returns NULL.
53  */
54 const char *cu_get_comp_dir(Dwarf_Die *cu_die)
55 {
56         Dwarf_Attribute attr;
57         if (dwarf_attr(cu_die, DW_AT_comp_dir, &attr) == NULL)
58                 return NULL;
59         return dwarf_formstring(&attr);
60 }
61
62 /**
63  * cu_find_lineinfo - Get a line number and file name for given address
64  * @cu_die: a CU DIE
65  * @addr: An address
66  * @fname: a pointer which returns the file name string
67  * @lineno: a pointer which returns the line number
68  *
69  * Find a line number and file name for @addr in @cu_die.
70  */
71 int cu_find_lineinfo(Dwarf_Die *cu_die, unsigned long addr,
72                     const char **fname, int *lineno)
73 {
74         Dwarf_Line *line;
75         Dwarf_Addr laddr;
76
77         line = dwarf_getsrc_die(cu_die, (Dwarf_Addr)addr);
78         if (line && dwarf_lineaddr(line, &laddr) == 0 &&
79             addr == (unsigned long)laddr && dwarf_lineno(line, lineno) == 0) {
80                 *fname = dwarf_linesrc(line, NULL, NULL);
81                 if (!*fname)
82                         /* line number is useless without filename */
83                         *lineno = 0;
84         }
85
86         return *lineno ?: -ENOENT;
87 }
88
89 static int __die_find_inline_cb(Dwarf_Die *die_mem, void *data);
90
91 /**
92  * cu_walk_functions_at - Walk on function DIEs at given address
93  * @cu_die: A CU DIE
94  * @addr: An address
95  * @callback: A callback which called with found DIEs
96  * @data: A user data
97  *
98  * Walk on function DIEs at given @addr in @cu_die. Passed DIEs
99  * should be subprogram or inlined-subroutines.
100  */
101 int cu_walk_functions_at(Dwarf_Die *cu_die, Dwarf_Addr addr,
102                     int (*callback)(Dwarf_Die *, void *), void *data)
103 {
104         Dwarf_Die die_mem;
105         Dwarf_Die *sc_die;
106         int ret = -ENOENT;
107
108         /* Inlined function could be recursive. Trace it until fail */
109         for (sc_die = die_find_realfunc(cu_die, addr, &die_mem);
110              sc_die != NULL;
111              sc_die = die_find_child(sc_die, __die_find_inline_cb, &addr,
112                                      &die_mem)) {
113                 ret = callback(sc_die, data);
114                 if (ret)
115                         break;
116         }
117
118         return ret;
119
120 }
121
122 /**
123  * die_get_linkage_name - Get the linkage name of the object
124  * @dw_die: A DIE of the object
125  *
126  * Get the linkage name attiribute of given @dw_die.
127  * For C++ binary, the linkage name will be the mangled symbol.
128  */
129 const char *die_get_linkage_name(Dwarf_Die *dw_die)
130 {
131         Dwarf_Attribute attr;
132
133         if (dwarf_attr_integrate(dw_die, DW_AT_linkage_name, &attr) == NULL)
134                 return NULL;
135         return dwarf_formstring(&attr);
136 }
137
138 /**
139  * die_compare_name - Compare diename and tname
140  * @dw_die: a DIE
141  * @tname: a string of target name
142  *
143  * Compare the name of @dw_die and @tname. Return false if @dw_die has no name.
144  */
145 bool die_compare_name(Dwarf_Die *dw_die, const char *tname)
146 {
147         const char *name;
148
149         name = dwarf_diename(dw_die);
150         return name ? (strcmp(tname, name) == 0) : false;
151 }
152
153 /**
154  * die_match_name - Match diename/linkage name and glob
155  * @dw_die: a DIE
156  * @glob: a string of target glob pattern
157  *
158  * Glob matching the name of @dw_die and @glob. Return false if matching fail.
159  * This also match linkage name.
160  */
161 bool die_match_name(Dwarf_Die *dw_die, const char *glob)
162 {
163         const char *name;
164
165         name = dwarf_diename(dw_die);
166         if (name && strglobmatch(name, glob))
167                 return true;
168         /* fall back to check linkage name */
169         name = die_get_linkage_name(dw_die);
170         if (name && strglobmatch(name, glob))
171                 return true;
172
173         return false;
174 }
175
176 /**
177  * die_get_call_lineno - Get callsite line number of inline-function instance
178  * @in_die: a DIE of an inlined function instance
179  *
180  * Get call-site line number of @in_die. This means from where the inline
181  * function is called.
182  */
183 int die_get_call_lineno(Dwarf_Die *in_die)
184 {
185         Dwarf_Attribute attr;
186         Dwarf_Word ret;
187
188         if (!dwarf_attr(in_die, DW_AT_call_line, &attr))
189                 return -ENOENT;
190
191         dwarf_formudata(&attr, &ret);
192         return (int)ret;
193 }
194
195 /**
196  * die_get_type - Get type DIE
197  * @vr_die: a DIE of a variable
198  * @die_mem: where to store a type DIE
199  *
200  * Get a DIE of the type of given variable (@vr_die), and store
201  * it to die_mem. Return NULL if fails to get a type DIE.
202  */
203 Dwarf_Die *die_get_type(Dwarf_Die *vr_die, Dwarf_Die *die_mem)
204 {
205         Dwarf_Attribute attr;
206
207         if (dwarf_attr_integrate(vr_die, DW_AT_type, &attr) &&
208             dwarf_formref_die(&attr, die_mem))
209                 return die_mem;
210         else
211                 return NULL;
212 }
213
214 /* Get a type die, but skip qualifiers */
215 static Dwarf_Die *__die_get_real_type(Dwarf_Die *vr_die, Dwarf_Die *die_mem)
216 {
217         int tag;
218
219         do {
220                 vr_die = die_get_type(vr_die, die_mem);
221                 if (!vr_die)
222                         break;
223                 tag = dwarf_tag(vr_die);
224         } while (tag == DW_TAG_const_type ||
225                  tag == DW_TAG_restrict_type ||
226                  tag == DW_TAG_volatile_type ||
227                  tag == DW_TAG_shared_type);
228
229         return vr_die;
230 }
231
232 /**
233  * die_get_real_type - Get a type die, but skip qualifiers and typedef
234  * @vr_die: a DIE of a variable
235  * @die_mem: where to store a type DIE
236  *
237  * Get a DIE of the type of given variable (@vr_die), and store
238  * it to die_mem. Return NULL if fails to get a type DIE.
239  * If the type is qualifiers (e.g. const) or typedef, this skips it
240  * and tries to find real type (structure or basic types, e.g. int).
241  */
242 Dwarf_Die *die_get_real_type(Dwarf_Die *vr_die, Dwarf_Die *die_mem)
243 {
244         do {
245                 vr_die = __die_get_real_type(vr_die, die_mem);
246         } while (vr_die && dwarf_tag(vr_die) == DW_TAG_typedef);
247
248         return vr_die;
249 }
250
251 /* Get attribute and translate it as a udata */
252 static int die_get_attr_udata(Dwarf_Die *tp_die, unsigned int attr_name,
253                               Dwarf_Word *result)
254 {
255         Dwarf_Attribute attr;
256
257         if (dwarf_attr(tp_die, attr_name, &attr) == NULL ||
258             dwarf_formudata(&attr, result) != 0)
259                 return -ENOENT;
260
261         return 0;
262 }
263
264 /* Get attribute and translate it as a sdata */
265 static int die_get_attr_sdata(Dwarf_Die *tp_die, unsigned int attr_name,
266                               Dwarf_Sword *result)
267 {
268         Dwarf_Attribute attr;
269
270         if (dwarf_attr(tp_die, attr_name, &attr) == NULL ||
271             dwarf_formsdata(&attr, result) != 0)
272                 return -ENOENT;
273
274         return 0;
275 }
276
277 /**
278  * die_is_signed_type - Check whether a type DIE is signed or not
279  * @tp_die: a DIE of a type
280  *
281  * Get the encoding of @tp_die and return true if the encoding
282  * is signed.
283  */
284 bool die_is_signed_type(Dwarf_Die *tp_die)
285 {
286         Dwarf_Word ret;
287
288         if (die_get_attr_udata(tp_die, DW_AT_encoding, &ret))
289                 return false;
290
291         return (ret == DW_ATE_signed_char || ret == DW_ATE_signed ||
292                 ret == DW_ATE_signed_fixed);
293 }
294
295 /**
296  * die_is_func_def - Ensure that this DIE is a subprogram and definition
297  * @dw_die: a DIE
298  *
299  * Ensure that this DIE is a subprogram and NOT a declaration. This
300  * returns true if @dw_die is a function definition.
301  **/
302 bool die_is_func_def(Dwarf_Die *dw_die)
303 {
304         Dwarf_Attribute attr;
305
306         return (dwarf_tag(dw_die) == DW_TAG_subprogram &&
307                 dwarf_attr(dw_die, DW_AT_declaration, &attr) == NULL);
308 }
309
310 /**
311  * die_is_func_instance - Ensure that this DIE is an instance of a subprogram
312  * @dw_die: a DIE
313  *
314  * Ensure that this DIE is an instance (which has an entry address).
315  * This returns true if @dw_die is a function instance. If not, you need to
316  * call die_walk_instances() to find actual instances.
317  **/
318 bool die_is_func_instance(Dwarf_Die *dw_die)
319 {
320         Dwarf_Addr tmp;
321         Dwarf_Attribute attr_mem;
322
323         /* Actually gcc optimizes non-inline as like as inlined */
324         return !dwarf_func_inline(dw_die) &&
325                (dwarf_entrypc(dw_die, &tmp) == 0 ||
326                 dwarf_attr(dw_die, DW_AT_ranges, &attr_mem) != NULL);
327 }
328
329 /**
330  * die_get_data_member_location - Get the data-member offset
331  * @mb_die: a DIE of a member of a data structure
332  * @offs: The offset of the member in the data structure
333  *
334  * Get the offset of @mb_die in the data structure including @mb_die, and
335  * stores result offset to @offs. If any error occurs this returns errno.
336  */
337 int die_get_data_member_location(Dwarf_Die *mb_die, Dwarf_Word *offs)
338 {
339         Dwarf_Attribute attr;
340         Dwarf_Op *expr;
341         size_t nexpr;
342         int ret;
343
344         if (dwarf_attr(mb_die, DW_AT_data_member_location, &attr) == NULL)
345                 return -ENOENT;
346
347         if (dwarf_formudata(&attr, offs) != 0) {
348                 /* DW_AT_data_member_location should be DW_OP_plus_uconst */
349                 ret = dwarf_getlocation(&attr, &expr, &nexpr);
350                 if (ret < 0 || nexpr == 0)
351                         return -ENOENT;
352
353                 if (expr[0].atom != DW_OP_plus_uconst || nexpr != 1) {
354                         pr_debug("Unable to get offset:Unexpected OP %x (%zd)\n",
355                                  expr[0].atom, nexpr);
356                         return -ENOTSUP;
357                 }
358                 *offs = (Dwarf_Word)expr[0].number;
359         }
360         return 0;
361 }
362
363 /* Get the call file index number in CU DIE */
364 static int die_get_call_fileno(Dwarf_Die *in_die)
365 {
366         Dwarf_Sword idx;
367
368         if (die_get_attr_sdata(in_die, DW_AT_call_file, &idx) == 0)
369                 return (int)idx;
370         else
371                 return -ENOENT;
372 }
373
374 /* Get the declared file index number in CU DIE */
375 static int die_get_decl_fileno(Dwarf_Die *pdie)
376 {
377         Dwarf_Sword idx;
378
379         if (die_get_attr_sdata(pdie, DW_AT_decl_file, &idx) == 0)
380                 return (int)idx;
381         else
382                 return -ENOENT;
383 }
384
385 /**
386  * die_get_call_file - Get callsite file name of inlined function instance
387  * @in_die: a DIE of an inlined function instance
388  *
389  * Get call-site file name of @in_die. This means from which file the inline
390  * function is called.
391  */
392 const char *die_get_call_file(Dwarf_Die *in_die)
393 {
394         Dwarf_Die cu_die;
395         Dwarf_Files *files;
396         int idx;
397
398         idx = die_get_call_fileno(in_die);
399         if (idx < 0 || !dwarf_diecu(in_die, &cu_die, NULL, NULL) ||
400             dwarf_getsrcfiles(&cu_die, &files, NULL) != 0)
401                 return NULL;
402
403         return dwarf_filesrc(files, idx, NULL, NULL);
404 }
405
406
407 /**
408  * die_find_child - Generic DIE search function in DIE tree
409  * @rt_die: a root DIE
410  * @callback: a callback function
411  * @data: a user data passed to the callback function
412  * @die_mem: a buffer for result DIE
413  *
414  * Trace DIE tree from @rt_die and call @callback for each child DIE.
415  * If @callback returns DIE_FIND_CB_END, this stores the DIE into
416  * @die_mem and returns it. If @callback returns DIE_FIND_CB_CONTINUE,
417  * this continues to trace the tree. Optionally, @callback can return
418  * DIE_FIND_CB_CHILD and DIE_FIND_CB_SIBLING, those means trace only
419  * the children and trace only the siblings respectively.
420  * Returns NULL if @callback can't find any appropriate DIE.
421  */
422 Dwarf_Die *die_find_child(Dwarf_Die *rt_die,
423                           int (*callback)(Dwarf_Die *, void *),
424                           void *data, Dwarf_Die *die_mem)
425 {
426         Dwarf_Die child_die;
427         int ret;
428
429         ret = dwarf_child(rt_die, die_mem);
430         if (ret != 0)
431                 return NULL;
432
433         do {
434                 ret = callback(die_mem, data);
435                 if (ret == DIE_FIND_CB_END)
436                         return die_mem;
437
438                 if ((ret & DIE_FIND_CB_CHILD) &&
439                     die_find_child(die_mem, callback, data, &child_die)) {
440                         memcpy(die_mem, &child_die, sizeof(Dwarf_Die));
441                         return die_mem;
442                 }
443         } while ((ret & DIE_FIND_CB_SIBLING) &&
444                  dwarf_siblingof(die_mem, die_mem) == 0);
445
446         return NULL;
447 }
448
449 struct __addr_die_search_param {
450         Dwarf_Addr      addr;
451         Dwarf_Die       *die_mem;
452 };
453
454 static int __die_search_func_tail_cb(Dwarf_Die *fn_die, void *data)
455 {
456         struct __addr_die_search_param *ad = data;
457         Dwarf_Addr addr = 0;
458
459         if (dwarf_tag(fn_die) == DW_TAG_subprogram &&
460             !dwarf_highpc(fn_die, &addr) &&
461             addr == ad->addr) {
462                 memcpy(ad->die_mem, fn_die, sizeof(Dwarf_Die));
463                 return DWARF_CB_ABORT;
464         }
465         return DWARF_CB_OK;
466 }
467
468 /**
469  * die_find_tailfunc - Search for a non-inlined function with tail call at
470  * given address
471  * @cu_die: a CU DIE which including @addr
472  * @addr: target address
473  * @die_mem: a buffer for result DIE
474  *
475  * Search for a non-inlined function DIE with tail call at @addr. Stores the
476  * DIE to @die_mem and returns it if found. Returns NULL if failed.
477  */
478 Dwarf_Die *die_find_tailfunc(Dwarf_Die *cu_die, Dwarf_Addr addr,
479                                     Dwarf_Die *die_mem)
480 {
481         struct __addr_die_search_param ad;
482         ad.addr = addr;
483         ad.die_mem = die_mem;
484         /* dwarf_getscopes can't find subprogram. */
485         if (!dwarf_getfuncs(cu_die, __die_search_func_tail_cb, &ad, 0))
486                 return NULL;
487         else
488                 return die_mem;
489 }
490
491 /* die_find callback for non-inlined function search */
492 static int __die_search_func_cb(Dwarf_Die *fn_die, void *data)
493 {
494         struct __addr_die_search_param *ad = data;
495
496         /*
497          * Since a declaration entry doesn't has given pc, this always returns
498          * function definition entry.
499          */
500         if (dwarf_tag(fn_die) == DW_TAG_subprogram &&
501             dwarf_haspc(fn_die, ad->addr)) {
502                 memcpy(ad->die_mem, fn_die, sizeof(Dwarf_Die));
503                 return DWARF_CB_ABORT;
504         }
505         return DWARF_CB_OK;
506 }
507
508 /**
509  * die_find_realfunc - Search a non-inlined function at given address
510  * @cu_die: a CU DIE which including @addr
511  * @addr: target address
512  * @die_mem: a buffer for result DIE
513  *
514  * Search a non-inlined function DIE which includes @addr. Stores the
515  * DIE to @die_mem and returns it if found. Returns NULL if failed.
516  */
517 Dwarf_Die *die_find_realfunc(Dwarf_Die *cu_die, Dwarf_Addr addr,
518                                     Dwarf_Die *die_mem)
519 {
520         struct __addr_die_search_param ad;
521         ad.addr = addr;
522         ad.die_mem = die_mem;
523         /* dwarf_getscopes can't find subprogram. */
524         if (!dwarf_getfuncs(cu_die, __die_search_func_cb, &ad, 0))
525                 return NULL;
526         else
527                 return die_mem;
528 }
529
530 /* die_find callback for inline function search */
531 static int __die_find_inline_cb(Dwarf_Die *die_mem, void *data)
532 {
533         Dwarf_Addr *addr = data;
534
535         if (dwarf_tag(die_mem) == DW_TAG_inlined_subroutine &&
536             dwarf_haspc(die_mem, *addr))
537                 return DIE_FIND_CB_END;
538
539         return DIE_FIND_CB_CONTINUE;
540 }
541
542 /**
543  * die_find_top_inlinefunc - Search the top inlined function at given address
544  * @sp_die: a subprogram DIE which including @addr
545  * @addr: target address
546  * @die_mem: a buffer for result DIE
547  *
548  * Search an inlined function DIE which includes @addr. Stores the
549  * DIE to @die_mem and returns it if found. Returns NULL if failed.
550  * Even if several inlined functions are expanded recursively, this
551  * doesn't trace it down, and returns the topmost one.
552  */
553 Dwarf_Die *die_find_top_inlinefunc(Dwarf_Die *sp_die, Dwarf_Addr addr,
554                                    Dwarf_Die *die_mem)
555 {
556         return die_find_child(sp_die, __die_find_inline_cb, &addr, die_mem);
557 }
558
559 /**
560  * die_find_inlinefunc - Search an inlined function at given address
561  * @sp_die: a subprogram DIE which including @addr
562  * @addr: target address
563  * @die_mem: a buffer for result DIE
564  *
565  * Search an inlined function DIE which includes @addr. Stores the
566  * DIE to @die_mem and returns it if found. Returns NULL if failed.
567  * If several inlined functions are expanded recursively, this trace
568  * it down and returns deepest one.
569  */
570 Dwarf_Die *die_find_inlinefunc(Dwarf_Die *sp_die, Dwarf_Addr addr,
571                                Dwarf_Die *die_mem)
572 {
573         Dwarf_Die tmp_die;
574
575         sp_die = die_find_child(sp_die, __die_find_inline_cb, &addr, &tmp_die);
576         if (!sp_die)
577                 return NULL;
578
579         /* Inlined function could be recursive. Trace it until fail */
580         while (sp_die) {
581                 memcpy(die_mem, sp_die, sizeof(Dwarf_Die));
582                 sp_die = die_find_child(sp_die, __die_find_inline_cb, &addr,
583                                         &tmp_die);
584         }
585
586         return die_mem;
587 }
588
589 struct __instance_walk_param {
590         void    *addr;
591         int     (*callback)(Dwarf_Die *, void *);
592         void    *data;
593         int     retval;
594 };
595
596 static int __die_walk_instances_cb(Dwarf_Die *inst, void *data)
597 {
598         struct __instance_walk_param *iwp = data;
599         Dwarf_Attribute attr_mem;
600         Dwarf_Die origin_mem;
601         Dwarf_Attribute *attr;
602         Dwarf_Die *origin;
603         int tmp;
604
605         attr = dwarf_attr(inst, DW_AT_abstract_origin, &attr_mem);
606         if (attr == NULL)
607                 return DIE_FIND_CB_CONTINUE;
608
609         origin = dwarf_formref_die(attr, &origin_mem);
610         if (origin == NULL || origin->addr != iwp->addr)
611                 return DIE_FIND_CB_CONTINUE;
612
613         /* Ignore redundant instances */
614         if (dwarf_tag(inst) == DW_TAG_inlined_subroutine) {
615                 dwarf_decl_line(origin, &tmp);
616                 if (die_get_call_lineno(inst) == tmp) {
617                         tmp = die_get_decl_fileno(origin);
618                         if (die_get_call_fileno(inst) == tmp)
619                                 return DIE_FIND_CB_CONTINUE;
620                 }
621         }
622
623         iwp->retval = iwp->callback(inst, iwp->data);
624
625         return (iwp->retval) ? DIE_FIND_CB_END : DIE_FIND_CB_CONTINUE;
626 }
627
628 /**
629  * die_walk_instances - Walk on instances of given DIE
630  * @or_die: an abstract original DIE
631  * @callback: a callback function which is called with instance DIE
632  * @data: user data
633  *
634  * Walk on the instances of give @in_die. @in_die must be an inlined function
635  * declartion. This returns the return value of @callback if it returns
636  * non-zero value, or -ENOENT if there is no instance.
637  */
638 int die_walk_instances(Dwarf_Die *or_die, int (*callback)(Dwarf_Die *, void *),
639                        void *data)
640 {
641         Dwarf_Die cu_die;
642         Dwarf_Die die_mem;
643         struct __instance_walk_param iwp = {
644                 .addr = or_die->addr,
645                 .callback = callback,
646                 .data = data,
647                 .retval = -ENOENT,
648         };
649
650         if (dwarf_diecu(or_die, &cu_die, NULL, NULL) == NULL)
651                 return -ENOENT;
652
653         die_find_child(&cu_die, __die_walk_instances_cb, &iwp, &die_mem);
654
655         return iwp.retval;
656 }
657
658 /* Line walker internal parameters */
659 struct __line_walk_param {
660         bool recursive;
661         line_walk_callback_t callback;
662         void *data;
663         int retval;
664 };
665
666 static int __die_walk_funclines_cb(Dwarf_Die *in_die, void *data)
667 {
668         struct __line_walk_param *lw = data;
669         Dwarf_Addr addr = 0;
670         const char *fname;
671         int lineno;
672
673         if (dwarf_tag(in_die) == DW_TAG_inlined_subroutine) {
674                 fname = die_get_call_file(in_die);
675                 lineno = die_get_call_lineno(in_die);
676                 if (fname && lineno > 0 && dwarf_entrypc(in_die, &addr) == 0) {
677                         lw->retval = lw->callback(fname, lineno, addr, lw->data);
678                         if (lw->retval != 0)
679                                 return DIE_FIND_CB_END;
680                 }
681                 if (!lw->recursive)
682                         return DIE_FIND_CB_SIBLING;
683         }
684
685         if (addr) {
686                 fname = dwarf_decl_file(in_die);
687                 if (fname && dwarf_decl_line(in_die, &lineno) == 0) {
688                         lw->retval = lw->callback(fname, lineno, addr, lw->data);
689                         if (lw->retval != 0)
690                                 return DIE_FIND_CB_END;
691                 }
692         }
693
694         /* Continue to search nested inlined function call-sites */
695         return DIE_FIND_CB_CONTINUE;
696 }
697
698 /* Walk on lines of blocks included in given DIE */
699 static int __die_walk_funclines(Dwarf_Die *sp_die, bool recursive,
700                                 line_walk_callback_t callback, void *data)
701 {
702         struct __line_walk_param lw = {
703                 .recursive = recursive,
704                 .callback = callback,
705                 .data = data,
706                 .retval = 0,
707         };
708         Dwarf_Die die_mem;
709         Dwarf_Addr addr;
710         const char *fname;
711         int lineno;
712
713         /* Handle function declaration line */
714         fname = dwarf_decl_file(sp_die);
715         if (fname && dwarf_decl_line(sp_die, &lineno) == 0 &&
716             dwarf_entrypc(sp_die, &addr) == 0) {
717                 lw.retval = callback(fname, lineno, addr, data);
718                 if (lw.retval != 0)
719                         goto done;
720         }
721         die_find_child(sp_die, __die_walk_funclines_cb, &lw, &die_mem);
722 done:
723         return lw.retval;
724 }
725
726 static int __die_walk_culines_cb(Dwarf_Die *sp_die, void *data)
727 {
728         struct __line_walk_param *lw = data;
729
730         /*
731          * Since inlined function can include another inlined function in
732          * the same file, we need to walk in it recursively.
733          */
734         lw->retval = __die_walk_funclines(sp_die, true, lw->callback, lw->data);
735         if (lw->retval != 0)
736                 return DWARF_CB_ABORT;
737
738         return DWARF_CB_OK;
739 }
740
741 /**
742  * die_walk_lines - Walk on lines inside given DIE
743  * @rt_die: a root DIE (CU, subprogram or inlined_subroutine)
744  * @callback: callback routine
745  * @data: user data
746  *
747  * Walk on all lines inside given @rt_die and call @callback on each line.
748  * If the @rt_die is a function, walk only on the lines inside the function,
749  * otherwise @rt_die must be a CU DIE.
750  * Note that this walks not only dwarf line list, but also function entries
751  * and inline call-site.
752  */
753 int die_walk_lines(Dwarf_Die *rt_die, line_walk_callback_t callback, void *data)
754 {
755         Dwarf_Lines *lines;
756         Dwarf_Line *line;
757         Dwarf_Addr addr;
758         const char *fname, *decf = NULL;
759         int lineno, ret = 0;
760         int decl = 0, inl;
761         Dwarf_Die die_mem, *cu_die;
762         size_t nlines, i;
763
764         /* Get the CU die */
765         if (dwarf_tag(rt_die) != DW_TAG_compile_unit) {
766                 cu_die = dwarf_diecu(rt_die, &die_mem, NULL, NULL);
767                 dwarf_decl_line(rt_die, &decl);
768                 decf = dwarf_decl_file(rt_die);
769         } else
770                 cu_die = rt_die;
771         if (!cu_die) {
772                 pr_debug2("Failed to get CU from given DIE.\n");
773                 return -EINVAL;
774         }
775
776         /* Get lines list in the CU */
777         if (dwarf_getsrclines(cu_die, &lines, &nlines) != 0) {
778                 pr_debug2("Failed to get source lines on this CU.\n");
779                 return -ENOENT;
780         }
781         pr_debug2("Get %zd lines from this CU\n", nlines);
782
783         /* Walk on the lines on lines list */
784         for (i = 0; i < nlines; i++) {
785                 line = dwarf_onesrcline(lines, i);
786                 if (line == NULL ||
787                     dwarf_lineno(line, &lineno) != 0 ||
788                     dwarf_lineaddr(line, &addr) != 0) {
789                         pr_debug2("Failed to get line info. "
790                                   "Possible error in debuginfo.\n");
791                         continue;
792                 }
793                 /* Filter lines based on address */
794                 if (rt_die != cu_die) {
795                         /*
796                          * Address filtering
797                          * The line is included in given function, and
798                          * no inline block includes it.
799                          */
800                         if (!dwarf_haspc(rt_die, addr))
801                                 continue;
802                         if (die_find_inlinefunc(rt_die, addr, &die_mem)) {
803                                 dwarf_decl_line(&die_mem, &inl);
804                                 if (inl != decl ||
805                                     decf != dwarf_decl_file(&die_mem))
806                                         continue;
807                         }
808                 }
809                 /* Get source line */
810                 fname = dwarf_linesrc(line, NULL, NULL);
811
812                 ret = callback(fname, lineno, addr, data);
813                 if (ret != 0)
814                         return ret;
815         }
816
817         /*
818          * Dwarf lines doesn't include function declarations and inlined
819          * subroutines. We have to check functions list or given function.
820          */
821         if (rt_die != cu_die)
822                 /*
823                  * Don't need walk inlined functions recursively, because
824                  * inner inlined functions don't have the lines of the
825                  * specified function.
826                  */
827                 ret = __die_walk_funclines(rt_die, false, callback, data);
828         else {
829                 struct __line_walk_param param = {
830                         .callback = callback,
831                         .data = data,
832                         .retval = 0,
833                 };
834                 dwarf_getfuncs(cu_die, __die_walk_culines_cb, &param, 0);
835                 ret = param.retval;
836         }
837
838         return ret;
839 }
840
841 struct __find_variable_param {
842         const char *name;
843         Dwarf_Addr addr;
844 };
845
846 static int __die_find_variable_cb(Dwarf_Die *die_mem, void *data)
847 {
848         struct __find_variable_param *fvp = data;
849         Dwarf_Attribute attr;
850         int tag;
851
852         tag = dwarf_tag(die_mem);
853         if ((tag == DW_TAG_formal_parameter ||
854              tag == DW_TAG_variable) &&
855             die_compare_name(die_mem, fvp->name) &&
856         /* Does the DIE have location information or external instance? */
857             (dwarf_attr(die_mem, DW_AT_external, &attr) ||
858              dwarf_attr(die_mem, DW_AT_location, &attr)))
859                 return DIE_FIND_CB_END;
860         if (dwarf_haspc(die_mem, fvp->addr))
861                 return DIE_FIND_CB_CONTINUE;
862         else
863                 return DIE_FIND_CB_SIBLING;
864 }
865
866 /**
867  * die_find_variable_at - Find a given name variable at given address
868  * @sp_die: a function DIE
869  * @name: variable name
870  * @addr: address
871  * @die_mem: a buffer for result DIE
872  *
873  * Find a variable DIE called @name at @addr in @sp_die.
874  */
875 Dwarf_Die *die_find_variable_at(Dwarf_Die *sp_die, const char *name,
876                                 Dwarf_Addr addr, Dwarf_Die *die_mem)
877 {
878         struct __find_variable_param fvp = { .name = name, .addr = addr};
879
880         return die_find_child(sp_die, __die_find_variable_cb, (void *)&fvp,
881                               die_mem);
882 }
883
884 static int __die_find_member_cb(Dwarf_Die *die_mem, void *data)
885 {
886         const char *name = data;
887
888         if (dwarf_tag(die_mem) == DW_TAG_member) {
889                 if (die_compare_name(die_mem, name))
890                         return DIE_FIND_CB_END;
891                 else if (!dwarf_diename(die_mem)) {     /* Unnamed structure */
892                         Dwarf_Die type_die, tmp_die;
893                         if (die_get_type(die_mem, &type_die) &&
894                             die_find_member(&type_die, name, &tmp_die))
895                                 return DIE_FIND_CB_END;
896                 }
897         }
898         return DIE_FIND_CB_SIBLING;
899 }
900
901 /**
902  * die_find_member - Find a given name member in a data structure
903  * @st_die: a data structure type DIE
904  * @name: member name
905  * @die_mem: a buffer for result DIE
906  *
907  * Find a member DIE called @name in @st_die.
908  */
909 Dwarf_Die *die_find_member(Dwarf_Die *st_die, const char *name,
910                            Dwarf_Die *die_mem)
911 {
912         return die_find_child(st_die, __die_find_member_cb, (void *)name,
913                               die_mem);
914 }
915
916 /**
917  * die_get_typename - Get the name of given variable DIE
918  * @vr_die: a variable DIE
919  * @buf: a strbuf for result type name
920  *
921  * Get the name of @vr_die and stores it to @buf. Return 0 if succeeded.
922  * and Return -ENOENT if failed to find type name.
923  * Note that the result will stores typedef name if possible, and stores
924  * "*(function_type)" if the type is a function pointer.
925  */
926 int die_get_typename(Dwarf_Die *vr_die, struct strbuf *buf)
927 {
928         Dwarf_Die type;
929         int tag, ret;
930         const char *tmp = "";
931
932         if (__die_get_real_type(vr_die, &type) == NULL)
933                 return -ENOENT;
934
935         tag = dwarf_tag(&type);
936         if (tag == DW_TAG_array_type || tag == DW_TAG_pointer_type)
937                 tmp = "*";
938         else if (tag == DW_TAG_subroutine_type) {
939                 /* Function pointer */
940                 return strbuf_add(buf, "(function_type)", 15);
941         } else {
942                 if (!dwarf_diename(&type))
943                         return -ENOENT;
944                 if (tag == DW_TAG_union_type)
945                         tmp = "union ";
946                 else if (tag == DW_TAG_structure_type)
947                         tmp = "struct ";
948                 else if (tag == DW_TAG_enumeration_type)
949                         tmp = "enum ";
950                 /* Write a base name */
951                 return strbuf_addf(buf, "%s%s", tmp, dwarf_diename(&type));
952         }
953         ret = die_get_typename(&type, buf);
954         return ret ? ret : strbuf_addstr(buf, tmp);
955 }
956
957 /**
958  * die_get_varname - Get the name and type of given variable DIE
959  * @vr_die: a variable DIE
960  * @buf: a strbuf for type and variable name
961  *
962  * Get the name and type of @vr_die and stores it in @buf as "type\tname".
963  */
964 int die_get_varname(Dwarf_Die *vr_die, struct strbuf *buf)
965 {
966         int ret;
967
968         ret = die_get_typename(vr_die, buf);
969         if (ret < 0) {
970                 pr_debug("Failed to get type, make it unknown.\n");
971                 ret = strbuf_add(buf, " (unknown_type)", 14);
972         }
973
974         return ret < 0 ? ret : strbuf_addf(buf, "\t%s", dwarf_diename(vr_die));
975 }
976
977 #ifdef HAVE_DWARF_GETLOCATIONS_SUPPORT
978 /**
979  * die_get_var_innermost_scope - Get innermost scope range of given variable DIE
980  * @sp_die: a subprogram DIE
981  * @vr_die: a variable DIE
982  * @buf: a strbuf for variable byte offset range
983  *
984  * Get the innermost scope range of @vr_die and stores it in @buf as
985  * "@<function_name+[NN-NN,NN-NN]>".
986  */
987 static int die_get_var_innermost_scope(Dwarf_Die *sp_die, Dwarf_Die *vr_die,
988                                 struct strbuf *buf)
989 {
990         Dwarf_Die *scopes;
991         int count;
992         size_t offset = 0;
993         Dwarf_Addr base;
994         Dwarf_Addr start, end;
995         Dwarf_Addr entry;
996         int ret;
997         bool first = true;
998         const char *name;
999
1000         ret = die_entrypc(sp_die, &entry);
1001         if (ret)
1002                 return ret;
1003
1004         name = dwarf_diename(sp_die);
1005         if (!name)
1006                 return -ENOENT;
1007
1008         count = dwarf_getscopes_die(vr_die, &scopes);
1009
1010         /* (*SCOPES)[1] is the DIE for the scope containing that scope */
1011         if (count <= 1) {
1012                 ret = -EINVAL;
1013                 goto out;
1014         }
1015
1016         while ((offset = dwarf_ranges(&scopes[1], offset, &base,
1017                                         &start, &end)) > 0) {
1018                 start -= entry;
1019                 end -= entry;
1020
1021                 if (first) {
1022                         ret = strbuf_addf(buf, "@<%s+[%" PRIu64 "-%" PRIu64,
1023                                           name, start, end);
1024                         first = false;
1025                 } else {
1026                         ret = strbuf_addf(buf, ",%" PRIu64 "-%" PRIu64,
1027                                           start, end);
1028                 }
1029                 if (ret < 0)
1030                         goto out;
1031         }
1032
1033         if (!first)
1034                 ret = strbuf_add(buf, "]>", 2);
1035
1036 out:
1037         free(scopes);
1038         return ret;
1039 }
1040
1041 /**
1042  * die_get_var_range - Get byte offset range of given variable DIE
1043  * @sp_die: a subprogram DIE
1044  * @vr_die: a variable DIE
1045  * @buf: a strbuf for type and variable name and byte offset range
1046  *
1047  * Get the byte offset range of @vr_die and stores it in @buf as
1048  * "@<function_name+[NN-NN,NN-NN]>".
1049  */
1050 int die_get_var_range(Dwarf_Die *sp_die, Dwarf_Die *vr_die, struct strbuf *buf)
1051 {
1052         int ret = 0;
1053         Dwarf_Addr base;
1054         Dwarf_Addr start, end;
1055         Dwarf_Addr entry;
1056         Dwarf_Op *op;
1057         size_t nops;
1058         size_t offset = 0;
1059         Dwarf_Attribute attr;
1060         bool first = true;
1061         const char *name;
1062
1063         ret = die_entrypc(sp_die, &entry);
1064         if (ret)
1065                 return ret;
1066
1067         name = dwarf_diename(sp_die);
1068         if (!name)
1069                 return -ENOENT;
1070
1071         if (dwarf_attr(vr_die, DW_AT_location, &attr) == NULL)
1072                 return -EINVAL;
1073
1074         while ((offset = dwarf_getlocations(&attr, offset, &base,
1075                                         &start, &end, &op, &nops)) > 0) {
1076                 if (start == 0) {
1077                         /* Single Location Descriptions */
1078                         ret = die_get_var_innermost_scope(sp_die, vr_die, buf);
1079                         goto out;
1080                 }
1081
1082                 /* Location Lists */
1083                 start -= entry;
1084                 end -= entry;
1085                 if (first) {
1086                         ret = strbuf_addf(buf, "@<%s+[%" PRIu64 "-%" PRIu64,
1087                                           name, start, end);
1088                         first = false;
1089                 } else {
1090                         ret = strbuf_addf(buf, ",%" PRIu64 "-%" PRIu64,
1091                                           start, end);
1092                 }
1093                 if (ret < 0)
1094                         goto out;
1095         }
1096
1097         if (!first)
1098                 ret = strbuf_add(buf, "]>", 2);
1099 out:
1100         return ret;
1101 }
1102 #else
1103 int die_get_var_range(Dwarf_Die *sp_die __maybe_unused,
1104                       Dwarf_Die *vr_die __maybe_unused,
1105                       struct strbuf *buf __maybe_unused)
1106 {
1107         return -ENOTSUP;
1108 }
1109 #endif
1110
1111 /*
1112  * die_has_loclist - Check if DW_AT_location of @vr_die is a location list
1113  * @vr_die: a variable DIE
1114  */
1115 static bool die_has_loclist(Dwarf_Die *vr_die)
1116 {
1117         Dwarf_Attribute loc;
1118         int tag = dwarf_tag(vr_die);
1119
1120         if (tag != DW_TAG_formal_parameter &&
1121             tag != DW_TAG_variable)
1122                 return false;
1123
1124         return (dwarf_attr_integrate(vr_die, DW_AT_location, &loc) &&
1125                 dwarf_whatform(&loc) == DW_FORM_sec_offset);
1126 }
1127
1128 /*
1129  * die_is_optimized_target - Check if target program is compiled with
1130  * optimization
1131  * @cu_die: a CU DIE
1132  *
1133  * For any object in given CU whose DW_AT_location is a location list,
1134  * target program is compiled with optimization. This is applicable to
1135  * clang as well.
1136  */
1137 bool die_is_optimized_target(Dwarf_Die *cu_die)
1138 {
1139         Dwarf_Die tmp_die;
1140
1141         if (die_has_loclist(cu_die))
1142                 return true;
1143
1144         if (!dwarf_child(cu_die, &tmp_die) &&
1145             die_is_optimized_target(&tmp_die))
1146                 return true;
1147
1148         if (!dwarf_siblingof(cu_die, &tmp_die) &&
1149             die_is_optimized_target(&tmp_die))
1150                 return true;
1151
1152         return false;
1153 }
1154
1155 /*
1156  * die_search_idx - Search index of given line address
1157  * @lines: Line records of single CU
1158  * @nr_lines: Number of @lines
1159  * @addr: address we are looking for
1160  * @idx: index to be set by this function (return value)
1161  *
1162  * Search for @addr by looping over every lines of CU. If address
1163  * matches, set index of that line in @idx. Note that single source
1164  * line can have multiple line records. i.e. single source line can
1165  * have multiple index.
1166  */
1167 static bool die_search_idx(Dwarf_Lines *lines, unsigned long nr_lines,
1168                            Dwarf_Addr addr, unsigned long *idx)
1169 {
1170         unsigned long i;
1171         Dwarf_Addr tmp;
1172
1173         for (i = 0; i < nr_lines; i++) {
1174                 if (dwarf_lineaddr(dwarf_onesrcline(lines, i), &tmp))
1175                         return false;
1176
1177                 if (tmp == addr) {
1178                         *idx = i;
1179                         return true;
1180                 }
1181         }
1182         return false;
1183 }
1184
1185 /*
1186  * die_get_postprologue_addr - Search next address after function prologue
1187  * @entrypc_idx: entrypc index
1188  * @lines: Line records of single CU
1189  * @nr_lines: Number of @lines
1190  * @hignpc: high PC address of function
1191  * @postprologue_addr: Next address after function prologue (return value)
1192  *
1193  * Look for prologue-end marker. If there is no explicit marker, return
1194  * address of next line record or next source line.
1195  */
1196 static bool die_get_postprologue_addr(unsigned long entrypc_idx,
1197                                       Dwarf_Lines *lines,
1198                                       unsigned long nr_lines,
1199                                       Dwarf_Addr highpc,
1200                                       Dwarf_Addr *postprologue_addr)
1201 {
1202         unsigned long i;
1203         int entrypc_lno, lno;
1204         Dwarf_Line *line;
1205         Dwarf_Addr addr;
1206         bool p_end;
1207
1208         /* entrypc_lno is actual source line number */
1209         line = dwarf_onesrcline(lines, entrypc_idx);
1210         if (dwarf_lineno(line, &entrypc_lno))
1211                 return false;
1212
1213         for (i = entrypc_idx; i < nr_lines; i++) {
1214                 line = dwarf_onesrcline(lines, i);
1215
1216                 if (dwarf_lineaddr(line, &addr) ||
1217                     dwarf_lineno(line, &lno)    ||
1218                     dwarf_lineprologueend(line, &p_end))
1219                         return false;
1220
1221                 /* highpc is exclusive. [entrypc,highpc) */
1222                 if (addr >= highpc)
1223                         break;
1224
1225                 /* clang supports prologue-end marker */
1226                 if (p_end)
1227                         break;
1228
1229                 /* Actual next line in source */
1230                 if (lno != entrypc_lno)
1231                         break;
1232
1233                 /*
1234                  * Single source line can have multiple line records.
1235                  * For Example,
1236                  *     void foo() { printf("hello\n"); }
1237                  * contains two line records. One points to declaration and
1238                  * other points to printf() line. Variable 'lno' won't get
1239                  * incremented in this case but 'i' will.
1240                  */
1241                 if (i != entrypc_idx)
1242                         break;
1243         }
1244
1245         dwarf_lineaddr(line, postprologue_addr);
1246         if (*postprologue_addr >= highpc)
1247                 dwarf_lineaddr(dwarf_onesrcline(lines, i - 1),
1248                                postprologue_addr);
1249
1250         return true;
1251 }
1252
1253 /*
1254  * die_skip_prologue - Use next address after prologue as probe location
1255  * @sp_die: a subprogram DIE
1256  * @cu_die: a CU DIE
1257  * @entrypc: entrypc of the function
1258  *
1259  * Function prologue prepares stack and registers before executing function
1260  * logic. When target program is compiled without optimization, function
1261  * parameter information is only valid after prologue. When we probe entrypc
1262  * of the function, and try to record function parameter, it contains
1263  * garbage value.
1264  */
1265 void die_skip_prologue(Dwarf_Die *sp_die, Dwarf_Die *cu_die,
1266                        Dwarf_Addr *entrypc)
1267 {
1268         size_t nr_lines = 0;
1269         unsigned long entrypc_idx = 0;
1270         Dwarf_Lines *lines = NULL;
1271         Dwarf_Addr postprologue_addr;
1272         Dwarf_Addr highpc;
1273
1274         if (dwarf_highpc(sp_die, &highpc))
1275                 return;
1276
1277         if (dwarf_getsrclines(cu_die, &lines, &nr_lines))
1278                 return;
1279
1280         if (!die_search_idx(lines, nr_lines, *entrypc, &entrypc_idx))
1281                 return;
1282
1283         if (!die_get_postprologue_addr(entrypc_idx, lines, nr_lines,
1284                                        highpc, &postprologue_addr))
1285                 return;
1286
1287         *entrypc = postprologue_addr;
1288 }