Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
b806b0e00a29649908dab707aee634691c2004a8
[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 <stdlib.h>
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 #include "mc_process.h"
28
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(simgrid::mc::Type* type, simgrid::mc::Type* member,
479                                           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       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::Type member;
565       member.type = tag;
566
567       // Global Offset:
568       member.id = dwarf_dieoffset(&child);
569
570       const char *name = MC_dwarf_attr_integrate_string(&child, DW_AT_name);
571       if (name)
572         member.name = name;
573       member.byte_size =
574           MC_dwarf_attr_integrate_uint(&child, DW_AT_byte_size, 0);
575       member.element_count = -1;
576       member.type_id = MC_dwarf_at_type(&child);
577
578       if (dwarf_hasattr(&child, DW_AT_data_bit_offset))
579         xbt_die("Can't groke DW_AT_data_bit_offset.");
580
581       MC_dwarf_fill_member_location(type, &member, &child);
582
583       if (!member.type_id)
584         xbt_die("Missing type for member %s of <%" PRIx64 ">%s",
585                 member.name.c_str(),
586                 (uint64_t) type->id, type->name.c_str());
587
588       type->members.push_back(std::move(member));
589     }
590   }
591 }
592
593 /** \brief Create a MC type object from a DIE
594  *
595  *  \param info current object info object
596  *  \param DIE (for a given type);
597  *  \param unit compilation unit of the current DIE
598  *  \return MC representation of the type
599  */
600 static simgrid::mc::Type MC_dwarf_die_to_type(
601   simgrid::mc::ObjectInformation* info, Dwarf_Die * die,
602   Dwarf_Die * unit, simgrid::mc::Frame* frame,
603   const char *ns)
604 {
605   simgrid::mc::Type type;
606   type.type = dwarf_tag(die);
607   type.name = std::string();
608   type.element_count = -1;
609
610   // Global Offset
611   type.id = dwarf_dieoffset(die);
612
613   const char *prefix = "";
614   switch (type.type) {
615   case DW_TAG_structure_type:
616     prefix = "struct ";
617     break;
618   case DW_TAG_union_type:
619     prefix = "union ";
620     break;
621   case DW_TAG_class_type:
622     prefix = "class ";
623     break;
624   default:
625     prefix = "";
626   }
627
628   const char *name = MC_dwarf_attr_integrate_string(die, DW_AT_name);
629   if (name != NULL) {
630     char* full_name = ns ? bprintf("%s%s::%s", prefix, ns, name) :
631       bprintf("%s%s", prefix, name);
632     type.name = std::string(full_name);
633     free(full_name);
634   }
635
636   type.type_id = MC_dwarf_at_type(die);
637
638   // Some compilers do not emit DW_AT_byte_size for pointer_type,
639   // so we fill this. We currently assume that the model-checked process is in
640   // the same architecture..
641   if (type.type == DW_TAG_pointer_type)
642     type.byte_size = sizeof(void*);
643
644   // Computation of the byte_size;
645   if (dwarf_hasattr_integrate(die, DW_AT_byte_size))
646     type.byte_size = MC_dwarf_attr_integrate_uint(die, DW_AT_byte_size, 0);
647   else if (type.type == DW_TAG_array_type
648            || type.type == DW_TAG_structure_type
649            || type.type == DW_TAG_class_type) {
650     Dwarf_Word size;
651     if (dwarf_aggregate_size(die, &size) == 0)
652       type.byte_size = size;
653   }
654
655   switch (type.type) {
656   case DW_TAG_array_type:
657     type.element_count = MC_dwarf_array_element_count(die, unit);
658     // TODO, handle DW_byte_stride and (not) DW_bit_stride
659     break;
660
661   case DW_TAG_pointer_type:
662   case DW_TAG_reference_type:
663   case DW_TAG_rvalue_reference_type:
664     type.is_pointer_type = 1;
665     break;
666
667   case DW_TAG_structure_type:
668   case DW_TAG_union_type:
669   case DW_TAG_class_type:
670     MC_dwarf_add_members(info, die, unit, &type);
671     char *new_ns = ns == NULL ? xbt_strdup(type.name.c_str())
672         : bprintf("%s::%s", ns, name);
673     MC_dwarf_handle_children(info, die, unit, frame, new_ns);
674     free(new_ns);
675     break;
676   }
677
678   return std::move(type);
679 }
680
681 static void MC_dwarf_handle_type_die(simgrid::mc::ObjectInformation* info, Dwarf_Die * die,
682                                      Dwarf_Die * unit, simgrid::mc::Frame* frame,
683                                      const char *ns)
684 {
685   simgrid::mc::Type type = MC_dwarf_die_to_type(info, die, unit, frame, ns);
686   auto& t = (info->types[type.id] = std::move(type));
687   if (!t.name.empty() && type.byte_size != 0)
688     info->full_types_by_name[t.name] = &t;
689 }
690
691 static int mc_anonymous_variable_index = 0;
692
693 static std::unique_ptr<simgrid::mc::Variable> MC_die_to_variable(
694   simgrid::mc::ObjectInformation* info, Dwarf_Die * die,
695   Dwarf_Die * unit, simgrid::mc::Frame* frame,
696   const char *ns)
697 {
698   // Skip declarations:
699   if (MC_dwarf_attr_flag(die, DW_AT_declaration, false))
700     return nullptr;
701
702   // Skip compile time constants:
703   if (dwarf_hasattr(die, DW_AT_const_value))
704     return nullptr;
705
706   Dwarf_Attribute attr_location;
707   if (dwarf_attr(die, DW_AT_location, &attr_location) == NULL)
708     // No location: do not add it ?
709     return nullptr;
710
711   std::unique_ptr<simgrid::mc::Variable> variable =
712     std::unique_ptr<simgrid::mc::Variable>(new simgrid::mc::Variable());
713   variable->dwarf_offset = dwarf_dieoffset(die);
714   variable->global = frame == NULL;     // Can be override base on DW_AT_location
715   variable->object_info = info;
716
717   const char *name = MC_dwarf_attr_integrate_string(die, DW_AT_name);
718   if (name)
719     variable->name = name;
720   variable->type_id = MC_dwarf_at_type(die);
721
722   int form = dwarf_whatform(&attr_location);
723   int klass =
724       form ==
725       DW_FORM_sec_offset ? MC_DW_CLASS_CONSTANT : MC_dwarf_form_get_class(form);
726   switch (klass) {
727   case MC_DW_CLASS_EXPRLOC:
728   case MC_DW_CLASS_BLOCK:
729     // Location expression:
730     {
731       Dwarf_Op *expr;
732       size_t len;
733       if (dwarf_getlocation(&attr_location, &expr, &len)) {
734         xbt_die(
735           "Could not read location expression in DW_AT_location "
736           "of variable <%" PRIx64 ">%s",
737           (uint64_t) variable->dwarf_offset,
738           variable->name.c_str());
739       }
740
741       if (len == 1 && expr[0].atom == DW_OP_addr) {
742         variable->global = 1;
743         uintptr_t offset = (uintptr_t) expr[0].number;
744         uintptr_t base = (uintptr_t) info->base_address();
745         variable->address = (void *) (base + offset);
746       } else {
747         simgrid::mc::LocationListEntry entry;
748         entry.expression = {expr, expr + len};
749         variable->location_list = { std::move(entry) };
750       }
751
752       break;
753     }
754   case MC_DW_CLASS_LOCLISTPTR:
755   case MC_DW_CLASS_CONSTANT:
756     // Reference to location list:
757     mc_dwarf_location_list_init(
758       &variable->location_list, info, die,
759       &attr_location);
760     break;
761   default:
762     xbt_die("Unexpected form 0x%x (%i), class 0x%x (%i) list for location "
763             "in <%" PRIx64 ">%s",
764             form, form, klass, klass,
765             (uint64_t) variable->dwarf_offset,
766             variable->name.c_str());
767   }
768
769   // Handle start_scope:
770   if (dwarf_hasattr(die, DW_AT_start_scope)) {
771     Dwarf_Attribute attr;
772     dwarf_attr(die, DW_AT_start_scope, &attr);
773     int form = dwarf_whatform(&attr);
774     int klass = MC_dwarf_form_get_class(form);
775     switch (klass) {
776     case MC_DW_CLASS_CONSTANT:
777       {
778         Dwarf_Word value;
779         variable->start_scope =
780             dwarf_formudata(&attr, &value) == 0 ? (size_t) value : 0;
781         break;
782       }
783     case MC_DW_CLASS_RANGELISTPTR:     // TODO
784     default:
785       xbt_die
786           ("Unhandled form 0x%x, class 0x%X for DW_AT_start_scope of variable %s",
787            form, klass, name == NULL ? "?" : name);
788     }
789   }
790
791   if (ns && variable->global)
792     variable->name =
793       std::string(ns) + "::" + variable->name;
794
795   // The current code needs a variable name,
796   // generate a fake one:
797   if (variable->name.empty())
798     variable->name =
799       "@anonymous#" + std::to_string(mc_anonymous_variable_index++);
800
801   return std::move(variable);
802 }
803
804 static void MC_dwarf_handle_variable_die(simgrid::mc::ObjectInformation* info, Dwarf_Die * die,
805                                          Dwarf_Die * unit, simgrid::mc::Frame* frame,
806                                          const char *ns)
807 {
808   std::unique_ptr<simgrid::mc::Variable> variable =
809     MC_die_to_variable(info, die, unit, frame, ns);
810   if (!variable)
811     return;
812   // Those arrays are sorted later:
813   else if (variable->global)
814     info->global_variables.push_back(std::move(*variable));
815   else if (frame != nullptr)
816     frame->variables.push_back(std::move(*variable));
817   else
818     xbt_die("No frame for this local variable");
819 }
820
821 static void MC_dwarf_handle_scope_die(simgrid::mc::ObjectInformation* info, Dwarf_Die * die,
822                                       Dwarf_Die * unit, simgrid::mc::Frame* parent_frame,
823                                       const char *ns)
824 {
825   // TODO, handle DW_TAG_type/DW_TAG_location for DW_TAG_with_stmt
826   int tag = dwarf_tag(die);
827   mc_tag_class klass = MC_dwarf_tag_classify(tag);
828
829   // (Template) Subprogram declaration:
830   if (klass == mc_tag_subprogram
831       && MC_dwarf_attr_flag(die, DW_AT_declaration, false))
832     return;
833
834   if (klass == mc_tag_scope)
835     xbt_assert(parent_frame, "No parent scope for this scope");
836
837   simgrid::mc::Frame frame;
838
839   frame.tag = tag;
840   frame.id = dwarf_dieoffset(die);
841   frame.object_info = info;
842
843   if (klass == mc_tag_subprogram) {
844     const char *name = MC_dwarf_attr_integrate_string(die, DW_AT_name);
845     if(ns)
846       frame.name  = std::string(ns) + "::" + name;
847     else if (name)
848       frame.name = name;
849     else
850       frame.name.clear();
851   }
852
853   frame.abstract_origin_id =
854     MC_dwarf_attr_dieoffset(die, DW_AT_abstract_origin);
855
856   // This is the base address for DWARF addresses.
857   // Relocated addresses are offset from this base address.
858   // See DWARF4 spec 7.5
859   void *base = info->base_address();
860
861   // TODO, support DW_AT_ranges
862   uint64_t low_pc = MC_dwarf_attr_integrate_addr(die, DW_AT_low_pc);
863   frame.low_pc = low_pc ? ((char *) base) + low_pc : 0;
864   if (low_pc) {
865     // DW_AT_high_pc:
866     Dwarf_Attribute attr;
867     if (!dwarf_attr_integrate(die, DW_AT_high_pc, &attr)) {
868       xbt_die("Missing DW_AT_high_pc matching with DW_AT_low_pc");
869     }
870
871     Dwarf_Sword offset;
872     Dwarf_Addr high_pc;
873
874     switch (MC_dwarf_form_get_class(dwarf_whatform(&attr))) {
875
876       // DW_AT_high_pc if an offset from the low_pc:
877     case MC_DW_CLASS_CONSTANT:
878
879       if (dwarf_formsdata(&attr, &offset) != 0)
880         xbt_die("Could not read constant");
881       frame.high_pc = (void *) ((char *) frame.low_pc + offset);
882       break;
883
884       // DW_AT_high_pc is a relocatable address:
885     case MC_DW_CLASS_ADDRESS:
886       if (dwarf_formaddr(&attr, &high_pc) != 0)
887         xbt_die("Could not read address");
888       frame.high_pc = ((char *) base) + high_pc;
889       break;
890
891     default:
892       xbt_die("Unexpected class for DW_AT_high_pc");
893
894     }
895   }
896
897   if (klass == mc_tag_subprogram) {
898     Dwarf_Attribute attr_frame_base;
899     if (dwarf_attr_integrate(die, DW_AT_frame_base, &attr_frame_base))
900       mc_dwarf_location_list_init(&frame.frame_base, info, die,
901                                   &attr_frame_base);
902   }
903
904   // Handle children:
905   MC_dwarf_handle_children(info, die, unit, &frame, ns);
906
907   // Someone needs this to be sorted but who?
908   std::sort(frame.variables.begin(), frame.variables.end(),
909     MC_compare_variable);
910
911   // Register it:
912   if (klass == mc_tag_subprogram)
913     info->subprograms[frame.id] = frame;
914   else if (klass == mc_tag_scope)
915     parent_frame->scopes.push_back(std::move(frame));
916 }
917
918 static void mc_dwarf_handle_namespace_die(simgrid::mc::ObjectInformation* info,
919                                           Dwarf_Die * die, Dwarf_Die * unit,
920                                           simgrid::mc::Frame* frame,
921                                           const char *ns)
922 {
923   const char *name = MC_dwarf_attr_integrate_string(die, DW_AT_name);
924   if (frame)
925     xbt_die("Unexpected namespace in a subprogram");
926   char *new_ns = ns == NULL ? xbt_strdup(name)
927       : bprintf("%s::%s", ns, name);
928   MC_dwarf_handle_children(info, die, unit, frame, new_ns);
929   xbt_free(new_ns);
930 }
931
932 static void MC_dwarf_handle_children(simgrid::mc::ObjectInformation* info, Dwarf_Die * die,
933                                      Dwarf_Die * unit, simgrid::mc::Frame* frame,
934                                      const char *ns)
935 {
936   // For each child DIE:
937   Dwarf_Die child;
938   int res;
939   for (res = dwarf_child(die, &child); res == 0;
940        res = dwarf_siblingof(&child, &child)) {
941     MC_dwarf_handle_die(info, &child, unit, frame, ns);
942   }
943 }
944
945 static void MC_dwarf_handle_die(simgrid::mc::ObjectInformation* info, Dwarf_Die * die,
946                                 Dwarf_Die * unit, simgrid::mc::Frame* frame,
947                                 const char *ns)
948 {
949   int tag = dwarf_tag(die);
950   mc_tag_class klass = MC_dwarf_tag_classify(tag);
951   switch (klass) {
952
953     // Type:
954   case mc_tag_type:
955     MC_dwarf_handle_type_die(info, die, unit, frame, ns);
956     break;
957
958     // Subprogram or scope:
959   case mc_tag_subprogram:
960   case mc_tag_scope:
961     MC_dwarf_handle_scope_die(info, die, unit, frame, ns);
962     return;
963
964     // Variable:
965   case mc_tag_variable:
966     MC_dwarf_handle_variable_die(info, die, unit, frame, ns);
967     break;
968
969   case mc_tag_namespace:
970     mc_dwarf_handle_namespace_die(info, die, unit, frame, ns);
971     break;
972
973   default:
974     break;
975
976   }
977 }
978
979 /** \brief Populate the debugging informations of the given ELF object
980  *
981  *  Read the DWARf information of the EFFL object and populate the
982  *  lists of types, variables, functions.
983  */
984 void MC_dwarf_get_variables(simgrid::mc::ObjectInformation* info)
985 {
986   int fd = open(info->file_name.c_str(), O_RDONLY);
987   if (fd < 0)
988     xbt_die("Could not open file %s", info->file_name.c_str());
989   Dwarf *dwarf = dwarf_begin(fd, DWARF_C_READ);
990   if (dwarf == NULL)
991     xbt_die("Missing debugging information in %s\n"
992       "Your program and its dependencies must have debugging information.\n"
993       "You might want to recompile with -g or install the suitable debugging package.\n",
994       info->file_name.c_str());
995   // For each compilation unit:
996   Dwarf_Off offset = 0;
997   Dwarf_Off next_offset = 0;
998   size_t length;
999
1000   while (dwarf_nextcu(dwarf, offset, &next_offset, &length, NULL, NULL, NULL) ==
1001          0) {
1002     Dwarf_Die unit_die;
1003     if (dwarf_offdie(dwarf, offset + length, &unit_die) != NULL)
1004       MC_dwarf_handle_children(info, &unit_die, &unit_die, NULL, NULL);
1005     offset = next_offset;
1006   }
1007
1008   dwarf_end(dwarf);
1009   close(fd);
1010 }
1011
1012 // ***** Functions index
1013
1014 static int MC_compare_frame_index_items(simgrid::mc::FunctionIndexEntry* a,
1015                                         simgrid::mc::FunctionIndexEntry* b)
1016 {
1017   if (a->low_pc < b->low_pc)
1018     return -1;
1019   else if (a->low_pc == b->low_pc)
1020     return 0;
1021   else
1022     return 1;
1023 }
1024
1025 static void MC_make_functions_index(simgrid::mc::ObjectInformation* info)
1026 {
1027   info->functions_index.clear();
1028
1029   for (auto& e : info->subprograms) {
1030     if (e.second.low_pc == nullptr)
1031       continue;
1032     simgrid::mc::FunctionIndexEntry entry;
1033     entry.low_pc = e.second.low_pc;
1034     entry.function = &e.second;
1035     info->functions_index.push_back(entry);
1036   }
1037
1038   info->functions_index.shrink_to_fit();
1039
1040   // Sort the array by low_pc:
1041   std::sort(info->functions_index.begin(), info->functions_index.end(),
1042         [](simgrid::mc::FunctionIndexEntry const& a,
1043           simgrid::mc::FunctionIndexEntry const& b)
1044         {
1045           return a.low_pc < b.low_pc;
1046         });
1047 }
1048
1049 static void MC_post_process_variables(simgrid::mc::ObjectInformation* info)
1050 {
1051   // Someone needs this to be sorted but who?
1052   std::sort(info->global_variables.begin(), info->global_variables.end(),
1053     MC_compare_variable);
1054
1055   for(simgrid::mc::Variable& variable : info->global_variables)
1056     if (variable.type_id)
1057       variable.type = simgrid::util::find_map_ptr(
1058         info->types, variable.type_id);
1059 }
1060
1061 static void mc_post_process_scope(simgrid::mc::ObjectInformation* info, simgrid::mc::Frame* scope)
1062 {
1063
1064   if (scope->tag == DW_TAG_inlined_subroutine) {
1065     // Attach correct namespaced name in inlined subroutine:
1066     auto i = info->subprograms.find(scope->abstract_origin_id);
1067     xbt_assert(i != info->subprograms.end(),
1068       "Could not lookup abstract origin %" PRIx64,
1069       (std::uint64_t) scope->abstract_origin_id);
1070     scope->name = i->second.name;
1071   }
1072
1073   // Direct:
1074   for (simgrid::mc::Variable& variable : scope->variables)
1075     if (variable.type_id)
1076       variable.type = simgrid::util::find_map_ptr(
1077         info->types, variable.type_id);
1078
1079   // Recursive post-processing of nested-scopes:
1080   for (simgrid::mc::Frame& nested_scope : scope->scopes)
1081       mc_post_process_scope(info, &nested_scope);
1082
1083 }
1084
1085 /** \brief Fill/lookup the "subtype" field.
1086  */
1087 static void MC_resolve_subtype(simgrid::mc::ObjectInformation* info, simgrid::mc::Type* type)
1088 {
1089   if (!type->type_id)
1090     return;
1091   type->subtype = simgrid::util::find_map_ptr(info->types, type->type_id);
1092   if (type->subtype == nullptr)
1093     return;
1094   if (type->subtype->byte_size != 0)
1095     return;
1096   if (type->subtype->name.empty())
1097     return;
1098   // Try to find a more complete description of the type:
1099   // We need to fix in order to support C++.
1100   simgrid::mc::Type** subtype = simgrid::util::find_map_ptr(
1101     info->full_types_by_name, type->subtype->name);
1102   if (subtype)
1103     type->subtype = *subtype;
1104 }
1105
1106 static void MC_post_process_types(simgrid::mc::ObjectInformation* info)
1107 {
1108   // Lookup "subtype" field:
1109   for(auto& i : info->types) {
1110     MC_resolve_subtype(info, &(i.second));
1111     for (simgrid::mc::Type& member : i.second.members)
1112       MC_resolve_subtype(info, &member);
1113   }
1114 }
1115
1116 /** \brief Finds informations about a given shared object/executable */
1117 std::shared_ptr<simgrid::mc::ObjectInformation> MC_find_object_info(
1118   std::vector<simgrid::mc::VmMap> const& maps, const char *name, int executable)
1119 {
1120   std::shared_ptr<simgrid::mc::ObjectInformation> result =
1121     std::make_shared<simgrid::mc::ObjectInformation>();
1122   if (executable)
1123     result->flags |= simgrid::mc::ObjectInformation::Executable;
1124   result->file_name = name;
1125   MC_find_object_address(maps, result.get());
1126   MC_dwarf_get_variables(result.get());
1127   MC_post_process_variables(result.get());
1128   MC_post_process_types(result.get());
1129   for (auto& entry : result.get()->subprograms)
1130     mc_post_process_scope(result.get(), &entry.second);
1131   MC_make_functions_index(result.get());
1132   return std::move(result);
1133 }
1134
1135 /*************************************************************************/
1136
1137 void MC_post_process_object_info(simgrid::mc::Process* process, simgrid::mc::ObjectInformation* info)
1138 {
1139   for (auto& i : info->types) {
1140
1141     simgrid::mc::Type* type = &(i.second);
1142     simgrid::mc::Type* subtype = type;
1143     while (subtype->type == DW_TAG_typedef
1144         || subtype->type == DW_TAG_volatile_type
1145         || subtype->type == DW_TAG_const_type)
1146       if (subtype->subtype)
1147         subtype = subtype->subtype;
1148       else
1149         break;
1150
1151     // Resolve full_type:
1152     if (!subtype->name.empty() && subtype->byte_size == 0) {
1153       for (auto const& object_info : process->object_infos) {
1154         auto i = object_info->full_types_by_name.find(subtype->name);
1155         if (i != object_info->full_types_by_name.end()
1156             && !i->second->name.empty() && i->second->byte_size) {
1157           type->full_type = i->second;
1158           break;
1159         }
1160       }
1161     } else type->full_type = subtype;
1162
1163   }
1164 }