Debian Codegraph @

src/symbols/dwarf/dwarf.hpp

raw
1 #ifndef DWARF_HPP
2 #define DWARF_HPP
3
4 #include <cpptrace/basic.hpp>
5 #include "utils/error.hpp"
6 #include "utils/microfmt.hpp"
7 #include "utils/utils.hpp"
8
9 #include <functional>
10 #include <type_traits>
11
12 #ifdef CPPTRACE_USE_NESTED_LIBDWARF_HEADER_PATH
13 #include <libdwarf/libdwarf.h>
14 #include <libdwarf/dwarf.h>
15 #else
16 #include <libdwarf.h>
17 #include <dwarf.h>
18 #endif
19
20 CPPTRACE_BEGIN_NAMESPACE
21 namespace detail {
22 namespace libdwarf {
23 static_assert(std::is_pointer<Dwarf_Die>::value, "Dwarf_Die not a pointer");
24 static_assert(std::is_pointer<Dwarf_Debug>::value, "Dwarf_Debug not a pointer");
25
26 using rangelist_entries = std::vector<std::pair<Dwarf_Addr, Dwarf_Addr>>;
27
28 [[noreturn]] inline void handle_dwarf_error(Dwarf_Debug dbg, Dwarf_Error error) {
29 Dwarf_Unsigned ev = dwarf_errno(error);
30 // dwarf_dealloc_error deallocates the message, attaching to msg is convenient
31 auto msg = raii_wrap(dwarf_errmsg(error), [dbg, error] (char*) { dwarf_dealloc_error(dbg, error); });
32 throw internal_error("dwarf error {} {}", ev, msg.get());
33 }
34
35 struct die_object {
36 Dwarf_Debug dbg = nullptr;
37 Dwarf_Die die = nullptr;
38
39 // Error handling helper
40 // For some reason R (*f)(Args..., void*)-style deduction isn't possible, seems like a bug in all compilers
41 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=56190
42 template<
43 typename... Args,
44 typename... Args2,
45 typename std::enable_if<
46 std::is_same<
47 decltype(
48 (void)std::declval<int(Args...)>()(std::forward<Args2>(std::declval<Args2>())..., nullptr)
49 ),
50 void
51 >::value,
52 int
53 >::type = 0
54 >
55 int wrap(int (*f)(Args...), Args2&&... args) const {
56 Dwarf_Error error = nullptr;
57 int ret = f(std::forward<Args2>(args)..., &error);
58 if(ret == DW_DLV_ERROR) {
59 handle_dwarf_error(dbg, error);
60 }
61 return ret;
62 }
63
64 die_object(Dwarf_Debug dbg, Dwarf_Die die) : dbg(dbg), die(die) {
65 ASSERT(dbg != nullptr);
66 }
67
68 ~die_object() {
69 release();
70 }
71
72 void release() {
73 if(die) {
74 dwarf_dealloc_die(exchange(die, nullptr));
75 }
76 }
77
78 die_object(const die_object&) = delete;
79
80 die_object& operator=(const die_object&) = delete;
81
82 // dbg doesn't strictly have to be st to null but it helps ensure attempts to use the die_object after this to
83 // segfault. A valid use otherwise would be moved_from.get_sibling() which would get the next CU.
84 die_object(die_object&& other) noexcept
85 : dbg(exchange(other.dbg, nullptr)), die(exchange(other.die, nullptr)) {}
86
87 die_object& operator=(die_object&& other) noexcept {
88 release();
89 dbg = exchange(other.dbg, nullptr);
90 die = exchange(other.die, nullptr);
91 return *this;
92 }
93
94 die_object clone() const {
95 Dwarf_Off global_offset = get_global_offset();
96 Dwarf_Bool is_info = dwarf_get_die_infotypes_flag(die);
97 Dwarf_Die die_copy = nullptr;
98 VERIFY(wrap(dwarf_offdie_b, dbg, global_offset, is_info, &die_copy) == DW_DLV_OK);
99 return {dbg, die_copy};
100 }
101
102 die_object get_child() const {
103 Dwarf_Die child = nullptr;
104 int ret = wrap(dwarf_child, die, &child);
105 if(ret == DW_DLV_OK) {
106 return die_object(dbg, child);
107 } else if(ret == DW_DLV_NO_ENTRY) {
108 return die_object(dbg, nullptr);
109 } else {
110 PANIC();
111 }
112 }
113
114 die_object get_sibling() const {
115 Dwarf_Die sibling = nullptr;
116 int ret = wrap(dwarf_siblingof_b, dbg, die, true, &sibling);
117 if(ret == DW_DLV_OK) {
118 return die_object(dbg, sibling);
119 } else if(ret == DW_DLV_NO_ENTRY) {
120 return die_object(dbg, nullptr);
121 } else {
122 PANIC();
123 }
124 }
125
126 operator bool() const {
127 return die != nullptr;
128 }
129
130 Dwarf_Die get() const {
131 return die;
132 }
133
134 std::string get_name() const {
135 char empty[] = "";
136 char* name = empty;
137 // Note: It's important to not free the string from this function.
138 int ret = wrap(dwarf_diename, die, &name);
139 std::string str;
140 if(ret != DW_DLV_NO_ENTRY) {
141 str = name;
142 }
143 return name;
144 }
145
146 optional<std::string> get_string_attribute(Dwarf_Half attr_num) const {
147 Dwarf_Attribute attr;
148 if(wrap(dwarf_attr, die, attr_num, &attr) == DW_DLV_OK) {
149 auto attwrapper = raii_wrap(attr, [] (Dwarf_Attribute attr) { dwarf_dealloc_attribute(attr); });
150 char* raw_str;
151 // Note: It's important to not free the string from this function.
152 // https://github.com/davea42/libdwarf-code/issues/279
153 VERIFY(wrap(dwarf_formstring, attr, &raw_str) == DW_DLV_OK);
154 std::string str = raw_str;
155 return str;
156 } else {
157 return nullopt;
158 }
159 }
160
161 optional<Dwarf_Unsigned> get_unsigned_attribute(Dwarf_Half attr_num) const {
162 Dwarf_Attribute attr;
163 if(wrap(dwarf_attr, die, attr_num, &attr) == DW_DLV_OK) {
164 auto attwrapper = raii_wrap(attr, [] (Dwarf_Attribute attr) { dwarf_dealloc_attribute(attr); });
165 // Dwarf_Half form = 0;
166 // VERIFY(wrap(dwarf_whatform, attr, &form) == DW_DLV_OK);
167 Dwarf_Unsigned val;
168 VERIFY(wrap(dwarf_formudata, attr, &val) == DW_DLV_OK);
169 return val;
170 } else {
171 return nullopt;
172 }
173 }
174
175 bool has_attr(Dwarf_Half attr_num) const {
176 Dwarf_Bool present = false;
177 VERIFY(wrap(dwarf_hasattr, die, attr_num, &present) == DW_DLV_OK);
178 return present;
179 }
180
181 Dwarf_Half get_tag() const {
182 Dwarf_Half tag = 0;
183 VERIFY(wrap(dwarf_tag, die, &tag) == DW_DLV_OK);
184 return tag;
185 }
186
187 const char* get_tag_name() const {
188 const char* tag_name;
189 if(dwarf_get_TAG_name(get_tag(), &tag_name) == DW_DLV_OK) {
190 return tag_name;
191 } else {
192 return "<unknown tag name>";
193 }
194 }
195
196 Dwarf_Off get_global_offset() const {
197 Dwarf_Off off;
198 VERIFY(wrap(dwarf_dieoffset, die, &off) == DW_DLV_OK);
199 return off;
200 }
201
202 die_object resolve_reference_attribute(Dwarf_Half attr_num) const {
203 Dwarf_Attribute attr;
204 VERIFY(dwarf_attr(die, attr_num, &attr, nullptr) == DW_DLV_OK);
205 auto wrapper = raii_wrap(attr, [] (Dwarf_Attribute attr) { dwarf_dealloc_attribute(attr); });
206 Dwarf_Half form = 0;
207 VERIFY(wrap(dwarf_whatform, attr, &form) == DW_DLV_OK);
208 switch(form) {
209 case DW_FORM_ref1:
210 case DW_FORM_ref2:
211 case DW_FORM_ref4:
212 case DW_FORM_ref8:
213 case DW_FORM_ref_udata:
214 {
215 Dwarf_Off off = 0;
216 Dwarf_Bool is_info = dwarf_get_die_infotypes_flag(die);
217 VERIFY(wrap(dwarf_formref, attr, &off, &is_info) == DW_DLV_OK);
218 Dwarf_Off global_offset = 0;
219 VERIFY(wrap(dwarf_convert_to_global_offset, attr, off, &global_offset) == DW_DLV_OK);
220 Dwarf_Die target = nullptr;
221 VERIFY(wrap(dwarf_offdie_b, dbg, global_offset, is_info, &target) == DW_DLV_OK);
222 return die_object(dbg, target);
223 }
224 case DW_FORM_ref_addr:
225 {
226 Dwarf_Off off;
227 VERIFY(wrap(dwarf_global_formref, attr, &off) == DW_DLV_OK);
228 int is_info = dwarf_get_die_infotypes_flag(die);
229 Dwarf_Die target = nullptr;
230 VERIFY(wrap(dwarf_offdie_b, dbg, off, is_info, &target) == DW_DLV_OK);
231 return die_object(dbg, target);
232 }
233 case DW_FORM_ref_sig8:
234 {
235 Dwarf_Sig8 signature;
236 VERIFY(wrap(dwarf_formsig8, attr, &signature) == DW_DLV_OK);
237 Dwarf_Die target = nullptr;
238 Dwarf_Bool targ_is_info = false;
239 VERIFY(wrap(dwarf_find_die_given_sig8, dbg, &signature, &target, &targ_is_info) == DW_DLV_OK);
240 return die_object(dbg, target);
241 }
242 default:
243 PANIC(microfmt::format("unknown form for attribute {} {}\n", attr_num, form));
244 }
245 }
246
247 Dwarf_Unsigned get_ranges_base_address(const die_object& cu_die) const {
248 // After libdwarf v0.11.0 this can use dwarf_get_ranges_baseaddress, however, in the interest of not
249 // requiring v0.11.0 just yet the logic is implemented here too.
250 // The base address is:
251 // - If the die has a rangelist, use the low_pc for that die
252 // - Otherwise use the low_pc from the CU if present
253 // - Otherwise 0
254 if(has_attr(DW_AT_ranges)) {
255 if(has_attr(DW_AT_low_pc)) {
256 Dwarf_Addr lowpc;
257 if(wrap(dwarf_lowpc, die, &lowpc) == DW_DLV_OK) {
258 return lowpc;
259 }
260 }
261 }
262 if(cu_die.has_attr(DW_AT_low_pc)) {
263 Dwarf_Addr lowpc;
264 if(wrap(dwarf_lowpc, cu_die.get(), &lowpc) == DW_DLV_OK) {
265 return lowpc;
266 }
267 }
268 return 0;
269 }
270
271 Dwarf_Unsigned get_ranges_offset(Dwarf_Attribute attr) const {
272 Dwarf_Unsigned off = 0;
273 Dwarf_Half form = 0;
274 VERIFY(wrap(dwarf_whatform, attr, &form) == DW_DLV_OK);
275 if (form == DW_FORM_rnglistx) {
276 VERIFY(wrap(dwarf_formudata, attr, &off) == DW_DLV_OK);
277 } else {
278 VERIFY(wrap(dwarf_global_formref, attr, &off) == DW_DLV_OK);
279 }
280 return off;
281 }
282
283 template<typename F>
284 // callback should return true to keep going
285 void dwarf5_ranges(F callback) const {
286 Dwarf_Attribute attr = nullptr;
287 if(wrap(dwarf_attr, die, DW_AT_ranges, &attr) != DW_DLV_OK) {
288 return;
289 }
290 auto attrwrapper = raii_wrap(attr, [] (Dwarf_Attribute attr) { dwarf_dealloc_attribute(attr); });
291 Dwarf_Unsigned offset = get_ranges_offset(attr);
292 Dwarf_Half form = 0;
293 VERIFY(wrap(dwarf_whatform, attr, &form) == DW_DLV_OK);
294 // get .debug_rnglists info
295 Dwarf_Rnglists_Head head = nullptr;
296 Dwarf_Unsigned rnglists_entries = 0;
297 Dwarf_Unsigned dw_global_offset_of_rle_set = 0;
298 int res = wrap(
299 dwarf_rnglists_get_rle_head,
300 attr,
301 form,
302 offset,
303 &head,
304 &rnglists_entries,
305 &dw_global_offset_of_rle_set
306 );
307 auto headwrapper = raii_wrap(head, [] (Dwarf_Rnglists_Head head) { dwarf_dealloc_rnglists_head(head); });
308 if(res == DW_DLV_NO_ENTRY) {
309 return;
310 }
311 VERIFY(res == DW_DLV_OK);
312 for(std::size_t i = 0 ; i < rnglists_entries; i++) {
313 unsigned entrylen = 0;
314 unsigned rle_value_out = 0;
315 Dwarf_Unsigned raw1 = 0;
316 Dwarf_Unsigned raw2 = 0;
317 Dwarf_Bool unavailable = 0;
318 Dwarf_Unsigned cooked1 = 0;
319 Dwarf_Unsigned cooked2 = 0;
320 res = wrap(
321 dwarf_get_rnglists_entry_fields_a,
322 head,
323 i,
324 &entrylen,
325 &rle_value_out,
326 &raw1,
327 &raw2,
328 &unavailable,
329 &cooked1,
330 &cooked2
331 );
332 if(res == DW_DLV_NO_ENTRY) {
333 continue;
334 }
335 VERIFY(res == DW_DLV_OK);
336 if(unavailable) {
337 continue;
338 }
339 switch(rle_value_out) {
340 // Following the same scheme from libdwarf-addr2line
341 case DW_RLE_end_of_list:
342 case DW_RLE_base_address:
343 case DW_RLE_base_addressx:
344 // Already handled
345 break;
346 case DW_RLE_offset_pair:
347 case DW_RLE_startx_endx:
348 case DW_RLE_start_end:
349 case DW_RLE_startx_length:
350 case DW_RLE_start_length:
351 if(!callback(cooked1, cooked2)) {
352 return;
353 }
354 break;
355 default:
356 PANIC("Something is wrong");
357 break;
358 }
359 }
360 }
361
362 template<typename F>
363 // callback should return true to keep going
364 void dwarf4_ranges(Dwarf_Addr baseaddr, F callback) const {
365 Dwarf_Attribute attr = nullptr;
366 if(wrap(dwarf_attr, die, DW_AT_ranges, &attr) != DW_DLV_OK) {
367 return;
368 }
369 auto attrwrapper = raii_wrap(attr, [] (Dwarf_Attribute attr) { dwarf_dealloc_attribute(attr); });
370 Dwarf_Unsigned offset;
371 if(wrap(dwarf_global_formref, attr, &offset) != DW_DLV_OK) {
372 return;
373 }
374 Dwarf_Addr baseaddr_original = baseaddr;
375 Dwarf_Ranges* ranges = nullptr;
376 Dwarf_Signed count = 0;
377 VERIFY(
378 wrap(
379 dwarf_get_ranges_b,
380 dbg,
381 offset,
382 die,
383 nullptr,
384 &ranges,
385 &count,
386 nullptr
387 ) == DW_DLV_OK
388 );
389 auto rangeswrapper = raii_wrap(
390 ranges,
391 [this, count] (Dwarf_Ranges* ranges) { dwarf_dealloc_ranges(dbg, ranges, count); }
392 );
393 for(int i = 0; i < count; i++) {
394 if(ranges[i].dwr_type == DW_RANGES_ENTRY) {
395 if(!callback(baseaddr + ranges[i].dwr_addr1, baseaddr + ranges[i].dwr_addr2)) {
396 return;
397 }
398 } else if(ranges[i].dwr_type == DW_RANGES_ADDRESS_SELECTION) {
399 baseaddr = ranges[i].dwr_addr2;
400 } else {
401 ASSERT(ranges[i].dwr_type == DW_RANGES_END);
402 baseaddr = baseaddr_original;
403 }
404 }
405 }
406
407 template<typename F>
408 // callback should return true to keep going
409 void dwarf_ranges(const die_object& cu_die, int version, F callback) const {
410 Dwarf_Addr lowpc;
411 if(wrap(dwarf_lowpc, die, &lowpc) == DW_DLV_OK) {
412 Dwarf_Addr highpc = 0;
413 enum Dwarf_Form_Class return_class;
414 if(wrap(dwarf_highpc_b, die, &highpc, nullptr, &return_class) == DW_DLV_OK) {
415 if(return_class == DW_FORM_CLASS_CONSTANT) {
416 highpc += lowpc;
417 }
418 if(!callback(lowpc, highpc)) {
419 return;
420 }
421 }
422 }
423 if(version >= 5) {
424 dwarf5_ranges(callback);
425 } else {
426 dwarf4_ranges(get_ranges_base_address(cu_die), callback);
427 }
428 }
429
430 rangelist_entries get_rangelist_entries(const die_object& cu_die, int version) const {
431 rangelist_entries vec;
432 dwarf_ranges(cu_die, version, [&vec] (Dwarf_Addr low, Dwarf_Addr high) {
433 // Simple coalescing optimization:
434 // Sometimes the range list entries are really continuous: [100, 200), [200, 300)
435 // Other times there's just one byte of separation [300, 399), [400, 500)
436 // Those are the main two cases I've observed.
437 // This will not catch all cases, presumably, as the range lists aren't sorted. But compilers/linkers
438 // seem to like to emit the ranges in sorted order.
439 if(!vec.empty() && low - vec.back().second <= 1) {
440 vec.back().second = high;
441 } else {
442 vec.push_back({low, high});
443 }
444 return true;
445 });
446 return vec;
447 }
448
449 Dwarf_Bool pc_in_die(const die_object& cu_die, int version, Dwarf_Addr pc) const {
450 bool found = false;
451 dwarf_ranges(cu_die, version, [&found, pc] (Dwarf_Addr low, Dwarf_Addr high) {
452 if(pc >= low && pc < high) {
453 found = true;
454 return false;
455 }
456 return true;
457 });
458 return found;
459 }
460
461 void print() const {
462 std::fprintf(
463 stderr,
464 "%08llx %s %s\n",
465 to_ull(get_global_offset()),
466 get_tag_name(),
467 get_name().c_str()
468 );
469 }
470 };
471
472 // walk die list, callback is called on each die and should return true to
473 // continue traversal
474 // returns true if traversal should continue
475 inline bool walk_die_list(
476 const die_object& die,
477 const std::function<bool(const die_object&)>& fn
478 ) {
479 // TODO: Refactor so there is only one fn call
480 bool continue_traversal = true;
481 if(fn(die)) {
482 die_object current = die.get_sibling();
483 while(current) {
484 if(fn(current)) {
485 current = current.get_sibling();
486 } else {
487 continue_traversal = false;
488 break;
489 }
490 }
491 }
492 return continue_traversal;
493 }
494
495 // walk die list, recursing into children, callback is called on each die
496 // and should return true to continue traversal
497 // returns true if traversal should continue
498 inline bool walk_die_list_recursive(
499 const die_object& die,
500 const std::function<bool(const die_object&)>& fn
501 ) {
502 return walk_die_list(
503 die,
504 [&fn](const die_object& die) {
505 auto child = die.get_child();
506 if(child) {
507 if(!walk_die_list_recursive(child, fn)) {
508 return false;
509 }
510 }
511 return fn(die);
512 }
513 );
514 }
515
516 class maybe_owned_die_object {
517 // Hacky... I wish std::variant existed.
518 optional<die_object> owned_die;
519 optional<const die_object*> ref_die;
520 maybe_owned_die_object(die_object&& die) : owned_die(std::move(die)) {}
521 maybe_owned_die_object(const die_object& die) : ref_die(&die) {}
522 public:
523 static maybe_owned_die_object owned(die_object&& die) {
524 return maybe_owned_die_object{std::move(die)};
525 }
526 static maybe_owned_die_object ref(const die_object& die) {
527 return maybe_owned_die_object{die};
528 }
529 const die_object& get() {
530 ASSERT(owned_die || ref_die, "Mal-formed maybe_owned_die_object");
531 if(owned_die) {
532 return owned_die.unwrap();
533 } else {
534 return *ref_die.unwrap();
535 }
536 }
537 };
538 }
539 }
540 CPPTRACE_END_NAMESPACE
541
542 #endif