Logo AND Algorithmique Numérique Distribuée

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