Logo AND Algorithmique Numérique Distribuée

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