Logo AND Algorithmique Numérique Distribuée

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