Logo AND Algorithmique Numérique Distribuée

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