Logo AND Algorithmique Numérique Distribuée

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