Logo AND Algorithmique Numérique Distribuée

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