Logo AND Algorithmique Numérique Distribuée

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