Logo AND Algorithmique Numérique Distribuée

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