]> sourceware.org Git - systemtap.git/blame - dwflpp.cxx
PR16019: improve duplicate error elimination
[systemtap.git] / dwflpp.cxx
CommitLineData
440f755a 1// C++ interface to dwfl
4c5d9906 2// Copyright (C) 2005-2013 Red Hat Inc.
440f755a
JS
3// Copyright (C) 2005-2007 Intel Corporation.
4// Copyright (C) 2008 James.Bottomley@HansenPartnership.com
5//
6// This file is part of systemtap, and is free software. You can
7// redistribute it and/or modify it under the terms of the GNU General
8// Public License (GPL); either version 2, or (at your option) any
9// later version.
10
11#include "dwflpp.h"
12#include "config.h"
13#include "staptree.h"
14#include "elaborate.h"
15#include "tapsets.h"
16#include "task_finder.h"
17#include "translate.h"
18#include "session.h"
19#include "util.h"
20#include "buildrun.h"
21#include "dwarf_wrappers.h"
22#include "auto_free.h"
23#include "hash.h"
2ed04863 24#include "rpm_finder.h"
3db9c843 25#include "setupdwfl.h"
440f755a
JS
26
27#include <cstdlib>
28#include <algorithm>
29#include <deque>
30#include <iostream>
31#include <map>
440f755a
JS
32#include <set>
33#include <sstream>
34#include <stdexcept>
35#include <vector>
36#include <cstdarg>
37#include <cassert>
38#include <iomanip>
39#include <cerrno>
40
41extern "C" {
42#include <fcntl.h>
43#include <elfutils/libdwfl.h>
44#include <elfutils/libdw.h>
45#include <dwarf.h>
46#include <elf.h>
47#include <obstack.h>
48#include <regex.h>
49#include <glob.h>
50#include <fnmatch.h>
51#include <stdio.h>
52#include <sys/types.h>
53
54#include "loc2c.h"
55#define __STDC_FORMAT_MACROS
56#include <inttypes.h>
57}
58
ae4163d9
MW
59// Older glibc elf.h don't know about this new constant.
60#ifndef STB_GNU_UNIQUE
61#define STB_GNU_UNIQUE 10
62#endif
63
440f755a 64
9aa8ffce
JS
65// debug flag to compare to the uncached version from libdw
66// #define DEBUG_DWFLPP_GETSCOPES 1
67
68
440f755a
JS
69using namespace std;
70using namespace __gnu_cxx;
71
72
73static string TOK_KERNEL("kernel");
74
75
ae2552da 76dwflpp::dwflpp(systemtap_session & session, const string& name, bool kernel_p):
d0b4a5ff 77 sess(session), module(NULL), module_bias(0), mod_info(NULL),
68983551 78 module_start(0), module_end(0), cu(NULL),
74fe61bc
LB
79 module_dwarf(NULL), function(NULL), blacklist_func(), blacklist_func_ret(),
80 blacklist_file(), blacklist_enabled(false)
440f755a 81{
ae2552da 82 if (kernel_p)
2eb99c62 83 setup_kernel(name, session);
440f755a 84 else
0c16d512
JS
85 {
86 vector<string> modules;
87 modules.push_back(name);
88 setup_user(modules);
89 }
90}
91
59c11f91
MW
92dwflpp::dwflpp(systemtap_session & session, const vector<string>& names,
93 bool kernel_p):
0c16d512 94 sess(session), module(NULL), module_bias(0), mod_info(NULL),
68983551 95 module_start(0), module_end(0), cu(NULL),
729455a7 96 module_dwarf(NULL), function(NULL), blacklist_enabled(false)
0c16d512 97{
59c11f91
MW
98 if (kernel_p)
99 setup_kernel(names);
100 else
101 setup_user(names);
440f755a
JS
102}
103
440f755a
JS
104dwflpp::~dwflpp()
105{
c9efa5c9
JS
106 delete_map(module_cu_cache);
107 delete_map(cu_function_cache);
4df79aaf 108 delete_map(mod_function_cache);
c9efa5c9
JS
109 delete_map(cu_inl_function_cache);
110 delete_map(global_alias_cache);
111 delete_map(cu_die_parent_cache);
9aa8ffce 112
68983551 113 dwfl_ptr.reset();
435f53a7
FCE
114 // NB: don't "delete mod_info;", as that may be shared
115 // between dwflpp instances, and are stored in
116 // session.module_cache[] anyway.
117}
118
119
120module_cache::~module_cache ()
121{
122 delete_map(cache);
440f755a
JS
123}
124
125
440f755a
JS
126void
127dwflpp::get_module_dwarf(bool required, bool report)
128{
129 module_dwarf = dwfl_module_getdwarf(module, &module_bias);
130 mod_info->dwarf_status = (module_dwarf ? info_present : info_absent);
131 if (!module_dwarf && report)
132 {
f9bbd346 133 string msg = _("cannot find ");
440f755a
JS
134 if (module_name == "")
135 msg += "kernel";
136 else
137 msg += string("module ") + module_name;
138 msg += " debuginfo";
139
140 int i = dwfl_errno();
141 if (i)
142 msg += string(": ") + dwfl_errmsg (i);
143
555fa669
FCE
144 msg += " [man warning::debuginfo]";
145
2ed04863
WC
146 /* add module_name to list to find rpm */
147 find_debug_rpms(sess, module_name.c_str());
148
440f755a
JS
149 if (required)
150 throw semantic_error (msg);
2713ea24
CM
151 else
152 sess.print_warning(msg);
440f755a
JS
153 }
154}
155
156
157void
158dwflpp::focus_on_module(Dwfl_Module * m, module_info * mi)
159{
160 module = m;
161 mod_info = mi;
162 if (m)
163 {
f517ee24
JS
164 module_name = dwfl_module_info(module, NULL, &module_start, &module_end,
165 NULL, NULL, NULL, NULL) ?: "module";
440f755a
JS
166 }
167 else
168 {
169 assert(mi && mi->name && mi->name == TOK_KERNEL);
170 module_name = mi->name;
171 module_start = 0;
172 module_end = 0;
173 module_bias = mi->bias;
174 }
175
176 // Reset existing pointers and names
177
178 module_dwarf = NULL;
179
440f755a
JS
180 cu = NULL;
181
182 function_name.clear();
183 function = NULL;
184}
185
186
187void
188dwflpp::focus_on_cu(Dwarf_Die * c)
189{
190 assert(c);
191 assert(module);
192
193 cu = c;
440f755a
JS
194
195 // Reset existing pointers and names
196 function_name.clear();
197 function = NULL;
198}
199
200
54417494
JS
201string
202dwflpp::cu_name(void)
203{
204 return dwarf_diename(cu) ?: "<unknown source>";
205}
206
207
440f755a
JS
208void
209dwflpp::focus_on_function(Dwarf_Die * f)
210{
211 assert(f);
212 assert(module);
213 assert(cu);
214
215 function = f;
f517ee24 216 function_name = dwarf_diename(function) ?: "function";
440f755a
JS
217}
218
219
1f8592d1
MW
220/* Return the Dwarf_Die for the given address in the current module.
221 * The address should be in the module address address space (this
222 * function will take care of any dw bias).
223 */
1adf8ef1
JS
224Dwarf_Die *
225dwflpp::query_cu_containing_address(Dwarf_Addr a)
440f755a
JS
226{
227 Dwarf_Addr bias;
68983551 228 assert(dwfl_ptr.get()->dwfl);
b6fa229b 229 assert(module);
440f755a 230 get_module_dwarf();
b6fa229b 231
440f755a 232 Dwarf_Die* cudie = dwfl_module_addrdie(module, a, &bias);
440f755a 233 assert(bias == module_bias);
1adf8ef1 234 return cudie;
440f755a
JS
235}
236
237
440f755a 238bool
5f4c8c6e 239dwflpp::module_name_matches(const string& pattern)
440f755a
JS
240{
241 bool t = (fnmatch(pattern.c_str(), module_name.c_str(), 0) == 0);
242 if (t && sess.verbose>3)
f9bbd346
LB
243 clog << _F("pattern '%s' matches module '%s'\n",
244 pattern.c_str(), module_name.c_str());
044a265a
FCE
245 if (!t && sess.verbose>4)
246 clog << _F("pattern '%s' does not match module '%s'\n",
247 pattern.c_str(), module_name.c_str());
248
440f755a
JS
249 return t;
250}
251
252
253bool
665e1256 254dwflpp::name_has_wildcard (const string& pattern)
440f755a
JS
255{
256 return (pattern.find('*') != string::npos ||
257 pattern.find('?') != string::npos ||
258 pattern.find('[') != string::npos);
259}
260
261
262bool
5f4c8c6e 263dwflpp::module_name_final_match(const string& pattern)
440f755a
JS
264{
265 // Assume module_name_matches(). Can there be any more matches?
266 // Not unless the pattern is a wildcard, since module names are
267 // presumed unique.
268 return !name_has_wildcard(pattern);
269}
270
271
272bool
5f4c8c6e 273dwflpp::function_name_matches_pattern(const string& name, const string& pattern)
440f755a
JS
274{
275 bool t = (fnmatch(pattern.c_str(), name.c_str(), 0) == 0);
276 if (t && sess.verbose>3)
f9bbd346 277 clog << _F("pattern '%s' matches function '%s'\n", pattern.c_str(), name.c_str());
440f755a
JS
278 return t;
279}
280
281
282bool
5f4c8c6e 283dwflpp::function_name_matches(const string& pattern)
440f755a
JS
284{
285 assert(function);
286 return function_name_matches_pattern(function_name, pattern);
287}
288
289
7d6d0afc 290bool
c646240d 291dwflpp::function_scope_matches(const vector<string>& scopes)
7d6d0afc
JS
292{
293 // walk up the containing scopes
294 Dwarf_Die* die = function;
295 for (int i = scopes.size() - 1; i >= 0; --i)
296 {
297 die = get_parent_scope(die);
298
299 // check if this scope matches, and prepend it if so
300 // NB: a NULL die is the global scope, compared as ""
301 string name = dwarf_diename(die) ?: "";
302 if (name_has_wildcard(scopes[i]) ?
303 function_name_matches_pattern(name, scopes[i]) :
304 name == scopes[i])
305 function_name = name + "::" + function_name;
306 else
307 return false;
308
309 // make sure there's no more if we're at the global scope
310 if (!die && i > 0)
311 return false;
312 }
313 return true;
314}
315
316
440f755a 317void
2eb99c62 318dwflpp::setup_kernel(const string& name, systemtap_session & s, bool debuginfo_needed)
440f755a 319{
440f755a
JS
320 if (! sess.module_cache)
321 sess.module_cache = new module_cache ();
322
3db9c843 323 unsigned offline_search_matches = 0;
68983551 324 dwfl_ptr = setup_dwfl_kernel(name, &offline_search_matches, sess);
440f755a 325
3db9c843 326 if (offline_search_matches < 1)
ae2552da
FCE
327 {
328 if (debuginfo_needed) {
329 // Suggest a likely kernel dir to find debuginfo rpm for
05fb3e0c 330 string dir = string(sess.sysroot + "/lib/modules/" + sess.kernel_release );
ae2552da
FCE
331 find_debug_rpms(sess, dir.c_str());
332 }
4c5d9906 333 throw semantic_error (_F("missing %s kernel/module debuginfo [man warning::debuginfo] under '%s'",
f9bbd346 334 sess.architecture.c_str(), sess.kernel_build_tree.c_str()));
209dd533 335 }
2eb99c62
CM
336 Dwfl *dwfl = dwfl_ptr.get()->dwfl;
337 if (dwfl != NULL)
338 {
339 ptrdiff_t off = 0;
340 do
341 {
e19ebcf7 342 assert_no_interrupts();
2eb99c62
CM
343 off = dwfl_getmodules (dwfl, &add_module_build_id_to_hash, &s, off);
344 }
345 while (off > 0);
346 dwfl_assert("dwfl_getmodules", off == 0);
347 }
440f755a 348
27646582 349 build_blacklist();
440f755a
JS
350}
351
59c11f91
MW
352void
353dwflpp::setup_kernel(const vector<string> &names, bool debuginfo_needed)
354{
355 if (! sess.module_cache)
356 sess.module_cache = new module_cache ();
357
358 unsigned offline_search_matches = 0;
359 set<string> offline_search_names(names.begin(), names.end());
68983551
MW
360 dwfl_ptr = setup_dwfl_kernel(offline_search_names,
361 &offline_search_matches,
362 sess);
59c11f91
MW
363
364 if (offline_search_matches < offline_search_names.size())
365 {
366 if (debuginfo_needed) {
367 // Suggest a likely kernel dir to find debuginfo rpm for
05fb3e0c 368 string dir = string(sess.sysroot + "/lib/modules/" + sess.kernel_release );
59c11f91
MW
369 find_debug_rpms(sess, dir.c_str());
370 }
4c5d9906 371 throw semantic_error (_F("missing %s kernel/module debuginfo [man warning::debuginfo] under '%s'",
f9bbd346 372 sess.architecture.c_str(), sess.kernel_build_tree.c_str()));
59c11f91
MW
373 }
374
375 build_blacklist();
376}
377
440f755a
JS
378
379void
0c16d512 380dwflpp::setup_user(const vector<string>& modules, bool debuginfo_needed)
440f755a
JS
381{
382 if (! sess.module_cache)
383 sess.module_cache = new module_cache ();
384
5f8ca04f 385 vector<string>::const_iterator it = modules.begin();
e1e8b44e 386 dwfl_ptr = setup_dwfl_user(it, modules.end(), debuginfo_needed, sess);
5f8ca04f 387 if (debuginfo_needed && it != modules.end())
ce0f6648
LB
388 dwfl_assert (string(_F("missing process %s %s debuginfo",
389 (*it).c_str(), sess.architecture.c_str())),
390 dwfl_ptr.get()->dwfl);
440f755a
JS
391}
392
440f755a
JS
393void
394dwflpp::iterate_over_modules(int (* callback)(Dwfl_Module *, void **,
395 const char *, Dwarf_Addr,
396 void *),
6bbcd339 397 void *data)
440f755a 398{
68983551 399 dwfl_getmodules (dwfl_ptr.get()->dwfl, callback, data, 0);
0e14e079 400
440f755a
JS
401 // Don't complain if we exited dwfl_getmodules early.
402 // This could be a $target variable error that will be
403 // reported soon anyway.
404 // dwfl_assert("dwfl_getmodules", off == 0);
405
406 // PR6864 XXX: For dwarfless case (if .../vmlinux is missing), then the
407 // "kernel" module is not reported in the loop above. However, we
408 // may be able to make do with symbol table data.
409}
410
411
440f755a
JS
412void
413dwflpp::iterate_over_cus (int (*callback)(Dwarf_Die * die, void * arg),
337b7c44 414 void * data, bool want_types)
440f755a
JS
415{
416 get_module_dwarf(false);
417 Dwarf *dw = module_dwarf;
418 if (!dw) return;
419
420 vector<Dwarf_Die>* v = module_cu_cache[dw];
421 if (v == 0)
422 {
423 v = new vector<Dwarf_Die>;
424 module_cu_cache[dw] = v;
425
426 Dwarf_Off off = 0;
427 size_t cuhl;
428 Dwarf_Off noff;
429 while (dwarf_nextcu (dw, off, &noff, &cuhl, NULL, NULL, NULL) == 0)
430 {
e19ebcf7 431 assert_no_interrupts();
440f755a
JS
432 Dwarf_Die die_mem;
433 Dwarf_Die *die;
434 die = dwarf_offdie (dw, off + cuhl, &die_mem);
dee830d9
MW
435 /* Skip partial units. */
436 if (dwarf_tag (die) == DW_TAG_compile_unit)
437 v->push_back (*die); /* copy */
440f755a
JS
438 off = noff;
439 }
440 }
441
337b7c44
TT
442 if (want_types && module_tus_read.find(dw) == module_tus_read.end())
443 {
444 // Process type units.
445 Dwarf_Off off = 0;
446 size_t cuhl;
447 Dwarf_Off noff;
448 uint64_t type_signature;
449 while (dwarf_next_unit (dw, off, &noff, &cuhl, NULL, NULL, NULL, NULL,
450 &type_signature, NULL) == 0)
451 {
e19ebcf7 452 assert_no_interrupts();
337b7c44
TT
453 Dwarf_Die die_mem;
454 Dwarf_Die *die;
455 die = dwarf_offdie_types (dw, off + cuhl, &die_mem);
dee830d9
MW
456 /* Skip partial units. */
457 if (dwarf_tag (die) == DW_TAG_type_unit)
458 v->push_back (*die); /* copy */
337b7c44
TT
459 off = noff;
460 }
461 module_tus_read.insert(dw);
462 }
463
c1c5bb9a 464 for (vector<Dwarf_Die>::iterator i = v->begin(); i != v->end(); ++i)
440f755a 465 {
c1c5bb9a 466 int rc = (*callback)(&*i, data);
e19ebcf7 467 assert_no_interrupts();
985892de 468 if (rc != DWARF_CB_OK)
c1c5bb9a 469 break;
440f755a
JS
470 }
471}
472
473
474bool
475dwflpp::func_is_inline()
476{
477 assert (function);
478 return dwarf_func_inline (function) != 0;
479}
480
481
4bda987e
SC
482bool
483dwflpp::func_is_exported()
484{
485 const char *name = dwarf_linkage_name (function) ?: dwarf_diename (function);
486
487 assert (function);
488
489 int syms = dwfl_module_getsymtab (module);
490 dwfl_assert (_("Getting symbols"), syms >= 0);
491
492 for (int i = 0; i < syms; i++)
493 {
494 GElf_Sym sym;
495 GElf_Word shndxp;
496 const char *symname = dwfl_module_getsym(module, i, &sym, &shndxp);
497 if (symname
498 && strcmp (name, symname) == 0)
499 {
500 if (GELF_ST_TYPE(sym.st_info) == STT_FUNC
501 && (GELF_ST_BIND(sym.st_info) == STB_GLOBAL
5c204fc3
SC
502 || GELF_ST_BIND(sym.st_info) == STB_WEAK
503 || GELF_ST_BIND(sym.st_info) == STB_GNU_UNIQUE))
4bda987e
SC
504 return true;
505 else
506 return false;
507 }
508 }
509 return false;
510}
511
8d7a7bd9
JS
512void
513dwflpp::cache_inline_instances (Dwarf_Die* die)
440f755a 514{
8d7a7bd9
JS
515 // If this is an inline instance, link it back to its origin
516 Dwarf_Die origin;
517 if (dwarf_tag(die) == DW_TAG_inlined_subroutine &&
518 dwarf_attr_die(die, DW_AT_abstract_origin, &origin))
519 {
520 vector<Dwarf_Die>*& v = cu_inl_function_cache[origin.addr];
521 if (!v)
522 v = new vector<Dwarf_Die>;
523 v->push_back(*die);
524 }
525
526 // Recurse through other scopes that may contain inlines
527 Dwarf_Die child, import;
528 if (dwarf_child(die, &child) == 0)
529 do
530 {
531 switch (dwarf_tag (&child))
532 {
533 // tags that could contain inlines
534 case DW_TAG_compile_unit:
535 case DW_TAG_module:
536 case DW_TAG_lexical_block:
537 case DW_TAG_with_stmt:
538 case DW_TAG_catch_block:
539 case DW_TAG_try_block:
540 case DW_TAG_entry_point:
541 case DW_TAG_inlined_subroutine:
542 case DW_TAG_subprogram:
543 cache_inline_instances(&child);
544 break;
545
546 // imported dies should be followed
547 case DW_TAG_imported_unit:
548 if (dwarf_attr_die(&child, DW_AT_import, &import))
549 cache_inline_instances(&import);
550 break;
551
552 // nothing to do for other tags
553 default:
554 break;
555 }
556 }
557 while (dwarf_siblingof(&child, &child) == 0);
440f755a
JS
558}
559
560
561void
562dwflpp::iterate_over_inline_instances (int (* callback)(Dwarf_Die * die, void * arg),
563 void * data)
564{
565 assert (function);
566 assert (func_is_inline ());
567
8d7a7bd9
JS
568 if (cu_inl_function_cache_done.insert(cu->addr).second)
569 cache_inline_instances(cu);
570
d089f5b2 571 vector<Dwarf_Die>* v = cu_inl_function_cache[function->addr];
8d7a7bd9
JS
572 if (!v)
573 return;
440f755a 574
c1c5bb9a 575 for (vector<Dwarf_Die>::iterator i = v->begin(); i != v->end(); ++i)
440f755a 576 {
c1c5bb9a 577 int rc = (*callback)(&*i, data);
e19ebcf7 578 assert_no_interrupts();
985892de 579 if (rc != DWARF_CB_OK)
c1c5bb9a 580 break;
440f755a
JS
581 }
582}
583
584
9aa8ffce
JS
585void
586dwflpp::cache_die_parents(cu_die_parent_cache_t* parents, Dwarf_Die* die)
587{
588 // Record and recurse through DIEs we care about
589 Dwarf_Die child, import;
590 if (dwarf_child(die, &child) == 0)
591 do
592 {
593 switch (dwarf_tag (&child))
594 {
595 // normal tags to recurse
596 case DW_TAG_compile_unit:
597 case DW_TAG_module:
598 case DW_TAG_lexical_block:
599 case DW_TAG_with_stmt:
600 case DW_TAG_catch_block:
601 case DW_TAG_try_block:
602 case DW_TAG_entry_point:
603 case DW_TAG_inlined_subroutine:
604 case DW_TAG_subprogram:
7d6d0afc
JS
605 case DW_TAG_namespace:
606 case DW_TAG_class_type:
607 case DW_TAG_structure_type:
9aa8ffce
JS
608 parents->insert(make_pair(child.addr, *die));
609 cache_die_parents(parents, &child);
610 break;
611
612 // record only, nothing to recurse
613 case DW_TAG_label:
614 parents->insert(make_pair(child.addr, *die));
615 break;
616
617 // imported dies should be followed
618 case DW_TAG_imported_unit:
619 if (dwarf_attr_die(&child, DW_AT_import, &import))
620 {
621 parents->insert(make_pair(import.addr, *die));
622 cache_die_parents(parents, &import);
623 }
624 break;
625
626 // nothing to do for other tags
627 default:
628 break;
629 }
630 }
631 while (dwarf_siblingof(&child, &child) == 0);
632}
633
634
729455a7
JS
635cu_die_parent_cache_t*
636dwflpp::get_die_parents()
9aa8ffce
JS
637{
638 assert (cu);
639
729455a7 640 cu_die_parent_cache_t *& parents = cu_die_parent_cache[cu->addr];
9aa8ffce
JS
641 if (!parents)
642 {
643 parents = new cu_die_parent_cache_t;
9aa8ffce
JS
644 cache_die_parents(parents, cu);
645 if (sess.verbose > 4)
f9bbd346
LB
646 clog << _F("die parent cache %s:%s size %zu", module_name.c_str(),
647 cu_name().c_str(), parents->size()) << endl;
9aa8ffce 648 }
729455a7
JS
649 return parents;
650}
651
652
653vector<Dwarf_Die>
654dwflpp::getscopes_die(Dwarf_Die* die)
655{
656 cu_die_parent_cache_t *parents = get_die_parents();
9aa8ffce
JS
657
658 vector<Dwarf_Die> scopes;
729455a7
JS
659 Dwarf_Die *scope = die;
660 cu_die_parent_cache_t::iterator it;
661 do
662 {
663 scopes.push_back(*scope);
664 it = parents->find(scope->addr);
665 scope = &it->second;
666 }
667 while (it != parents->end());
9aa8ffce
JS
668
669#ifdef DEBUG_DWFLPP_GETSCOPES
729455a7 670 Dwarf_Die *dscopes = NULL;
9aa8ffce
JS
671 int nscopes = dwarf_getscopes_die(die, &dscopes);
672
673 assert(nscopes == (int)scopes.size());
674 for (unsigned i = 0; i < scopes.size(); ++i)
675 assert(scopes[i].addr == dscopes[i].addr);
676 free(dscopes);
677#endif
678
679 return scopes;
680}
681
682
729455a7
JS
683std::vector<Dwarf_Die>
684dwflpp::getscopes(Dwarf_Die* die)
685{
686 cu_die_parent_cache_t *parents = get_die_parents();
687
688 vector<Dwarf_Die> scopes;
689
690 Dwarf_Die origin;
691 Dwarf_Die *scope = die;
692 cu_die_parent_cache_t::iterator it;
693 do
694 {
695 scopes.push_back(*scope);
696 if (dwarf_tag(scope) == DW_TAG_inlined_subroutine &&
697 dwarf_attr_die(scope, DW_AT_abstract_origin, &origin))
698 scope = &origin;
699
700 it = parents->find(scope->addr);
701 scope = &it->second;
702 }
703 while (it != parents->end());
704
705#ifdef DEBUG_DWFLPP_GETSCOPES
706 // there isn't an exact libdw equivalent, but if dwarf_getscopes on the
707 // entrypc returns the same first die, then all the scopes should match
708 Dwarf_Addr pc;
709 if (die_entrypc(die, &pc))
710 {
711 Dwarf_Die *dscopes = NULL;
712 int nscopes = dwarf_getscopes(cu, pc, &dscopes);
713 if (nscopes > 0 && dscopes[0].addr == die->addr)
714 {
715 assert(nscopes == (int)scopes.size());
716 for (unsigned i = 0; i < scopes.size(); ++i)
717 assert(scopes[i].addr == dscopes[i].addr);
718 }
719 free(dscopes);
720 }
721#endif
722
723 return scopes;
724}
725
726
727std::vector<Dwarf_Die>
728dwflpp::getscopes(Dwarf_Addr pc)
729{
730 // The die_parent_cache doesn't help us without knowing where the pc is
731 // contained, so we have to do this one the old fashioned way.
732
733 assert (cu);
734
735 vector<Dwarf_Die> scopes;
736
737 Dwarf_Die* dwarf_scopes;
738 int nscopes = dwarf_getscopes(cu, pc, &dwarf_scopes);
739 if (nscopes > 0)
740 {
741 scopes.assign(dwarf_scopes, dwarf_scopes + nscopes);
742 free(dwarf_scopes);
743 }
744
745#ifdef DEBUG_DWFLPP_GETSCOPES
746 // check that getscopes on the starting die gets the same result
747 if (!scopes.empty())
748 {
749 vector<Dwarf_Die> other = getscopes(&scopes[0]);
750 assert(scopes.size() == other.size());
751 for (unsigned i = 0; i < scopes.size(); ++i)
752 assert(scopes[i].addr == other[i].addr);
753 }
754#endif
755
756 return scopes;
757}
758
759
7d6d0afc
JS
760Dwarf_Die*
761dwflpp::get_parent_scope(Dwarf_Die* die)
762{
763 Dwarf_Die specification;
764 if (dwarf_attr_die(die, DW_AT_specification, &specification))
765 die = &specification;
766
767 cu_die_parent_cache_t *parents = get_die_parents();
768 cu_die_parent_cache_t::iterator it = parents->find(die->addr);
769 while (it != parents->end())
770 {
771 Dwarf_Die* scope = &it->second;
772 switch (dwarf_tag (scope))
773 {
774 case DW_TAG_namespace:
775 case DW_TAG_class_type:
776 case DW_TAG_structure_type:
777 return scope;
778
779 default:
780 break;
781 }
782 it = parents->find(scope->addr);
783 }
784 return NULL;
785}
786
a44a7cb5
JS
787static const char*
788cache_type_prefix(Dwarf_Die* type)
789{
790 switch (dwarf_tag(type))
791 {
792 case DW_TAG_enumeration_type:
793 return "enum ";
794 case DW_TAG_structure_type:
795 case DW_TAG_class_type:
796 // treating struct/class as equals
797 return "struct ";
798 case DW_TAG_union_type:
799 return "union ";
800 }
801 return "";
802}
7d6d0afc 803
87eeec94
MW
804/* GCC might generate a struct/class without DW_AT_declaration,
805 but that only contains members which have DW_AT_declaration
806 set. We aren't interested in those. PR14434 (GCC bug #54181). */
807static bool
808has_only_decl_members (Dwarf_Die *die)
809{
dee830d9 810 Dwarf_Die child, import;
87eeec94
MW
811 if (dwarf_child(die, &child) != 0)
812 return false; /* no members */
813
814 do
815 {
816 if (! dwarf_hasattr(&child, DW_AT_declaration))
817 return false; /* real member found. */
818 int tag = dwarf_tag(&child);
819 if ((tag == DW_TAG_namespace
820 || tag == DW_TAG_structure_type
821 || tag == DW_TAG_class_type)
822 && ! has_only_decl_members (&child))
823 return false; /* real grand child member found. */
dee830d9
MW
824
825 // Unlikely to ever happen, but if there is an imported unit
826 // then check its children as if they are children of this DIE.
827 if (tag == DW_TAG_imported_unit
828 && dwarf_attr_die(&child, DW_AT_import, &import)
829 && ! has_only_decl_members (&import))
830 return false;
87eeec94
MW
831 }
832 while (dwarf_siblingof(&child, &child) == 0);
833
834 return true; /* Tried all children and grandchildren. */
835}
836
440f755a 837int
3805a31e
JS
838dwflpp::global_alias_caching_callback(Dwarf_Die *die, bool has_inner_types,
839 const string& prefix, void *arg)
440f755a 840{
b7478964 841 cu_type_cache_t *cache = static_cast<cu_type_cache_t*>(arg);
440f755a
JS
842 const char *name = dwarf_diename(die);
843
87eeec94
MW
844 if (!name || dwarf_hasattr(die, DW_AT_declaration)
845 || has_only_decl_members(die))
440f755a
JS
846 return DWARF_CB_OK;
847
3805a31e
JS
848 int tag = dwarf_tag(die);
849 if (has_inner_types && (tag == DW_TAG_namespace
850 || tag == DW_TAG_structure_type
851 || tag == DW_TAG_class_type))
852 iterate_over_types(die, has_inner_types, prefix + name + "::",
853 global_alias_caching_callback, arg);
854
855 if (tag != DW_TAG_namespace)
856 {
857 string type_name = prefix + cache_type_prefix(die) + name;
858 if (cache->find(type_name) == cache->end())
859 (*cache)[type_name] = *die;
860 }
440f755a
JS
861
862 return DWARF_CB_OK;
863}
864
063906a9
MW
865int
866dwflpp::global_alias_caching_callback_cus(Dwarf_Die *die, void *arg)
867{
868 mod_cu_type_cache_t *global_alias_cache;
869 global_alias_cache = &static_cast<dwflpp *>(arg)->global_alias_cache;
870
871 cu_type_cache_t *v = (*global_alias_cache)[die->addr];
872 if (v != 0)
873 return DWARF_CB_OK;
874
875 v = new cu_type_cache_t;
876 (*global_alias_cache)[die->addr] = v;
877 iterate_over_globals(die, global_alias_caching_callback, v);
878
879 return DWARF_CB_OK;
880}
881
882Dwarf_Die *
a44a7cb5 883dwflpp::declaration_resolve_other_cus(const string& name)
063906a9 884{
337b7c44 885 iterate_over_cus(global_alias_caching_callback_cus, this, true);
063906a9
MW
886 for (mod_cu_type_cache_t::iterator i = global_alias_cache.begin();
887 i != global_alias_cache.end(); ++i)
888 {
889 cu_type_cache_t *v = (*i).second;
890 if (v->find(name) != v->end())
891 return & ((*v)[name]);
892 }
893
894 return NULL;
895}
440f755a
JS
896
897Dwarf_Die *
a44a7cb5 898dwflpp::declaration_resolve(const string& name)
440f755a 899{
b7478964 900 cu_type_cache_t *v = global_alias_cache[cu->addr];
440f755a
JS
901 if (v == 0) // need to build the cache, just once per encountered module/cu
902 {
b7478964 903 v = new cu_type_cache_t;
54558065 904 global_alias_cache[cu->addr] = v;
063906a9 905 iterate_over_globals(cu, global_alias_caching_callback, v);
440f755a 906 if (sess.verbose > 4)
f9bbd346
LB
907 clog << _F("global alias cache %s:%s size %zu", module_name.c_str(),
908 cu_name().c_str(), v->size()) << endl;
440f755a
JS
909 }
910
911 // XXX: it may be desirable to search other modules' declarations
912 // too, in case a module/shared-library processes a
913 // forward-declared pointer type only, where the actual definition
914 // may only be in vmlinux or the application.
915
440f755a 916 if (v->find(name) == v->end())
063906a9 917 return declaration_resolve_other_cus(name);
440f755a
JS
918
919 return & ((*v)[name]);
920}
921
a44a7cb5
JS
922Dwarf_Die *
923dwflpp::declaration_resolve(Dwarf_Die *type)
924{
925 const char* name = dwarf_diename(type);
926 if (!name)
927 return NULL;
928
929 string type_name = cache_type_prefix(type) + string(name);
930 return declaration_resolve(type_name);
931}
932
440f755a
JS
933
934int
935dwflpp::cu_function_caching_callback (Dwarf_Die* func, void *arg)
936{
937 cu_function_cache_t* v = static_cast<cu_function_cache_t*>(arg);
938 const char *name = dwarf_diename(func);
939 if (!name)
940 return DWARF_CB_OK;
941
b7478964 942 v->insert(make_pair(string(name), *func));
440f755a
JS
943 return DWARF_CB_OK;
944}
945
946
4df79aaf
JS
947int
948dwflpp::mod_function_caching_callback (Dwarf_Die* cu, void *arg)
949{
950 dwarf_getfuncs (cu, cu_function_caching_callback, arg, 0);
951 return DWARF_CB_OK;
952}
953
954
440f755a
JS
955int
956dwflpp::iterate_over_functions (int (* callback)(Dwarf_Die * func, base_query * q),
5898b6e1 957 base_query * q, const string& function)
440f755a
JS
958{
959 int rc = DWARF_CB_OK;
960 assert (module);
961 assert (cu);
962
54558065 963 cu_function_cache_t *v = cu_function_cache[cu->addr];
440f755a
JS
964 if (v == 0)
965 {
966 v = new cu_function_cache_t;
54558065 967 cu_function_cache[cu->addr] = v;
440f755a
JS
968 dwarf_getfuncs (cu, cu_function_caching_callback, v, 0);
969 if (sess.verbose > 4)
f9bbd346
LB
970 clog << _F("function cache %s:%s size %zu", module_name.c_str(),
971 cu_name().c_str(), v->size()) << endl;
1c6b77e5 972 mod_info->update_symtab(v);
440f755a
JS
973 }
974
b7478964
JS
975 cu_function_cache_t::iterator it;
976 cu_function_cache_range_t range = v->equal_range(function);
977 if (range.first != range.second)
440f755a 978 {
b7478964
JS
979 for (it = range.first; it != range.second; ++it)
980 {
981 Dwarf_Die& die = it->second;
982 if (sess.verbose > 4)
f9bbd346
LB
983 clog << _F("function cache %s:%s hit %s", module_name.c_str(),
984 cu_name().c_str(), function.c_str()) << endl;
b7478964
JS
985 rc = (*callback)(& die, q);
986 if (rc != DWARF_CB_OK) break;
987 }
440f755a 988 }
1ffb8bd1
JS
989 else if (startswith(function, "_Z"))
990 {
991 // C++ names are mangled starting with a "_Z" prefix. Most of the time
992 // we can discover the mangled name from a die's MIPS_linkage_name
993 // attribute, so we read that to match against the user's function
994 // pattern. Note that this isn't perfect, as not all will have that
995 // attribute (notably ctors and dtors), but we do what we can...
996 for (it = v->begin(); it != v->end(); ++it)
997 {
998 if (pending_interrupts) return DWARF_CB_ABORT;
999 Dwarf_Die& die = it->second;
157f5dd0 1000 const char* linkage_name = NULL;
f450a7e3 1001 if ((linkage_name = dwarf_linkage_name (&die))
1ffb8bd1
JS
1002 && function_name_matches_pattern (linkage_name, function))
1003 {
1004 if (sess.verbose > 4)
f9bbd346
LB
1005 clog << _F("function cache %s:%s match %s vs %s", module_name.c_str(),
1006 cu_name().c_str(), linkage_name, function.c_str()) << endl;
1ffb8bd1
JS
1007
1008 rc = (*callback)(& die, q);
1009 if (rc != DWARF_CB_OK) break;
1010 }
1011 }
1012 }
5f4c8c6e 1013 else if (name_has_wildcard (function))
440f755a 1014 {
c1c5bb9a 1015 for (it = v->begin(); it != v->end(); ++it)
440f755a 1016 {
85007c04 1017 if (pending_interrupts) return DWARF_CB_ABORT;
1c6b77e5
JS
1018 const string& func_name = it->first;
1019 Dwarf_Die& die = it->second;
5f4c8c6e 1020 if (function_name_matches_pattern (func_name, function))
440f755a
JS
1021 {
1022 if (sess.verbose > 4)
f9bbd346
LB
1023 clog << _F("function cache %s:%s match %s vs %s", module_name.c_str(),
1024 cu_name().c_str(), func_name.c_str(), function.c_str()) << endl;
440f755a
JS
1025
1026 rc = (*callback)(& die, q);
1027 if (rc != DWARF_CB_OK) break;
1028 }
1029 }
1030 }
1ffb8bd1 1031 else // not a linkage name or wildcard and no match in this CU
440f755a
JS
1032 {
1033 // do nothing
1034 }
1035 return rc;
1036}
1037
1038
4df79aaf
JS
1039int
1040dwflpp::iterate_single_function (int (* callback)(Dwarf_Die * func, base_query * q),
1041 base_query * q, const string& function)
1042{
1043 int rc = DWARF_CB_OK;
1044 assert (module);
1045
1046 get_module_dwarf(false);
1047 if (!module_dwarf)
1048 return rc;
1049
1050 cu_function_cache_t *v = mod_function_cache[module_dwarf];
1051 if (v == 0)
1052 {
1053 v = new cu_function_cache_t;
1054 mod_function_cache[module_dwarf] = v;
337b7c44 1055 iterate_over_cus (mod_function_caching_callback, v, false);
4df79aaf 1056 if (sess.verbose > 4)
f9bbd346
LB
1057 clog << _F("module function cache %s size %zu", module_name.c_str(),
1058 v->size()) << endl;
d1fa8b15 1059 mod_info->update_symtab(v);
4df79aaf
JS
1060 }
1061
1062 cu_function_cache_t::iterator it;
1063 cu_function_cache_range_t range = v->equal_range(function);
1064 if (range.first != range.second)
1065 {
1066 for (it = range.first; it != range.second; ++it)
1067 {
1068 Dwarf_Die cu_mem;
1069 Dwarf_Die& die = it->second;
1070 if (sess.verbose > 4)
f9bbd346
LB
1071 clog << _F("module function cache %s hit %s", module_name.c_str(),
1072 function.c_str()) << endl;
4df79aaf
JS
1073
1074 // since we're iterating out of cu-context, we need each focus
1075 focus_on_cu(dwarf_diecu(&die, &cu_mem, NULL, NULL));
1076
1077 rc = (*callback)(& die, q);
1078 if (rc != DWARF_CB_OK) break;
1079 }
1080 }
1081
1082 // undo the focus_on_cu
1083 this->cu = NULL;
1084 this->function_name.clear();
1085 this->function = NULL;
1086
1087 return rc;
1088}
1089
1090
440f755a
JS
1091/* This basically only goes one level down from the compile unit so it
1092 * only picks up top level stuff (i.e. nothing in a lower scope) */
1093int
063906a9 1094dwflpp::iterate_over_globals (Dwarf_Die *cu_die,
3805a31e
JS
1095 int (* callback)(Dwarf_Die *, bool,
1096 const string&, void *),
440f755a 1097 void * data)
3805a31e
JS
1098{
1099 assert (cu_die);
337b7c44 1100 assert (dwarf_tag(cu_die) == DW_TAG_compile_unit
dee830d9
MW
1101 || dwarf_tag(cu_die) == DW_TAG_type_unit
1102 || dwarf_tag(cu_die) == DW_TAG_partial_unit);
1103
1104 // Ignore partial_unit, if they get imported by a real unit, then
1105 // iterate_over_types will traverse them.
1106 if (dwarf_tag(cu_die) == DW_TAG_partial_unit)
1107 return DWARF_CB_OK;
3805a31e
JS
1108
1109 // If this is C++, recurse for any inner types
1110 bool has_inner_types = dwarf_srclang(cu_die) == DW_LANG_C_plus_plus;
1111
1112 return iterate_over_types(cu_die, has_inner_types, "", callback, data);
1113}
1114
1115
1116int
1117dwflpp::iterate_over_types (Dwarf_Die *top_die,
1118 bool has_inner_types,
1119 const string& prefix,
1120 int (* callback)(Dwarf_Die *, bool,
1121 const string&, void *),
1122 void * data)
440f755a
JS
1123{
1124 int rc = DWARF_CB_OK;
dee830d9 1125 Dwarf_Die die, import;
440f755a 1126
3805a31e 1127 assert (top_die);
440f755a 1128
3805a31e 1129 if (dwarf_child(top_die, &die) != 0)
440f755a
JS
1130 return rc;
1131
1132 do
1133 /* We're only currently looking for named types,
1134 * although other types of declarations exist */
1135 switch (dwarf_tag(&die))
1136 {
1137 case DW_TAG_base_type:
1138 case DW_TAG_enumeration_type:
1139 case DW_TAG_structure_type:
9c119951 1140 case DW_TAG_class_type:
440f755a
JS
1141 case DW_TAG_typedef:
1142 case DW_TAG_union_type:
3805a31e
JS
1143 case DW_TAG_namespace:
1144 rc = (*callback)(&die, has_inner_types, prefix, data);
440f755a 1145 break;
dee830d9
MW
1146
1147 case DW_TAG_imported_unit:
1148 // Follow the imported_unit and iterate over its contents
1149 // (either a partial_unit or a full compile_unit), all its
1150 // children should be treated as if they appear in this place.
1151 if (dwarf_attr_die(&die, DW_AT_import, &import))
1152 rc = iterate_over_types(&import, has_inner_types, prefix,
1153 callback, data);
1154 break;
440f755a
JS
1155 }
1156 while (rc == DWARF_CB_OK && dwarf_siblingof(&die, &die) == 0);
1157
1158 return rc;
1159}
1160
1161
fea74777
SC
1162/* For each notes section in the current module call 'callback', use
1163 * 'data' for the notes buffer and pass 'object' back in case
1164 * 'callback' is a method */
1165
1166int
1167dwflpp::iterate_over_notes (void *object, void (*callback)(void *object, int type, const char *data, size_t len))
1168{
1169 Dwarf_Addr bias;
1189063f
MW
1170 // Note we really want the actual elf file, not the dwarf .debug file.
1171 // Older binutils had a bug where they mangled the SHT_NOTE type during
1172 // --keep-debug.
1173 Elf* elf = dwfl_module_getelf (module, &bias);
fea74777
SC
1174 size_t shstrndx;
1175 if (elf_getshdrstrndx (elf, &shstrndx))
1176 return elf_errno();
1177
fea74777
SC
1178 Elf_Scn *scn = NULL;
1179
1180 vector<Dwarf_Die> notes;
1181
1182 while ((scn = elf_nextscn (elf, scn)) != NULL)
1183 {
1184 GElf_Shdr shdr;
1185 if (gelf_getshdr (scn, &shdr) == NULL)
1186 continue;
1187 switch (shdr.sh_type)
1188 {
1189 case SHT_NOTE:
1190 if (!(shdr.sh_flags & SHF_ALLOC))
1191 {
fea74777
SC
1192 Elf_Data *data = elf_getdata (scn, NULL);
1193 size_t next;
1194 GElf_Nhdr nhdr;
1195 size_t name_off;
1196 size_t desc_off;
1197 for (size_t offset = 0;
1198 (next = gelf_getnote (data, offset, &nhdr, &name_off, &desc_off)) > 0;
1199 offset = next)
1200 (*callback) (object, nhdr.n_type, (const char*)((long)(data->d_buf) + (long)desc_off), nhdr.n_descsz);
1201 }
1202 break;
1203 }
1204 }
1205 return 0;
1206}
1207
1208
5d5bd369
SC
1209/* For each entry in the .dynamic section in the current module call 'callback'
1210 * returning 'object' in case 'callback' is a method */
84c84ac4
SC
1211
1212void
6bbcd339 1213dwflpp::iterate_over_libraries (void (*callback)(void *object, const char *arg), void *q)
84c84ac4
SC
1214{
1215 std::set<std::string> added;
1216 string interpreter;
1217
1218 assert (this->module_name.length() != 0);
1219
1220 Dwarf_Addr bias;
6bbcd339
SC
1221// We cannot use this: dwarf_getelf (dwfl_module_getdwarf (module, &bias))
1222 Elf *elf = dwfl_module_getelf (module, &bias);
c1e8b3af 1223// elf_getphdrnum (elf, &phnum) is not available in all versions of elfutils
e050d62f 1224// needs libelf from elfutils 0.144+
c1e8b3af 1225 for (int i = 0; ; i++)
84c84ac4
SC
1226 {
1227 GElf_Phdr mem;
c1e8b3af
SC
1228 GElf_Phdr *phdr;
1229 phdr = gelf_getphdr (elf, i, &mem);
1230 if (phdr == NULL)
1231 break;
84c84ac4
SC
1232 if (phdr->p_type == PT_INTERP)
1233 {
1234 size_t maxsize;
1235 char *filedata = elf_rawfile (elf, &maxsize);
1236
1237 if (filedata != NULL && phdr->p_offset < maxsize)
1238 interpreter = (char*) (filedata + phdr->p_offset);
84c84ac4
SC
1239 break;
1240 }
1241 }
1242
6bbcd339
SC
1243 if (interpreter.length() == 0)
1244 return;
58502ae4
JS
1245 // If it gets cumbersome to maintain this whitelist, we could just check for
1246 // startswith("/lib/ld") || startswith("/lib64/ld"), and trust that no admin
1247 // would install untrustworthy loaders in those paths.
4ff68987
FCE
1248 // See also http://sourceware.org/git/?p=glibc.git;a=blob;f=shlib-versions;hb=HEAD
1249 if (interpreter != "/lib/ld.so.1" // s390, ppc
1250 && interpreter != "/lib/ld64.so.1" // s390x, ppc64
1251 && interpreter != "/lib64/ld64.so.1"
1252 && interpreter != "/lib/ld-linux-ia64.so.2" // ia64
1253 && interpreter != "/emul/ia32-linux/lib/ld-linux.so.2"
1254 && interpreter != "/lib64/ld-linux-x86-64.so.2" // x8664
1255 && interpreter != "/lib/ld-linux.so.2" // x86
1256 && interpreter != "/lib/ld-linux.so.3" // arm
1257 && interpreter != "/lib/ld-linux-armhf.so.3" // arm
1258 )
d785c8d1 1259 {
2713ea24 1260 sess.print_warning (_F("module %s --ldd skipped: unsupported interpreter: %s",
d785c8d1
FCE
1261 module_name.c_str(), interpreter.c_str()));
1262 return;
1263 }
84c84ac4 1264
58502ae4
JS
1265 vector<string> ldd_command;
1266 ldd_command.push_back("/usr/bin/env");
1267 ldd_command.push_back("LD_TRACE_LOADED_OBJECTS=1");
1268 ldd_command.push_back("LD_WARN=yes");
1269 ldd_command.push_back("LD_BIND_NOW=yes");
1270 ldd_command.push_back(interpreter);
1271 ldd_command.push_back(module_name);
1272
1273 FILE *fp;
1274 int child_fd;
1275 pid_t child = stap_spawn_piped(sess.verbose, ldd_command, NULL, &child_fd);
1276 if (child <= 0 || !(fp = fdopen(child_fd, "r")))
1277 clog << _F("library iteration on %s failed: %s",
1278 module_name.c_str(), strerror(errno)) << endl;
84c84ac4
SC
1279 else
1280 {
1281 while (1) // this parsing loop borrowed from add_unwindsym_ldd
1282 {
1283 char linebuf[256];
1284 char *soname = 0;
1285 char *shlib = 0;
1286 unsigned long int addr = 0;
1287
1288 char *line = fgets (linebuf, 256, fp);
1289 if (line == 0) break; // EOF or error
1290
62a4021d
FCE
1291#if __GLIBC__ >2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 7)
1292#define MS_FMT "%ms"
1293#else
1294#define MS_FMT "%as"
1295#endif
84c84ac4 1296 // Try soname => shlib (0xaddr)
62a4021d 1297 int nf = sscanf (line, MS_FMT " => " MS_FMT " (0x%lx)",
84c84ac4
SC
1298 &soname, &shlib, &addr);
1299 if (nf != 3 || shlib[0] != '/')
1300 {
1301 // Try shlib (0xaddr)
62a4021d 1302 nf = sscanf (line, " " MS_FMT " (0x%lx)", &shlib, &addr);
84c84ac4
SC
1303 if (nf != 2 || shlib[0] != '/')
1304 continue; // fewer than expected fields, or bad shlib.
1305 }
1306
1307 if (added.find (shlib) == added.end())
1308 {
1309 if (sess.verbose > 2)
1310 {
1311 clog << _F("Added -d '%s", shlib);
1312 if (nf == 3)
1313 clog << _F("' due to '%s'", soname);
1314 else
1315 clog << "'";
1316 clog << endl;
1317 }
1318 added.insert (shlib);
1319 }
1320
1321 free (soname);
1322 free (shlib);
1323 }
2713ea24
CM
1324 if ((fclose(fp) || stap_waitpid(sess.verbose, child)))
1325 sess.print_warning("failed to read libraries from " + module_name + ": " + strerror(errno));
84c84ac4
SC
1326 }
1327
1328 for (std::set<std::string>::iterator it = added.begin();
1329 it != added.end();
1330 it++)
1331 {
1332 string modname = *it;
5d5bd369 1333 (callback) (q, modname.c_str());
84c84ac4
SC
1334 }
1335}
1336
1337
576eaefe
SC
1338/* For each plt section in the current module call 'callback', pass the plt entry
1339 * 'address' and 'name' back, and pass 'object' back in case 'callback' is a method */
1340
1341int
1342dwflpp::iterate_over_plt (void *object, void (*callback)(void *object, const char *name, size_t addr))
1343{
1344 Dwarf_Addr load_addr;
1345 // Note we really want the actual elf file, not the dwarf .debug file.
1346 Elf* elf = dwfl_module_getelf (module, &load_addr);
1347 size_t shstrndx;
1348 assert (elf_getshdrstrndx (elf, &shstrndx) >= 0);
1349
1350 // Get the load address
1351 for (int i = 0; ; i++)
1352 {
1353 GElf_Phdr mem;
1354 GElf_Phdr *phdr;
1355 phdr = gelf_getphdr (elf, i, &mem);
1356 if (phdr == NULL)
1357 break;
1358 if (phdr->p_type == PT_LOAD)
1359 {
1360 load_addr = phdr->p_vaddr;
1361 break;
1362 }
1363 }
1364
1365 // Get the plt section header
1366 Elf_Scn *scn = NULL;
1367 GElf_Shdr *plt_shdr = NULL;
1368 GElf_Shdr plt_shdr_mem;
1369 while ((scn = elf_nextscn (elf, scn)))
1370 {
1acfc030
JS
1371 GElf_Shdr *shdr = gelf_getshdr (scn, &plt_shdr_mem);
1372 assert (shdr != NULL);
1373 if (strcmp (elf_strptr (elf, shstrndx, shdr->sh_name), ".plt") == 0)
1374 {
1375 plt_shdr = shdr;
1376 break;
1377 }
576eaefe 1378 }
1acfc030
JS
1379 if (plt_shdr == NULL)
1380 return 0;
1381
576eaefe
SC
1382 // Layout of the plt section
1383 int plt0_entry_size;
1384 int plt_entry_size;
1385 GElf_Ehdr ehdr_mem;
1386 GElf_Ehdr* em = gelf_getehdr (elf, &ehdr_mem);
1387 switch (em->e_machine)
1388 {
4e309f0b 1389 case EM_386: plt0_entry_size = 16; plt_entry_size = 16; break;
576eaefe 1390 case EM_X86_64: plt0_entry_size = 16; plt_entry_size = 16; break;
13b528f4 1391 case EM_ARM: plt0_entry_size = 20; plt_entry_size = 12; break;
576eaefe
SC
1392 case EM_PPC64:
1393 case EM_S390:
1394 case EM_PPC:
1395 default:
1396 throw semantic_error(".plt is not supported on this architecture");
1397 }
1398
1399 scn = NULL;
1400 while ((scn = elf_nextscn (elf, scn)))
1401 {
1402 GElf_Shdr shdr_mem;
1403 GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
e245d57f
SC
1404 bool have_rela = false;
1405 bool have_rel = false;
4e309f0b 1406
576eaefe
SC
1407 if (shdr == NULL)
1408 continue;
1409 assert (shdr != NULL);
1410
4e309f0b
SC
1411 if ((have_rela = (strcmp (elf_strptr (elf, shstrndx, shdr->sh_name), ".rela.plt") == 0))
1412 || (have_rel = (strcmp (elf_strptr (elf, shstrndx, shdr->sh_name), ".rel.plt") == 0)))
576eaefe
SC
1413 {
1414 /* Get the data of the section. */
1415 Elf_Data *data = elf_getdata (scn, NULL);
1416 assert (data != NULL);
1417 /* Get the symbol table information. */
1418 Elf_Scn *symscn = elf_getscn (elf, shdr->sh_link);
1419 GElf_Shdr symshdr_mem;
1420 GElf_Shdr *symshdr = gelf_getshdr (symscn, &symshdr_mem);
1421 assert (symshdr != NULL);
1422 Elf_Data *symdata = elf_getdata (symscn, NULL);
1423 assert (symdata != NULL);
1424
1425 unsigned int nsyms = shdr->sh_size / shdr->sh_entsize;
1426
1427 for (unsigned int cnt = 0; cnt < nsyms; ++cnt)
1428 {
1429 GElf_Ehdr ehdr_mem;
1430 GElf_Ehdr* em = gelf_getehdr (elf, &ehdr_mem);
1431 if (em == 0) { dwfl_assert ("dwfl_getehdr", dwfl_errno()); }
1432
4e309f0b 1433 GElf_Rela relamem;
ffffb6b5 1434 GElf_Rela *rela = NULL;
4e309f0b 1435 GElf_Rel relmem;
ffffb6b5 1436 GElf_Rel *rel = NULL;
4e309f0b
SC
1437 if (have_rela)
1438 {
1439 rela = gelf_getrela (data, cnt, &relamem);
1440 assert (rela != NULL);
1441 }
1442 else if (have_rel)
1443 {
1444 rel = gelf_getrel (data, cnt, &relmem);
1445 assert (rel != NULL);
1446 }
576eaefe
SC
1447 GElf_Sym symmem;
1448 Elf32_Word xndx;
1449 Elf_Data *xndxdata = NULL;
4e309f0b
SC
1450 GElf_Sym *sym =
1451 gelf_getsymshndx (symdata, xndxdata,
1452 GELF_R_SYM (have_rela ? rela->r_info : rel->r_info),
1453 &symmem, &xndx);
576eaefe
SC
1454 assert (sym != NULL);
1455 Dwarf_Addr addr = plt_shdr->sh_offset + plt0_entry_size + cnt * plt_entry_size;
1456
1457 if (elf_strptr (elf, symshdr->sh_link, sym->st_name))
1458 (*callback) (object, elf_strptr (elf, symshdr->sh_link, sym->st_name), addr + load_addr);
1459 }
1460 break; // while scn
1461 }
1462 }
1463 return 0;
1464}
1465
1466
440f755a
JS
1467// This little test routine represents an unfortunate breakdown in
1468// abstraction between dwflpp (putatively, a layer right on top of
1469// elfutils), and dwarf_query (interpreting a systemtap probe point).
1470// It arises because we sometimes try to fix up slightly-off
1471// .statement() probes (something we find out in fairly low-level).
1472//
1473// An alternative would be to put some more intelligence into query_cu(),
1474// and have it print additional suggestions after finding that
1475// q->dw.iterate_over_srcfile_lines resulted in no new finished_results.
1476
1477bool
1478dwflpp::has_single_line_record (dwarf_query * q, char const * srcfile, int lineno)
1479{
1480 if (lineno < 0)
1481 return false;
1482
35c68acb
SC
1483 Dwarf_Line **srcsp = NULL;
1484 size_t nsrcs = 0;
440f755a 1485
35c68acb
SC
1486 dwarf_assert ("dwarf_getsrc_file",
1487 dwarf_getsrc_file (module_dwarf,
1488 srcfile, lineno, 0,
1489 &srcsp, &nsrcs));
440f755a 1490
35c68acb
SC
1491 if (nsrcs != 1)
1492 {
1493 if (sess.verbose>4)
1494 clog << _F("alternative line %d rejected: nsrcs=%zu", lineno, nsrcs) << endl;
1495 return false;
1496 }
440f755a 1497
35c68acb
SC
1498 // We also try to filter out lines that leave the selected
1499 // functions (if any).
440f755a 1500
35c68acb
SC
1501 dwarf_line_t line(srcsp[0]);
1502 Dwarf_Addr addr = line.addr();
440f755a 1503
35c68acb
SC
1504 func_info_map_t *filtered_functions = get_filtered_functions(q);
1505 for (func_info_map_t::iterator i = filtered_functions->begin();
1506 i != filtered_functions->end(); ++i)
1507 {
1508 if (die_has_pc (i->die, addr))
1509 {
1510 if (sess.verbose>4)
1511 clog << _F("alternative line %d accepted: fn=%s", lineno, i->name.c_str()) << endl;
1512 return true;
1513 }
1514 }
440f755a 1515
35c68acb
SC
1516 inline_instance_map_t *filtered_inlines = get_filtered_inlines(q);
1517 for (inline_instance_map_t::iterator i = filtered_inlines->begin();
1518 i != filtered_inlines->end(); ++i)
1519 {
1520 if (die_has_pc (i->die, addr))
1521 {
1522 if (sess.verbose>4)
1523 clog << _F("alternative line %d accepted: ifn=%s", lineno, i->name.c_str()) << endl;
1524 return true;
1525 }
1526 }
440f755a 1527
35c68acb
SC
1528 if (sess.verbose>4)
1529 //TRANSLATORS: given line number leaves (is beyond) given function.
1530 clog << _F("alternative line %d rejected: leaves selected fns", lineno) << endl;
1531 return false;
440f755a
JS
1532}
1533
1534
1535void
1536dwflpp::iterate_over_srcfile_lines (char const * srcfile,
1537 int lines[2],
1538 bool need_single_match,
1539 enum line_t line_type,
1540 void (* callback) (const dwarf_line_t& line,
1541 void * arg),
9b988eff 1542 const std::string& func_pattern,
440f755a
JS
1543 void *data)
1544{
1545 Dwarf_Line **srcsp = NULL;
1546 size_t nsrcs = 0;
1547 dwarf_query * q = static_cast<dwarf_query *>(data);
1548 int lineno = lines[0];
1549 auto_free_ref<Dwarf_Line**> free_srcsp(srcsp);
1550
1551 get_module_dwarf();
e679283a
WH
1552 if (!this->function)
1553 return;
440f755a
JS
1554
1555 if (line_type == RELATIVE)
1556 {
1557 Dwarf_Addr addr;
1558 Dwarf_Line *line;
1559 int line_number;
1560
6a3a5e98
SC
1561 die_entrypc(this->function, &addr);
1562
1563 if (addr != 0)
1564 {
1565 line = dwarf_getsrc_die (this->cu, addr);
1566 dwarf_assert ("dwarf_getsrc_die", line == NULL);
1567 dwarf_assert ("dwarf_lineno", dwarf_lineno (line, &line_number));
1568 }
1569 else if (dwarf_decl_line (this->function, &line_number) != 0)
1570 {
1571 // use DW_AT_decl_line as a fallback method
1572 Dwarf_Attribute type_attr;
1573 Dwarf_Word constant;
1574 if (dwarf_attr_integrate (this->function, DW_AT_decl_line, &type_attr))
1575 {
1576 dwarf_formudata (&type_attr, &constant);
1577 line_number = constant;
1578 }
1579 else
1580 return;
1581 }
440f755a
JS
1582 lineno += line_number;
1583 }
78e2a671
DT
1584 else if (line_type == WILDCARD) {
1585 if (name_has_wildcard(func_pattern)) /* PR14774: look at whole file if function name is wildcard */
1586 lineno = 0;
1587 else
1588 function_line (&lineno);
1589 }
1123a74a
WH
1590 else if (line_type == RANGE) { /* correct lineno */
1591 int start_lineno;
1592
9b988eff
WH
1593 if (name_has_wildcard(func_pattern)) /* PR10294: wider range like statement("*@foo.c") */
1594 start_lineno = lineno;
1595 else
1596 function_line (&start_lineno);
1123a74a
WH
1597 lineno = lineno < start_lineno ? start_lineno : lineno;
1598 if (lineno > lines[1]) { /* invalid line range */
1599 stringstream advice;
f9bbd346 1600 advice << _("Invalid line range (") << lines[0] << "-" << lines[1] << ")";
1123a74a 1601 if (start_lineno > lines[1])
f9bbd346 1602 advice << _(", the end line number ") << lines[1] << " < " << start_lineno;
1123a74a
WH
1603 throw semantic_error (advice.str());
1604 }
1605 }
1606
440f755a
JS
1607
1608 for (int l = lineno; ; l = l + 1)
1609 {
1610 set<int> lines_probed;
1611 pair<set<int>::iterator,bool> line_probed;
1123a74a
WH
1612 int ret = 0;
1613
e19ebcf7 1614 assert_no_interrupts();
b8c632dc 1615
35c68acb 1616 nsrcs = 0;
1123a74a
WH
1617 ret = dwarf_getsrc_file (module_dwarf, srcfile, l, 0,
1618 &srcsp, &nsrcs);
8aaef2fb
JS
1619 if (ret != 0) /* tolerate invalid line number */
1620 break;
1123a74a 1621
440f755a
JS
1622 if (line_type == WILDCARD || line_type == RANGE)
1623 {
1624 Dwarf_Addr line_addr;
1123a74a 1625
440f755a 1626 dwarf_lineno (srcsp [0], &lineno);
1123a74a
WH
1627 /* Maybe lineno will exceed the input end */
1628 if (line_type == RANGE && lineno > lines[1])
1629 break;
440f755a
JS
1630 line_probed = lines_probed.insert(lineno);
1631 if (lineno != l || line_probed.second == false || nsrcs > 1)
1632 continue;
1633 dwarf_lineaddr (srcsp [0], &line_addr);
9b988eff 1634 if (!function_name_matches(func_pattern) && dwarf_haspc (function, line_addr) != 1)
440f755a
JS
1635 break;
1636 }
1637
1638 // NB: Formerly, we used to filter, because:
1639
1640 // dwarf_getsrc_file gets one *near hits* for line numbers, not
1641 // exact matches. For example, an existing file but a nonexistent
1642 // line number will be rounded up to the next definition in that
1643 // file. This may be similar to the GDB breakpoint algorithm, but
1644 // we don't want to be so fuzzy in systemtap land. So we filter.
1645
1646 // But we now see the error of our ways, and skip this filtering.
1647
1648 // XXX: the code also fails to match e.g. inline function
1649 // definitions when the srcfile is a header file rather than the
1650 // CU name.
1651
1652 size_t remaining_nsrcs = nsrcs;
1653
1654 if (need_single_match && remaining_nsrcs > 1)
1655 {
1656 // We wanted a single line record (a unique address for the
1657 // line) and we got a bunch of line records. We're going to
1658 // skip this probe (throw an exception) but before we throw
1659 // we're going to look around a bit to see if there's a low or
1660 // high line number nearby which *doesn't* have this problem,
1661 // so we can give the user some advice.
1662
1663 int lo_try = -1;
1664 int hi_try = -1;
1665 for (size_t i = 1; i < 6; ++i)
1666 {
1667 if (lo_try == -1 && has_single_line_record(q, srcfile, lineno - i))
1668 lo_try = lineno - i;
1669
1670 if (hi_try == -1 && has_single_line_record(q, srcfile, lineno + i))
1671 hi_try = lineno + i;
1672 }
1673
1674 stringstream advice;
4c5d9906 1675 advice << _F("multiple addresses for %s:%d [man error::dwarf]", srcfile, lineno);
440f755a
JS
1676 if (lo_try > 0 || hi_try > 0)
1677 {
f9bbd346
LB
1678 //TRANSLATORS: Here we are trying to advise what source file
1679 //TRANSLATORS: to attempt.
1680 advice << _(" (try ");
440f755a
JS
1681 if (lo_try > 0)
1682 advice << srcfile << ":" << lo_try;
1683 if (lo_try > 0 && hi_try > 0)
f9bbd346 1684 advice << _(" or ");
440f755a
JS
1685 if (hi_try > 0)
1686 advice << srcfile << ":" << hi_try;
1687 advice << ")";
1688 }
1689 throw semantic_error (advice.str());
1690 }
1691
1692 for (size_t i = 0; i < nsrcs; ++i)
1693 {
e19ebcf7 1694 assert_no_interrupts();
440f755a
JS
1695 if (srcsp [i]) // skip over mismatched lines
1696 callback (dwarf_line_t(srcsp[i]), data);
1697 }
1698
1699 if (line_type == ABSOLUTE || line_type == RELATIVE)
1700 break;
1701 else if (line_type == RANGE && l == lines[1])
1702 break;
1703 }
1704}
1705
1706
1707void
1708dwflpp::iterate_over_labels (Dwarf_Die *begin_die,
8096dd7d 1709 const string& sym,
f09d0d1e 1710 const string& function,
8096dd7d 1711 dwarf_query *q,
440f755a 1712 void (* callback)(const string &,
8096dd7d 1713 const char *,
440f755a
JS
1714 const char *,
1715 int,
1716 Dwarf_Die *,
1717 Dwarf_Addr,
f09d0d1e 1718 dwarf_query *))
440f755a 1719{
440f755a
JS
1720 get_module_dwarf();
1721
dee830d9 1722 Dwarf_Die die, import;
f09d0d1e 1723 const char *name;
440f755a
JS
1724 int res = dwarf_child (begin_die, &die);
1725 if (res != 0)
1726 return; // die without children, bail out.
1727
440f755a
JS
1728 do
1729 {
f09d0d1e 1730 switch (dwarf_tag(&die))
440f755a
JS
1731 {
1732 case DW_TAG_label:
f09d0d1e
JS
1733 name = dwarf_diename (&die);
1734 if (name &&
8096dd7d
JS
1735 (name == sym
1736 || (name_has_wildcard(sym)
1737 && function_name_matches_pattern (name, sym))))
1738 {
8096dd7d
JS
1739 // Don't try to be smart. Just drop no addr labels.
1740 Dwarf_Addr stmt_addr;
1741 if (dwarf_lowpc (&die, &stmt_addr) == 0)
1742 {
f09d0d1e
JS
1743 // Get the file/line number for this label
1744 int dline;
1745 const char *file = dwarf_decl_file (&die);
1746 dwarf_decl_line (&die, &dline);
1747
9aa8ffce
JS
1748 vector<Dwarf_Die> scopes = getscopes_die(&die);
1749 if (scopes.size() > 1)
f5958c8f
JS
1750 {
1751 Dwarf_Die scope;
2713ea24 1752 if (!inner_die_containing_pc(scopes[1], stmt_addr, scope))
2a43d5db 1753 {
7e456f65
LB
1754 sess.print_warning(_F("label '%s' at address %s (dieoffset: %s) is not "
1755 "contained by its scope '%s' (dieoffset: %s) -- bad"
4c5d9906 1756 " debuginfo? [man error::dwarf]", name, lex_cast_hex(stmt_addr).c_str(),
7e456f65
LB
1757 lex_cast_hex(dwarf_dieoffset(&die)).c_str(),
1758 (dwarf_diename(&scope) ?: "<unknown>"),
1759 lex_cast_hex(dwarf_dieoffset(&scope)).c_str()));
2a43d5db 1760 }
f5958c8f
JS
1761 callback(function, name, file, dline,
1762 &scope, stmt_addr, q);
1763 }
8096dd7d
JS
1764 }
1765 }
440f755a 1766 break;
8096dd7d 1767
440f755a 1768 case DW_TAG_subprogram:
30868aad 1769 case DW_TAG_inlined_subroutine:
f09d0d1e
JS
1770 // Stay within our filtered function
1771 break;
1772
dee830d9
MW
1773 case DW_TAG_imported_unit:
1774 // Iterate over the children of the imported unit as if they
1775 // were inserted in place.
1776 if (dwarf_attr_die(&die, DW_AT_import, &import))
1777 iterate_over_labels (&import, sym, function, q, callback);
1778 break;
1779
440f755a
JS
1780 default:
1781 if (dwarf_haschildren (&die))
f09d0d1e 1782 iterate_over_labels (&die, sym, function, q, callback);
8096dd7d 1783 break;
440f755a
JS
1784 }
1785 }
1786 while (dwarf_siblingof (&die, &die) == 0);
1787}
1788
1789
1790void
1791dwflpp::collect_srcfiles_matching (string const & pattern,
bd25380d 1792 set<string> & filtered_srcfiles)
440f755a
JS
1793{
1794 assert (module);
1795 assert (cu);
1796
1797 size_t nfiles;
1798 Dwarf_Files *srcfiles;
1799
1800 // PR 5049: implicit * in front of given path pattern.
1801 // NB: fnmatch() is used without FNM_PATHNAME.
1802 string prefixed_pattern = string("*/") + pattern;
1803
1804 dwarf_assert ("dwarf_getsrcfiles",
1805 dwarf_getsrcfiles (cu, &srcfiles, &nfiles));
1806 {
1807 for (size_t i = 0; i < nfiles; ++i)
1808 {
1809 char const * fname = dwarf_filesrc (srcfiles, i, NULL, NULL);
1810 if (fnmatch (pattern.c_str(), fname, 0) == 0 ||
1811 fnmatch (prefixed_pattern.c_str(), fname, 0) == 0)
1812 {
1813 filtered_srcfiles.insert (fname);
1814 if (sess.verbose>2)
f9bbd346 1815 clog << _F("selected source file '%s'\n", fname);
440f755a
JS
1816 }
1817 }
1818 }
1819}
1820
1821
1822void
1823dwflpp::resolve_prologue_endings (func_info_map_t & funcs)
1824{
1825 // This heuristic attempts to pick the first address that has a
1826 // source line distinct from the function declaration's. In a
1827 // perfect world, this would be the first statement *past* the
1828 // prologue.
1829
1830 assert(module);
1831 assert(cu);
1832
1833 size_t nlines = 0;
1834 Dwarf_Lines *lines = NULL;
1835
1836 /* trouble cases:
1837 malloc do_symlink in init/initramfs.c tail-recursive/tiny then no-prologue
1838 sys_get?id in kernel/timer.c no-prologue
1839 sys_exit_group tail-recursive
1840 {do_,}sys_open extra-long-prologue (gcc 3.4)
1841 cpu_to_logical_apicid NULL-decl_file
1842 */
1843
1844 // Fetch all srcline records, sorted by address.
1845 dwarf_assert ("dwarf_getsrclines",
1846 dwarf_getsrclines(cu, &lines, &nlines));
1847 // XXX: free lines[] later, but how?
1848
1849 for(func_info_map_t::iterator it = funcs.begin(); it != funcs.end(); it++)
1850 {
1851#if 0 /* someday */
1852 Dwarf_Addr* bkpts = 0;
1853 int n = dwarf_entry_breakpoints (& it->die, & bkpts);
1854 // ...
1855 free (bkpts);
1856#endif
1857
1858 Dwarf_Addr entrypc = it->entrypc;
1859 Dwarf_Addr highpc; // NB: highpc is exclusive: [entrypc,highpc)
1860 dwfl_assert ("dwarf_highpc", dwarf_highpc (& it->die,
1861 & highpc));
1862
1863 if (it->decl_file == 0) it->decl_file = "";
1864
1865 unsigned entrypc_srcline_idx = 0;
1866 dwarf_line_t entrypc_srcline;
1867 // open-code binary search for exact match
1868 {
1869 unsigned l = 0, h = nlines;
1870 while (l < h)
1871 {
1872 entrypc_srcline_idx = (l + h) / 2;
1873 const dwarf_line_t lr(dwarf_onesrcline(lines,
1874 entrypc_srcline_idx));
1875 Dwarf_Addr addr = lr.addr();
1876 if (addr == entrypc) { entrypc_srcline = lr; break; }
1877 else if (l + 1 == h) { break; } // ran off bottom of tree
1878 else if (addr < entrypc) { l = entrypc_srcline_idx; }
1879 else { h = entrypc_srcline_idx; }
1880 }
1881 }
1882 if (!entrypc_srcline)
1883 {
1884 if (sess.verbose > 2)
f9bbd346
LB
1885 clog << _F("missing entrypc dwarf line record for function '%s'\n",
1886 it->name.c_str());
440f755a
JS
1887 // This is probably an inlined function. We'll end up using
1888 // its lowpc as a probe address.
1889 continue;
1890 }
1891
48390b53
FCE
1892 if (entrypc == 0)
1893 {
1894 if (sess.verbose > 2)
f9bbd346
LB
1895 clog << _F("null entrypc dwarf line record for function '%s'\n",
1896 it->name.c_str());
48390b53
FCE
1897 // This is probably an inlined function. We'll skip this instance;
1898 // it is messed up.
1899 continue;
1900 }
1901
440f755a 1902 if (sess.verbose>2)
2a97f50b 1903 clog << _F("searching for prologue of function '%s' %#" PRIx64 "-%#" PRIx64
f9bbd346
LB
1904 "@%s:%d\n", it->name.c_str(), entrypc, highpc, it->decl_file,
1905 it->decl_line);
440f755a
JS
1906
1907 // Now we go searching for the first line record that has a
1908 // file/line different from the one in the declaration.
1909 // Normally, this will be the next one. BUT:
1910 //
1911 // We may have to skip a few because some old compilers plop
1912 // in dummy line records for longer prologues. If we go too
1913 // far (addr >= highpc), we take the previous one. Or, it may
1914 // be the first one, if the function had no prologue, and thus
1915 // the entrypc maps to a statement in the body rather than the
1916 // declaration.
1917
1918 unsigned postprologue_srcline_idx = entrypc_srcline_idx;
1919 bool ranoff_end = false;
1920 while (postprologue_srcline_idx < nlines)
1921 {
1922 dwarf_line_t lr(dwarf_onesrcline(lines, postprologue_srcline_idx));
1923 Dwarf_Addr postprologue_addr = lr.addr();
1924 const char* postprologue_file = lr.linesrc();
1925 int postprologue_lineno = lr.lineno();
1926
1927 if (sess.verbose>2)
2a97f50b 1928 clog << _F("checking line record %#" PRIx64 "@%s:%d\n", postprologue_addr,
f9bbd346 1929 postprologue_file, postprologue_lineno);
440f755a
JS
1930
1931 if (postprologue_addr >= highpc)
1932 {
1933 ranoff_end = true;
1934 postprologue_srcline_idx --;
1935 continue;
1936 }
1937 if (ranoff_end ||
1938 (strcmp (postprologue_file, it->decl_file) || // We have a winner!
1939 (postprologue_lineno != it->decl_line)))
1940 {
1941 it->prologue_end = postprologue_addr;
1942
1943 if (sess.verbose>2)
1944 {
f9bbd346 1945 clog << _F("prologue found function '%s'", it->name.c_str());
440f755a 1946 // Add a little classification datum
ce0f6648 1947 //TRANSLATORS: Here we're adding some classification datum (ie Prologue Free)
f9bbd346 1948 if (postprologue_srcline_idx == entrypc_srcline_idx) clog << _(" (naked)");
ce0f6648 1949 //TRANSLATORS: Here we're adding some classification datum (ie Prologue Free)
f9bbd346 1950 if (ranoff_end) clog << _(" (tail-call?)");
440f755a
JS
1951 clog << " = 0x" << hex << postprologue_addr << dec << "\n";
1952 }
1953
1954 break;
1955 }
1956
1957 // Let's try the next srcline.
1958 postprologue_srcline_idx ++;
1959 } // loop over srclines
1960
1961 // if (strlen(it->decl_file) == 0) it->decl_file = NULL;
1962
1963 } // loop over functions
1964
1965 // XXX: how to free lines?
1966}
1967
1968
1969bool
1970dwflpp::function_entrypc (Dwarf_Addr * addr)
1971{
1972 assert (function);
1973 return (dwarf_entrypc (function, addr) == 0);
440f755a
JS
1974}
1975
1976
1977bool
1978dwflpp::die_entrypc (Dwarf_Die * die, Dwarf_Addr * addr)
1979{
1980 int rc = 0;
1981 string lookup_method;
1982
1983 * addr = 0;
1984
1985 lookup_method = "dwarf_entrypc";
1986 rc = dwarf_entrypc (die, addr);
1987
440f755a
JS
1988 if (rc)
1989 {
1990 lookup_method = "dwarf_ranges";
1991
1992 Dwarf_Addr base;
1993 Dwarf_Addr begin;
1994 Dwarf_Addr end;
1995 ptrdiff_t offset = dwarf_ranges (die, 0, &base, &begin, &end);
1996 if (offset < 0) rc = -1;
1997 else if (offset > 0)
1998 {
1999 * addr = begin;
2000 rc = 0;
2001
2002 // Now we need to check that there are no more ranges
2003 // associated with this function, which could conceivably
2004 // happen if a function is inlined, then pieces of it are
2005 // split amongst different conditional branches. It's not
2006 // obvious which of them to favour. As a heuristic, we
2007 // pick the beginning of the first range, and ignore the
2008 // others (but with a warning).
2009
2010 unsigned extra = 0;
2011 while ((offset = dwarf_ranges (die, offset, &base, &begin, &end)) > 0)
2012 extra ++;
2013 if (extra)
f9bbd346 2014 lookup_method += _F(", ignored %s more", lex_cast(extra).c_str());
440f755a
JS
2015 }
2016 }
2017
4ad42007
FCE
2018 // PR10574: reject subprograms where the entrypc address turns out
2019 // to be 0, since they tend to correspond to duplicate-eliminated
2020 // COMDAT copies of C++ functions.
2021 if (rc == 0 && *addr == 0)
2022 {
f9bbd346 2023 lookup_method += _(" (skip comdat)");
4ad42007
FCE
2024 rc = 1;
2025 }
2026
440f755a 2027 if (sess.verbose > 2)
e045bb07 2028 clog << _F("entry-pc lookup (%s dieoffset: %s) = %#" PRIx64 " (rc %d)", lookup_method.c_str(),
f9bbd346 2029 lex_cast_hex(dwarf_dieoffset(die)).c_str(), *addr, rc) << endl;
4ad42007 2030
440f755a
JS
2031 return (rc == 0);
2032}
2033
2034
2035void
2036dwflpp::function_die (Dwarf_Die *d)
2037{
2038 assert (function);
2039 *d = *function;
2040}
2041
2042
2043void
2044dwflpp::function_file (char const ** c)
2045{
2046 assert (function);
2047 assert (c);
2048 *c = dwarf_decl_file (function);
2049}
2050
2051
2052void
2053dwflpp::function_line (int *linep)
2054{
2055 assert (function);
2056 dwarf_decl_line (function, linep);
2057}
2058
2059
2060bool
2061dwflpp::die_has_pc (Dwarf_Die & die, Dwarf_Addr pc)
2062{
2063 int res = dwarf_haspc (&die, pc);
2064 // dwarf_ranges will return -1 if a function die has no DW_AT_ranges
2065 // if (res == -1)
2066 // dwarf_assert ("dwarf_haspc", res);
2067 return res == 1;
2068}
2069
2070
2a43d5db 2071bool
f5958c8f
JS
2072dwflpp::inner_die_containing_pc(Dwarf_Die& scope, Dwarf_Addr addr,
2073 Dwarf_Die& result)
2074{
793f98d5
JS
2075 result = scope;
2076
2077 // Sometimes we're in a bad scope to begin with -- just let it be. This can
2078 // happen for example if the compiler outputs a label PC that's just outside
2079 // the lexical scope. We can't really do anything about that, but variables
2080 // will probably not be accessible in this case.
f5958c8f 2081 if (!die_has_pc(scope, addr))
2a43d5db 2082 return false;
f5958c8f 2083
dee830d9 2084 Dwarf_Die child, import;
f5958c8f
JS
2085 int rc = dwarf_child(&result, &child);
2086 while (rc == 0)
2087 {
2088 switch (dwarf_tag (&child))
2089 {
dee830d9
MW
2090 case DW_TAG_imported_unit:
2091 // The children of the imported unit need to be treated as if
2092 // they are inserted here. So look inside and set result if
2093 // found.
2094 if (dwarf_attr_die(&child, DW_AT_import, &import))
2095 {
2096 Dwarf_Die import_result;
2097 if (inner_die_containing_pc(import, addr, import_result))
2098 {
2099 result = import_result;
2100 return true;
2101 }
2102 }
2103 break;
2104
f5958c8f
JS
2105 // lexical tags to recurse within the same starting scope
2106 // NB: this intentionally doesn't cross into inlines!
2107 case DW_TAG_lexical_block:
2108 case DW_TAG_with_stmt:
2109 case DW_TAG_catch_block:
2110 case DW_TAG_try_block:
2111 case DW_TAG_entry_point:
2112 if (die_has_pc(child, addr))
2113 {
2114 result = child;
2115 rc = dwarf_child(&result, &child);
2116 continue;
2117 }
2118 }
2119 rc = dwarf_siblingof(&child, &child);
2120 }
2a43d5db 2121 return true;
f5958c8f
JS
2122}
2123
2124
440f755a
JS
2125void
2126dwflpp::loc2c_error (void *, const char *fmt, ...)
2127{
2128 const char *msg = "?";
2129 char *tmp = NULL;
2130 int rc;
2131 va_list ap;
2132 va_start (ap, fmt);
2133 rc = vasprintf (& tmp, fmt, ap);
2134 if (rc < 0)
2135 msg = "?";
2136 else
2137 msg = tmp;
2138 va_end (ap);
2139 throw semantic_error (msg);
2140}
2141
2142
2143// This function generates code used for addressing computations of
2144// target variables.
2145void
2146dwflpp::emit_address (struct obstack *pool, Dwarf_Addr address)
2147{
2d7232ca 2148 int n = dwfl_module_relocations (module);
440f755a
JS
2149 dwfl_assert ("dwfl_module_relocations", n >= 0);
2150 Dwarf_Addr reloc_address = address;
2d7232ca
MW
2151 const char *secname = "";
2152 if (n > 1)
2153 {
2154 int i = dwfl_module_relocate_address (module, &reloc_address);
2155 dwfl_assert ("dwfl_module_relocate_address", i >= 0);
2156 secname = dwfl_module_relocation_info (module, i, NULL);
2157 }
440f755a
JS
2158
2159 if (sess.verbose > 2)
2160 {
2a97f50b 2161 clog << _F("emit dwarf addr %#" PRIx64 " => module %s section %s relocaddr %#" PRIx64,
2d7232ca
MW
2162 address, module_name.c_str (), (secname ?: "null"),
2163 reloc_address) << endl;
440f755a
JS
2164 }
2165
2166 if (n > 0 && !(n == 1 && secname == NULL))
2167 {
2168 dwfl_assert ("dwfl_module_relocation_info", secname);
2169 if (n > 1 || secname[0] != '\0')
2170 {
2171 // This gives us the module name, and section name within the
2172 // module, for a kernel module (or other ET_REL module object).
f685b2fe 2173 obstack_printf (pool, "({ unsigned long addr = 0; ");
a049e342 2174 obstack_printf (pool, "addr = _stp_kmodule_relocate (\"%s\",\"%s\",%#" PRIx64 "); ",
2d7232ca 2175 module_name.c_str(), secname, reloc_address);
440f755a
JS
2176 obstack_printf (pool, "addr; })");
2177 }
2178 else if (n == 1 && module_name == TOK_KERNEL && secname[0] == '\0')
2179 {
2180 // elfutils' way of telling us that this is a relocatable kernel address, which we
2181 // need to treat the same way here as dwarf_query::add_probe_point does: _stext.
2182 address -= sess.sym_stext;
2183 secname = "_stext";
f685b2fe
MW
2184 // Note we "cache" the result here through a static because the
2185 // kernel will never move after being loaded (unlike modules and
2186 // user-space dynamic share libraries).
440f755a 2187 obstack_printf (pool, "({ static unsigned long addr = 0; ");
a049e342 2188 obstack_printf (pool, "if (addr==0) addr = _stp_kmodule_relocate (\"%s\",\"%s\",%#" PRIx64 "); ",
2d7232ca 2189 module_name.c_str(), secname, address); // PR10000 NB: not reloc_address
440f755a
JS
2190 obstack_printf (pool, "addr; })");
2191 }
2192 else
2193 {
7f085e3f 2194 obstack_printf (pool, "/* pragma:vma */");
f685b2fe 2195 obstack_printf (pool, "({ unsigned long addr = 0; ");
a049e342 2196 obstack_printf (pool, "addr = _stp_umodule_relocate (\"%s\",%#" PRIx64 ", current); ",
5bca76a8 2197 resolve_path(module_name.c_str()).c_str(), address);
a295050e 2198 obstack_printf (pool, "addr; })");
440f755a
JS
2199 }
2200 }
2201 else
2202 obstack_printf (pool, "%#" PRIx64 "UL", address); // assume as constant
2203}
2204
2205
2206void
2207dwflpp::loc2c_emit_address (void *arg, struct obstack *pool,
2208 Dwarf_Addr address)
2209{
c94efd63 2210 static_cast<dwflpp *>(arg)->emit_address (pool, address);
440f755a
JS
2211}
2212
2213
2214void
729455a7 2215dwflpp::print_locals(vector<Dwarf_Die>& scopes, ostream &o)
440f755a 2216{
729455a7
JS
2217 // XXX Shouldn't this be walking up to outer scopes too?
2218
dee830d9
MW
2219 print_locals_die(scopes[0], o);
2220}
2221
2222void
2223dwflpp::print_locals_die(Dwarf_Die& die, ostream &o)
2224{
440f755a 2225 // Try to get the first child of die.
dee830d9
MW
2226 Dwarf_Die child, import;
2227 if (dwarf_child (&die, &child) == 0)
440f755a
JS
2228 {
2229 do
2230 {
2231 const char *name;
2232 // Output each sibling's name (that is a variable or
2233 // parameter) to 'o'.
2234 switch (dwarf_tag (&child))
2235 {
2236 case DW_TAG_variable:
2237 case DW_TAG_formal_parameter:
2238 name = dwarf_diename (&child);
2239 if (name)
4ca5acc8 2240 o << " $" << name;
440f755a 2241 break;
dee830d9
MW
2242 case DW_TAG_imported_unit:
2243 // Treat the imported unit children as if they are
2244 // children of the given DIE.
2245 if (dwarf_attr_die(&child, DW_AT_import, &import))
2246 print_locals_die (import, o);
2247 break;
440f755a
JS
2248 default:
2249 break;
2250 }
2251 }
2252 while (dwarf_siblingof (&child, &child) == 0);
2253 }
2254}
2255
2256
2257Dwarf_Attribute *
729455a7 2258dwflpp::find_variable_and_frame_base (vector<Dwarf_Die>& scopes,
440f755a
JS
2259 Dwarf_Addr pc,
2260 string const & local,
2261 const target_symbol *e,
2262 Dwarf_Die *vardie,
2263 Dwarf_Attribute *fb_attr_mem)
2264{
729455a7 2265 Dwarf_Die *scope_die = &scopes[0];
440f755a
JS
2266 Dwarf_Attribute *fb_attr = NULL;
2267
2268 assert (cu);
2269
729455a7 2270 int declaring_scope = dwarf_getscopevar (&scopes[0], scopes.size(),
440f755a
JS
2271 local.c_str(),
2272 0, NULL, 0, 0,
2273 vardie);
2274 if (declaring_scope < 0)
2275 {
2276 stringstream alternatives;
2277 print_locals (scopes, alternatives);
bd1fcbad 2278 if (pc)
4c5d9906 2279 throw semantic_error (_F("unable to find local '%s', [man error::dwarf] dieoffset %s in %s, near pc %s %s %s %s (%s)",
3d9381fc 2280 local.c_str(),
54bc3392
MW
2281 lex_cast_hex(dwarf_dieoffset(scope_die)).c_str(),
2282 module_name.c_str(),
3d9381fc
MW
2283 lex_cast_hex(pc).c_str(),
2284 (scope_die == NULL) ? "" : _("in"),
2285 (dwarf_diename(scope_die) ?: "<unknown>"),
2286 (dwarf_diename(cu) ?: "<unknown>"),
2287 (alternatives.str() == ""
2288 ? (_("<no alternatives>"))
6c779e63 2289 : (_("alternatives:")
3d9381fc
MW
2290 + alternatives.str())).c_str()),
2291 e->tok);
2292 else
4c5d9906 2293 throw semantic_error (_F("unable to find global '%s', [man error::dwarf] dieoffset %s in %s, %s %s %s (%s)",
3d9381fc 2294 local.c_str(),
54bc3392
MW
2295 lex_cast_hex(dwarf_dieoffset(scope_die)).c_str(),
2296 module_name.c_str(),
3d9381fc
MW
2297 (scope_die == NULL) ? "" : _("in"),
2298 (dwarf_diename(scope_die) ?: "<unknown>"),
bd1fcbad 2299 cu_name().c_str(),
3d9381fc
MW
2300 (alternatives.str() == ""
2301 ? (_("<no alternatives>"))
6c779e63 2302 : (_("alternatives:")
3d9381fc
MW
2303 + alternatives.str())).c_str()),
2304 e->tok);
440f755a
JS
2305 }
2306
4d51e8ca
MW
2307 /* Some GCC versions would output duplicate external variables, one
2308 without a location attribute. If so, try to find the other if it
2309 exists in the same scope. See GCC PR51410. */
2310 Dwarf_Attribute attr_mem;
2311 if (dwarf_attr_integrate (vardie, DW_AT_const_value, &attr_mem) == NULL
2312 && dwarf_attr_integrate (vardie, DW_AT_location, &attr_mem) == NULL
2313 && dwarf_attr_integrate (vardie, DW_AT_external, &attr_mem) != NULL
2314 && dwarf_tag(&scopes[declaring_scope]) == DW_TAG_compile_unit)
2315 {
ea484b93 2316 Dwarf_Die orig_vardie = *vardie;
4d51e8ca
MW
2317 bool alt_found = false;
2318 if (dwarf_child(&scopes[declaring_scope], vardie) == 0)
2319 do
2320 {
dee830d9
MW
2321 // Note, not handling DW_TAG_imported_unit, assuming GCC
2322 // version is recent enough to not need this workaround if
2323 // we would see an imported unit.
4d51e8ca
MW
2324 if (dwarf_tag (vardie) == DW_TAG_variable
2325 && strcmp (dwarf_diename (vardie), local.c_str ()) == 0
2326 && (dwarf_attr_integrate (vardie, DW_AT_external, &attr_mem)
2327 != NULL)
2328 && ((dwarf_attr_integrate (vardie, DW_AT_const_value, &attr_mem)
2329 != NULL)
2330 || (dwarf_attr_integrate (vardie, DW_AT_location, &attr_mem)
2331 != NULL)))
2332 alt_found = true;
2333 }
2334 while (!alt_found && dwarf_siblingof(vardie, vardie) == 0);
2335
2336 if (! alt_found)
ea484b93 2337 *vardie = orig_vardie;
4d51e8ca
MW
2338 }
2339
3965e105 2340 // Global vars don't need (cannot use) frame base in location descriptor.
bd1fcbad 2341 if (pc == 0)
3965e105
MW
2342 return NULL;
2343
7bce6f87
MW
2344 /* We start out walking the "lexical scopes" as returned by
2345 * as returned by dwarf_getscopes for the address, starting with the
2346 * declaring_scope that the variable was found in.
2347 */
729455a7
JS
2348 vector<Dwarf_Die> physcopes, *fbscopes = &scopes;
2349 for (size_t inner = declaring_scope;
2350 inner < fbscopes->size() && fb_attr == NULL;
7bce6f87 2351 ++inner)
440f755a 2352 {
729455a7
JS
2353 Dwarf_Die& scope = (*fbscopes)[inner];
2354 switch (dwarf_tag (&scope))
440f755a
JS
2355 {
2356 default:
2357 continue;
2358 case DW_TAG_subprogram:
2359 case DW_TAG_entry_point:
729455a7 2360 fb_attr = dwarf_attr_integrate (&scope,
7bce6f87
MW
2361 DW_AT_frame_base,
2362 fb_attr_mem);
2363 break;
2364 case DW_TAG_inlined_subroutine:
2365 /* Unless we already are going through the "pyshical die tree",
2366 * we now need to start walking the die tree where this
2367 * subroutine is inlined to find the appropriate frame base. */
2368 if (declaring_scope != -1)
2369 {
729455a7
JS
2370 physcopes = getscopes_die(&scope);
2371 if (physcopes.empty())
f9bbd346
LB
2372 throw semantic_error (_F("unable to get die scopes for '%s' in an inlined subroutine",
2373 local.c_str()), e->tok);
729455a7 2374 fbscopes = &physcopes;
7bce6f87
MW
2375 inner = 0; // zero is current scope, for look will increase.
2376 declaring_scope = -1;
2377 }
440f755a
JS
2378 break;
2379 }
2380 }
7bce6f87 2381
440f755a
JS
2382 return fb_attr;
2383}
2384
2385
2386struct location *
2387dwflpp::translate_location(struct obstack *pool,
00730da1
MW
2388 Dwarf_Attribute *attr, Dwarf_Die *die,
2389 Dwarf_Addr pc,
440f755a
JS
2390 Dwarf_Attribute *fb_attr,
2391 struct location **tail,
2392 const target_symbol *e)
2393{
619d9aaf
MW
2394
2395 /* DW_AT_data_member_location, can be either constant offsets
e050d62f 2396 (struct member fields), or full blown location expressions. */
619d9aaf 2397
03ba05b6
MW
2398 /* There is no location expression, but a constant value instead. */
2399 if (dwarf_whatattr (attr) == DW_AT_const_value)
2400 {
2401 *tail = c_translate_constant (pool, &loc2c_error, this,
2402 &loc2c_emit_address, 0, pc, attr);
2403 return *tail;
2404 }
2405
440f755a
JS
2406 Dwarf_Op *expr;
2407 size_t len;
2408
2409 /* PR9768: formerly, we added pc+module_bias here. However, that bias value
2410 is not present in the pc value by the time we get it, so adding it would
2411 result in false negatives of variable reachibility. In other instances
2412 further below, the c_translate_FOO functions, the module_bias value used
2413 to be passed in, but instead should now be zero for the same reason. */
2414
45b02a36 2415 retry:
440f755a
JS
2416 switch (dwarf_getlocation_addr (attr, pc /*+ module_bias*/, &expr, &len, 1))
2417 {
2418 case 1: /* Should always happen. */
2419 if (len > 0)
2420 break;
2421 /* Fall through. */
2422
45b02a36
FCE
2423 case 0: /* Shouldn't happen.... but can, e.g. due to PR15123. */
2424 {
2425 Dwarf_Addr pc2 = pr15123_retry_addr (pc, die);
2426 if (pc2 != 0) {
2427 pc = pc2;
2428 goto retry;
2429 }
2430 }
2431
2432 /* FALLTHROUGH */
4c5d9906 2433 throw semantic_error (_F("not accessible at this address [man error::dwarf] (%s, dieoffset: %s)",
f9bbd346
LB
2434 lex_cast_hex(pc).c_str(), lex_cast_hex(dwarf_dieoffset(die)).c_str()),
2435 e->tok);
440f755a
JS
2436
2437 default: /* Shouldn't happen. */
2438 case -1:
4c5d9906 2439 throw semantic_error (_F("dwarf_getlocation_addr failed [man error::dwarf] , %s", dwarf_errmsg(-1)), e->tok);
440f755a
JS
2440 }
2441
3965e105 2442 Dwarf_Op *cfa_ops;
87748e2b
MW
2443 // pc is in the dw address space of the current module, which is what
2444 // c_translate_location expects. get_cfa_ops wants the global dwfl address.
3965e105 2445 // cfa_ops only make sense for locals.
bd1fcbad 2446 if (pc)
3965e105
MW
2447 {
2448 Dwarf_Addr addr = pc + module_bias;
2449 cfa_ops = get_cfa_ops (addr);
2450 }
2451 else
2452 cfa_ops = NULL;
2453
440f755a
JS
2454 return c_translate_location (pool, &loc2c_error, this,
2455 &loc2c_emit_address,
2456 1, 0 /* PR9768 */,
24c7957b 2457 pc, attr, expr, len, tail, fb_attr, cfa_ops);
440f755a
JS
2458}
2459
2460
2461void
28a494df 2462dwflpp::print_members(Dwarf_Die *typedie, ostream &o, set<string> &dupes)
440f755a 2463{
28a494df 2464 const int typetag = dwarf_tag (typedie);
440f755a 2465
dee830d9
MW
2466 /* compile and partial unit included for recursion through
2467 imported_unit below. */
9c119951
JS
2468 if (typetag != DW_TAG_structure_type &&
2469 typetag != DW_TAG_class_type &&
dee830d9
MW
2470 typetag != DW_TAG_union_type &&
2471 typetag != DW_TAG_compile_unit &&
2472 typetag != DW_TAG_partial_unit)
440f755a 2473 {
28a494df
MW
2474 o << _F(" Error: %s isn't a struct/class/union",
2475 dwarf_type_name(typedie).c_str());
440f755a
JS
2476 return;
2477 }
2478
2479 // Try to get the first child of vardie.
dee830d9 2480 Dwarf_Die die_mem, import;
440f755a 2481 Dwarf_Die *die = &die_mem;
28a494df 2482 switch (dwarf_child (typedie, die))
440f755a
JS
2483 {
2484 case 1: // No children.
28a494df 2485 o << _F("%s is empty", dwarf_type_name(typedie).c_str());
c150b595 2486 return;
440f755a
JS
2487
2488 case -1: // Error.
2489 default: // Shouldn't happen.
28a494df 2490 o << dwarf_type_name(typedie)
440f755a 2491 << ": " << dwarf_errmsg (-1);
c150b595 2492 return;
440f755a
JS
2493
2494 case 0: // Success.
2495 break;
2496 }
2497
2498 // Output each sibling's name to 'o'.
9c119951 2499 do
440f755a 2500 {
9c119951 2501 int tag = dwarf_tag(die);
dee830d9
MW
2502
2503 /* The children of an imported_unit should be treated as members too. */
2504 if (tag == DW_TAG_imported_unit
2505 && dwarf_attr_die(die, DW_AT_import, &import))
2506 print_members(&import, o, dupes);
2507
9c119951
JS
2508 if (tag != DW_TAG_member && tag != DW_TAG_inheritance)
2509 continue;
2510
23d106b9 2511 const char *member = dwarf_diename (die) ;
440f755a 2512
9c119951 2513 if ( tag == DW_TAG_member && member != NULL )
1de6dd7a
JS
2514 {
2515 // Only output if this is new, to avoid inheritance dupes.
2516 if (dupes.insert(member).second)
2517 o << " " << member;
2518 }
440f755a
JS
2519 else
2520 {
f1c8f8a5 2521 Dwarf_Die temp_die;
3d1ad340 2522 if (!dwarf_attr_die (die, DW_AT_type, &temp_die))
440f755a 2523 {
f1c8f8a5
JS
2524 string source = dwarf_decl_file(die) ?: "<unknown source>";
2525 int line = -1;
2526 dwarf_decl_line(die, &line);
f9bbd346
LB
2527 clog << _F("\n Error in obtaining type attribute for anonymous "
2528 "member at %s:%d", source.c_str(), line);
440f755a
JS
2529 return;
2530 }
2531
1de6dd7a 2532 print_members(&temp_die, o, dupes);
440f755a
JS
2533 }
2534
440f755a 2535 }
9c119951 2536 while (dwarf_siblingof (die, die) == 0);
440f755a
JS
2537}
2538
2539
2540bool
c67847a0 2541dwflpp::find_struct_member(const target_symbol::component& c,
440f755a 2542 Dwarf_Die *parentdie,
440f755a 2543 Dwarf_Die *memberdie,
00730da1 2544 vector<Dwarf_Die>& dies,
440f755a
JS
2545 vector<Dwarf_Attribute>& locs)
2546{
2547 Dwarf_Attribute attr;
b57ba9b8 2548 Dwarf_Die die;
440f755a 2549
e5a573c0
JS
2550 /* With inheritance, a subclass may mask member names of parent classes, so
2551 * our search among the inheritance tree must be breadth-first rather than
2552 * depth-first (recursive). The parentdie is still our starting point. */
2553 deque<Dwarf_Die> inheritees(1, *parentdie);
2554 for (; !inheritees.empty(); inheritees.pop_front())
440f755a 2555 {
e5a573c0 2556 switch (dwarf_child (&inheritees.front(), &die))
440f755a 2557 {
e5a573c0
JS
2558 case 0: /* First child found. */
2559 break;
2560 case 1: /* No children. */
2561 continue;
2562 case -1: /* Error. */
2563 default: /* Shouldn't happen */
2564 throw semantic_error (dwarf_type_name(&inheritees.front()) + ": "
2565 + string (dwarf_errmsg (-1)),
2566 c.tok);
440f755a 2567 }
e5a573c0
JS
2568
2569 do
440f755a 2570 {
e5a573c0 2571 int tag = dwarf_tag(&die);
dee830d9
MW
2572 /* recurse into imported units as if they are anonymoust structs */
2573 Dwarf_Die import;
2574 if (tag == DW_TAG_imported_unit
2575 && dwarf_attr_die(&die, DW_AT_import, &import)
2576 && find_struct_member(c, &import, memberdie, dies, locs))
2577 goto success;
2578
e5a573c0
JS
2579 if (tag != DW_TAG_member && tag != DW_TAG_inheritance)
2580 continue;
2581
2582 const char *name = dwarf_diename(&die);
2583 if (tag == DW_TAG_inheritance)
2584 {
2585 /* Remember inheritee for breadth-first search. */
2586 Dwarf_Die inheritee;
2587 if (dwarf_attr_die (&die, DW_AT_type, &inheritee))
2588 inheritees.push_back(inheritee);
2589 }
2590 else if (name == NULL)
2591 {
2592 /* Need to recurse for anonymous structs/unions. */
2593 Dwarf_Die subdie;
2594 if (dwarf_attr_die (&die, DW_AT_type, &subdie) &&
2595 find_struct_member(c, &subdie, memberdie, dies, locs))
2596 goto success;
2597 }
2598 else if (name == c.member)
2599 {
2600 *memberdie = die;
2601 goto success;
2602 }
440f755a 2603 }
e5a573c0 2604 while (dwarf_siblingof (&die, &die) == 0);
440f755a 2605 }
440f755a
JS
2606
2607 return false;
2608
2609success:
2610 /* As we unwind the recursion, we need to build the chain of
2611 * locations that got to the final answer. */
2612 if (dwarf_attr_integrate (&die, DW_AT_data_member_location, &attr))
00730da1
MW
2613 {
2614 dies.insert(dies.begin(), die);
2615 locs.insert(locs.begin(), attr);
2616 }
440f755a
JS
2617
2618 /* Union members don't usually have a location,
2619 * but just use the containing union's location. */
2620 else if (dwarf_tag(parentdie) != DW_TAG_union_type)
f9bbd346
LB
2621 throw semantic_error (_F("no location for field '%s':%s",
2622 c.member.c_str(), dwarf_errmsg(-1)), c.tok);
440f755a
JS
2623
2624 return true;
2625}
2626
2627
6ce303b8
JS
2628static inline void
2629dwarf_die_type (Dwarf_Die *die, Dwarf_Die *typedie_mem, const token *tok=NULL)
2630{
2631 if (!dwarf_attr_die (die, DW_AT_type, typedie_mem))
f9bbd346 2632 throw semantic_error (_F("cannot get type of field: %s", dwarf_errmsg(-1)), tok);
6ce303b8
JS
2633}
2634
2635
2636void
440f755a
JS
2637dwflpp::translate_components(struct obstack *pool,
2638 struct location **tail,
2639 Dwarf_Addr pc,
2640 const target_symbol *e,
2641 Dwarf_Die *vardie,
f3b5366d
JS
2642 Dwarf_Die *typedie,
2643 unsigned first)
440f755a 2644{
f3b5366d 2645 unsigned i = first;
440f755a
JS
2646 while (i < e->components.size())
2647 {
c67847a0
JS
2648 const target_symbol::component& c = e->components[i];
2649
440f755a
JS
2650 /* XXX: This would be desirable, but we don't get the target_symbol token,
2651 and printing that gives us the file:line number too early anyway. */
2652#if 0
2653 // Emit a marker to note which field is being access-attempted, to give
2654 // better error messages if deref() fails.
aca66a36 2655 string piece = string(...target_symbol token...) + string ("#") + lex_cast(components[i].second);
440f755a
JS
2656 obstack_printf (pool, "c->last_stmt = %s;", lex_cast_qstring(piece).c_str());
2657#endif
2658
6ce303b8 2659 switch (dwarf_tag (typedie))
440f755a
JS
2660 {
2661 case DW_TAG_typedef:
2662 case DW_TAG_const_type:
2663 case DW_TAG_volatile_type:
2664 /* Just iterate on the referent type. */
6ce303b8 2665 dwarf_die_type (typedie, typedie, c.tok);
440f755a
JS
2666 break;
2667
9c119951
JS
2668 case DW_TAG_reference_type:
2669 case DW_TAG_rvalue_reference_type:
5f36109e
JS
2670 if (pool)
2671 c_translate_pointer (pool, 1, 0 /* PR9768*/, typedie, tail);
6ce303b8 2672 dwarf_die_type (typedie, typedie, c.tok);
9c119951
JS
2673 break;
2674
440f755a 2675 case DW_TAG_pointer_type:
c4dddae6 2676 /* A pointer with no type is a void* -- can't dereference it. */
6ce303b8 2677 if (!dwarf_hasattr_integrate (typedie, DW_AT_type))
ce0f6648 2678 throw semantic_error (_F("invalid access '%s' vs '%s'", lex_cast(c).c_str(),
f9bbd346 2679 dwarf_type_name(typedie).c_str()), c.tok);
c4dddae6 2680
5f36109e
JS
2681 if (pool)
2682 c_translate_pointer (pool, 1, 0 /* PR9768*/, typedie, tail);
6fda2dff
JS
2683 if (c.type != target_symbol::comp_literal_array_index &&
2684 c.type != target_symbol::comp_expression_array_index)
6ce303b8
JS
2685 {
2686 dwarf_die_type (typedie, typedie, c.tok);
2687 break;
2688 }
d52761f8 2689 /* else fall through as an array access */
440f755a
JS
2690
2691 case DW_TAG_array_type:
c67847a0 2692 if (c.type == target_symbol::comp_literal_array_index)
5f36109e
JS
2693 {
2694 if (pool)
2695 c_translate_array (pool, 1, 0 /* PR9768 */, typedie, tail,
2696 NULL, c.num_index);
2697 }
6fda2dff
JS
2698 else if (c.type == target_symbol::comp_expression_array_index)
2699 {
0386bbcf 2700 string index = "STAP_ARG_index" + lex_cast(i);
5f36109e
JS
2701 if (pool)
2702 c_translate_array (pool, 1, 0 /* PR9768 */, typedie, tail,
2703 index.c_str(), 0);
6fda2dff 2704 }
440f755a 2705 else
f9bbd346
LB
2706 throw semantic_error (_F("invalid access '%s' for array type",
2707 lex_cast(c).c_str()), c.tok);
6ce303b8
JS
2708
2709 dwarf_die_type (typedie, typedie, c.tok);
2710 *vardie = *typedie;
2711 ++i;
440f755a
JS
2712 break;
2713
2714 case DW_TAG_structure_type:
2715 case DW_TAG_union_type:
9c119951 2716 case DW_TAG_class_type:
c67847a0 2717 if (c.type != target_symbol::comp_struct_member)
f9bbd346
LB
2718 throw semantic_error (_F("invalid access '%s' for %s",
2719 lex_cast(c).c_str(), dwarf_type_name(typedie).c_str()));
c67847a0 2720
6ce303b8 2721 if (dwarf_hasattr(typedie, DW_AT_declaration))
440f755a 2722 {
a44a7cb5 2723 Dwarf_Die *tmpdie = declaration_resolve(typedie);
440f755a 2724 if (tmpdie == NULL)
f9bbd346 2725 throw semantic_error (_F("unresolved %s", dwarf_type_name(typedie).c_str()), c.tok);
6ce303b8 2726 *typedie = *tmpdie;
440f755a
JS
2727 }
2728
2729 {
00730da1 2730 vector<Dwarf_Die> dies;
440f755a 2731 vector<Dwarf_Attribute> locs;
00730da1 2732 if (!find_struct_member(c, typedie, vardie, dies, locs))
440f755a 2733 {
72c5ecc2
JS
2734 /* Add a file:line hint for anonymous types */
2735 string source;
6ce303b8 2736 if (!dwarf_hasattr_integrate(typedie, DW_AT_name))
72c5ecc2
JS
2737 {
2738 int line;
6ce303b8
JS
2739 const char *file = dwarf_decl_file(typedie);
2740 if (file && dwarf_decl_line(typedie, &line) == 0)
72c5ecc2 2741 source = " (" + string(file) + ":"
aca66a36 2742 + lex_cast(line) + ")";
72c5ecc2
JS
2743 }
2744
440f755a
JS
2745 string alternatives;
2746 stringstream members;
1de6dd7a
JS
2747 set<string> member_dupes;
2748 print_members(typedie, members, member_dupes);
440f755a 2749 if (members.str().size() != 0)
72c5ecc2 2750 alternatives = " (alternatives:" + members.str() + ")";
f9bbd346
LB
2751 throw semantic_error(_F("unable to find member '%s' for %s%s%s", c.member.c_str(),
2752 dwarf_type_name(typedie).c_str(), source.c_str(),
2753 alternatives.c_str()), c.tok);
440f755a
JS
2754 }
2755
2756 for (unsigned j = 0; j < locs.size(); ++j)
5f36109e 2757 if (pool)
00730da1
MW
2758 translate_location (pool, &locs[j], &dies[j],
2759 pc, NULL, tail, e);
440f755a
JS
2760 }
2761
6ce303b8 2762 dwarf_die_type (vardie, typedie, c.tok);
440f755a
JS
2763 ++i;
2764 break;
2765
2766 case DW_TAG_enumeration_type:
440f755a 2767 case DW_TAG_base_type:
1e41115c 2768 throw semantic_error (_F("invalid access '%s' vs. %s", lex_cast(c).c_str(),
f9bbd346 2769 dwarf_type_name(typedie).c_str()), c.tok);
440f755a 2770 break;
f1c8f8a5 2771
440f755a 2772 case -1:
f9bbd346 2773 throw semantic_error (_F("cannot find type: %s", dwarf_errmsg(-1)), c.tok);
440f755a
JS
2774 break;
2775
2776 default:
f9bbd346
LB
2777 throw semantic_error (_F("%s: unexpected type tag %s", dwarf_type_name(typedie).c_str(),
2778 lex_cast(dwarf_tag(typedie)).c_str()), c.tok);
440f755a
JS
2779 break;
2780 }
440f755a 2781 }
440f755a
JS
2782}
2783
2784
6ce303b8
JS
2785void
2786dwflpp::resolve_unqualified_inner_typedie (Dwarf_Die *typedie,
2787 Dwarf_Die *innerdie,
440f755a
JS
2788 const target_symbol *e)
2789{
6ce303b8
JS
2790 int typetag = dwarf_tag (typedie);
2791 *innerdie = *typedie;
2792 while (typetag == DW_TAG_typedef ||
2793 typetag == DW_TAG_const_type ||
2794 typetag == DW_TAG_volatile_type)
440f755a 2795 {
6ce303b8 2796 if (!dwarf_attr_die (innerdie, DW_AT_type, innerdie))
f9bbd346 2797 throw semantic_error (_F("cannot get type of pointee: %s", dwarf_errmsg(-1)), e->tok);
6ce303b8 2798 typetag = dwarf_tag (innerdie);
440f755a 2799 }
440f755a
JS
2800}
2801
2802
2803void
2804dwflpp::translate_final_fetch_or_store (struct obstack *pool,
2805 struct location **tail,
822a6a3d 2806 Dwarf_Addr /*module_bias*/,
6ce303b8
JS
2807 Dwarf_Die *vardie,
2808 Dwarf_Die *start_typedie,
440f755a
JS
2809 bool lvalue,
2810 const target_symbol *e,
2811 string &,
2812 string &,
2813 exp_type & ty)
2814{
2815 /* First boil away any qualifiers associated with the type DIE of
2816 the final location to be accessed. */
2817
6ce303b8
JS
2818 Dwarf_Die typedie_mem, *typedie = &typedie_mem;
2819 resolve_unqualified_inner_typedie (start_typedie, typedie, e);
440f755a 2820
03c75a4a
JS
2821 /* If we're looking for an address, then we can just provide what
2822 we computed to this point, without using a fetch/store. */
2823 if (e->addressof)
2824 {
2825 if (lvalue)
f9bbd346 2826 throw semantic_error (_("cannot write to member address"), e->tok);
03c75a4a 2827
6ce303b8 2828 if (dwarf_hasattr_integrate (vardie, DW_AT_bit_offset))
f9bbd346 2829 throw semantic_error (_("cannot take address of bit-field"), e->tok);
03c75a4a 2830
0386bbcf 2831 c_translate_addressof (pool, 1, 0, vardie, typedie, tail, "STAP_RETVALUE");
03c75a4a
JS
2832 ty = pe_long;
2833 return;
2834 }
2835
440f755a
JS
2836 /* Then switch behavior depending on the type of fetch/store we
2837 want, and the type and pointer-ness of the final location. */
2838
6ce303b8 2839 int typetag = dwarf_tag (typedie);
440f755a
JS
2840 switch (typetag)
2841 {
2842 default:
f9bbd346
LB
2843 throw semantic_error (_F("unsupported type tag %s for %s", lex_cast(typetag).c_str(),
2844 dwarf_type_name(typedie).c_str()), e->tok);
440f755a
JS
2845 break;
2846
2847 case DW_TAG_structure_type:
9c119951 2848 case DW_TAG_class_type:
440f755a 2849 case DW_TAG_union_type:
f9bbd346
LB
2850 throw semantic_error (_F("'%s' is being accessed instead of a member",
2851 dwarf_type_name(typedie).c_str()), e->tok);
440f755a
JS
2852 break;
2853
440f755a
JS
2854 case DW_TAG_base_type:
2855
2856 // Reject types we can't handle in systemtap
2857 {
440f755a
JS
2858 Dwarf_Attribute encoding_attr;
2859 Dwarf_Word encoding = (Dwarf_Word) -1;
2860 dwarf_formudata (dwarf_attr_integrate (typedie, DW_AT_encoding, &encoding_attr),
2861 & encoding);
822a6a3d 2862 if (encoding == (Dwarf_Word) -1)
440f755a
JS
2863 {
2864 // clog << "bad type1 " << encoding << " diestr" << endl;
e5f690c7 2865 throw semantic_error (_F("unsupported type (mystery encoding %s for %s", lex_cast(encoding).c_str(),
f9bbd346 2866 dwarf_type_name(typedie).c_str()), e->tok);
440f755a
JS
2867 }
2868
2869 if (encoding == DW_ATE_float
2870 || encoding == DW_ATE_complex_float
2871 /* XXX || many others? */)
2872 {
2873 // clog << "bad type " << encoding << " diestr" << endl;
f9bbd346
LB
2874 throw semantic_error (_F("unsupported type (encoding %s) for %s", lex_cast(encoding).c_str(),
2875 dwarf_type_name(typedie).c_str()), e->tok);
440f755a
JS
2876 }
2877 }
5c7ef8e7
MW
2878 // Fallthrough. enumeration_types are always scalar.
2879 case DW_TAG_enumeration_type:
440f755a
JS
2880
2881 ty = pe_long;
2882 if (lvalue)
6ce303b8 2883 c_translate_store (pool, 1, 0 /* PR9768 */, vardie, typedie, tail,
0386bbcf 2884 "STAP_ARG_value");
440f755a 2885 else
6ce303b8 2886 c_translate_fetch (pool, 1, 0 /* PR9768 */, vardie, typedie, tail,
0386bbcf 2887 "STAP_RETVALUE");
440f755a
JS
2888 break;
2889
2890 case DW_TAG_array_type:
2891 case DW_TAG_pointer_type:
9c119951
JS
2892 case DW_TAG_reference_type:
2893 case DW_TAG_rvalue_reference_type:
440f755a 2894
440f755a
JS
2895 if (lvalue)
2896 {
2897 ty = pe_long;
2898 if (typetag == DW_TAG_array_type)
f9bbd346 2899 throw semantic_error (_("cannot write to array address"), e->tok);
9c119951
JS
2900 if (typetag == DW_TAG_reference_type ||
2901 typetag == DW_TAG_rvalue_reference_type)
f9bbd346 2902 throw semantic_error (_("cannot write to reference"), e->tok);
440f755a
JS
2903 assert (typetag == DW_TAG_pointer_type);
2904 c_translate_pointer_store (pool, 1, 0 /* PR9768 */, typedie, tail,
0386bbcf 2905 "STAP_ARG_value");
440f755a
JS
2906 }
2907 else
2908 {
2909 // We have the pointer: cast it to an integral type via &(*(...))
2910
2911 // NB: per bug #1187, at one point char*-like types were
2912 // automagically converted here to systemtap string values.
2913 // For several reasons, this was taken back out, leaving
2914 // pointer-to-string "conversion" (copying) to tapset functions.
2915
2916 ty = pe_long;
2917 if (typetag == DW_TAG_array_type)
2918 c_translate_array (pool, 1, 0 /* PR9768 */, typedie, tail, NULL, 0);
2919 else
2920 c_translate_pointer (pool, 1, 0 /* PR9768 */, typedie, tail);
6ce303b8 2921 c_translate_addressof (pool, 1, 0 /* PR9768 */, NULL, NULL, tail,
0386bbcf 2922 "STAP_RETVALUE");
440f755a 2923 }
440f755a
JS
2924 break;
2925 }
2926}
2927
2928
2929string
2930dwflpp::express_as_string (string prelude,
2931 string postlude,
2932 struct location *head)
2933{
e7899657
FCE
2934 size_t bufsz = 0;
2935 char *buf = 0; // NB: it would leak to pre-allocate a buffer here
440f755a
JS
2936 FILE *memstream = open_memstream (&buf, &bufsz);
2937 assert(memstream);
2938
2939 fprintf(memstream, "{\n");
2940 fprintf(memstream, "%s", prelude.c_str());
ebaa9618 2941
85dfc5c8
RM
2942 unsigned int stack_depth;
2943 bool deref = c_emit_location (memstream, head, 1, &stack_depth);
ebaa9618
JS
2944
2945 // Ensure that DWARF keeps loc2c to a "reasonable" stack size
2946 // 32 intptr_t leads to max 256 bytes on the stack
2947 if (stack_depth > 32)
2948 throw semantic_error("oversized DWARF stack");
2949
440f755a
JS
2950 fprintf(memstream, "%s", postlude.c_str());
2951 fprintf(memstream, " goto out;\n");
2952
2953 // dummy use of deref_fault label, to disable warning if deref() not used
2954 fprintf(memstream, "if (0) goto deref_fault;\n");
2955
2956 // XXX: deref flag not reliable; emit fault label unconditionally
2957 (void) deref;
2958 fprintf(memstream,
2959 "deref_fault:\n"
2960 " goto out;\n");
2961 fprintf(memstream, "}\n");
2962
2963 fclose (memstream);
2964 string result(buf);
2965 free (buf);
2966 return result;
2967}
2968
228af5c4
MW
2969Dwarf_Addr
2970dwflpp::vardie_from_symtable (Dwarf_Die *vardie, Dwarf_Addr *addr)
2971{
f450a7e3 2972 const char *name = dwarf_linkage_name (vardie) ?: dwarf_diename (vardie);
b0490786 2973
228af5c4 2974 if (sess.verbose > 2)
f9bbd346 2975 clog << _F("finding symtable address for %s\n", name);
228af5c4
MW
2976
2977 *addr = 0;
2978 int syms = dwfl_module_getsymtab (module);
f9bbd346 2979 dwfl_assert (_("Getting symbols"), syms >= 0);
228af5c4
MW
2980
2981 for (int i = 0; *addr == 0 && i < syms; i++)
2982 {
2983 GElf_Sym sym;
2984 GElf_Word shndxp;
2985 const char *symname = dwfl_module_getsym(module, i, &sym, &shndxp);
2986 if (symname
2987 && ! strcmp (name, symname)
2988 && sym.st_shndx != SHN_UNDEF
d124d4de
MW
2989 && (GELF_ST_TYPE (sym.st_info) == STT_NOTYPE // PR13284
2990 || GELF_ST_TYPE (sym.st_info) == STT_OBJECT))
228af5c4
MW
2991 *addr = sym.st_value;
2992 }
2993
2d7232ca
MW
2994 // Don't relocate for the kernel, or kernel modules we handle those
2995 // specially in emit_address.
2996 if (dwfl_module_relocations (module) == 1 && module_name != TOK_KERNEL)
2997 dwfl_module_relocate_address (module, addr);
2998
228af5c4 2999 if (sess.verbose > 2)
2a97f50b 3000 clog << _F("found %s @%#" PRIx64 "\n", name, *addr);
228af5c4
MW
3001
3002 return *addr;
3003}
440f755a
JS
3004
3005string
729455a7 3006dwflpp::literal_stmt_for_local (vector<Dwarf_Die>& scopes,
440f755a
JS
3007 Dwarf_Addr pc,
3008 string const & local,
3009 const target_symbol *e,
3010 bool lvalue,
3011 exp_type & ty)
3012{
3013 Dwarf_Die vardie;
3014 Dwarf_Attribute fb_attr_mem, *fb_attr = NULL;
3015
729455a7 3016 fb_attr = find_variable_and_frame_base (scopes, pc, local, e,
440f755a
JS
3017 &vardie, &fb_attr_mem);
3018
3019 if (sess.verbose>2)
3d9381fc 3020 {
bd1fcbad 3021 if (pc)
3d9381fc
MW
3022 clog << _F("finding location for local '%s' near address %#" PRIx64
3023 ", module bias %#" PRIx64 "\n", local.c_str(), pc,
3024 module_bias);
3025 else
3026 clog << _F("finding location for global '%s' in CU '%s'\n",
bd1fcbad 3027 local.c_str(), cu_name().c_str());
3d9381fc
MW
3028 }
3029
440f755a 3030
228af5c4
MW
3031#define obstack_chunk_alloc malloc
3032#define obstack_chunk_free free
3033
3034 struct obstack pool;
3035 obstack_init (&pool);
3036 struct location *tail = NULL;
3037
3038 /* Given $foo->bar->baz[NN], translate the location of foo. */
3039
3040 struct location *head;
3041
440f755a 3042 Dwarf_Attribute attr_mem;
03ba05b6
MW
3043 if (dwarf_attr_integrate (&vardie, DW_AT_const_value, &attr_mem) == NULL
3044 && dwarf_attr_integrate (&vardie, DW_AT_location, &attr_mem) == NULL)
440f755a 3045 {
228af5c4 3046 Dwarf_Op addr_loc;
e9483a80 3047 memset(&addr_loc, 0, sizeof(Dwarf_Op));
228af5c4
MW
3048 addr_loc.atom = DW_OP_addr;
3049 // If it is an external variable try the symbol table. PR10622.
3050 if (dwarf_attr_integrate (&vardie, DW_AT_external, &attr_mem) != NULL
3051 && vardie_from_symtable (&vardie, &addr_loc.number) != 0)
3052 {
3053 head = c_translate_location (&pool, &loc2c_error, this,
3054 &loc2c_emit_address,
3055 1, 0, pc,
3056 NULL, &addr_loc, 1, &tail, NULL, NULL);
3057 }
3058 else
4c5d9906 3059 throw semantic_error (_F("failed to retrieve location attribute for '%s' [man error::dwarf] (dieoffset: %s)",
f9bbd346 3060 local.c_str(), lex_cast_hex(dwarf_dieoffset(&vardie)).c_str()), e->tok);
440f755a 3061 }
228af5c4 3062 else
00730da1 3063 head = translate_location (&pool, &attr_mem, &vardie, pc, fb_attr, &tail, e);
440f755a 3064
6ce303b8
JS
3065 /* Translate the ->bar->baz[NN] parts. */
3066
3067 Dwarf_Die typedie;
3068 if (dwarf_attr_die (&vardie, DW_AT_type, &typedie) == NULL)
4c5d9906 3069 throw semantic_error(_F("failed to retrieve type attribute for '%s' [man error::dwarf] (dieoffset: %s)", local.c_str(), lex_cast_hex(dwarf_dieoffset(&vardie)).c_str()), e->tok);
440f755a 3070
6ce303b8 3071 translate_components (&pool, &tail, pc, e, &vardie, &typedie);
440f755a
JS
3072
3073 /* Translate the assignment part, either
3074 x = $foo->bar->baz[NN]
3075 or
3076 $foo->bar->baz[NN] = x
3077 */
3078
3079 string prelude, postlude;
3080 translate_final_fetch_or_store (&pool, &tail, module_bias,
6ce303b8 3081 &vardie, &typedie, lvalue, e,
440f755a
JS
3082 prelude, postlude, ty);
3083
3084 /* Write the translation to a string. */
e7899657
FCE
3085 string result = express_as_string(prelude, postlude, head);
3086 obstack_free (&pool, 0);
3087 return result;
440f755a
JS
3088}
3089
5f36109e
JS
3090Dwarf_Die*
3091dwflpp::type_die_for_local (vector<Dwarf_Die>& scopes,
3092 Dwarf_Addr pc,
3093 string const & local,
3094 const target_symbol *e,
3095 Dwarf_Die *typedie)
3096{
3097 Dwarf_Die vardie;
3098 Dwarf_Attribute attr_mem;
3099
3100 find_variable_and_frame_base (scopes, pc, local, e, &vardie, &attr_mem);
3101
3102 if (dwarf_attr_die (&vardie, DW_AT_type, typedie) == NULL)
4c5d9906 3103 throw semantic_error(_F("failed to retrieve type attribute for '%s' [man error::dwarf]", local.c_str()), e->tok);
5f36109e
JS
3104
3105 translate_components (NULL, NULL, pc, e, &vardie, typedie);
3106 return typedie;
3107}
3108
440f755a
JS
3109
3110string
3111dwflpp::literal_stmt_for_return (Dwarf_Die *scope_die,
3112 Dwarf_Addr pc,
3113 const target_symbol *e,
3114 bool lvalue,
3115 exp_type & ty)
3116{
3117 if (sess.verbose>2)
f9bbd346
LB
3118 clog << _F("literal_stmt_for_return: finding return value for %s (%s)\n",
3119 (dwarf_diename(scope_die) ?: "<unknown>"), (dwarf_diename(cu) ?: "<unknown>"));
440f755a
JS
3120
3121 struct obstack pool;
3122 obstack_init (&pool);
3123 struct location *tail = NULL;
3124
3125 /* Given $return->bar->baz[NN], translate the location of return. */
3126 const Dwarf_Op *locops;
3127 int nlocops = dwfl_module_return_value_location (module, scope_die,
3128 &locops);
3129 if (nlocops < 0)
3130 {
4c5d9906 3131 throw semantic_error(_F("failed to retrieve return value location for %s [man error::dwarf] (%s)",
f9bbd346
LB
3132 (dwarf_diename(scope_die) ?: "<unknown>"),
3133 (dwarf_diename(cu) ?: "<unknown>")), e->tok);
440f755a
JS
3134 }
3135 // the function has no return value (e.g. "void" in C)
3136 else if (nlocops == 0)
3137 {
f9bbd346
LB
3138 throw semantic_error(_F("function %s (%s) has no return value",
3139 (dwarf_diename(scope_die) ?: "<unknown>"),
3140 (dwarf_diename(cu) ?: "<unknown>")), e->tok);
440f755a
JS
3141 }
3142
3143 struct location *head = c_translate_location (&pool, &loc2c_error, this,
3144 &loc2c_emit_address,
3145 1, 0 /* PR9768 */,
24c7957b 3146 pc, NULL, locops, nlocops,
00b01a99 3147 &tail, NULL, NULL);
440f755a
JS
3148
3149 /* Translate the ->bar->baz[NN] parts. */
3150
6ce303b8
JS
3151 Dwarf_Die vardie = *scope_die, typedie;
3152 if (dwarf_attr_die (&vardie, DW_AT_type, &typedie) == NULL)
4c5d9906 3153 throw semantic_error(_F("failed to retrieve return value type attribute for %s [man error::dwarf] (%s)",
f9bbd346
LB
3154 (dwarf_diename(&vardie) ?: "<unknown>"),
3155 (dwarf_diename(cu) ?: "<unknown>")), e->tok);
440f755a 3156
6ce303b8 3157 translate_components (&pool, &tail, pc, e, &vardie, &typedie);
440f755a
JS
3158
3159 /* Translate the assignment part, either
3160 x = $return->bar->baz[NN]
3161 or
3162 $return->bar->baz[NN] = x
3163 */
3164
3165 string prelude, postlude;
3166 translate_final_fetch_or_store (&pool, &tail, module_bias,
6ce303b8 3167 &vardie, &typedie, lvalue, e,
440f755a
JS
3168 prelude, postlude, ty);
3169
3170 /* Write the translation to a string. */
e7899657
FCE
3171 string result = express_as_string(prelude, postlude, head);
3172 obstack_free (&pool, 0);
3173 return result;
440f755a
JS
3174}
3175
5f36109e
JS
3176Dwarf_Die*
3177dwflpp::type_die_for_return (Dwarf_Die *scope_die,
3178 Dwarf_Addr pc,
3179 const target_symbol *e,
3180 Dwarf_Die *typedie)
3181{
3182 Dwarf_Die vardie = *scope_die;
3183 if (dwarf_attr_die (&vardie, DW_AT_type, typedie) == NULL)
4c5d9906 3184 throw semantic_error(_F("failed to retrieve return value type attribute for %s [man error::dwarf] (%s)",
f9bbd346
LB
3185 (dwarf_diename(&vardie) ?: "<unknown>"),
3186 (dwarf_diename(cu) ?: "<unknown>")), e->tok);
5f36109e
JS
3187
3188 translate_components (NULL, NULL, pc, e, &vardie, typedie);
3189 return typedie;
3190}
3191
440f755a
JS
3192
3193string
6ce303b8 3194dwflpp::literal_stmt_for_pointer (Dwarf_Die *start_typedie,
440f755a
JS
3195 const target_symbol *e,
3196 bool lvalue,
3197 exp_type & ty)
3198{
3199 if (sess.verbose>2)
f9bbd346
LB
3200 clog << _F("literal_stmt_for_pointer: finding value for %s (%s)\n",
3201 dwarf_type_name(start_typedie).c_str(), (dwarf_diename(cu) ?: "<unknown>"));
440f755a
JS
3202
3203 struct obstack pool;
3204 obstack_init (&pool);
3205 struct location *head = c_translate_argument (&pool, &loc2c_error, this,
3206 &loc2c_emit_address,
0386bbcf 3207 1, "STAP_ARG_pointer");
440f755a
JS
3208 struct location *tail = head;
3209
3210 /* Translate the ->bar->baz[NN] parts. */
3211
f3b5366d 3212 unsigned first = 0;
6ce303b8 3213 Dwarf_Die typedie = *start_typedie, vardie = typedie;
f3b5366d 3214
0386bbcf
SM
3215 /* As a special case when typedie is not an array or pointer, we can
3216 * allow array indexing on STAP_ARG_pointer instead (since we do
3217 * know the pointee type and can determine its size). PR11556. */
f3b5366d
JS
3218 const target_symbol::component* c =
3219 e->components.empty() ? NULL : &e->components[0];
3220 if (c && (c->type == target_symbol::comp_literal_array_index ||
3221 c->type == target_symbol::comp_expression_array_index))
3222 {
3223 resolve_unqualified_inner_typedie (&typedie, &typedie, e);
3224 int typetag = dwarf_tag (&typedie);
3225 if (typetag != DW_TAG_pointer_type &&
3226 typetag != DW_TAG_array_type)
3227 {
3228 if (c->type == target_symbol::comp_literal_array_index)
3229 c_translate_array_pointer (&pool, 1, &typedie, &tail, NULL, c->num_index);
3230 else
0386bbcf 3231 c_translate_array_pointer (&pool, 1, &typedie, &tail, "STAP_ARG_index0", 0);
f3b5366d
JS
3232 ++first;
3233 }
3234 }
3235
3236 /* Now translate the rest normally. */
3237
3238 translate_components (&pool, &tail, 0, e, &vardie, &typedie, first);
440f755a
JS
3239
3240 /* Translate the assignment part, either
0386bbcf 3241 x = (STAP_ARG_pointer)->bar->baz[NN]
440f755a 3242 or
0386bbcf 3243 (STAP_ARG_pointer)->bar->baz[NN] = x
440f755a
JS
3244 */
3245
3246 string prelude, postlude;
3247 translate_final_fetch_or_store (&pool, &tail, module_bias,
6ce303b8 3248 &vardie, &typedie, lvalue, e,
440f755a
JS
3249 prelude, postlude, ty);
3250
3251 /* Write the translation to a string. */
e7899657
FCE
3252 string result = express_as_string(prelude, postlude, head);
3253 obstack_free (&pool, 0);
3254 return result;
440f755a
JS
3255}
3256
5f36109e
JS
3257Dwarf_Die*
3258dwflpp::type_die_for_pointer (Dwarf_Die *start_typedie,
3259 const target_symbol *e,
3260 Dwarf_Die *typedie)
3261{
3262 unsigned first = 0;
3263 *typedie = *start_typedie;
3264 Dwarf_Die vardie = *typedie;
3265
3266 /* Handle the same PR11556 case as above. */
3267 const target_symbol::component* c =
3268 e->components.empty() ? NULL : &e->components[0];
3269 if (c && (c->type == target_symbol::comp_literal_array_index ||
3270 c->type == target_symbol::comp_expression_array_index))
3271 {
3272 resolve_unqualified_inner_typedie (typedie, typedie, e);
3273 int typetag = dwarf_tag (typedie);
3274 if (typetag != DW_TAG_pointer_type &&
3275 typetag != DW_TAG_array_type)
3276 ++first;
3277 }
3278
3279 translate_components (NULL, NULL, 0, e, &vardie, typedie, first);
3280 return typedie;
3281}
3282
440f755a 3283
27646582
JS
3284static bool
3285in_kprobes_function(systemtap_session& sess, Dwarf_Addr addr)
3286{
3287 if (sess.sym_kprobes_text_start != 0 && sess.sym_kprobes_text_end != 0)
3288 {
3289 // If the probe point address is anywhere in the __kprobes
3290 // address range, we can't use this probe point.
3291 if (addr >= sess.sym_kprobes_text_start && addr < sess.sym_kprobes_text_end)
3292 return true;
3293 }
3294 return false;
3295}
3296
3297
3298bool
3299dwflpp::blacklisted_p(const string& funcname,
3300 const string& filename,
3301 int,
3302 const string& module,
27646582
JS
3303 Dwarf_Addr addr,
3304 bool has_return)
3305{
3306 if (!blacklist_enabled)
3307 return false; // no blacklist for userspace
3308
6ac012fc
FCE
3309 bool blacklisted = false;
3310
3311 // check against section blacklist
789448a3 3312 string section = get_blacklist_section(addr);
ac08441a
FCE
3313 // PR6503: modules don't need special init/exit treatment
3314 if (module == TOK_KERNEL && !regexec (&blacklist_section, section.c_str(), 0, NULL, 0))
27646582 3315 {
6ac012fc 3316 blacklisted = true;
27646582 3317 if (sess.verbose>1)
6ac012fc 3318 clog << _(" init/exit");
27646582
JS
3319 }
3320
3321 // Check for function marked '__kprobes'.
3322 if (module == TOK_KERNEL && in_kprobes_function(sess, addr))
3323 {
6ac012fc 3324 blacklisted = true;
27646582 3325 if (sess.verbose>1)
6ac012fc 3326 clog << _(" __kprobes");
27646582
JS
3327 }
3328
6ac012fc 3329 // Check probe point against file/function blacklists.
27646582
JS
3330 int goodfn = regexec (&blacklist_func, funcname.c_str(), 0, NULL, 0);
3331 if (has_return)
3332 goodfn = goodfn && regexec (&blacklist_func_ret, funcname.c_str(), 0, NULL, 0);
3333 int goodfile = regexec (&blacklist_file, filename.c_str(), 0, NULL, 0);
3334
3335 if (! (goodfn && goodfile))
3336 {
6ac012fc
FCE
3337 blacklisted = true;
3338 if (sess.verbose>1)
3339 clog << _(" file/function blacklist");
27646582
JS
3340 }
3341
6ac012fc
FCE
3342 if (sess.guru_mode && blacklisted)
3343 {
3344 blacklisted = false;
3345 if (sess.verbose>1)
3346 clog << _(" - not skipped (guru mode enabled)");
3347 }
3348
3349 if (blacklisted && sess.verbose>1)
3350 clog << _(" - skipped");
3351
27646582 3352 // This probe point is not blacklisted.
6ac012fc 3353 return blacklisted;
27646582
JS
3354}
3355
3356
3357void
3358dwflpp::build_blacklist()
3359{
3360 // We build up the regexps in these strings
3361
3362 // Add ^ anchors at the front; $ will be added just before regcomp.
3363
3364 string blfn = "^(";
3365 string blfn_ret = "^(";
3366 string blfile = "^(";
178ac3f6
JS
3367 string blsection = "^(";
3368
3369 blsection += "\\.init\\."; // first alternative, no "|"
3370 blsection += "|\\.exit\\.";
3371 blsection += "|\\.devinit\\.";
3372 blsection += "|\\.devexit\\.";
3373 blsection += "|\\.cpuinit\\.";
3374 blsection += "|\\.cpuexit\\.";
3375 blsection += "|\\.meminit\\.";
3376 blsection += "|\\.memexit\\.";
27646582 3377
44a7e76a
MW
3378 /* NOTE all include/asm .h blfile patterns might need "full path"
3379 so prefix those with '.*' - see PR13108 and PR13112. */
b969d16b
JS
3380 blfile += "kernel/kprobes\\.c"; // first alternative, no "|"
3381 blfile += "|arch/.*/kernel/kprobes\\.c";
44a7e76a 3382 blfile += "|.*/include/asm/io\\.h";
4a507da2 3383 blfile += "|.*/include/asm/io_64\\.h";
44a7e76a 3384 blfile += "|.*/include/asm/bitops\\.h";
b969d16b 3385 blfile += "|drivers/ide/ide-iops\\.c";
1b438943
MW
3386 // paravirt ops
3387 blfile += "|arch/.*/kernel/paravirt\\.c";
4a507da2 3388 blfile += "|.*/include/asm/paravirt\\.h";
27646582
JS
3389
3390 // XXX: it would be nice if these blacklisted functions were pulled
3391 // in dynamically, instead of being statically defined here.
3392 // Perhaps it could be populated from script files. A "noprobe
3393 // kernel.function("...")" construct might do the trick.
3394
3395 // Most of these are marked __kprobes in newer kernels. We list
3396 // them here (anyway) so the translator can block them on older
3397 // kernels that don't have the __kprobes function decorator. This
3398 // also allows detection of problems at translate- rather than
3399 // run-time.
3400
3401 blfn += "atomic_notifier_call_chain"; // first blfn; no "|"
3402 blfn += "|default_do_nmi";
3403 blfn += "|__die";
3404 blfn += "|die_nmi";
3405 blfn += "|do_debug";
3406 blfn += "|do_general_protection";
3407 blfn += "|do_int3";
3408 blfn += "|do_IRQ";
3409 blfn += "|do_page_fault";
3410 blfn += "|do_sparc64_fault";
3411 blfn += "|do_trap";
3412 blfn += "|dummy_nmi_callback";
3413 blfn += "|flush_icache_range";
3414 blfn += "|ia64_bad_break";
3415 blfn += "|ia64_do_page_fault";
3416 blfn += "|ia64_fault";
3417 blfn += "|io_check_error";
3418 blfn += "|mem_parity_error";
3419 blfn += "|nmi_watchdog_tick";
3420 blfn += "|notifier_call_chain";
3421 blfn += "|oops_begin";
3422 blfn += "|oops_end";
3423 blfn += "|program_check_exception";
3424 blfn += "|single_step_exception";
3425 blfn += "|sync_regs";
3426 blfn += "|unhandled_fault";
3427 blfn += "|unknown_nmi_error";
48aad766
FCE
3428 blfn += "|xen_[gs]et_debugreg";
3429 blfn += "|xen_irq_.*";
3430 blfn += "|xen_.*_fl_direct.*";
10d96538
TJL
3431 blfn += "|check_events";
3432 blfn += "|xen_adjust_exception_frame";
48aad766
FCE
3433 blfn += "|xen_iret.*";
3434 blfn += "|xen_sysret64.*";
3435 blfn += "|test_ti_thread_flag.*";
10d96538
TJL
3436 blfn += "|inat_get_opcode_attribute";
3437 blfn += "|system_call_after_swapgs";
5db0d1ab
TJL
3438 blfn += "|HYPERVISOR_[gs]et_debugreg";
3439 blfn += "|HYPERVISOR_event_channel_op";
3440 blfn += "|hash_64";
3441 blfn += "|hash_ptr";
3442 blfn += "|native_set_pte";
27646582
JS
3443
3444 // Lots of locks
65d79153
MW
3445 blfn += "|.*raw_.*_lock.*";
3446 blfn += "|.*raw_.*_unlock.*";
3447 blfn += "|.*raw_.*_trylock.*";
3448 blfn += "|.*read_lock.*";
3449 blfn += "|.*read_unlock.*";
3450 blfn += "|.*read_trylock.*";
3451 blfn += "|.*write_lock.*";
3452 blfn += "|.*write_unlock.*";
3453 blfn += "|.*write_trylock.*";
3454 blfn += "|.*write_seqlock.*";
3455 blfn += "|.*write_sequnlock.*";
3456 blfn += "|.*spin_lock.*";
3457 blfn += "|.*spin_unlock.*";
3458 blfn += "|.*spin_trylock.*";
3459 blfn += "|.*spin_is_locked.*";
3460 blfn += "|rwsem_.*lock.*";
27646582
JS
3461 blfn += "|.*mutex_.*lock.*";
3462 blfn += "|raw_.*";
27646582
JS
3463
3464 // atomic functions
3465 blfn += "|atomic_.*";
3466 blfn += "|atomic64_.*";
3467
3468 // few other problematic cases
3469 blfn += "|get_bh";
3470 blfn += "|put_bh";
3471
3472 // Experimental
3473 blfn += "|.*apic.*|.*APIC.*";
3474 blfn += "|.*softirq.*";
3475 blfn += "|.*IRQ.*";
3476 blfn += "|.*_intr.*";
3477 blfn += "|__delay";
3478 blfn += "|.*kernel_text.*";
3479 blfn += "|get_current";
3480 blfn += "|current_.*";
3481 blfn += "|.*exception_tables.*";
3482 blfn += "|.*setup_rt_frame.*";
3483
3484 // PR 5759, CONFIG_PREEMPT kernels
3485 blfn += "|.*preempt_count.*";
3486 blfn += "|preempt_schedule";
3487
3488 // These functions don't return, so return probes would never be recovered
3489 blfn_ret += "do_exit"; // no "|"
3490 blfn_ret += "|sys_exit";
3491 blfn_ret += "|sys_exit_group";
3492
3493 // __switch_to changes "current" on x86_64 and i686, so return probes
3494 // would cause kernel panic, and it is marked as "__kprobes" on x86_64
3495 if (sess.architecture == "x86_64")
3496 blfn += "|__switch_to";
3497 if (sess.architecture == "i686")
3498 blfn_ret += "|__switch_to";
3499
08ee70c3
FCE
3500 // RHEL6 pre-beta 2.6.32-19.el6
3501 blfn += "|special_mapping_.*";
2fd5495a
FCE
3502 blfn += "|.*_pte_.*"; // or "|smaps_pte_range";
3503 blfile += "|fs/seq_file\\.c";
08ee70c3 3504
27646582
JS
3505 blfn += ")$";
3506 blfn_ret += ")$";
3507 blfile += ")$";
178ac3f6 3508 blsection += ")"; // NB: no $, sections match just the beginning
27646582
JS
3509
3510 if (sess.verbose > 2)
3511 {
f9bbd346 3512 clog << _("blacklist regexps:") << endl;
27646582
JS
3513 clog << "blfn: " << blfn << endl;
3514 clog << "blfn_ret: " << blfn_ret << endl;
3515 clog << "blfile: " << blfile << endl;
178ac3f6 3516 clog << "blsection: " << blsection << endl;
27646582
JS
3517 }
3518
3519 int rc = regcomp (& blacklist_func, blfn.c_str(), REG_NOSUB|REG_EXTENDED);
f9bbd346 3520 if (rc) throw semantic_error (_("blacklist_func regcomp failed"));
27646582 3521 rc = regcomp (& blacklist_func_ret, blfn_ret.c_str(), REG_NOSUB|REG_EXTENDED);
f9bbd346 3522 if (rc) throw semantic_error (_("blacklist_func_ret regcomp failed"));
27646582 3523 rc = regcomp (& blacklist_file, blfile.c_str(), REG_NOSUB|REG_EXTENDED);
f9bbd346 3524 if (rc) throw semantic_error (_("blacklist_file regcomp failed"));
178ac3f6 3525 rc = regcomp (& blacklist_section, blsection.c_str(), REG_NOSUB|REG_EXTENDED);
f9bbd346 3526 if (rc) throw semantic_error (_("blacklist_section regcomp failed"));
27646582
JS
3527
3528 blacklist_enabled = true;
3529}
3530
3531
3532string
3533dwflpp::get_blacklist_section(Dwarf_Addr addr)
3534{
3535 string blacklist_section;
3536 Dwarf_Addr bias;
3537 // We prefer dwfl_module_getdwarf to dwfl_module_getelf here,
3538 // because dwfl_module_getelf can force costly section relocations
3539 // we don't really need, while either will do for this purpose.
3540 Elf* elf = (dwarf_getelf (dwfl_module_getdwarf (module, &bias))
3541 ?: dwfl_module_getelf (module, &bias));
3542
3543 Dwarf_Addr offset = addr - bias;
3544 if (elf)
3545 {
3546 Elf_Scn* scn = 0;
3547 size_t shstrndx;
fcc30d6d 3548 dwfl_assert ("getshdrstrndx", elf_getshdrstrndx (elf, &shstrndx));
27646582
JS
3549 while ((scn = elf_nextscn (elf, scn)) != NULL)
3550 {
3551 GElf_Shdr shdr_mem;
3552 GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
3553 if (! shdr)
3554 continue; // XXX error?
3555
3556 if (!(shdr->sh_flags & SHF_ALLOC))
3557 continue;
3558
3559 GElf_Addr start = shdr->sh_addr;
3560 GElf_Addr end = start + shdr->sh_size;
3561 if (! (offset >= start && offset < end))
3562 continue;
3563
3564 blacklist_section = elf_strptr (elf, shstrndx, shdr->sh_name);
3565 break;
3566 }
3567 }
3568 return blacklist_section;
3569}
3570
3571
fea74777
SC
3572/* Find the section named 'section_name' in the current module
3573 * returning the section header using 'shdr_mem' */
3574
3575GElf_Shdr *
448a86b7 3576dwflpp::get_section(string section_name, GElf_Shdr *shdr_mem, Elf **elf_ret)
fea74777
SC
3577{
3578 GElf_Shdr *shdr = NULL;
3579 Elf* elf;
3580 Dwarf_Addr bias;
3581 size_t shstrndx;
3582
3583 // Explicitly look in the main elf file first.
3584 elf = dwfl_module_getelf (module, &bias);
3585 Elf_Scn *probe_scn = NULL;
3586
3587 dwfl_assert ("getshdrstrndx", elf_getshdrstrndx (elf, &shstrndx));
3588
3589 bool have_section = false;
3590
3591 while ((probe_scn = elf_nextscn (elf, probe_scn)))
3592 {
3593 shdr = gelf_getshdr (probe_scn, shdr_mem);
3594 assert (shdr != NULL);
3595
3596 if (elf_strptr (elf, shstrndx, shdr->sh_name) == section_name)
3597 {
3598 have_section = true;
3599 break;
3600 }
3601 }
3602
3603 // Older versions may put the section in the debuginfo dwarf file,
3604 // so check if it actually exists, if not take a look in the debuginfo file
3605 if (! have_section || (have_section && shdr->sh_type == SHT_NOBITS))
3606 {
3607 elf = dwarf_getelf (dwfl_module_getdwarf (module, &bias));
3608 if (! elf)
448a86b7 3609 return NULL;
fea74777
SC
3610 dwfl_assert ("getshdrstrndx", elf_getshdrstrndx (elf, &shstrndx));
3611 probe_scn = NULL;
3612 while ((probe_scn = elf_nextscn (elf, probe_scn)))
3613 {
3614 shdr = gelf_getshdr (probe_scn, shdr_mem);
3615 if (elf_strptr (elf, shstrndx, shdr->sh_name) == section_name)
3616 {
3617 have_section = true;
3618 break;
3619 }
3620 }
3621 }
3622
3623 if (!have_section)
3624 return NULL;
448a86b7
JS
3625
3626 if (elf_ret)
3627 *elf_ret = elf;
3628 return shdr;
fea74777
SC
3629}
3630
3631
27646582 3632Dwarf_Addr
789448a3 3633dwflpp::relocate_address(Dwarf_Addr dw_addr, string& reloc_section)
27646582 3634{
d2309c6c
MW
3635 // PR10273
3636 // libdw address, so adjust for bias gotten from dwfl_module_getdwarf
3637 Dwarf_Addr reloc_addr = dw_addr + module_bias;
27646582
JS
3638 if (!module)
3639 {
3640 assert(module_name == TOK_KERNEL);
3641 reloc_section = "";
27646582
JS
3642 }
3643 else if (dwfl_module_relocations (module) > 0)
3644 {
3645 // This is a relocatable module; libdwfl already knows its
3646 // sections, so we can relativize addr.
3647 int idx = dwfl_module_relocate_address (module, &reloc_addr);
3648 const char* r_s = dwfl_module_relocation_info (module, idx, NULL);
3649 if (r_s)
3650 reloc_section = r_s;
27646582
JS
3651
3652 if (reloc_section == "" && dwfl_module_relocations (module) == 1)
27646582 3653 reloc_section = ".dynamic";
27646582
JS
3654 }
3655 else
789448a3 3656 reloc_section = ".absolute";
27646582
JS
3657 return reloc_addr;
3658}
3659
88eaee9f
MW
3660/* Returns the call frame address operations for the given program counter
3661 * in the libdw address space.
3662 */
00b01a99
MW
3663Dwarf_Op *
3664dwflpp::get_cfa_ops (Dwarf_Addr pc)
3665{
3666 Dwarf_Op *cfa_ops = NULL;
3667
88eaee9f
MW
3668 if (sess.verbose > 2)
3669 clog << "get_cfa_ops @0x" << hex << pc << dec
3670 << ", module_start @0x" << hex << module_start << dec << endl;
3671
6a38401c 3672 // Try debug_frame first, then fall back on eh_frame.
87748e2b
MW
3673 size_t cfa_nops = 0;
3674 Dwarf_Addr bias = 0;
3675 Dwarf_Frame *frame = NULL;
00b01a99
MW
3676 Dwarf_CFI *cfi = dwfl_module_dwarf_cfi (module, &bias);
3677 if (cfi != NULL)
3678 {
88eaee9f
MW
3679 if (sess.verbose > 3)
3680 clog << "got dwarf cfi bias: 0x" << hex << bias << dec << endl;
87748e2b 3681 if (dwarf_cfi_addrframe (cfi, pc - bias, &frame) == 0)
97f529ab 3682 dwarf_frame_cfa (frame, &cfa_ops, &cfa_nops);
88eaee9f
MW
3683 else if (sess.verbose > 3)
3684 clog << "dwarf_cfi_addrframe failed: " << dwarf_errmsg(-1) << endl;
00b01a99 3685 }
88eaee9f
MW
3686 else if (sess.verbose > 3)
3687 clog << "dwfl_module_dwarf_cfi failed: " << dwfl_errmsg(-1) << endl;
3688
00b01a99
MW
3689 if (cfa_ops == NULL)
3690 {
3691 cfi = dwfl_module_eh_cfi (module, &bias);
3692 if (cfi != NULL)
3693 {
88eaee9f
MW
3694 if (sess.verbose > 3)
3695 clog << "got eh cfi bias: 0x" << hex << bias << dec << endl;
00b01a99 3696 Dwarf_Frame *frame = NULL;
87748e2b 3697 if (dwarf_cfi_addrframe (cfi, pc - bias, &frame) == 0)
97f529ab 3698 dwarf_frame_cfa (frame, &cfa_ops, &cfa_nops);
88eaee9f
MW
3699 else if (sess.verbose > 3)
3700 clog << "dwarf_cfi_addrframe failed: " << dwarf_errmsg(-1) << endl;
00b01a99 3701 }
88eaee9f
MW
3702 else if (sess.verbose > 3)
3703 clog << "dwfl_module_eh_cfi failed: " << dwfl_errmsg(-1) << endl;
3704
00b01a99 3705 }
00b01a99 3706
88eaee9f 3707 if (sess.verbose > 2)
87748e2b
MW
3708 {
3709 if (cfa_ops == NULL)
f9bbd346 3710 clog << _("not found cfa") << endl;
87748e2b
MW
3711 else
3712 {
3713 Dwarf_Addr frame_start, frame_end;
3714 bool frame_signalp;
3715 int info = dwarf_frame_info (frame, &frame_start, &frame_end,
3716 &frame_signalp);
2a97f50b 3717 clog << _F("found cfa, info: %d [start: %#" PRIx64 ", end: %#" PRIx64
f9bbd346 3718 ", nops: %zu", info, frame_start, frame_end, cfa_nops) << endl;
87748e2b
MW
3719 }
3720 }
88eaee9f 3721
00b01a99
MW
3722 return cfa_ops;
3723}
c8ad0687 3724
2eb99c62
CM
3725int
3726dwflpp::add_module_build_id_to_hash (Dwfl_Module *m,
3727 void **userdata __attribute__ ((unused)),
3728 const char *name,
3729 Dwarf_Addr base,
3730 void *arg)
3731{
3732 string modname = name;
3733 systemtap_session * s = (systemtap_session *)arg;
3734 if (pending_interrupts)
3735 return DWARF_CB_ABORT;
3736
3737 // Extract the build ID
3738 const unsigned char *bits;
3739 GElf_Addr vaddr;
3740 int bits_length = dwfl_module_build_id(m, &bits, &vaddr);
3741 if(bits_length > 0)
3742 {
3743 // Convert the binary bits to a hex string
3744 string hex = hex_dump(bits, bits_length);
3745
3746 // Store the build ID in the session
3747 s->build_ids.push_back(hex);
3748 }
3749
3750 return DWARF_CB_OK;
3751}
3752
45b02a36
FCE
3753
3754
3755// Perform PR15123 heuristic for given variable at given address.
3756// Return alternate pc address to do location-list lookup at, or 0 if
3757// inapplicable.
3758//
3759Dwarf_Addr
3760dwflpp::pr15123_retry_addr (Dwarf_Addr pc, Dwarf_Die* die)
3761{
3762 // For PR15123, we'd like to detect the situation where the
3763 // incoming PC may point to a couple-of-byte instruction
3764 // sequence that gcc emits for CFLAGS=-mfentry, and where
3765 // context variables are in fact available throughout, *but* due
3766 // to the bug, the dwarf debuginfo location-list only starts a
3767 // few instructions later. Prologue searching does not resolve
3768 // this as a line-record is in place at the -mfentry prologue.
3769 //
3770 // Detecting this is complicated because ...
3771 // - we only want to do this if -mfentry was actually used
3772 // - if <pc> points to the a function entry point
3773 // - if the architecture is familiar enough that we can have a
3774 // hard-coded constant to skip over the prologue.
3775 //
98df4dae
VB
3776 // Otherwise, we could give a false-positive - return corrupted
3777 // data.
3778 //
3779 // Use of -mfentry is detectable only if CFLAGS=-grecord-gcc-switches
3780 // was used. Without it, set the PR15123_ASSUME_MFENTRY environment
3781 // variable to override the -mfentry test.
45b02a36
FCE
3782
3783 if (getenv ("PR15123_DISABLE"))
3784 return 0;
3785
3786 Dwarf_Die cudie;
3787 Dwarf_Attribute cudie_producer;
3788 dwarf_diecu (die, &cudie, NULL, NULL);
3789 if (! dwarf_attr_integrate(&cudie, DW_AT_producer, &cudie_producer))
3790 return 0;
3791
98df4dae
VB
3792 if (!getenv ("PR15123_ASSUME_MFENTRY")) {
3793 const char* producer = dwarf_formstring(&cudie_producer);
3794 if (!producer)
3795 return 0;
3796 if (! strstr(producer, "-mfentry"))
3797 return 0;
3798 }
45b02a36
FCE
3799
3800 // Determine if this pc maps to the beginning of a
3801 // real function (not some inlined doppelganger. This
3802 // is made tricker by this->function may not be
3803 // pointing at the right DIE (say e.g. stap encountered
3804 // the inlined copy first, so was focus_on_function'd).
3805 vector<Dwarf_Die> scopes = getscopes(pc);
3806 if (scopes.size() == 0)
3807 return 0;
3808
3809 Dwarf_Die outer_function_die = scopes[0];
3810 Dwarf_Addr entrypc;
3811 die_entrypc(& outer_function_die, &entrypc);
3812 if (entrypc != pc) // (will fail on retry, so we won't loop more than once)
3813 return 0;
3814
3815 if (sess.architecture == "i386" ||
3816 sess.architecture == "x86_64") {
3817 /* pull the trigger */
3818 if (sess.verbose > 2)
3819 clog << _("retrying variable location-list lookup at address pc+5\n");
3820 return pc + 5;
3821 }
3822
3823 return 0;
3824}
3825
c5810d31
LB
3826bool
3827dwflpp::has_gnu_debugdata ()
3828{
3829 Dwarf_Addr load_addr;
3830 // Note we really want the actual elf file, not the dwarf .debug file.
3831 Elf* elf = dwfl_module_getelf (module, &load_addr);
3832 size_t shstrndx;
3833 assert (elf_getshdrstrndx (elf, &shstrndx) >= 0);
3834
3835 // Get the gnu_debugdata section header
3836 Elf_Scn *scn = NULL;
3837 GElf_Shdr *gnu_debugdata_shdr = NULL;
3838 GElf_Shdr gnu_debugdata_shdr_mem;
3839 while ((scn = elf_nextscn (elf, scn)))
3840 {
3841 gnu_debugdata_shdr = gelf_getshdr (scn, &gnu_debugdata_shdr_mem);
3842 assert (gnu_debugdata_shdr != NULL);
3843 if (strcmp (elf_strptr (elf, shstrndx, gnu_debugdata_shdr->sh_name), ".gnu_debugdata") == 0)
3844 return true;
3845 }
3846 return false;
3847}
3848
45b02a36 3849
440f755a 3850/* vim: set sw=2 ts=8 cino=>4,n-2,{2,^-2,t0,(0,u0,w1,M1 : */
This page took 0.5605 seconds and 5 git commands to generate.