Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
[mc] Remove more useless braces
[simgrid.git] / src / mc / mc_dwarf.cpp
1 /* Copyright (c) 2008-2015. The SimGrid Team.
2  * All rights reserved.                                                     */
3
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. */
6
7 #include <cinttypes>
8 #include <cstdint>
9
10 #include <algorithm>
11 #include <memory>
12
13 #include <cstdlib>
14 #define DW_LANG_Objc DW_LANG_ObjC       /* fix spelling error in older dwarf.h */
15 #include <dwarf.h>
16 #include <elfutils/libdw.h>
17
18 #include <simgrid_config.h>
19 #include "src/simgrid/util.hpp"
20 #include <xbt/log.h>
21 #include <xbt/sysdep.h>
22
23 #include "src/mc/mc_private.h"
24 #include "src/mc/mc_dwarf.hpp"
25
26 #include "src/mc/mc_object_info.h"
27 #include "src/mc/Process.hpp"
28 #include "src/mc/ObjectInformation.hpp"
29 #include "src/mc/Variable.hpp"
30
31 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_dwarf, mc, "DWARF processing");
32
33 /** \brief The default DW_TAG_lower_bound for a given DW_AT_language.
34  *
35  *  The default for a given language is defined in the DWARF spec.
36  *
37  *  \param language consant as defined by the DWARf spec
38  */
39 static uint64_t MC_dwarf_default_lower_bound(int lang);
40
41 /** \brief Computes the the element_count of a DW_TAG_enumeration_type DIE
42  *
43  * This is the number of elements in a given array dimension.
44  *
45  * A reference of the compilation unit (DW_TAG_compile_unit) is
46  * needed because the default lower bound (when there is no DW_AT_lower_bound)
47  * depends of the language of the compilation unit (DW_AT_language).
48  *
49  * \param die  DIE for the DW_TAG_enumeration_type or DW_TAG_subrange_type
50  * \param unit DIE of the DW_TAG_compile_unit
51  */
52 static uint64_t MC_dwarf_subrange_element_count(Dwarf_Die * die,
53                                                 Dwarf_Die * unit);
54
55 /** \brief Computes the number of elements of a given DW_TAG_array_type.
56  *
57  * \param die DIE for the DW_TAG_array_type
58  */
59 static uint64_t MC_dwarf_array_element_count(Dwarf_Die * die, Dwarf_Die * unit);
60
61 /** \brief Process a DIE
62  *
63  *  \param info the resulting object fot the library/binary file (output)
64  *  \param die  the current DIE
65  *  \param unit the DIE of the compile unit of the current DIE
66  *  \param frame containg frame if any
67  */
68 static void MC_dwarf_handle_die(simgrid::mc::ObjectInformation* info, Dwarf_Die * die,
69                                 Dwarf_Die * unit, simgrid::mc::Frame* frame,
70                                 const char *ns);
71
72 /** \brief Process a type DIE
73  */
74 static void MC_dwarf_handle_type_die(simgrid::mc::ObjectInformation* info, Dwarf_Die * die,
75                                      Dwarf_Die * unit, simgrid::mc::Frame* frame,
76                                      const char *ns);
77
78 /** \brief Calls MC_dwarf_handle_die on all childrend of the given die
79  *
80  *  \param info the resulting object fot the library/binary file (output)
81  *  \param die  the current DIE
82  *  \param unit the DIE of the compile unit of the current DIE
83  *  \param frame containg frame if any
84  */
85 static void MC_dwarf_handle_children(simgrid::mc::ObjectInformation* info, Dwarf_Die * die,
86                                      Dwarf_Die * unit, simgrid::mc::Frame* frame,
87                                      const char *ns);
88
89 /** \brief Handle a variable (DW_TAG_variable or other)
90  *
91  *  \param info the resulting object fot the library/binary file (output)
92  *  \param die  the current DIE
93  *  \param unit the DIE of the compile unit of the current DIE
94  *  \param frame containg frame if any
95  */
96 static void MC_dwarf_handle_variable_die(simgrid::mc::ObjectInformation* info, Dwarf_Die * die,
97                                          Dwarf_Die * unit, simgrid::mc::Frame* frame,
98                                          const char *ns);
99
100 /** \brief Get the DW_TAG_type of the DIE
101  *
102  *  \param die DIE
103  *  \return DW_TAG_type attribute as a new string (nullptr if none)
104  */
105 static std::uint64_t MC_dwarf_at_type(Dwarf_Die * die);
106
107 namespace simgrid {
108 namespace dwarf {
109
110 enum class TagClass {
111   Unknown,
112   Type,
113   Subprogram,
114   Variable,
115   Scope,
116   Namespace
117 };
118
119 /*** Class of forms defined in the DWARF standard */
120 enum class FormClass {
121   Unknown,
122   Address,   // Location in the program's address space
123   Block,     // Arbitrary block of bytes
124   Constant,
125   String,
126   Flag,      // Boolean value
127   Reference, // Reference to another DIE
128   ExprLoc,   // DWARF expression/location description
129   LinePtr,
130   LocListPtr,
131   MacPtr,
132   RangeListPtr
133 };
134
135 static
136 TagClass classify_tag(int tag)
137 {
138   switch (tag) {
139
140   case DW_TAG_array_type:
141   case DW_TAG_class_type:
142   case DW_TAG_enumeration_type:
143   case DW_TAG_typedef:
144   case DW_TAG_pointer_type:
145   case DW_TAG_reference_type:
146   case DW_TAG_rvalue_reference_type:
147   case DW_TAG_string_type:
148   case DW_TAG_structure_type:
149   case DW_TAG_subroutine_type:
150   case DW_TAG_union_type:
151   case DW_TAG_ptr_to_member_type:
152   case DW_TAG_set_type:
153   case DW_TAG_subrange_type:
154   case DW_TAG_base_type:
155   case DW_TAG_const_type:
156   case DW_TAG_file_type:
157   case DW_TAG_packed_type:
158   case DW_TAG_volatile_type:
159   case DW_TAG_restrict_type:
160   case DW_TAG_interface_type:
161   case DW_TAG_unspecified_type:
162   case DW_TAG_shared_type:
163     return TagClass::Type;
164
165   case DW_TAG_subprogram:
166     return TagClass::Subprogram;
167
168   case DW_TAG_variable:
169   case DW_TAG_formal_parameter:
170     return TagClass::Variable;
171
172   case DW_TAG_lexical_block:
173   case DW_TAG_try_block:
174   case DW_TAG_catch_block:
175   case DW_TAG_inlined_subroutine:
176   case DW_TAG_with_stmt:
177     return TagClass::Scope;
178
179   case DW_TAG_namespace:
180     return TagClass::Namespace;
181
182   default:
183     return TagClass::Unknown;
184   }
185 }
186
187 /** \brief Find the DWARF data class for a given DWARF data form
188  *
189  *  This mapping is defined in the DWARF spec.
190  *
191  *  \param form The form (values taken from the DWARF spec)
192  *  \return An internal representation for the corresponding class
193  * */
194 static
195 FormClass classify_form(int form)
196 {
197   switch (form) {
198   case DW_FORM_addr:
199     return FormClass::Address;
200   case DW_FORM_block2:
201   case DW_FORM_block4:
202   case DW_FORM_block:
203   case DW_FORM_block1:
204     return FormClass::Block;
205   case DW_FORM_data1:
206   case DW_FORM_data2:
207   case DW_FORM_data4:
208   case DW_FORM_data8:
209   case DW_FORM_udata:
210   case DW_FORM_sdata:
211     return FormClass::Constant;
212   case DW_FORM_string:
213   case DW_FORM_strp:
214     return FormClass::String;
215   case DW_FORM_ref_addr:
216   case DW_FORM_ref1:
217   case DW_FORM_ref2:
218   case DW_FORM_ref4:
219   case DW_FORM_ref8:
220   case DW_FORM_ref_udata:
221     return FormClass::Reference;
222   case DW_FORM_flag:
223   case DW_FORM_flag_present:
224     return FormClass::Flag;
225   case DW_FORM_exprloc:
226     return FormClass::ExprLoc;
227     // TODO sec offset
228     // TODO indirect
229   default:
230     return FormClass::Unknown;
231   }
232 }
233
234 /** \brief Get the name of the tag of a given DIE
235  *
236  *  \param die DIE
237  *  \return name of the tag of this DIE
238  */
239 inline XBT_PRIVATE
240 const char *tagname(Dwarf_Die * die)
241 {
242   return simgrid::dwarf::tagname(dwarf_tag(die));
243 }
244
245 }
246 }
247
248 // ***** Attributes
249
250 /** \brief Get an attribute of a given DIE as a string
251  *
252  *  \param die       the DIE
253  *  \param attribute attribute
254  *  \return value of the given attribute of the given DIE
255  */
256 static const char *MC_dwarf_attr_integrate_string(Dwarf_Die * die,
257                                                   int attribute)
258 {
259   Dwarf_Attribute attr;
260   if (!dwarf_attr_integrate(die, attribute, &attr))
261     return nullptr;
262   else
263     return dwarf_formstring(&attr);
264 }
265
266 /** \brief Get the linkage name of a DIE.
267  *
268  *  Use either DW_AT_linkage_name or DW_AT_MIPS_linkage_name.
269  *  DW_AT_linkage_name is standardized since DWARF 4.
270  *  Before this version of DWARF, the MIPS extensions
271  *  DW_AT_MIPS_linkage_name is used (at least by GCC).
272  *
273  *  \param  the DIE
274  *  \return linkage name of the given DIE (or nullptr)
275  * */
276 static const char *MC_dwarf_at_linkage_name(Dwarf_Die * die)
277 {
278   const char *name = MC_dwarf_attr_integrate_string(die, DW_AT_linkage_name);
279   if (!name)
280     name = MC_dwarf_attr_integrate_string(die, DW_AT_MIPS_linkage_name);
281   return name;
282 }
283
284 static Dwarf_Off MC_dwarf_attr_dieoffset(Dwarf_Die * die, int attribute)
285 {
286   Dwarf_Attribute attr;
287   if (dwarf_hasattr_integrate(die, attribute) == 0)
288     return 0;
289   dwarf_attr_integrate(die, attribute, &attr);
290   Dwarf_Die subtype_die;
291   if (dwarf_formref_die(&attr, &subtype_die) == nullptr)
292     xbt_die("Could not find DIE");
293   return dwarf_dieoffset(&subtype_die);
294 }
295
296 static Dwarf_Off MC_dwarf_attr_integrate_dieoffset(Dwarf_Die * die,
297                                                    int attribute)
298 {
299   Dwarf_Attribute attr;
300   if (dwarf_hasattr_integrate(die, attribute) == 0)
301     return 0;
302   dwarf_attr_integrate(die, DW_AT_type, &attr);
303   Dwarf_Die subtype_die;
304   if (dwarf_formref_die(&attr, &subtype_die) == nullptr)
305     xbt_die("Could not find DIE");
306   return dwarf_dieoffset(&subtype_die);
307 }
308
309 /** \brief Find the type/subtype (DW_AT_type) for a DIE
310  *
311  *  \param dit the DIE
312  *  \return DW_AT_type reference as a global offset in hexadecimal (or nullptr)
313  */
314 static
315 std::uint64_t MC_dwarf_at_type(Dwarf_Die * die)
316 {
317   return MC_dwarf_attr_integrate_dieoffset(die, DW_AT_type);
318 }
319
320 static uint64_t MC_dwarf_attr_integrate_addr(Dwarf_Die * die, int attribute)
321 {
322   Dwarf_Attribute attr;
323   if (dwarf_attr_integrate(die, attribute, &attr) == nullptr)
324     return 0;
325   Dwarf_Addr value;
326   if (dwarf_formaddr(&attr, &value) == 0)
327     return (uint64_t) value;
328   else
329     return 0;
330 }
331
332 static uint64_t MC_dwarf_attr_integrate_uint(Dwarf_Die * die, int attribute,
333                                              uint64_t default_value)
334 {
335   Dwarf_Attribute attr;
336   if (dwarf_attr_integrate(die, attribute, &attr) == nullptr)
337     return default_value;
338   Dwarf_Word value;
339   return dwarf_formudata(dwarf_attr_integrate(die, attribute, &attr),
340                          &value) == 0 ? (uint64_t) value : default_value;
341 }
342
343 static bool MC_dwarf_attr_flag(Dwarf_Die * die, int attribute, bool integrate)
344 {
345   Dwarf_Attribute attr;
346   if ((integrate ? dwarf_attr_integrate(die, attribute, &attr)
347        : dwarf_attr(die, attribute, &attr)) == 0)
348     return false;
349
350   bool result;
351   if (dwarf_formflag(&attr, &result))
352     xbt_die("Unexpected form for attribute %s",
353       simgrid::dwarf::attrname(attribute));
354   return result;
355 }
356
357 /** \brief Find the default lower bound for a given language
358  *
359  *  The default lower bound of an array (when DW_TAG_lower_bound
360  *  is missing) depends on the language of the compilation unit.
361  *
362  *  \param lang Language of the compilation unit (values defined in the DWARF spec)
363  *  \return     Default lower bound of an array in this compilation unit
364  * */
365 static uint64_t MC_dwarf_default_lower_bound(int lang)
366 {
367   switch (lang) {
368   case DW_LANG_C:
369   case DW_LANG_C89:
370   case DW_LANG_C99:
371   case DW_LANG_C_plus_plus:
372   case DW_LANG_D:
373   case DW_LANG_Java:
374   case DW_LANG_ObjC:
375   case DW_LANG_ObjC_plus_plus:
376   case DW_LANG_Python:
377   case DW_LANG_UPC:
378     return 0;
379   case DW_LANG_Ada83:
380   case DW_LANG_Ada95:
381   case DW_LANG_Fortran77:
382   case DW_LANG_Fortran90:
383   case DW_LANG_Fortran95:
384   case DW_LANG_Modula2:
385   case DW_LANG_Pascal83:
386   case DW_LANG_PL1:
387   case DW_LANG_Cobol74:
388   case DW_LANG_Cobol85:
389     return 1;
390   default:
391     xbt_die("No default DW_TAG_lower_bound for language %i and none given",
392             lang);
393     return 0;
394   }
395 }
396
397 /** \brief Finds the number of elements in a DW_TAG_subrange_type or DW_TAG_enumeration_type DIE
398  *
399  *  \param die  the DIE
400  *  \param unit DIE of the compilation unit
401  *  \return     number of elements in the range
402  * */
403 static uint64_t MC_dwarf_subrange_element_count(Dwarf_Die * die,
404                                                 Dwarf_Die * unit)
405 {
406   xbt_assert(dwarf_tag(die) == DW_TAG_enumeration_type
407              || dwarf_tag(die) == DW_TAG_subrange_type,
408              "MC_dwarf_subrange_element_count called with DIE of type %s",
409              simgrid::dwarf::tagname(die));
410
411   // Use DW_TAG_count if present:
412   if (dwarf_hasattr_integrate(die, DW_AT_count))
413     return MC_dwarf_attr_integrate_uint(die, DW_AT_count, 0);
414   // Otherwise compute DW_TAG_upper_bound-DW_TAG_lower_bound + 1:
415
416   if (!dwarf_hasattr_integrate(die, DW_AT_upper_bound))
417     // This is not really 0, but the code expects this (we do not know):
418     return 0;
419
420   uint64_t upper_bound =
421       MC_dwarf_attr_integrate_uint(die, DW_AT_upper_bound, -1);
422
423   uint64_t lower_bound = 0;
424   if (dwarf_hasattr_integrate(die, DW_AT_lower_bound))
425     lower_bound = MC_dwarf_attr_integrate_uint(die, DW_AT_lower_bound, -1);
426   else
427     lower_bound = MC_dwarf_default_lower_bound(dwarf_srclang(unit));
428   return upper_bound - lower_bound + 1;
429 }
430
431 /** \brief Finds the number of elements in a array type (DW_TAG_array_type)
432  *
433  *  The compilation unit might be needed because the default lower
434  *  bound depends on the language of the compilation unit.
435  *
436  *  \param die the DIE of the DW_TAG_array_type
437  *  \param unit the DIE of the compilation unit
438  *  \return number of elements in this array type
439  * */
440 static uint64_t MC_dwarf_array_element_count(Dwarf_Die * die, Dwarf_Die * unit)
441 {
442   xbt_assert(dwarf_tag(die) == DW_TAG_array_type,
443              "MC_dwarf_array_element_count called with DIE of type %s",
444              simgrid::dwarf::tagname(die));
445
446   int result = 1;
447   Dwarf_Die child;
448   int res;
449   for (res = dwarf_child(die, &child); res == 0;
450        res = dwarf_siblingof(&child, &child)) {
451     int child_tag = dwarf_tag(&child);
452     if (child_tag == DW_TAG_subrange_type
453         || child_tag == DW_TAG_enumeration_type)
454       result *= MC_dwarf_subrange_element_count(&child, unit);
455   }
456   return result;
457 }
458
459 // ***** Variable
460
461 /** Sort the variable by name and address.
462  *
463  *  We could use boost::container::flat_set instead.
464  */
465 static bool MC_compare_variable(
466   simgrid::mc::Variable const& a, simgrid::mc::Variable const& b)
467 {
468   int cmp = strcmp(a.name.c_str(), b.name.c_str());
469   if (cmp < 0)
470     return true;
471   else if (cmp > 0)
472     return false;
473   else
474     return a.address < b.address;
475 }
476
477 // ***** simgrid::mc::Type*
478
479 /** \brief Initialize the location of a member of a type
480  * (DW_AT_data_member_location of a DW_TAG_member).
481  *
482  *  \param  type   a type (struct, class)
483  *  \param  member the member of the type
484  *  \param  child  DIE of the member (DW_TAG_member)
485  */
486 static void MC_dwarf_fill_member_location(
487   simgrid::mc::Type* type, simgrid::mc::Member* member, Dwarf_Die * child)
488 {
489   if (dwarf_hasattr(child, DW_AT_data_bit_offset))
490     xbt_die("Can't groke DW_AT_data_bit_offset.");
491
492   if (!dwarf_hasattr_integrate(child, DW_AT_data_member_location)) {
493     if (type->type == DW_TAG_union_type)
494       return;
495     xbt_die
496         ("Missing DW_AT_data_member_location field in DW_TAG_member %s of type <%"
497          PRIx64 ">%s", member->name.c_str(),
498          (uint64_t) type->id, type->name.c_str());
499   }
500
501   Dwarf_Attribute attr;
502   dwarf_attr_integrate(child, DW_AT_data_member_location, &attr);
503   int form = dwarf_whatform(&attr);
504   simgrid::dwarf::FormClass form_class = simgrid::dwarf::classify_form(form);
505   switch (form_class) {
506   case simgrid::dwarf::FormClass::ExprLoc:
507   case simgrid::dwarf::FormClass::Block:
508     // Location expression:
509     {
510       Dwarf_Op *expr;
511       size_t len;
512       if (dwarf_getlocation(&attr, &expr, &len))
513         xbt_die
514             ("Could not read location expression DW_AT_data_member_location in DW_TAG_member %s of type <%"
515              PRIx64 ">%s", MC_dwarf_attr_integrate_string(child, DW_AT_name),
516              (uint64_t) type->id, type->name.c_str());
517       member->location_expression = simgrid::dwarf::DwarfExpression(expr, expr+len);
518       break;
519     }
520   case simgrid::dwarf::FormClass::Constant:
521     // Offset from the base address of the object:
522     {
523       Dwarf_Word offset;
524       if (!dwarf_formudata(&attr, &offset))
525         member->offset(offset);
526       else
527         xbt_die("Cannot get %s location <%" PRIx64 ">%s",
528                 MC_dwarf_attr_integrate_string(child, DW_AT_name),
529                 (uint64_t) type->id, type->name.c_str());
530       break;
531     }
532   case simgrid::dwarf::FormClass::LocListPtr:
533     // Reference to a location list:
534     // TODO
535   case simgrid::dwarf::FormClass::Reference:
536     // It's supposed to be possible in DWARF2 but I couldn't find its semantic
537     // in the spec.
538   default:
539     xbt_die("Can't handle form class (%i) / form 0x%x as DW_AT_member_location",
540             (int) form_class, form);
541   }
542
543 }
544
545 /** \brief Populate the list of members of a type
546  *
547  *  \param info ELF object containing the type DIE
548  *  \param die  DIE of the type
549  *  \param unit DIE of the compilation unit containing the type DIE
550  *  \param type the type
551  */
552 static void MC_dwarf_add_members(simgrid::mc::ObjectInformation* info, Dwarf_Die * die,
553                                  Dwarf_Die * unit, simgrid::mc::Type* type)
554 {
555   int res;
556   Dwarf_Die child;
557   xbt_assert(type->members.empty());
558   for (res = dwarf_child(die, &child); res == 0;
559        res = dwarf_siblingof(&child, &child)) {
560     int tag = dwarf_tag(&child);
561     if (tag == DW_TAG_member || tag == DW_TAG_inheritance) {
562
563       // Skip declarations:
564       if (MC_dwarf_attr_flag(&child, DW_AT_declaration, false))
565         continue;
566
567       // Skip compile time constants:
568       if (dwarf_hasattr(&child, DW_AT_const_value))
569         continue;
570
571       // TODO, we should use another type (because is is not a type but a member)
572       simgrid::mc::Member member;
573       member.inheritance = tag == DW_TAG_inheritance;
574
575       const char *name = MC_dwarf_attr_integrate_string(&child, DW_AT_name);
576       if (name)
577         member.name = name;
578       member.byte_size =
579           MC_dwarf_attr_integrate_uint(&child, DW_AT_byte_size, 0);
580       member.type_id = MC_dwarf_at_type(&child);
581
582       if (dwarf_hasattr(&child, DW_AT_data_bit_offset))
583         xbt_die("Can't groke DW_AT_data_bit_offset.");
584
585       MC_dwarf_fill_member_location(type, &member, &child);
586
587       if (!member.type_id)
588         xbt_die("Missing type for member %s of <%" PRIx64 ">%s",
589                 member.name.c_str(),
590                 (uint64_t) type->id, type->name.c_str());
591
592       type->members.push_back(std::move(member));
593     }
594   }
595 }
596
597 /** \brief Create a MC type object from a DIE
598  *
599  *  \param info current object info object
600  *  \param DIE (for a given type);
601  *  \param unit compilation unit of the current DIE
602  *  \return MC representation of the type
603  */
604 static simgrid::mc::Type MC_dwarf_die_to_type(
605   simgrid::mc::ObjectInformation* info, Dwarf_Die * die,
606   Dwarf_Die * unit, simgrid::mc::Frame* frame,
607   const char *ns)
608 {
609   simgrid::mc::Type type;
610   type.type = dwarf_tag(die);
611   type.name = std::string();
612   type.element_count = -1;
613
614   // Global Offset
615   type.id = dwarf_dieoffset(die);
616
617   const char *prefix = "";
618   switch (type.type) {
619   case DW_TAG_structure_type:
620     prefix = "struct ";
621     break;
622   case DW_TAG_union_type:
623     prefix = "union ";
624     break;
625   case DW_TAG_class_type:
626     prefix = "class ";
627     break;
628   default:
629     prefix = "";
630   }
631
632   const char *name = MC_dwarf_attr_integrate_string(die, DW_AT_name);
633   if (name != nullptr) {
634     char* full_name = ns ? bprintf("%s%s::%s", prefix, ns, name) :
635       bprintf("%s%s", prefix, name);
636     type.name = std::string(full_name);
637     free(full_name);
638   }
639
640   type.type_id = MC_dwarf_at_type(die);
641
642   // Some compilers do not emit DW_AT_byte_size for pointer_type,
643   // so we fill this. We currently assume that the model-checked process is in
644   // the same architecture..
645   if (type.type == DW_TAG_pointer_type)
646     type.byte_size = sizeof(void*);
647
648   // Computation of the byte_size;
649   if (dwarf_hasattr_integrate(die, DW_AT_byte_size))
650     type.byte_size = MC_dwarf_attr_integrate_uint(die, DW_AT_byte_size, 0);
651   else if (type.type == DW_TAG_array_type
652            || type.type == DW_TAG_structure_type
653            || type.type == DW_TAG_class_type) {
654     Dwarf_Word size;
655     if (dwarf_aggregate_size(die, &size) == 0)
656       type.byte_size = size;
657   }
658
659   switch (type.type) {
660   case DW_TAG_array_type:
661     type.element_count = MC_dwarf_array_element_count(die, unit);
662     // TODO, handle DW_byte_stride and (not) DW_bit_stride
663     break;
664
665   case DW_TAG_pointer_type:
666   case DW_TAG_reference_type:
667   case DW_TAG_rvalue_reference_type:
668     break;
669
670   case DW_TAG_structure_type:
671   case DW_TAG_union_type:
672   case DW_TAG_class_type:
673     MC_dwarf_add_members(info, die, unit, &type);
674     char *new_ns = ns == nullptr ? xbt_strdup(type.name.c_str())
675         : bprintf("%s::%s", ns, name);
676     MC_dwarf_handle_children(info, die, unit, frame, new_ns);
677     free(new_ns);
678     break;
679   }
680
681   return std::move(type);
682 }
683
684 static void MC_dwarf_handle_type_die(simgrid::mc::ObjectInformation* info, Dwarf_Die * die,
685                                      Dwarf_Die * unit, simgrid::mc::Frame* frame,
686                                      const char *ns)
687 {
688   simgrid::mc::Type type = MC_dwarf_die_to_type(info, die, unit, frame, ns);
689   auto& t = (info->types[type.id] = std::move(type));
690   if (!t.name.empty() && type.byte_size != 0)
691     info->full_types_by_name[t.name] = &t;
692 }
693
694 static int mc_anonymous_variable_index = 0;
695
696 static std::unique_ptr<simgrid::mc::Variable> MC_die_to_variable(
697   simgrid::mc::ObjectInformation* info, Dwarf_Die * die,
698   Dwarf_Die * unit, simgrid::mc::Frame* frame,
699   const char *ns)
700 {
701   // Skip declarations:
702   if (MC_dwarf_attr_flag(die, DW_AT_declaration, false))
703     return nullptr;
704
705   // Skip compile time constants:
706   if (dwarf_hasattr(die, DW_AT_const_value))
707     return nullptr;
708
709   Dwarf_Attribute attr_location;
710   if (dwarf_attr(die, DW_AT_location, &attr_location) == nullptr)
711     // No location: do not add it ?
712     return nullptr;
713
714   std::unique_ptr<simgrid::mc::Variable> variable =
715     std::unique_ptr<simgrid::mc::Variable>(new simgrid::mc::Variable());
716   variable->dwarf_offset = dwarf_dieoffset(die);
717   variable->global = frame == nullptr;     // Can be override base on DW_AT_location
718   variable->object_info = info;
719
720   const char *name = MC_dwarf_attr_integrate_string(die, DW_AT_name);
721   if (name)
722     variable->name = name;
723   variable->type_id = MC_dwarf_at_type(die);
724
725   int form = dwarf_whatform(&attr_location);
726   simgrid::dwarf::FormClass form_class;
727   if (form == DW_FORM_sec_offset)
728     form_class = simgrid::dwarf::FormClass::Constant;
729   else
730     form_class = simgrid::dwarf::classify_form(form);
731   switch (form_class) {
732   case simgrid::dwarf::FormClass::ExprLoc:
733   case simgrid::dwarf::FormClass::Block:
734     // Location expression:
735     {
736       Dwarf_Op *expr;
737       size_t len;
738       if (dwarf_getlocation(&attr_location, &expr, &len)) {
739         xbt_die(
740           "Could not read location expression in DW_AT_location "
741           "of variable <%" PRIx64 ">%s",
742           (uint64_t) variable->dwarf_offset,
743           variable->name.c_str());
744       }
745
746       if (len == 1 && expr[0].atom == DW_OP_addr) {
747         variable->global = 1;
748         uintptr_t offset = (uintptr_t) expr[0].number;
749         uintptr_t base = (uintptr_t) info->base_address();
750         variable->address = (void *) (base + offset);
751       } else
752         variable->location_list = {
753           simgrid::dwarf::DwarfExpression(expr, expr + len) };
754
755       break;
756     }
757
758   case simgrid::dwarf::FormClass::LocListPtr:
759   case simgrid::dwarf::FormClass::Constant:
760     // Reference to location list:
761     variable->location_list = simgrid::dwarf::location_list(
762       *info, attr_location);
763     break;
764
765   default:
766     xbt_die("Unexpected form 0x%x (%i), class 0x%x (%i) list for location "
767             "in <%" PRIx64 ">%s",
768             form, form, (int) form_class, (int) form_class,
769             (uint64_t) variable->dwarf_offset,
770             variable->name.c_str());
771   }
772
773   // Handle start_scope:
774   if (dwarf_hasattr(die, DW_AT_start_scope)) {
775     Dwarf_Attribute attr;
776     dwarf_attr(die, DW_AT_start_scope, &attr);
777     int form = dwarf_whatform(&attr);
778     simgrid::dwarf::FormClass form_class = simgrid::dwarf::classify_form(form);
779     switch (form_class) {
780     case simgrid::dwarf::FormClass::Constant:
781       {
782         Dwarf_Word value;
783         variable->start_scope =
784             dwarf_formudata(&attr, &value) == 0 ? (size_t) value : 0;
785         break;
786       }
787
788     case simgrid::dwarf::FormClass::RangeListPtr:     // TODO
789     default:
790       xbt_die
791           ("Unhandled form 0x%x, class 0x%X for DW_AT_start_scope of variable %s",
792            form, (int) form_class, name == nullptr ? "?" : name);
793     }
794   }
795
796   if (ns && variable->global)
797     variable->name =
798       std::string(ns) + "::" + variable->name;
799
800   // The current code needs a variable name,
801   // generate a fake one:
802   if (variable->name.empty())
803     variable->name =
804       "@anonymous#" + std::to_string(mc_anonymous_variable_index++);
805
806   return std::move(variable);
807 }
808
809 static void MC_dwarf_handle_variable_die(simgrid::mc::ObjectInformation* info, Dwarf_Die * die,
810                                          Dwarf_Die * unit, simgrid::mc::Frame* frame,
811                                          const char *ns)
812 {
813   std::unique_ptr<simgrid::mc::Variable> variable =
814     MC_die_to_variable(info, die, unit, frame, ns);
815   if (!variable)
816     return;
817   // Those arrays are sorted later:
818   else if (variable->global)
819     info->global_variables.push_back(std::move(*variable));
820   else if (frame != nullptr)
821     frame->variables.push_back(std::move(*variable));
822   else
823     xbt_die("No frame for this local variable");
824 }
825
826 static void MC_dwarf_handle_scope_die(simgrid::mc::ObjectInformation* info, Dwarf_Die * die,
827                                       Dwarf_Die * unit, simgrid::mc::Frame* parent_frame,
828                                       const char *ns)
829 {
830   // TODO, handle DW_TAG_type/DW_TAG_location for DW_TAG_with_stmt
831   int tag = dwarf_tag(die);
832   simgrid::dwarf::TagClass klass = simgrid::dwarf::classify_tag(tag);
833
834   // (Template) Subprogram declaration:
835   if (klass == simgrid::dwarf::TagClass::Subprogram
836       && MC_dwarf_attr_flag(die, DW_AT_declaration, false))
837     return;
838
839   if (klass == simgrid::dwarf::TagClass::Scope)
840     xbt_assert(parent_frame, "No parent scope for this scope");
841
842   simgrid::mc::Frame frame;
843   frame.tag = tag;
844   frame.id = dwarf_dieoffset(die);
845   frame.object_info = info;
846
847   if (klass == simgrid::dwarf::TagClass::Subprogram) {
848     const char *name = MC_dwarf_attr_integrate_string(die, DW_AT_name);
849     if (ns)
850       frame.name  = std::string(ns) + "::" + name;
851     else if (name)
852       frame.name = name;
853   }
854
855   frame.abstract_origin_id =
856     MC_dwarf_attr_dieoffset(die, DW_AT_abstract_origin);
857
858   // This is the base address for DWARF addresses.
859   // Relocated addresses are offset from this base address.
860   // See DWARF4 spec 7.5
861   std::uint64_t base = (std::uint64_t) info->base_address();
862
863   // TODO, support DW_AT_ranges
864   uint64_t low_pc = MC_dwarf_attr_integrate_addr(die, DW_AT_low_pc);
865   frame.range.begin() = low_pc ? (std::uint64_t) base + low_pc : 0;
866   if (low_pc) {
867     // DW_AT_high_pc:
868     Dwarf_Attribute attr;
869     if (!dwarf_attr_integrate(die, DW_AT_high_pc, &attr))
870       xbt_die("Missing DW_AT_high_pc matching with DW_AT_low_pc");
871
872     Dwarf_Sword offset;
873     Dwarf_Addr high_pc;
874
875     switch (simgrid::dwarf::classify_form(dwarf_whatform(&attr))) {
876
877       // DW_AT_high_pc if an offset from the low_pc:
878     case simgrid::dwarf::FormClass::Constant:
879
880       if (dwarf_formsdata(&attr, &offset) != 0)
881         xbt_die("Could not read constant");
882       frame.range.end() = frame.range.begin() + offset;
883       break;
884
885       // DW_AT_high_pc is a relocatable address:
886     case simgrid::dwarf::FormClass::Address:
887       if (dwarf_formaddr(&attr, &high_pc) != 0)
888         xbt_die("Could not read address");
889       frame.range.begin() = base + high_pc;
890       break;
891
892     default:
893       xbt_die("Unexpected class for DW_AT_high_pc");
894
895     }
896   }
897
898   if (klass == simgrid::dwarf::TagClass::Subprogram) {
899     Dwarf_Attribute attr_frame_base;
900     if (dwarf_attr_integrate(die, DW_AT_frame_base, &attr_frame_base))
901       frame.frame_base_location = simgrid::dwarf::location_list(*info,
902                                   attr_frame_base);
903   }
904
905   // Handle children:
906   MC_dwarf_handle_children(info, die, unit, &frame, ns);
907
908   // We sort them in order to have an (somewhat) efficient by name
909   // lookup:
910   std::sort(frame.variables.begin(), frame.variables.end(),
911     MC_compare_variable);
912
913   // Register it:
914   if (klass == simgrid::dwarf::TagClass::Subprogram)
915     info->subprograms[frame.id] = std::move(frame);
916   else if (klass == simgrid::dwarf::TagClass::Scope)
917     parent_frame->scopes.push_back(std::move(frame));
918 }
919
920 static void mc_dwarf_handle_namespace_die(simgrid::mc::ObjectInformation* info,
921                                           Dwarf_Die * die, Dwarf_Die * unit,
922                                           simgrid::mc::Frame* frame,
923                                           const char *ns)
924 {
925   const char *name = MC_dwarf_attr_integrate_string(die, DW_AT_name);
926   if (frame)
927     xbt_die("Unexpected namespace in a subprogram");
928   char *new_ns = ns == nullptr ? xbt_strdup(name)
929       : bprintf("%s::%s", ns, name);
930   MC_dwarf_handle_children(info, die, unit, frame, new_ns);
931   xbt_free(new_ns);
932 }
933
934 static void MC_dwarf_handle_children(simgrid::mc::ObjectInformation* info, Dwarf_Die * die,
935                                      Dwarf_Die * unit, simgrid::mc::Frame* frame,
936                                      const char *ns)
937 {
938   // For each child DIE:
939   Dwarf_Die child;
940   int res;
941   for (res = dwarf_child(die, &child); res == 0;
942        res = dwarf_siblingof(&child, &child))
943     MC_dwarf_handle_die(info, &child, unit, frame, ns);
944 }
945
946 static void MC_dwarf_handle_die(simgrid::mc::ObjectInformation* info, Dwarf_Die * die,
947                                 Dwarf_Die * unit, simgrid::mc::Frame* frame,
948                                 const char *ns)
949 {
950   int tag = dwarf_tag(die);
951   simgrid::dwarf::TagClass klass = simgrid::dwarf::classify_tag(tag);
952   switch (klass) {
953
954     // Type:
955   case simgrid::dwarf::TagClass::Type:
956     MC_dwarf_handle_type_die(info, die, unit, frame, ns);
957     break;
958
959     // Subprogram or scope:
960   case simgrid::dwarf::TagClass::Subprogram:
961   case simgrid::dwarf::TagClass::Scope:
962     MC_dwarf_handle_scope_die(info, die, unit, frame, ns);
963     return;
964
965     // Variable:
966   case simgrid::dwarf::TagClass::Variable:
967     MC_dwarf_handle_variable_die(info, die, unit, frame, ns);
968     break;
969
970   case simgrid::dwarf::TagClass::Namespace:
971     mc_dwarf_handle_namespace_die(info, die, unit, frame, ns);
972     break;
973
974   default:
975     break;
976
977   }
978 }
979
980 static
981 Elf64_Half MC_dwarf_elf_type(Dwarf* dwarf)
982 {
983   Elf* elf = dwarf_getelf(dwarf);
984   Elf64_Ehdr* ehdr64 = elf64_getehdr(elf);
985   if (ehdr64)
986     return ehdr64->e_type;
987   Elf32_Ehdr* ehdr32 = elf32_getehdr(elf);
988   if (ehdr32)
989     return ehdr32->e_type;
990   xbt_die("Could not get ELF heeader");
991 }
992
993 /** \brief Populate the debugging informations of the given ELF object
994  *
995  *  Read the DWARf information of the EFFL object and populate the
996  *  lists of types, variables, functions.
997  */
998 static
999 void MC_dwarf_get_variables(simgrid::mc::ObjectInformation* info)
1000 {
1001   int fd = open(info->file_name.c_str(), O_RDONLY);
1002   if (fd < 0)
1003     xbt_die("Could not open file %s", info->file_name.c_str());
1004   Dwarf *dwarf = dwarf_begin(fd, DWARF_C_READ);
1005   if (dwarf == nullptr)
1006     xbt_die("Missing debugging information in %s\n"
1007       "Your program and its dependencies must have debugging information.\n"
1008       "You might want to recompile with -g or install the suitable debugging package.\n",
1009       info->file_name.c_str());
1010
1011   Elf64_Half elf_type = MC_dwarf_elf_type(dwarf);
1012   if (elf_type == ET_EXEC)
1013     info->flags |= simgrid::mc::ObjectInformation::Executable;
1014
1015   // For each compilation unit:
1016   Dwarf_Off offset = 0;
1017   Dwarf_Off next_offset = 0;
1018   size_t length;
1019
1020   while (dwarf_nextcu(dwarf, offset, &next_offset, &length, nullptr, NULL, NULL) ==
1021          0) {
1022     Dwarf_Die unit_die;
1023     if (dwarf_offdie(dwarf, offset + length, &unit_die) != nullptr)
1024       MC_dwarf_handle_children(info, &unit_die, &unit_die, nullptr, NULL);
1025     offset = next_offset;
1026   }
1027
1028   dwarf_end(dwarf);
1029   close(fd);
1030 }
1031
1032 // ***** Functions index
1033
1034 static int MC_compare_frame_index_items(simgrid::mc::FunctionIndexEntry* a,
1035                                         simgrid::mc::FunctionIndexEntry* b)
1036 {
1037   if (a->low_pc < b->low_pc)
1038     return -1;
1039   else if (a->low_pc == b->low_pc)
1040     return 0;
1041   else
1042     return 1;
1043 }
1044
1045 static void MC_make_functions_index(simgrid::mc::ObjectInformation* info)
1046 {
1047   info->functions_index.clear();
1048
1049   for (auto& e : info->subprograms) {
1050     if (e.second.range.begin() == 0)
1051       continue;
1052     simgrid::mc::FunctionIndexEntry entry;
1053     entry.low_pc = (void*) e.second.range.begin();
1054     entry.function = &e.second;
1055     info->functions_index.push_back(entry);
1056   }
1057
1058   info->functions_index.shrink_to_fit();
1059
1060   // Sort the array by low_pc:
1061   std::sort(info->functions_index.begin(), info->functions_index.end(),
1062         [](simgrid::mc::FunctionIndexEntry const& a,
1063           simgrid::mc::FunctionIndexEntry const& b)
1064         {
1065           return a.low_pc < b.low_pc;
1066         });
1067 }
1068
1069 static void MC_post_process_variables(simgrid::mc::ObjectInformation* info)
1070 {
1071   // Someone needs this to be sorted but who?
1072   std::sort(info->global_variables.begin(), info->global_variables.end(),
1073     MC_compare_variable);
1074
1075   for(simgrid::mc::Variable& variable : info->global_variables)
1076     if (variable.type_id)
1077       variable.type = simgrid::util::find_map_ptr(
1078         info->types, variable.type_id);
1079 }
1080
1081 static void mc_post_process_scope(simgrid::mc::ObjectInformation* info, simgrid::mc::Frame* scope)
1082 {
1083
1084   if (scope->tag == DW_TAG_inlined_subroutine) {
1085     // Attach correct namespaced name in inlined subroutine:
1086     auto i = info->subprograms.find(scope->abstract_origin_id);
1087     xbt_assert(i != info->subprograms.end(),
1088       "Could not lookup abstract origin %" PRIx64,
1089       (std::uint64_t) scope->abstract_origin_id);
1090     scope->name = i->second.name;
1091   }
1092
1093   // Direct:
1094   for (simgrid::mc::Variable& variable : scope->variables)
1095     if (variable.type_id)
1096       variable.type = simgrid::util::find_map_ptr(
1097         info->types, variable.type_id);
1098
1099   // Recursive post-processing of nested-scopes:
1100   for (simgrid::mc::Frame& nested_scope : scope->scopes)
1101       mc_post_process_scope(info, &nested_scope);
1102
1103 }
1104
1105 static
1106 simgrid::mc::Type* MC_resolve_type(
1107   simgrid::mc::ObjectInformation* info, unsigned type_id)
1108 {
1109   if (!type_id)
1110     return nullptr;
1111   simgrid::mc::Type* type = simgrid::util::find_map_ptr(info->types, type_id);
1112   if (type == nullptr)
1113     return nullptr;
1114
1115   // We already have the information on the type:
1116   if (type->byte_size != 0)
1117     return type;
1118
1119   // Don't have a name, we can't find a more complete version:
1120   if (type->name.empty())
1121     return type;
1122
1123   // Try to find a more complete description of the type:
1124   // We need to fix in order to support C++.
1125   simgrid::mc::Type** subtype = simgrid::util::find_map_ptr(
1126     info->full_types_by_name, type->name);
1127   if (subtype)
1128     type = *subtype;
1129   return type;
1130 }
1131
1132 static void MC_post_process_types(simgrid::mc::ObjectInformation* info)
1133 {
1134   // Lookup "subtype" field:
1135   for(auto& i : info->types) {
1136     i.second.subtype = MC_resolve_type(info, i.second.type_id);
1137     for (simgrid::mc::Member& member : i.second.members)
1138       member.type = MC_resolve_type(info, member.type_id);
1139   }
1140 }
1141
1142 /** \brief Finds informations about a given shared object/executable */
1143 std::shared_ptr<simgrid::mc::ObjectInformation> MC_find_object_info(
1144   std::vector<simgrid::xbt::VmMap> const& maps, const char *name)
1145 {
1146   std::shared_ptr<simgrid::mc::ObjectInformation> result =
1147     std::make_shared<simgrid::mc::ObjectInformation>();
1148   result->file_name = name;
1149   simgrid::mc::find_object_address(maps, result.get());
1150   MC_dwarf_get_variables(result.get());
1151   MC_post_process_variables(result.get());
1152   MC_post_process_types(result.get());
1153   for (auto& entry : result.get()->subprograms)
1154     mc_post_process_scope(result.get(), &entry.second);
1155   MC_make_functions_index(result.get());
1156   return std::move(result);
1157 }
1158
1159 /*************************************************************************/
1160
1161 void MC_post_process_object_info(simgrid::mc::Process* process, simgrid::mc::ObjectInformation* info)
1162 {
1163   for (auto& i : info->types) {
1164
1165     simgrid::mc::Type* type = &(i.second);
1166     simgrid::mc::Type* subtype = type;
1167     while (subtype->type == DW_TAG_typedef
1168         || subtype->type == DW_TAG_volatile_type
1169         || subtype->type == DW_TAG_const_type)
1170       if (subtype->subtype)
1171         subtype = subtype->subtype;
1172       else
1173         break;
1174
1175     // Resolve full_type:
1176     if (!subtype->name.empty() && subtype->byte_size == 0)
1177       for (auto const& object_info : process->object_infos) {
1178         auto i = object_info->full_types_by_name.find(subtype->name);
1179         if (i != object_info->full_types_by_name.end()
1180             && !i->second->name.empty() && i->second->byte_size) {
1181           type->full_type = i->second;
1182           break;
1183         }
1184       }
1185     else type->full_type = subtype;
1186
1187   }
1188 }
1189
1190 namespace simgrid {
1191 namespace dwarf {
1192
1193 /** Convert a DWARF register into a libunwind register
1194  *
1195  *  DWARF and libunwind does not use the same convention for numbering the
1196  *  registers on some architectures. The function makes the necessary
1197  *  convertion.
1198  */
1199 int dwarf_register_to_libunwind(int dwarf_register)
1200 {
1201 #if defined(__x86_64__)
1202   // It seems for this arch, DWARF and libunwind agree in the numbering:
1203   return dwarf_register;
1204 #elif defined(__i386__)
1205   // Could't find the authoritative source of information for this.
1206   // This is inspired from http://source.winehq.org/source/dlls/dbghelp/cpu_i386.c#L517.
1207   switch (dwarf_register) {
1208   case 0:
1209     return UNW_X86_EAX;
1210   case 1:
1211     return UNW_X86_ECX;
1212   case 2:
1213     return UNW_X86_EDX;
1214   case 3:
1215     return UNW_X86_EBX;
1216   case 4:
1217     return UNW_X86_ESP;
1218   case 5:
1219     return UNW_X86_EBP;
1220   case 6:
1221     return UNW_X86_ESI;
1222   case 7:
1223     return UNW_X86_EDI;
1224   case 8:
1225     return UNW_X86_EIP;
1226   case 9:
1227     return UNW_X86_EFLAGS;
1228   case 10:
1229     return UNW_X86_CS;
1230   case 11:
1231     return UNW_X86_SS;
1232   case 12:
1233     return UNW_X86_DS;
1234   case 13:
1235     return UNW_X86_ES;
1236   case 14:
1237     return UNW_X86_FS;
1238   case 15:
1239     return UNW_X86_GS;
1240   case 16:
1241     return UNW_X86_ST0;
1242   case 17:
1243     return UNW_X86_ST1;
1244   case 18:
1245     return UNW_X86_ST2;
1246   case 19:
1247     return UNW_X86_ST3;
1248   case 20:
1249     return UNW_X86_ST4;
1250   case 21:
1251     return UNW_X86_ST5;
1252   case 22:
1253     return UNW_X86_ST6;
1254   case 23:
1255     return UNW_X86_ST7;
1256   default:
1257     xbt_die("Bad/unknown register number.");
1258   }
1259 #else
1260 #error This architecture is not supported yet for DWARF expression evaluation.
1261 #endif
1262 }
1263
1264 }
1265 }