1 /* Copyright (c) 2008-2018. The SimGrid Team.
2 * All rights reserved. */
4 /* This program is free software; you can redistribute it and/or modify it
5 * under the terms of the license (GNU LGPL) which comes with this package. */
13 #include <boost/range/algorithm.hpp>
17 #include <elfutils/libdw.h>
19 #include <boost/algorithm/string/predicate.hpp>
21 #include "src/simgrid/util.hpp"
23 #include "xbt/string.hpp"
24 #include "xbt/sysdep.h"
25 #include <simgrid/config.h>
27 #include "src/mc/mc_dwarf.hpp"
28 #include "src/mc/mc_private.hpp"
30 #include "src/mc/ObjectInformation.hpp"
31 #include "src/mc/Variable.hpp"
32 #include "src/mc/remote/RemoteClient.hpp"
34 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_dwarf, mc, "DWARF processing");
36 /** \brief The default DW_TAG_lower_bound for a given DW_AT_language.
38 * The default for a given language is defined in the DWARF spec.
40 * \param language constant as defined by the DWARf spec
42 static uint64_t MC_dwarf_default_lower_bound(int lang);
44 /** \brief Computes the the element_count of a DW_TAG_enumeration_type DIE
46 * This is the number of elements in a given array dimension.
48 * A reference of the compilation unit (DW_TAG_compile_unit) is
49 * needed because the default lower bound (when there is no DW_AT_lower_bound)
50 * depends of the language of the compilation unit (DW_AT_language).
52 * \param die DIE for the DW_TAG_enumeration_type or DW_TAG_subrange_type
53 * \param unit DIE of the DW_TAG_compile_unit
55 static uint64_t MC_dwarf_subrange_element_count(Dwarf_Die* die, Dwarf_Die* unit);
57 /** \brief Computes the number of elements of a given DW_TAG_array_type.
59 * \param die DIE for the DW_TAG_array_type
61 static uint64_t MC_dwarf_array_element_count(Dwarf_Die * die, Dwarf_Die * unit);
63 /** \brief Process a DIE
65 * \param info the resulting object fot the library/binary file (output)
66 * \param die the current DIE
67 * \param unit the DIE of the compile unit of the current DIE
68 * \param frame containing frame if any
70 static void MC_dwarf_handle_die(simgrid::mc::ObjectInformation* info, Dwarf_Die * die,
71 Dwarf_Die * unit, simgrid::mc::Frame* frame,
74 /** \brief Process a type DIE
76 static void MC_dwarf_handle_type_die(simgrid::mc::ObjectInformation* info, Dwarf_Die * die,
77 Dwarf_Die * unit, simgrid::mc::Frame* frame,
80 /** \brief Calls MC_dwarf_handle_die on all children of the given die
82 * \param info the resulting object fot the library/binary file (output)
83 * \param die the current DIE
84 * \param unit the DIE of the compile unit of the current DIE
85 * \param frame containing frame if any
87 static void MC_dwarf_handle_children(simgrid::mc::ObjectInformation* info, Dwarf_Die * die,
88 Dwarf_Die * unit, simgrid::mc::Frame* frame,
91 /** \brief Handle a variable (DW_TAG_variable or other)
93 * \param info the resulting object fot the library/binary file (output)
94 * \param die the current DIE
95 * \param unit the DIE of the compile unit of the current DIE
96 * \param frame containing frame if any
98 static void MC_dwarf_handle_variable_die(simgrid::mc::ObjectInformation* info, Dwarf_Die * die,
99 Dwarf_Die * unit, simgrid::mc::Frame* frame,
102 /** \brief Get the DW_TAG_type of the DIE
105 * \return DW_TAG_type attribute as a new string (nullptr if none)
107 static std::uint64_t MC_dwarf_at_type(Dwarf_Die * die);
112 enum class TagClass {
121 /*** Class of forms defined in the DWARF standard */
122 enum class FormClass {
124 Address, // Location in the program's address space
125 Block, // Arbitrary block of bytes
128 Flag, // Boolean value
129 Reference, // Reference to another DIE
130 ExprLoc, // DWARF expression/location description
138 TagClass classify_tag(int tag)
142 case DW_TAG_array_type:
143 case DW_TAG_class_type:
144 case DW_TAG_enumeration_type:
146 case DW_TAG_pointer_type:
147 case DW_TAG_reference_type:
148 case DW_TAG_rvalue_reference_type:
149 case DW_TAG_string_type:
150 case DW_TAG_structure_type:
151 case DW_TAG_subroutine_type:
152 case DW_TAG_union_type:
153 case DW_TAG_ptr_to_member_type:
154 case DW_TAG_set_type:
155 case DW_TAG_subrange_type:
156 case DW_TAG_base_type:
157 case DW_TAG_const_type:
158 case DW_TAG_file_type:
159 case DW_TAG_packed_type:
160 case DW_TAG_volatile_type:
161 case DW_TAG_restrict_type:
162 case DW_TAG_interface_type:
163 case DW_TAG_unspecified_type:
164 case DW_TAG_shared_type:
165 return TagClass::Type;
167 case DW_TAG_subprogram:
168 return TagClass::Subprogram;
170 case DW_TAG_variable:
171 case DW_TAG_formal_parameter:
172 return TagClass::Variable;
174 case DW_TAG_lexical_block:
175 case DW_TAG_try_block:
176 case DW_TAG_catch_block:
177 case DW_TAG_inlined_subroutine:
178 case DW_TAG_with_stmt:
179 return TagClass::Scope;
181 case DW_TAG_namespace:
182 return TagClass::Namespace;
185 return TagClass::Unknown;
189 /** \brief Find the DWARF data class for a given DWARF data form
191 * This mapping is defined in the DWARF spec.
193 * \param form The form (values taken from the DWARF spec)
194 * \return An internal representation for the corresponding class
197 FormClass classify_form(int form)
201 return FormClass::Address;
206 return FormClass::Block;
213 return FormClass::Constant;
216 return FormClass::String;
217 case DW_FORM_ref_addr:
222 case DW_FORM_ref_udata:
223 return FormClass::Reference;
225 case DW_FORM_flag_present:
226 return FormClass::Flag;
227 case DW_FORM_exprloc:
228 return FormClass::ExprLoc;
232 return FormClass::Unknown;
236 /** \brief Get the name of the tag of a given DIE
239 * \return name of the tag of this DIE
242 const char *tagname(Dwarf_Die * die)
244 return simgrid::dwarf::tagname(dwarf_tag(die));
252 /** \brief Get an attribute of a given DIE as a string
255 * \param attribute attribute
256 * \return value of the given attribute of the given DIE
258 static const char *MC_dwarf_attr_integrate_string(Dwarf_Die * die,
261 Dwarf_Attribute attr;
262 if (not dwarf_attr_integrate(die, attribute, &attr))
265 return dwarf_formstring(&attr);
268 static Dwarf_Off MC_dwarf_attr_dieoffset(Dwarf_Die * die, int attribute)
270 Dwarf_Attribute attr;
271 if (dwarf_hasattr_integrate(die, attribute) == 0)
273 dwarf_attr_integrate(die, attribute, &attr);
274 Dwarf_Die subtype_die;
275 if (dwarf_formref_die(&attr, &subtype_die) == nullptr)
276 xbt_die("Could not find DIE");
277 return dwarf_dieoffset(&subtype_die);
280 static Dwarf_Off MC_dwarf_attr_integrate_dieoffset(Dwarf_Die * die,
283 Dwarf_Attribute attr;
284 if (dwarf_hasattr_integrate(die, attribute) == 0)
286 dwarf_attr_integrate(die, DW_AT_type, &attr);
287 Dwarf_Die subtype_die;
288 if (dwarf_formref_die(&attr, &subtype_die) == nullptr)
289 xbt_die("Could not find DIE");
290 return dwarf_dieoffset(&subtype_die);
293 /** \brief Find the type/subtype (DW_AT_type) for a DIE
296 * \return DW_AT_type reference as a global offset in hexadecimal (or nullptr)
299 std::uint64_t MC_dwarf_at_type(Dwarf_Die * die)
301 return MC_dwarf_attr_integrate_dieoffset(die, DW_AT_type);
304 static uint64_t MC_dwarf_attr_integrate_addr(Dwarf_Die * die, int attribute)
306 Dwarf_Attribute attr;
307 if (dwarf_attr_integrate(die, attribute, &attr) == nullptr)
310 if (dwarf_formaddr(&attr, &value) == 0)
311 return (uint64_t) value;
316 static uint64_t MC_dwarf_attr_integrate_uint(Dwarf_Die * die, int attribute,
317 uint64_t default_value)
319 Dwarf_Attribute attr;
320 if (dwarf_attr_integrate(die, attribute, &attr) == nullptr)
321 return default_value;
323 return dwarf_formudata(dwarf_attr_integrate(die, attribute, &attr),
324 &value) == 0 ? (uint64_t) value : default_value;
327 static bool MC_dwarf_attr_flag(Dwarf_Die * die, int attribute, bool integrate)
329 Dwarf_Attribute attr;
330 if ((integrate ? dwarf_attr_integrate(die, attribute, &attr)
331 : dwarf_attr(die, attribute, &attr)) == 0)
335 if (dwarf_formflag(&attr, &result))
336 xbt_die("Unexpected form for attribute %s",
337 simgrid::dwarf::attrname(attribute));
341 /** @brief Find the default lower bound for a given language
343 * The default lower bound of an array (when DW_TAG_lower_bound
344 * is missing) depends on the language of the compilation unit.
346 * @param lang Language of the compilation unit (values defined in the DWARF spec)
347 * @return Default lower bound of an array in this compilation unit
349 static uint64_t MC_dwarf_default_lower_bound(int lang)
355 case DW_LANG_C_plus_plus:
359 case DW_LANG_ObjC_plus_plus:
365 case DW_LANG_Fortran77:
366 case DW_LANG_Fortran90:
367 case DW_LANG_Fortran95:
368 case DW_LANG_Modula2:
369 case DW_LANG_Pascal83:
371 case DW_LANG_Cobol74:
372 case DW_LANG_Cobol85:
375 xbt_die("No default DW_TAG_lower_bound for language %i and none given",
381 /** \brief Finds the number of elements in a DW_TAG_subrange_type or DW_TAG_enumeration_type DIE
384 * \param unit DIE of the compilation unit
385 * \return number of elements in the range
387 static uint64_t MC_dwarf_subrange_element_count(Dwarf_Die * die,
390 xbt_assert(dwarf_tag(die) == DW_TAG_enumeration_type
391 || dwarf_tag(die) == DW_TAG_subrange_type,
392 "MC_dwarf_subrange_element_count called with DIE of type %s",
393 simgrid::dwarf::tagname(die));
395 // Use DW_TAG_count if present:
396 if (dwarf_hasattr_integrate(die, DW_AT_count))
397 return MC_dwarf_attr_integrate_uint(die, DW_AT_count, 0);
398 // Otherwise compute DW_TAG_upper_bound-DW_TAG_lower_bound + 1:
400 if (not dwarf_hasattr_integrate(die, DW_AT_upper_bound))
401 // This is not really 0, but the code expects this (we do not know):
404 uint64_t upper_bound = MC_dwarf_attr_integrate_uint(die, DW_AT_upper_bound, static_cast<uint64_t>(-1));
406 uint64_t lower_bound = 0;
407 if (dwarf_hasattr_integrate(die, DW_AT_lower_bound))
408 lower_bound = MC_dwarf_attr_integrate_uint(die, DW_AT_lower_bound, static_cast<uint64_t>(-1));
410 lower_bound = MC_dwarf_default_lower_bound(dwarf_srclang(unit));
411 return upper_bound - lower_bound + 1;
414 /** \brief Finds the number of elements in a array type (DW_TAG_array_type)
416 * The compilation unit might be needed because the default lower
417 * bound depends on the language of the compilation unit.
419 * \param die the DIE of the DW_TAG_array_type
420 * \param unit the DIE of the compilation unit
421 * \return number of elements in this array type
423 static uint64_t MC_dwarf_array_element_count(Dwarf_Die * die, Dwarf_Die * unit)
425 xbt_assert(dwarf_tag(die) == DW_TAG_array_type,
426 "MC_dwarf_array_element_count called with DIE of type %s",
427 simgrid::dwarf::tagname(die));
432 for (res = dwarf_child(die, &child); res == 0;
433 res = dwarf_siblingof(&child, &child)) {
434 int child_tag = dwarf_tag(&child);
435 if (child_tag == DW_TAG_subrange_type
436 || child_tag == DW_TAG_enumeration_type)
437 result *= MC_dwarf_subrange_element_count(&child, unit);
444 /** Sort the variable by name and address.
446 * We could use boost::container::flat_set instead.
448 static bool MC_compare_variable(
449 simgrid::mc::Variable const& a, simgrid::mc::Variable const& b)
451 int cmp = strcmp(a.name.c_str(), b.name.c_str());
457 return a.address < b.address;
460 // ***** simgrid::mc::Type*
462 /** \brief Initialize the location of a member of a type
463 * (DW_AT_data_member_location of a DW_TAG_member).
465 * \param type a type (struct, class)
466 * \param member the member of the type
467 * \param child DIE of the member (DW_TAG_member)
469 static void MC_dwarf_fill_member_location(
470 simgrid::mc::Type* type, simgrid::mc::Member* member, Dwarf_Die * child)
472 if (dwarf_hasattr(child, DW_AT_data_bit_offset))
473 xbt_die("Can't groke DW_AT_data_bit_offset.");
475 if (not dwarf_hasattr_integrate(child, DW_AT_data_member_location)) {
476 if (type->type == DW_TAG_union_type)
479 ("Missing DW_AT_data_member_location field in DW_TAG_member %s of type <%"
480 PRIx64 ">%s", member->name.c_str(),
481 (uint64_t) type->id, type->name.c_str());
484 Dwarf_Attribute attr;
485 dwarf_attr_integrate(child, DW_AT_data_member_location, &attr);
486 int form = dwarf_whatform(&attr);
487 simgrid::dwarf::FormClass form_class = simgrid::dwarf::classify_form(form);
488 switch (form_class) {
489 case simgrid::dwarf::FormClass::ExprLoc:
490 case simgrid::dwarf::FormClass::Block:
491 // Location expression:
495 if (dwarf_getlocation(&attr, &expr, &len))
497 ("Could not read location expression DW_AT_data_member_location in DW_TAG_member %s of type <%"
498 PRIx64 ">%s", MC_dwarf_attr_integrate_string(child, DW_AT_name),
499 (uint64_t) type->id, type->name.c_str());
500 member->location_expression = simgrid::dwarf::DwarfExpression(expr, expr+len);
503 case simgrid::dwarf::FormClass::Constant:
504 // Offset from the base address of the object:
507 if (not dwarf_formudata(&attr, &offset))
508 member->offset(offset);
510 xbt_die("Cannot get %s location <%" PRIx64 ">%s",
511 MC_dwarf_attr_integrate_string(child, DW_AT_name),
512 (uint64_t) type->id, type->name.c_str());
517 // includes FormClass::LocListPtr (reference to a location list: TODO) and FormClass::Reference (it's supposed to be
518 // possible in DWARF2 but I couldn't find its semantic in the spec)
519 xbt_die("Can't handle form class (%d) / form 0x%x as DW_AT_member_location", (int)form_class, (unsigned)form);
524 /** \brief Populate the list of members of a type
526 * \param info ELF object containing the type DIE
527 * \param die DIE of the type
528 * \param unit DIE of the compilation unit containing the type DIE
529 * \param type the type
531 static void MC_dwarf_add_members(simgrid::mc::ObjectInformation* info, Dwarf_Die * die,
532 Dwarf_Die * unit, simgrid::mc::Type* type)
536 xbt_assert(type->members.empty());
537 for (res = dwarf_child(die, &child); res == 0;
538 res = dwarf_siblingof(&child, &child)) {
539 int tag = dwarf_tag(&child);
540 if (tag == DW_TAG_member || tag == DW_TAG_inheritance) {
542 // Skip declarations:
543 if (MC_dwarf_attr_flag(&child, DW_AT_declaration, false))
546 // Skip compile time constants:
547 if (dwarf_hasattr(&child, DW_AT_const_value))
550 // TODO, we should use another type (because is is not a type but a member)
551 simgrid::mc::Member member;
552 if (tag == DW_TAG_inheritance)
553 member.flags |= simgrid::mc::Member::INHERITANCE_FLAG;
555 const char *name = MC_dwarf_attr_integrate_string(&child, DW_AT_name);
558 // Those base names are used by GCC and clang for virtual table pointers
559 // respectively ("__vptr$ClassName", "__vptr.ClassName"):
560 if (boost::algorithm::starts_with(member.name, "__vptr$") ||
561 boost::algorithm::starts_with(member.name, "__vptr."))
562 member.flags |= simgrid::mc::Member::VIRTUAL_POINTER_FLAG;
563 // A cleaner solution would be to check against the type:
565 // tag: DW_TAG_member
568 // # Type for a pointer to a vtable
569 // tag: DW_TAG_pointer_type
571 // # Type for a vtable:
572 // tag: DW_TAG_pointer_type
573 // name: "__vtbl_ptr_type"
575 // tag: DW_TAG_subroutine_type
577 // tag: DW_TAG_base_type
582 MC_dwarf_attr_integrate_uint(&child, DW_AT_byte_size, 0);
583 member.type_id = MC_dwarf_at_type(&child);
585 if (dwarf_hasattr(&child, DW_AT_data_bit_offset))
586 xbt_die("Can't groke DW_AT_data_bit_offset.");
588 MC_dwarf_fill_member_location(type, &member, &child);
590 if (not member.type_id)
591 xbt_die("Missing type for member %s of <%" PRIx64 ">%s",
593 (uint64_t) type->id, type->name.c_str());
595 type->members.push_back(std::move(member));
600 /** \brief Create a MC type object from a DIE
602 * \param info current object info object
603 * \param die DIE (for a given type)
604 * \param unit compilation unit of the current DIE
605 * \return MC representation of the type
607 static simgrid::mc::Type MC_dwarf_die_to_type(
608 simgrid::mc::ObjectInformation* info, Dwarf_Die * die,
609 Dwarf_Die * unit, simgrid::mc::Frame* frame,
612 simgrid::mc::Type type;
613 type.type = dwarf_tag(die);
614 type.name = std::string();
615 type.element_count = -1;
618 type.id = dwarf_dieoffset(die);
620 const char *prefix = "";
622 case DW_TAG_structure_type:
625 case DW_TAG_union_type:
628 case DW_TAG_class_type:
635 const char *name = MC_dwarf_attr_integrate_string(die, DW_AT_name);
636 if (name != nullptr) {
638 type.name = simgrid::xbt::string_printf("%s%s::%s", prefix, ns, name);
640 type.name = simgrid::xbt::string_printf("%s%s", prefix, name);
643 type.type_id = MC_dwarf_at_type(die);
645 // Some compilers do not emit DW_AT_byte_size for pointer_type,
646 // so we fill this. We currently assume that the model-checked process is in
647 // the same architecture..
648 if (type.type == DW_TAG_pointer_type)
649 type.byte_size = sizeof(void*);
651 // Computation of the byte_size
652 if (dwarf_hasattr_integrate(die, DW_AT_byte_size))
653 type.byte_size = MC_dwarf_attr_integrate_uint(die, DW_AT_byte_size, 0);
654 else if (type.type == DW_TAG_array_type
655 || type.type == DW_TAG_structure_type
656 || type.type == DW_TAG_class_type) {
658 if (dwarf_aggregate_size(die, &size) == 0)
659 type.byte_size = size;
663 case DW_TAG_array_type:
664 type.element_count = MC_dwarf_array_element_count(die, unit);
665 // TODO, handle DW_byte_stride and (not) DW_bit_stride
668 case DW_TAG_pointer_type:
669 case DW_TAG_reference_type:
670 case DW_TAG_rvalue_reference_type:
673 case DW_TAG_structure_type:
674 case DW_TAG_union_type:
675 case DW_TAG_class_type:
676 MC_dwarf_add_members(info, die, unit, &type);
677 MC_dwarf_handle_children(info, die, unit, frame,
678 ns ? simgrid::xbt::string_printf("%s::%s", ns, name).c_str() : type.name.c_str());
682 XBT_DEBUG("Unhandled type: %d (%s)", type.type, simgrid::dwarf::tagname(type.type));
689 static void MC_dwarf_handle_type_die(simgrid::mc::ObjectInformation* info, Dwarf_Die * die,
690 Dwarf_Die * unit, simgrid::mc::Frame* frame,
693 simgrid::mc::Type type = MC_dwarf_die_to_type(info, die, unit, frame, ns);
694 auto& t = (info->types[type.id] = std::move(type));
695 if (not t.name.empty() && type.byte_size != 0)
696 info->full_types_by_name[t.name] = &t;
699 static int mc_anonymous_variable_index = 0;
701 static std::unique_ptr<simgrid::mc::Variable> MC_die_to_variable(
702 simgrid::mc::ObjectInformation* info, Dwarf_Die * die,
703 Dwarf_Die * unit, simgrid::mc::Frame* frame,
706 // Skip declarations:
707 if (MC_dwarf_attr_flag(die, DW_AT_declaration, false))
710 // Skip compile time constants:
711 if (dwarf_hasattr(die, DW_AT_const_value))
714 Dwarf_Attribute attr_location;
715 if (dwarf_attr(die, DW_AT_location, &attr_location) == nullptr)
716 // No location: do not add it ?
719 std::unique_ptr<simgrid::mc::Variable> variable =
720 std::unique_ptr<simgrid::mc::Variable>(new simgrid::mc::Variable());
721 variable->id = dwarf_dieoffset(die);
722 variable->global = frame == nullptr; // Can be override base on DW_AT_location
723 variable->object_info = info;
725 const char *name = MC_dwarf_attr_integrate_string(die, DW_AT_name);
727 variable->name = name;
728 variable->type_id = MC_dwarf_at_type(die);
730 int form = dwarf_whatform(&attr_location);
731 simgrid::dwarf::FormClass form_class;
732 if (form == DW_FORM_sec_offset)
733 form_class = simgrid::dwarf::FormClass::Constant;
735 form_class = simgrid::dwarf::classify_form(form);
736 switch (form_class) {
737 case simgrid::dwarf::FormClass::ExprLoc:
738 case simgrid::dwarf::FormClass::Block:
739 // Location expression:
743 if (dwarf_getlocation(&attr_location, &expr, &len)) {
745 "Could not read location expression in DW_AT_location "
746 "of variable <%" PRIx64 ">%s",
747 (uint64_t) variable->id,
748 variable->name.c_str());
751 if (len == 1 && expr[0].atom == DW_OP_addr) {
752 variable->global = true;
753 uintptr_t offset = (uintptr_t) expr[0].number;
754 uintptr_t base = (uintptr_t) info->base_address();
755 variable->address = (void *) (base + offset);
757 variable->location_list = {
758 simgrid::dwarf::LocationListEntry(simgrid::dwarf::DwarfExpression(expr, expr + len))};
763 case simgrid::dwarf::FormClass::LocListPtr:
764 case simgrid::dwarf::FormClass::Constant:
765 // Reference to location list:
766 variable->location_list = simgrid::dwarf::location_list(
767 *info, attr_location);
771 xbt_die("Unexpected form 0x%x (%i), class 0x%x (%i) list for location in <%" PRIx64 ">%s", (unsigned)form, form,
772 (unsigned)form_class, (int)form_class, (uint64_t)variable->id, variable->name.c_str());
775 // Handle start_scope:
776 if (dwarf_hasattr(die, DW_AT_start_scope)) {
777 Dwarf_Attribute attr;
778 dwarf_attr(die, DW_AT_start_scope, &attr);
779 int form = dwarf_whatform(&attr);
780 simgrid::dwarf::FormClass form_class = simgrid::dwarf::classify_form(form);
781 if (form_class == simgrid::dwarf::FormClass::Constant) {
783 variable->start_scope = dwarf_formudata(&attr, &value) == 0 ? (size_t)value : 0;
785 // TODO: FormClass::RangeListPtr
786 xbt_die("Unhandled form 0x%x, class 0x%X for DW_AT_start_scope of variable %s", (unsigned)form,
787 (unsigned)form_class, name == nullptr ? "?" : name);
791 if (ns && variable->global)
793 std::string(ns) + "::" + variable->name;
795 // The current code needs a variable name,
796 // generate a fake one:
797 if (variable->name.empty()) {
798 variable->name = "@anonymous#" + std::to_string(mc_anonymous_variable_index);
799 mc_anonymous_variable_index++;
804 static void MC_dwarf_handle_variable_die(simgrid::mc::ObjectInformation* info, Dwarf_Die * die,
805 Dwarf_Die * unit, simgrid::mc::Frame* frame,
808 std::unique_ptr<simgrid::mc::Variable> variable =
809 MC_die_to_variable(info, die, unit, frame, ns);
812 // Those arrays are sorted later:
813 if (variable->global)
814 info->global_variables.push_back(std::move(*variable));
815 else if (frame != nullptr)
816 frame->variables.push_back(std::move(*variable));
818 xbt_die("No frame for this local variable");
821 static void MC_dwarf_handle_scope_die(simgrid::mc::ObjectInformation* info, Dwarf_Die * die,
822 Dwarf_Die * unit, simgrid::mc::Frame* parent_frame,
825 // TODO, handle DW_TAG_type/DW_TAG_location for DW_TAG_with_stmt
826 int tag = dwarf_tag(die);
827 simgrid::dwarf::TagClass klass = simgrid::dwarf::classify_tag(tag);
829 // (Template) Subprogram declaration:
830 if (klass == simgrid::dwarf::TagClass::Subprogram
831 && MC_dwarf_attr_flag(die, DW_AT_declaration, false))
834 if (klass == simgrid::dwarf::TagClass::Scope)
835 xbt_assert(parent_frame, "No parent scope for this scope");
837 simgrid::mc::Frame frame;
839 frame.id = dwarf_dieoffset(die);
840 frame.object_info = info;
842 if (klass == simgrid::dwarf::TagClass::Subprogram) {
843 const char *name = MC_dwarf_attr_integrate_string(die, DW_AT_name);
845 frame.name = std::string(ns) + "::" + name;
850 frame.abstract_origin_id =
851 MC_dwarf_attr_dieoffset(die, DW_AT_abstract_origin);
853 // This is the base address for DWARF addresses.
854 // Relocated addresses are offset from this base address.
855 // See DWARF4 spec 7.5
856 std::uint64_t base = (std::uint64_t) info->base_address();
858 // TODO, support DW_AT_ranges
859 uint64_t low_pc = MC_dwarf_attr_integrate_addr(die, DW_AT_low_pc);
860 frame.range.begin() = low_pc ? (std::uint64_t) base + low_pc : 0;
863 Dwarf_Attribute attr;
864 if (not dwarf_attr_integrate(die, DW_AT_high_pc, &attr))
865 xbt_die("Missing DW_AT_high_pc matching with DW_AT_low_pc");
870 switch (simgrid::dwarf::classify_form(dwarf_whatform(&attr))) {
872 // DW_AT_high_pc if an offset from the low_pc:
873 case simgrid::dwarf::FormClass::Constant:
875 if (dwarf_formsdata(&attr, &offset) != 0)
876 xbt_die("Could not read constant");
877 frame.range.end() = frame.range.begin() + offset;
880 // DW_AT_high_pc is a relocatable address:
881 case simgrid::dwarf::FormClass::Address:
882 if (dwarf_formaddr(&attr, &high_pc) != 0)
883 xbt_die("Could not read address");
884 frame.range.end() = base + high_pc;
888 xbt_die("Unexpected class for DW_AT_high_pc");
893 if (klass == simgrid::dwarf::TagClass::Subprogram) {
894 Dwarf_Attribute attr_frame_base;
895 if (dwarf_attr_integrate(die, DW_AT_frame_base, &attr_frame_base))
896 frame.frame_base_location = simgrid::dwarf::location_list(*info,
901 MC_dwarf_handle_children(info, die, unit, &frame, ns);
903 // We sort them in order to have an (somewhat) efficient by name
905 boost::range::sort(frame.variables, MC_compare_variable);
908 if (klass == simgrid::dwarf::TagClass::Subprogram)
909 info->subprograms[frame.id] = std::move(frame);
910 else if (klass == simgrid::dwarf::TagClass::Scope)
911 parent_frame->scopes.push_back(std::move(frame));
914 static void mc_dwarf_handle_namespace_die(simgrid::mc::ObjectInformation* info,
915 Dwarf_Die * die, Dwarf_Die * unit,
916 simgrid::mc::Frame* frame,
919 const char *name = MC_dwarf_attr_integrate_string(die, DW_AT_name);
921 xbt_die("Unexpected namespace in a subprogram");
922 char *new_ns = ns == nullptr ? xbt_strdup(name)
923 : bprintf("%s::%s", ns, name);
924 MC_dwarf_handle_children(info, die, unit, frame, new_ns);
928 static void MC_dwarf_handle_children(simgrid::mc::ObjectInformation* info, Dwarf_Die * die,
929 Dwarf_Die * unit, simgrid::mc::Frame* frame,
932 // For each child DIE:
935 for (res = dwarf_child(die, &child); res == 0;
936 res = dwarf_siblingof(&child, &child))
937 MC_dwarf_handle_die(info, &child, unit, frame, ns);
940 static void MC_dwarf_handle_die(simgrid::mc::ObjectInformation* info, Dwarf_Die * die,
941 Dwarf_Die * unit, simgrid::mc::Frame* frame,
944 int tag = dwarf_tag(die);
945 simgrid::dwarf::TagClass klass = simgrid::dwarf::classify_tag(tag);
949 case simgrid::dwarf::TagClass::Type:
950 MC_dwarf_handle_type_die(info, die, unit, frame, ns);
953 // Subprogram or scope:
954 case simgrid::dwarf::TagClass::Subprogram:
955 case simgrid::dwarf::TagClass::Scope:
956 MC_dwarf_handle_scope_die(info, die, unit, frame, ns);
960 case simgrid::dwarf::TagClass::Variable:
961 MC_dwarf_handle_variable_die(info, die, unit, frame, ns);
964 case simgrid::dwarf::TagClass::Namespace:
965 mc_dwarf_handle_namespace_die(info, die, unit, frame, ns);
975 Elf64_Half get_type(Elf* elf)
977 Elf64_Ehdr* ehdr64 = elf64_getehdr(elf);
979 return ehdr64->e_type;
980 Elf32_Ehdr* ehdr32 = elf32_getehdr(elf);
982 return ehdr32->e_type;
983 xbt_die("Could not get ELF heeader");
987 void read_dwarf_info(simgrid::mc::ObjectInformation* info, Dwarf* dwarf)
989 // For each compilation unit:
990 Dwarf_Off offset = 0;
991 Dwarf_Off next_offset = 0;
994 while (dwarf_nextcu(dwarf, offset, &next_offset, &length, nullptr, nullptr, nullptr) ==
997 if (dwarf_offdie(dwarf, offset + length, &unit_die) != nullptr)
998 MC_dwarf_handle_children(info, &unit_die, &unit_die, nullptr, nullptr);
999 offset = next_offset;
1003 /** Get the build-id (NT_GNU_BUILD_ID) from the ELF file
1005 * This build-id may is used to locate an external debug (DWARF) file
1006 * for this ELF file.
1008 * @param elf libelf handle for an ELF file
1009 * @return build-id for this ELF file (or an empty vector if none is found)
1012 std::vector<char> get_build_id(Elf* elf)
1015 // Summary: the GNU build ID is stored in a ("GNU, NT_GNU_BUILD_ID) note
1016 // found in a PT_NOTE entry in the program header table.
1019 if (elf_getphdrnum (elf, &phnum) != 0)
1020 xbt_die("Could not read program headers");
1022 // Iterate over the program headers and find the PT_NOTE ones:
1023 for (size_t i = 0; i < phnum; ++i) {
1024 GElf_Phdr phdr_temp;
1025 GElf_Phdr *phdr = gelf_getphdr(elf, i, &phdr_temp);
1026 if (phdr->p_type != PT_NOTE)
1029 Elf_Data* data = elf_getdata_rawchunk(elf, phdr->p_offset, phdr->p_filesz, ELF_T_NHDR);
1031 // Iterate over the notes and find the NT_GNU_BUILD_ID one:
1033 while (pos < data->d_size) {
1035 // Location of the name within Elf_Data:
1038 pos = gelf_getnote(data, pos, &nhdr, &name_pos, &desc_pos);
1039 // A build ID note is identified by the pair ("GNU", NT_GNU_BUILD_ID)
1040 // (a namespace and a type within this namespace):
1041 if (nhdr.n_type == NT_GNU_BUILD_ID
1042 && nhdr.n_namesz == sizeof("GNU")
1043 && memcmp((char*) data->d_buf + name_pos, "GNU", sizeof("GNU")) == 0) {
1044 XBT_DEBUG("Found GNU/NT_GNU_BUILD_ID note");
1045 char* start = (char*) data->d_buf + desc_pos;
1046 char* end = (char*) start + nhdr.n_descsz;
1047 return std::vector<char>(start, end);
1053 return std::vector<char>();
1056 static char hexdigits[16] = {
1057 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
1058 'a', 'b', 'c', 'd', 'e', 'f'
1061 /** Binary data to hexadecimal */
1063 std::array<char, 2> to_hex(std::uint8_t byte)
1065 // Horrid double braces!
1066 // Apparently, this is needed in C++11 (not in C++14).
1067 return { { hexdigits[byte >> 4], hexdigits[byte & 0xF] } };
1070 /** Binary data to hexadecimal */
1072 std::string to_hex(const char* data, std::size_t count)
1075 res.resize(2*count);
1076 for (std::size_t i = 0; i < count; i++) {
1077 std::array<char, 2> hex_byte = to_hex(data[i]);
1078 for (int j = 0; j < 2; ++j)
1079 res[2 * i + j] = hex_byte[j];
1084 /** Binary data to hexadecimal */
1086 std::string to_hex(std::vector<char> const& data)
1088 return to_hex(data.data(), data.size());
1091 /** Base directories for external debug files */
1093 const char* debug_paths[] = {
1095 "/usr/local/lib/debug/",
1098 /** Locate an external debug file from the NT_GNU_BUILD_ID
1100 * This is one of the mechanisms used for
1101 * [separate debug files](https://sourceware.org/gdb/onlinedocs/gdb/Separate-Debug-Files.html).
1104 // /usr/lib/debug/.build-id/0b/dc77f1c29aea2b14ff5acd9a19ab3175ffdeae.debug
1106 std::string find_by_build_id(std::vector<char> id)
1108 std::string filename;
1109 std::string hex = to_hex(id);
1110 for (const char* const& debug_path : debug_paths) {
1112 filename = std::string(debug_path) + ".build-id/"
1113 + to_hex(id.data(), 1) + '/'
1114 + to_hex(id.data() + 1, id.size() - 1) + ".debug";
1115 XBT_DEBUG("Checking debug file: %s", filename.c_str());
1116 if (access(filename.c_str(), F_OK) == 0) {
1117 XBT_DEBUG("Found debug file: %s\n", hex.c_str());
1121 XBT_DEBUG("Not debuf info found for build ID %s\n", hex.data());
1122 return std::string();
1125 /** \brief Populate the debugging informations of the given ELF object
1127 * Read the DWARf information of the EFFL object and populate the
1128 * lists of types, variables, functions.
1131 void MC_load_dwarf(simgrid::mc::ObjectInformation* info)
1133 if (elf_version(EV_CURRENT) == EV_NONE)
1134 xbt_die("libelf initialization error");
1136 // Open the ELF file:
1137 int fd = open(info->file_name.c_str(), O_RDONLY);
1139 xbt_die("Could not open file %s", info->file_name.c_str());
1140 Elf* elf = elf_begin(fd, ELF_C_READ, nullptr);
1142 xbt_die("Not an ELF file");
1143 Elf_Kind kind = elf_kind(elf);
1144 if (kind != ELF_K_ELF)
1145 xbt_die("Not an ELF file");
1147 // Remember if this is a `ET_EXEC` (fixed location) or `ET_DYN`:
1148 Elf64_Half type = get_type(elf);
1149 if (type == ET_EXEC)
1150 info->flags |= simgrid::mc::ObjectInformation::Executable;
1152 // Read DWARF debug information in the file:
1153 Dwarf* dwarf = dwarf_begin_elf (elf, DWARF_C_READ, nullptr);
1154 if (dwarf != nullptr) {
1155 read_dwarf_info(info, dwarf);
1163 // If there was no DWARF in the file, try to find it in a separate file.
1164 // Different methods might be used to store the DWARF informations:
1165 // * GNU NT_GNU_BUILD_ID
1167 // See https://sourceware.org/gdb/onlinedocs/gdb/Separate-Debug-Files.html
1168 // for reference of what we are doing.
1170 // Try with NT_GNU_BUILD_ID: we find the build ID in the ELF file and then
1171 // use this ID to find the file in some known locations in the filesystem.
1172 std::vector<char> build_id = get_build_id(elf);
1173 if (not build_id.empty()) {
1177 // Find the debug file using the build id:
1178 std::string debug_file = find_by_build_id(build_id);
1179 if (debug_file.empty()) {
1180 std::string hex = to_hex(build_id);
1181 xbt_die("Missing debug info for %s with build-id %s\n"
1182 "You might want to install the suitable debugging package.\n",
1183 info->file_name.c_str(), hex.c_str());
1186 // Load the DWARF info from this file:
1187 XBT_DEBUG("Load DWARF for %s from %s",
1188 info->file_name.c_str(), debug_file.c_str());
1189 fd = open(debug_file.c_str(), O_RDONLY);
1191 xbt_die("Could not open file %s", debug_file.c_str());
1192 Dwarf* dwarf = dwarf_begin(fd, DWARF_C_READ);
1193 if (dwarf == nullptr)
1194 xbt_die("No DWARF info in %s for %s",
1195 debug_file.c_str(), info->file_name.c_str());
1196 read_dwarf_info(info, dwarf);
1202 // TODO, try to find DWARF info using .gnu_debuglink.
1206 xbt_die("Debugging information not found for %s\n"
1207 "Try recompiling with -g\n",
1208 info->file_name.c_str());
1211 // ***** Functions index
1213 static void MC_make_functions_index(simgrid::mc::ObjectInformation* info)
1215 info->functions_index.clear();
1217 for (auto& e : info->subprograms) {
1218 if (e.second.range.begin() == 0)
1220 simgrid::mc::FunctionIndexEntry entry;
1221 entry.low_pc = (void*) e.second.range.begin();
1222 entry.function = &e.second;
1223 info->functions_index.push_back(entry);
1226 info->functions_index.shrink_to_fit();
1228 // Sort the array by low_pc:
1229 boost::range::sort(info->functions_index,
1230 [](simgrid::mc::FunctionIndexEntry const& a,
1231 simgrid::mc::FunctionIndexEntry const& b)
1233 return a.low_pc < b.low_pc;
1237 static void MC_post_process_variables(simgrid::mc::ObjectInformation* info)
1239 // Someone needs this to be sorted but who?
1240 boost::range::sort(info->global_variables, MC_compare_variable);
1242 for (simgrid::mc::Variable& variable : info->global_variables)
1243 if (variable.type_id)
1244 variable.type = simgrid::util::find_map_ptr(
1245 info->types, variable.type_id);
1248 static void mc_post_process_scope(simgrid::mc::ObjectInformation* info, simgrid::mc::Frame* scope)
1251 if (scope->tag == DW_TAG_inlined_subroutine) {
1252 // Attach correct namespaced name in inlined subroutine:
1253 auto i = info->subprograms.find(scope->abstract_origin_id);
1254 xbt_assert(i != info->subprograms.end(),
1255 "Could not lookup abstract origin %" PRIx64,
1256 (std::uint64_t) scope->abstract_origin_id);
1257 scope->name = i->second.name;
1261 for (simgrid::mc::Variable& variable : scope->variables)
1262 if (variable.type_id)
1263 variable.type = simgrid::util::find_map_ptr(
1264 info->types, variable.type_id);
1266 // Recursive post-processing of nested-scopes:
1267 for (simgrid::mc::Frame& nested_scope : scope->scopes)
1268 mc_post_process_scope(info, &nested_scope);
1272 simgrid::mc::Type* MC_resolve_type(
1273 simgrid::mc::ObjectInformation* info, unsigned type_id)
1277 simgrid::mc::Type* type = simgrid::util::find_map_ptr(info->types, type_id);
1278 if (type == nullptr)
1281 // We already have the information on the type:
1282 if (type->byte_size != 0)
1285 // Don't have a name, we can't find a more complete version:
1286 if (type->name.empty())
1289 // Try to find a more complete description of the type:
1290 // We need to fix in order to support C++.
1291 simgrid::mc::Type** subtype = simgrid::util::find_map_ptr(
1292 info->full_types_by_name, type->name);
1298 static void MC_post_process_types(simgrid::mc::ObjectInformation* info)
1300 // Lookup "subtype" field:
1301 for (auto& i : info->types) {
1302 i.second.subtype = MC_resolve_type(info, i.second.type_id);
1303 for (simgrid::mc::Member& member : i.second.members)
1304 member.type = MC_resolve_type(info, member.type_id);
1311 /** \brief Finds informations about a given shared object/executable */
1312 std::shared_ptr<simgrid::mc::ObjectInformation> createObjectInformation(
1313 std::vector<simgrid::xbt::VmMap> const& maps, const char *name)
1315 std::shared_ptr<simgrid::mc::ObjectInformation> result =
1316 std::make_shared<simgrid::mc::ObjectInformation>();
1317 result->file_name = name;
1318 simgrid::mc::find_object_address(maps, result.get());
1319 MC_load_dwarf(result.get());
1320 MC_post_process_variables(result.get());
1321 MC_post_process_types(result.get());
1322 for (auto& entry : result.get()->subprograms)
1323 mc_post_process_scope(result.get(), &entry.second);
1324 MC_make_functions_index(result.get());
1328 /*************************************************************************/
1330 void postProcessObjectInformation(simgrid::mc::RemoteClient* process, simgrid::mc::ObjectInformation* info)
1332 for (auto& i : info->types) {
1334 simgrid::mc::Type* type = &(i.second);
1335 simgrid::mc::Type* subtype = type;
1336 while (subtype->type == DW_TAG_typedef
1337 || subtype->type == DW_TAG_volatile_type
1338 || subtype->type == DW_TAG_const_type)
1339 if (subtype->subtype)
1340 subtype = subtype->subtype;
1344 // Resolve full_type:
1345 if (not subtype->name.empty() && subtype->byte_size == 0)
1346 for (auto const& object_info : process->object_infos) {
1347 auto i = object_info->full_types_by_name.find(subtype->name);
1348 if (i != object_info->full_types_by_name.end() && not i->second->name.empty() && i->second->byte_size) {
1349 type->full_type = i->second;
1353 else type->full_type = subtype;
1364 /** Convert a DWARF register into a libunwind register
1366 * DWARF and libunwind does not use the same convention for numbering the
1367 * registers on some architectures. The function makes the necessary
1370 int dwarf_register_to_libunwind(int dwarf_register)
1372 #if defined(__x86_64__)
1373 // It seems for this arch, DWARF and libunwind agree in the numbering:
1374 return dwarf_register;
1375 #elif defined(__i386__)
1376 // Couldn't find the authoritative source of information for this.
1377 // This is inspired from http://source.winehq.org/source/dlls/dbghelp/cpu_i386.c#L517.
1378 switch (dwarf_register) {
1398 return UNW_X86_EFLAGS;
1428 xbt_die("Bad/unknown register number.");
1431 #error This architecture is not supported yet for DWARF expression evaluation.