Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
empty portable.h and spread the include in files
[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 #include <utility>
13
14 #include <fcntl.h>
15 #include <cstdlib>
16 #define DW_LANG_Objc DW_LANG_ObjC       /* fix spelling error in older dwarf.h */
17 #include <dwarf.h>
18 #include <elfutils/libdw.h>
19
20 #include <simgrid_config.h>
21 #include "src/simgrid/util.hpp"
22 #include <xbt/log.h>
23 #include <xbt/sysdep.h>
24
25 #include "src/mc/mc_private.h"
26 #include "src/mc/mc_dwarf.hpp"
27
28 #include "src/mc/mc_object_info.h"
29 #include "src/mc/Process.hpp"
30 #include "src/mc/ObjectInformation.hpp"
31 #include "src/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 (nullptr 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 static
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 static
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 nullptr;
264   else
265     return dwarf_formstring(&attr);
266 }
267
268 /** \brief Get the linkage name of a DIE.
269  *
270  *  Use either DW_AT_linkage_name or DW_AT_MIPS_linkage_name.
271  *  DW_AT_linkage_name is standardized since DWARF 4.
272  *  Before this version of DWARF, the MIPS extensions
273  *  DW_AT_MIPS_linkage_name is used (at least by GCC).
274  *
275  *  \param  the DIE
276  *  \return linkage name of the given DIE (or nullptr)
277  * */
278 static const char *MC_dwarf_at_linkage_name(Dwarf_Die * die)
279 {
280   const char *name = MC_dwarf_attr_integrate_string(die, DW_AT_linkage_name);
281   if (!name)
282     name = MC_dwarf_attr_integrate_string(die, DW_AT_MIPS_linkage_name);
283   return name;
284 }
285
286 static Dwarf_Off MC_dwarf_attr_dieoffset(Dwarf_Die * die, int attribute)
287 {
288   Dwarf_Attribute attr;
289   if (dwarf_hasattr_integrate(die, attribute) == 0)
290     return 0;
291   dwarf_attr_integrate(die, attribute, &attr);
292   Dwarf_Die subtype_die;
293   if (dwarf_formref_die(&attr, &subtype_die) == nullptr)
294     xbt_die("Could not find DIE");
295   return dwarf_dieoffset(&subtype_die);
296 }
297
298 static Dwarf_Off MC_dwarf_attr_integrate_dieoffset(Dwarf_Die * die,
299                                                    int attribute)
300 {
301   Dwarf_Attribute attr;
302   if (dwarf_hasattr_integrate(die, attribute) == 0)
303     return 0;
304   dwarf_attr_integrate(die, DW_AT_type, &attr);
305   Dwarf_Die subtype_die;
306   if (dwarf_formref_die(&attr, &subtype_die) == nullptr)
307     xbt_die("Could not find DIE");
308   return dwarf_dieoffset(&subtype_die);
309 }
310
311 /** \brief Find the type/subtype (DW_AT_type) for a DIE
312  *
313  *  \param dit the DIE
314  *  \return DW_AT_type reference as a global offset in hexadecimal (or nullptr)
315  */
316 static
317 std::uint64_t MC_dwarf_at_type(Dwarf_Die * die)
318 {
319   return MC_dwarf_attr_integrate_dieoffset(die, DW_AT_type);
320 }
321
322 static uint64_t MC_dwarf_attr_integrate_addr(Dwarf_Die * die, int attribute)
323 {
324   Dwarf_Attribute attr;
325   if (dwarf_attr_integrate(die, attribute, &attr) == nullptr)
326     return 0;
327   Dwarf_Addr value;
328   if (dwarf_formaddr(&attr, &value) == 0)
329     return (uint64_t) value;
330   else
331     return 0;
332 }
333
334 static uint64_t MC_dwarf_attr_integrate_uint(Dwarf_Die * die, int attribute,
335                                              uint64_t default_value)
336 {
337   Dwarf_Attribute attr;
338   if (dwarf_attr_integrate(die, attribute, &attr) == nullptr)
339     return default_value;
340   Dwarf_Word value;
341   return dwarf_formudata(dwarf_attr_integrate(die, attribute, &attr),
342                          &value) == 0 ? (uint64_t) value : default_value;
343 }
344
345 static bool MC_dwarf_attr_flag(Dwarf_Die * die, int attribute, bool integrate)
346 {
347   Dwarf_Attribute attr;
348   if ((integrate ? dwarf_attr_integrate(die, attribute, &attr)
349        : dwarf_attr(die, attribute, &attr)) == 0)
350     return false;
351
352   bool result;
353   if (dwarf_formflag(&attr, &result))
354     xbt_die("Unexpected form for attribute %s",
355       simgrid::dwarf::attrname(attribute));
356   return result;
357 }
358
359 /** \brief Find the default lower bound for a given language
360  *
361  *  The default lower bound of an array (when DW_TAG_lower_bound
362  *  is missing) depends on the language of the compilation unit.
363  *
364  *  \param lang Language of the compilation unit (values defined in the DWARF spec)
365  *  \return     Default lower bound of an array in this compilation unit
366  * */
367 static uint64_t MC_dwarf_default_lower_bound(int lang)
368 {
369   switch (lang) {
370   case DW_LANG_C:
371   case DW_LANG_C89:
372   case DW_LANG_C99:
373   case DW_LANG_C_plus_plus:
374   case DW_LANG_D:
375   case DW_LANG_Java:
376   case DW_LANG_ObjC:
377   case DW_LANG_ObjC_plus_plus:
378   case DW_LANG_Python:
379   case DW_LANG_UPC:
380     return 0;
381   case DW_LANG_Ada83:
382   case DW_LANG_Ada95:
383   case DW_LANG_Fortran77:
384   case DW_LANG_Fortran90:
385   case DW_LANG_Fortran95:
386   case DW_LANG_Modula2:
387   case DW_LANG_Pascal83:
388   case DW_LANG_PL1:
389   case DW_LANG_Cobol74:
390   case DW_LANG_Cobol85:
391     return 1;
392   default:
393     xbt_die("No default DW_TAG_lower_bound for language %i and none given",
394             lang);
395     return 0;
396   }
397 }
398
399 /** \brief Finds the number of elements in a DW_TAG_subrange_type or DW_TAG_enumeration_type DIE
400  *
401  *  \param die  the DIE
402  *  \param unit DIE of the compilation unit
403  *  \return     number of elements in the range
404  * */
405 static uint64_t MC_dwarf_subrange_element_count(Dwarf_Die * die,
406                                                 Dwarf_Die * unit)
407 {
408   xbt_assert(dwarf_tag(die) == DW_TAG_enumeration_type
409              || dwarf_tag(die) == DW_TAG_subrange_type,
410              "MC_dwarf_subrange_element_count called with DIE of type %s",
411              simgrid::dwarf::tagname(die));
412
413   // Use DW_TAG_count if present:
414   if (dwarf_hasattr_integrate(die, DW_AT_count))
415     return MC_dwarf_attr_integrate_uint(die, DW_AT_count, 0);
416   // Otherwise compute DW_TAG_upper_bound-DW_TAG_lower_bound + 1:
417
418   if (!dwarf_hasattr_integrate(die, DW_AT_upper_bound))
419     // This is not really 0, but the code expects this (we do not know):
420     return 0;
421
422   uint64_t upper_bound =
423       MC_dwarf_attr_integrate_uint(die, DW_AT_upper_bound, -1);
424
425   uint64_t lower_bound = 0;
426   if (dwarf_hasattr_integrate(die, DW_AT_lower_bound))
427     lower_bound = MC_dwarf_attr_integrate_uint(die, DW_AT_lower_bound, -1);
428   else
429     lower_bound = MC_dwarf_default_lower_bound(dwarf_srclang(unit));
430   return upper_bound - lower_bound + 1;
431 }
432
433 /** \brief Finds the number of elements in a array type (DW_TAG_array_type)
434  *
435  *  The compilation unit might be needed because the default lower
436  *  bound depends on the language of the compilation unit.
437  *
438  *  \param die the DIE of the DW_TAG_array_type
439  *  \param unit the DIE of the compilation unit
440  *  \return number of elements in this array type
441  * */
442 static uint64_t MC_dwarf_array_element_count(Dwarf_Die * die, Dwarf_Die * unit)
443 {
444   xbt_assert(dwarf_tag(die) == DW_TAG_array_type,
445              "MC_dwarf_array_element_count called with DIE of type %s",
446              simgrid::dwarf::tagname(die));
447
448   int result = 1;
449   Dwarf_Die child;
450   int res;
451   for (res = dwarf_child(die, &child); res == 0;
452        res = dwarf_siblingof(&child, &child)) {
453     int child_tag = dwarf_tag(&child);
454     if (child_tag == DW_TAG_subrange_type
455         || child_tag == DW_TAG_enumeration_type)
456       result *= MC_dwarf_subrange_element_count(&child, unit);
457   }
458   return result;
459 }
460
461 // ***** Variable
462
463 /** Sort the variable by name and address.
464  *
465  *  We could use boost::container::flat_set instead.
466  */
467 static bool MC_compare_variable(
468   simgrid::mc::Variable const& a, simgrid::mc::Variable const& b)
469 {
470   int cmp = strcmp(a.name.c_str(), b.name.c_str());
471   if (cmp < 0)
472     return true;
473   else if (cmp > 0)
474     return false;
475   else
476     return a.address < b.address;
477 }
478
479 // ***** simgrid::mc::Type*
480
481 /** \brief Initialize the location of a member of a type
482  * (DW_AT_data_member_location of a DW_TAG_member).
483  *
484  *  \param  type   a type (struct, class)
485  *  \param  member the member of the type
486  *  \param  child  DIE of the member (DW_TAG_member)
487  */
488 static void MC_dwarf_fill_member_location(
489   simgrid::mc::Type* type, simgrid::mc::Member* member, Dwarf_Die * child)
490 {
491   if (dwarf_hasattr(child, DW_AT_data_bit_offset))
492     xbt_die("Can't groke DW_AT_data_bit_offset.");
493
494   if (!dwarf_hasattr_integrate(child, DW_AT_data_member_location)) {
495     if (type->type == DW_TAG_union_type)
496       return;
497     xbt_die
498         ("Missing DW_AT_data_member_location field in DW_TAG_member %s of type <%"
499          PRIx64 ">%s", member->name.c_str(),
500          (uint64_t) type->id, type->name.c_str());
501   }
502
503   Dwarf_Attribute attr;
504   dwarf_attr_integrate(child, DW_AT_data_member_location, &attr);
505   int form = dwarf_whatform(&attr);
506   simgrid::dwarf::FormClass form_class = simgrid::dwarf::classify_form(form);
507   switch (form_class) {
508   case simgrid::dwarf::FormClass::ExprLoc:
509   case simgrid::dwarf::FormClass::Block:
510     // Location expression:
511     {
512       Dwarf_Op *expr;
513       size_t len;
514       if (dwarf_getlocation(&attr, &expr, &len))
515         xbt_die
516             ("Could not read location expression DW_AT_data_member_location in DW_TAG_member %s of type <%"
517              PRIx64 ">%s", MC_dwarf_attr_integrate_string(child, DW_AT_name),
518              (uint64_t) type->id, type->name.c_str());
519       member->location_expression = simgrid::dwarf::DwarfExpression(expr, expr+len);
520       break;
521     }
522   case simgrid::dwarf::FormClass::Constant:
523     // Offset from the base address of the object:
524     {
525       Dwarf_Word offset;
526       if (!dwarf_formudata(&attr, &offset))
527         member->offset(offset);
528       else
529         xbt_die("Cannot get %s location <%" PRIx64 ">%s",
530                 MC_dwarf_attr_integrate_string(child, DW_AT_name),
531                 (uint64_t) type->id, type->name.c_str());
532       break;
533     }
534   case simgrid::dwarf::FormClass::LocListPtr:
535     // Reference to a location list:
536     // TODO
537   case simgrid::dwarf::FormClass::Reference:
538     // It's supposed to be possible in DWARF2 but I couldn't find its semantic
539     // in the spec.
540   default:
541     xbt_die("Can't handle form class (%i) / form 0x%x as DW_AT_member_location",
542             (int) form_class, form);
543   }
544
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(simgrid::mc::ObjectInformation* info, Dwarf_Die * die,
555                                  Dwarf_Die * unit, simgrid::mc::Type* 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::Member member;
575       member.inheritance = tag == DW_TAG_inheritance;
576
577       const char *name = MC_dwarf_attr_integrate_string(&child, DW_AT_name);
578       if (name)
579         member.name = name;
580       member.byte_size =
581           MC_dwarf_attr_integrate_uint(&child, DW_AT_byte_size, 0);
582       member.type_id = MC_dwarf_at_type(&child);
583
584       if (dwarf_hasattr(&child, DW_AT_data_bit_offset))
585         xbt_die("Can't groke DW_AT_data_bit_offset.");
586
587       MC_dwarf_fill_member_location(type, &member, &child);
588
589       if (!member.type_id)
590         xbt_die("Missing type for member %s of <%" PRIx64 ">%s",
591                 member.name.c_str(),
592                 (uint64_t) type->id, type->name.c_str());
593
594       type->members.push_back(std::move(member));
595     }
596   }
597 }
598
599 /** \brief Create a MC type object from a DIE
600  *
601  *  \param info current object info object
602  *  \param DIE (for a given type);
603  *  \param unit compilation unit of the current DIE
604  *  \return MC representation of the type
605  */
606 static simgrid::mc::Type MC_dwarf_die_to_type(
607   simgrid::mc::ObjectInformation* info, Dwarf_Die * die,
608   Dwarf_Die * unit, simgrid::mc::Frame* frame,
609   const char *ns)
610 {
611   simgrid::mc::Type type;
612   type.type = dwarf_tag(die);
613   type.name = std::string();
614   type.element_count = -1;
615
616   // Global Offset
617   type.id = dwarf_dieoffset(die);
618
619   const char *prefix = "";
620   switch (type.type) {
621   case DW_TAG_structure_type:
622     prefix = "struct ";
623     break;
624   case DW_TAG_union_type:
625     prefix = "union ";
626     break;
627   case DW_TAG_class_type:
628     prefix = "class ";
629     break;
630   default:
631     prefix = "";
632   }
633
634   const char *name = MC_dwarf_attr_integrate_string(die, DW_AT_name);
635   if (name != nullptr) {
636     char* full_name = ns ? bprintf("%s%s::%s", prefix, ns, name) :
637       bprintf("%s%s", prefix, name);
638     type.name = std::string(full_name);
639     free(full_name);
640   }
641
642   type.type_id = MC_dwarf_at_type(die);
643
644   // Some compilers do not emit DW_AT_byte_size for pointer_type,
645   // so we fill this. We currently assume that the model-checked process is in
646   // the same architecture..
647   if (type.type == DW_TAG_pointer_type)
648     type.byte_size = sizeof(void*);
649
650   // Computation of the byte_size;
651   if (dwarf_hasattr_integrate(die, DW_AT_byte_size))
652     type.byte_size = MC_dwarf_attr_integrate_uint(die, DW_AT_byte_size, 0);
653   else if (type.type == DW_TAG_array_type
654            || type.type == DW_TAG_structure_type
655            || type.type == DW_TAG_class_type) {
656     Dwarf_Word size;
657     if (dwarf_aggregate_size(die, &size) == 0)
658       type.byte_size = size;
659   }
660
661   switch (type.type) {
662   case DW_TAG_array_type:
663     type.element_count = MC_dwarf_array_element_count(die, unit);
664     // TODO, handle DW_byte_stride and (not) DW_bit_stride
665     break;
666
667   case DW_TAG_pointer_type:
668   case DW_TAG_reference_type:
669   case DW_TAG_rvalue_reference_type:
670     break;
671
672   case DW_TAG_structure_type:
673   case DW_TAG_union_type:
674   case DW_TAG_class_type:
675     MC_dwarf_add_members(info, die, unit, &type);
676     char *new_ns = ns == nullptr ? xbt_strdup(type.name.c_str())
677         : bprintf("%s::%s", ns, name);
678     MC_dwarf_handle_children(info, die, unit, frame, new_ns);
679     free(new_ns);
680     break;
681   }
682
683   return std::move(type);
684 }
685
686 static void MC_dwarf_handle_type_die(simgrid::mc::ObjectInformation* info, Dwarf_Die * die,
687                                      Dwarf_Die * unit, simgrid::mc::Frame* frame,
688                                      const char *ns)
689 {
690   simgrid::mc::Type type = MC_dwarf_die_to_type(info, die, unit, frame, ns);
691   auto& t = (info->types[type.id] = std::move(type));
692   if (!t.name.empty() && type.byte_size != 0)
693     info->full_types_by_name[t.name] = &t;
694 }
695
696 static int mc_anonymous_variable_index = 0;
697
698 static std::unique_ptr<simgrid::mc::Variable> MC_die_to_variable(
699   simgrid::mc::ObjectInformation* info, Dwarf_Die * die,
700   Dwarf_Die * unit, simgrid::mc::Frame* frame,
701   const char *ns)
702 {
703   // Skip declarations:
704   if (MC_dwarf_attr_flag(die, DW_AT_declaration, false))
705     return nullptr;
706
707   // Skip compile time constants:
708   if (dwarf_hasattr(die, DW_AT_const_value))
709     return nullptr;
710
711   Dwarf_Attribute attr_location;
712   if (dwarf_attr(die, DW_AT_location, &attr_location) == nullptr)
713     // No location: do not add it ?
714     return nullptr;
715
716   std::unique_ptr<simgrid::mc::Variable> variable =
717     std::unique_ptr<simgrid::mc::Variable>(new simgrid::mc::Variable());
718   variable->dwarf_offset = dwarf_dieoffset(die);
719   variable->global = frame == nullptr;     // Can be override base on DW_AT_location
720   variable->object_info = info;
721
722   const char *name = MC_dwarf_attr_integrate_string(die, DW_AT_name);
723   if (name)
724     variable->name = name;
725   variable->type_id = MC_dwarf_at_type(die);
726
727   int form = dwarf_whatform(&attr_location);
728   simgrid::dwarf::FormClass form_class;
729   if (form == DW_FORM_sec_offset)
730     form_class = simgrid::dwarf::FormClass::Constant;
731   else
732     form_class = simgrid::dwarf::classify_form(form);
733   switch (form_class) {
734   case simgrid::dwarf::FormClass::ExprLoc:
735   case simgrid::dwarf::FormClass::Block:
736     // Location expression:
737     {
738       Dwarf_Op *expr;
739       size_t len;
740       if (dwarf_getlocation(&attr_location, &expr, &len)) {
741         xbt_die(
742           "Could not read location expression in DW_AT_location "
743           "of variable <%" PRIx64 ">%s",
744           (uint64_t) variable->dwarf_offset,
745           variable->name.c_str());
746       }
747
748       if (len == 1 && expr[0].atom == DW_OP_addr) {
749         variable->global = 1;
750         uintptr_t offset = (uintptr_t) expr[0].number;
751         uintptr_t base = (uintptr_t) info->base_address();
752         variable->address = (void *) (base + offset);
753       } else
754         variable->location_list = {
755           simgrid::dwarf::DwarfExpression(expr, expr + len) };
756
757       break;
758     }
759
760   case simgrid::dwarf::FormClass::LocListPtr:
761   case simgrid::dwarf::FormClass::Constant:
762     // Reference to location list:
763     variable->location_list = simgrid::dwarf::location_list(
764       *info, attr_location);
765     break;
766
767   default:
768     xbt_die("Unexpected form 0x%x (%i), class 0x%x (%i) list for location "
769             "in <%" PRIx64 ">%s",
770             form, form, (int) form_class, (int) form_class,
771             (uint64_t) variable->dwarf_offset,
772             variable->name.c_str());
773   }
774
775   // Handle start_scope:
776   if (dwarf_hasattr(die, DW_AT_start_scope)) {
777     Dwarf_Attribute attr;
778     dwarf_attr(die, DW_AT_start_scope, &attr);
779     int form = dwarf_whatform(&attr);
780     simgrid::dwarf::FormClass form_class = simgrid::dwarf::classify_form(form);
781     switch (form_class) {
782     case simgrid::dwarf::FormClass::Constant:
783       {
784         Dwarf_Word value;
785         variable->start_scope =
786             dwarf_formudata(&attr, &value) == 0 ? (size_t) value : 0;
787         break;
788       }
789
790     case simgrid::dwarf::FormClass::RangeListPtr:     // TODO
791     default:
792       xbt_die
793           ("Unhandled form 0x%x, class 0x%X for DW_AT_start_scope of variable %s",
794            form, (int) form_class, name == nullptr ? "?" : name);
795     }
796   }
797
798   if (ns && variable->global)
799     variable->name =
800       std::string(ns) + "::" + variable->name;
801
802   // The current code needs a variable name,
803   // generate a fake one:
804   if (variable->name.empty())
805     variable->name =
806       "@anonymous#" + std::to_string(mc_anonymous_variable_index++);
807
808   return std::move(variable);
809 }
810
811 static void MC_dwarf_handle_variable_die(simgrid::mc::ObjectInformation* info, Dwarf_Die * die,
812                                          Dwarf_Die * unit, simgrid::mc::Frame* frame,
813                                          const char *ns)
814 {
815   std::unique_ptr<simgrid::mc::Variable> variable =
816     MC_die_to_variable(info, die, unit, frame, ns);
817   if (!variable)
818     return;
819   // Those arrays are sorted later:
820   else if (variable->global)
821     info->global_variables.push_back(std::move(*variable));
822   else if (frame != nullptr)
823     frame->variables.push_back(std::move(*variable));
824   else
825     xbt_die("No frame for this local variable");
826 }
827
828 static void MC_dwarf_handle_scope_die(simgrid::mc::ObjectInformation* info, Dwarf_Die * die,
829                                       Dwarf_Die * unit, simgrid::mc::Frame* parent_frame,
830                                       const char *ns)
831 {
832   // TODO, handle DW_TAG_type/DW_TAG_location for DW_TAG_with_stmt
833   int tag = dwarf_tag(die);
834   simgrid::dwarf::TagClass klass = simgrid::dwarf::classify_tag(tag);
835
836   // (Template) Subprogram declaration:
837   if (klass == simgrid::dwarf::TagClass::Subprogram
838       && MC_dwarf_attr_flag(die, DW_AT_declaration, false))
839     return;
840
841   if (klass == simgrid::dwarf::TagClass::Scope)
842     xbt_assert(parent_frame, "No parent scope for this scope");
843
844   simgrid::mc::Frame frame;
845   frame.tag = tag;
846   frame.id = dwarf_dieoffset(die);
847   frame.object_info = info;
848
849   if (klass == simgrid::dwarf::TagClass::Subprogram) {
850     const char *name = MC_dwarf_attr_integrate_string(die, DW_AT_name);
851     if (ns)
852       frame.name  = std::string(ns) + "::" + name;
853     else if (name)
854       frame.name = name;
855   }
856
857   frame.abstract_origin_id =
858     MC_dwarf_attr_dieoffset(die, DW_AT_abstract_origin);
859
860   // This is the base address for DWARF addresses.
861   // Relocated addresses are offset from this base address.
862   // See DWARF4 spec 7.5
863   std::uint64_t base = (std::uint64_t) info->base_address();
864
865   // TODO, support DW_AT_ranges
866   uint64_t low_pc = MC_dwarf_attr_integrate_addr(die, DW_AT_low_pc);
867   frame.range.begin() = low_pc ? (std::uint64_t) base + low_pc : 0;
868   if (low_pc) {
869     // DW_AT_high_pc:
870     Dwarf_Attribute attr;
871     if (!dwarf_attr_integrate(die, DW_AT_high_pc, &attr))
872       xbt_die("Missing DW_AT_high_pc matching with DW_AT_low_pc");
873
874     Dwarf_Sword offset;
875     Dwarf_Addr high_pc;
876
877     switch (simgrid::dwarf::classify_form(dwarf_whatform(&attr))) {
878
879       // DW_AT_high_pc if an offset from the low_pc:
880     case simgrid::dwarf::FormClass::Constant:
881
882       if (dwarf_formsdata(&attr, &offset) != 0)
883         xbt_die("Could not read constant");
884       frame.range.end() = frame.range.begin() + offset;
885       break;
886
887       // DW_AT_high_pc is a relocatable address:
888     case simgrid::dwarf::FormClass::Address:
889       if (dwarf_formaddr(&attr, &high_pc) != 0)
890         xbt_die("Could not read address");
891       frame.range.begin() = base + high_pc;
892       break;
893
894     default:
895       xbt_die("Unexpected class for DW_AT_high_pc");
896
897     }
898   }
899
900   if (klass == simgrid::dwarf::TagClass::Subprogram) {
901     Dwarf_Attribute attr_frame_base;
902     if (dwarf_attr_integrate(die, DW_AT_frame_base, &attr_frame_base))
903       frame.frame_base_location = simgrid::dwarf::location_list(*info,
904                                   attr_frame_base);
905   }
906
907   // Handle children:
908   MC_dwarf_handle_children(info, die, unit, &frame, ns);
909
910   // We sort them in order to have an (somewhat) efficient by name
911   // lookup:
912   std::sort(frame.variables.begin(), frame.variables.end(),
913     MC_compare_variable);
914
915   // Register it:
916   if (klass == simgrid::dwarf::TagClass::Subprogram)
917     info->subprograms[frame.id] = std::move(frame);
918   else if (klass == simgrid::dwarf::TagClass::Scope)
919     parent_frame->scopes.push_back(std::move(frame));
920 }
921
922 static void mc_dwarf_handle_namespace_die(simgrid::mc::ObjectInformation* info,
923                                           Dwarf_Die * die, Dwarf_Die * unit,
924                                           simgrid::mc::Frame* frame,
925                                           const char *ns)
926 {
927   const char *name = MC_dwarf_attr_integrate_string(die, DW_AT_name);
928   if (frame)
929     xbt_die("Unexpected namespace in a subprogram");
930   char *new_ns = ns == nullptr ? xbt_strdup(name)
931       : bprintf("%s::%s", ns, name);
932   MC_dwarf_handle_children(info, die, unit, frame, new_ns);
933   xbt_free(new_ns);
934 }
935
936 static void MC_dwarf_handle_children(simgrid::mc::ObjectInformation* info, Dwarf_Die * die,
937                                      Dwarf_Die * unit, simgrid::mc::Frame* frame,
938                                      const char *ns)
939 {
940   // For each child DIE:
941   Dwarf_Die child;
942   int res;
943   for (res = dwarf_child(die, &child); res == 0;
944        res = dwarf_siblingof(&child, &child))
945     MC_dwarf_handle_die(info, &child, unit, frame, ns);
946 }
947
948 static void MC_dwarf_handle_die(simgrid::mc::ObjectInformation* info, Dwarf_Die * die,
949                                 Dwarf_Die * unit, simgrid::mc::Frame* frame,
950                                 const char *ns)
951 {
952   int tag = dwarf_tag(die);
953   simgrid::dwarf::TagClass klass = simgrid::dwarf::classify_tag(tag);
954   switch (klass) {
955
956     // Type:
957   case simgrid::dwarf::TagClass::Type:
958     MC_dwarf_handle_type_die(info, die, unit, frame, ns);
959     break;
960
961     // Subprogram or scope:
962   case simgrid::dwarf::TagClass::Subprogram:
963   case simgrid::dwarf::TagClass::Scope:
964     MC_dwarf_handle_scope_die(info, die, unit, frame, ns);
965     return;
966
967     // Variable:
968   case simgrid::dwarf::TagClass::Variable:
969     MC_dwarf_handle_variable_die(info, die, unit, frame, ns);
970     break;
971
972   case simgrid::dwarf::TagClass::Namespace:
973     mc_dwarf_handle_namespace_die(info, die, unit, frame, ns);
974     break;
975
976   default:
977     break;
978
979   }
980 }
981
982 static
983 Elf64_Half get_type(Elf* elf)
984 {
985   Elf64_Ehdr* ehdr64 = elf64_getehdr(elf);
986   if (ehdr64)
987     return ehdr64->e_type;
988   Elf32_Ehdr* ehdr32 = elf32_getehdr(elf);
989   if (ehdr32)
990     return ehdr32->e_type;
991   xbt_die("Could not get ELF heeader");
992 }
993
994 static
995 void read_dwarf_info(simgrid::mc::ObjectInformation* info, Dwarf* dwarf)
996 {
997   // For each compilation unit:
998   Dwarf_Off offset = 0;
999   Dwarf_Off next_offset = 0;
1000   size_t length;
1001
1002   while (dwarf_nextcu(dwarf, offset, &next_offset, &length, nullptr, NULL, NULL) ==
1003          0) {
1004     Dwarf_Die unit_die;
1005     if (dwarf_offdie(dwarf, offset + length, &unit_die) != nullptr)
1006       MC_dwarf_handle_children(info, &unit_die, &unit_die, nullptr, NULL);
1007     offset = next_offset;
1008   }
1009 }
1010
1011 /** Get the build-id (NT_GNU_BUILD_ID) from the ELF file
1012  *
1013  *  This build-id may is used to locate an external debug (DWARF) file
1014  *  for this ELF file.
1015  *
1016  *  @param  elf libelf handle for an ELF file
1017  *  @return build-id for this ELF file (or an empty vector if none is found)
1018  */
1019 static
1020 std::vector<char> get_build_id(Elf* elf)
1021 {
1022   size_t phnum;
1023   if (elf_getphdrnum (elf, &phnum) != 0)
1024     xbt_die("Could not read program headers");
1025
1026   // Iterate over the program headers and find the PT_NOTE ones:
1027   for (size_t i = 0; i < phnum; ++i) {
1028     GElf_Phdr phdr_temp;
1029     GElf_Phdr *phdr = gelf_getphdr(elf, i, &phdr_temp);
1030     if (phdr->p_type != PT_NOTE)
1031       continue;
1032
1033     Elf_Data* data = elf_getdata_rawchunk(elf, phdr->p_offset, phdr->p_filesz, ELF_T_NHDR);
1034
1035     // Iterate over the notes and find the NT_GNU_BUILD_ID one:
1036     size_t pos = 0;
1037     while (1) {
1038       GElf_Nhdr nhdr;
1039       size_t name_pos;
1040       size_t desc_pos;
1041       pos = gelf_getnote(data, pos, &nhdr, &name_pos, &desc_pos);
1042       // A note is identified by a name "GNU" and a integer type within
1043       // the namespace defined by this name (here NT_GNU_BUILD_ID):
1044       if (nhdr.n_type == NT_GNU_BUILD_ID
1045           && nhdr.n_namesz == sizeof("GNU")
1046           && memcmp((char*) data->d_buf + name_pos, "GNU", sizeof("GNU")) == 0) {
1047
1048         // Found the NT_GNU_BUILD_ID note:
1049         char* start = (char*) data->d_buf + desc_pos;
1050         char* end = (char*) start + nhdr.n_descsz;
1051         return std::vector<char>(start, end);
1052
1053       }
1054     }
1055
1056   }
1057   return std::vector<char>();
1058 }
1059
1060 static char hexdigits[16] = {
1061   '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
1062   'a', 'b', 'c', 'd', 'e', 'f'
1063 };
1064
1065 /** Binary data to hexadecimal */
1066 static inline
1067 std::array<char, 2> to_hex(std::uint8_t byte)
1068 {
1069   // Horrid double braces!
1070   // Apparently, this is needed in C++11 (not in C++14).
1071   return { { hexdigits[byte >> 4], hexdigits[byte & 0xF] } };
1072 }
1073
1074 /** Binary data to hexadecimal */
1075 static
1076 std::string to_hex(const char* data, std::size_t count)
1077 {
1078   std::string res;
1079   res.resize(2*count);
1080   for (std::size_t i = 0; i < count; i++) {
1081     std::array<char, 2> hex_byte = to_hex(data[i]);
1082     for (int j = 0; j < 2; ++j)
1083       res[2 * i + j] = hex_byte[j];
1084   }
1085   return std::move(res);
1086 }
1087
1088 /** Binary data to hexadecimal */
1089 static
1090 std::string to_hex(std::vector<char> const& data)
1091 {
1092   return to_hex(data.data(), data.size());
1093 }
1094
1095 /** Base directories for external debug files */
1096 const char* debug_paths[] = {
1097   "/usr/lib/debug/",
1098   "/usr/local/lib/debug/",
1099 };
1100
1101 /** Locate an external debug file from the NT_GNU_BUILD_ID
1102  *
1103  *  This is one of the mechanisms used for
1104  *  [separate debug files](https://sourceware.org/gdb/onlinedocs/gdb/Separate-Debug-Files.html).
1105  */
1106 static
1107 std::string find_by_build_id(std::vector<char> id)
1108 {
1109   std::string filename;
1110   for (const char* debug_path : debug_paths) {
1111     filename = debug_path;
1112     filename += ".build-id/" + to_hex(id.data(), 1) + '/'
1113       + to_hex(id.data() + 1, id.size() - 1) + ".debug";
1114     XBT_DEBUG("Checking debug file: %s", filename.c_str());
1115     if (access(filename.c_str(), F_OK) == 0)
1116       return std::move(filename);
1117   }
1118   return std::string();
1119 }
1120
1121 /** \brief Populate the debugging informations of the given ELF object
1122  *
1123  *  Read the DWARf information of the EFFL object and populate the
1124  *  lists of types, variables, functions.
1125  */
1126 static
1127 void MC_dwarf_get_variables(simgrid::mc::ObjectInformation* info)
1128 {
1129   if (elf_version(EV_CURRENT) == EV_NONE)
1130     xbt_die("libelf initialization error");
1131
1132   // Open the ELF file:
1133   int fd = open(info->file_name.c_str(), O_RDONLY);
1134   if (fd < 0)
1135     xbt_die("Could not open file %s", info->file_name.c_str());
1136   Elf* elf = elf_begin(fd, ELF_C_READ, nullptr);
1137   if (elf == nullptr)
1138     xbt_die("Not an ELF file 1");
1139   Elf_Kind kind = elf_kind(elf);
1140   if (kind != ELF_K_ELF)
1141     xbt_die("Not an ELF file 2");
1142
1143   // Remember if this is a `ET_EXEC` (fixed location) or `ET_DYN` (relocatable):
1144   Elf64_Half type = get_type(elf);
1145   if (type == ET_EXEC)
1146     info->flags |= simgrid::mc::ObjectInformation::Executable;
1147
1148   // Read DWARF debug information in the file:
1149   Dwarf* dwarf = dwarf_begin_elf (elf, DWARF_C_READ, nullptr);
1150   if (dwarf != nullptr) {
1151     read_dwarf_info(info, dwarf);
1152     dwarf_end(dwarf);
1153     elf_end(elf);
1154     close(fd);
1155     return;
1156   }
1157   dwarf_end(dwarf);
1158
1159   // If there was no DWARF in the file, try to find it in a separate file
1160   // with NT_GNU_BUILD_ID:
1161   std::vector<char> build_id = get_build_id(elf);
1162   if (!build_id.empty()) {
1163     elf_end(elf);
1164     close(fd);
1165
1166     // Find the debug file using the build id:
1167     std::string debug_file = find_by_build_id(build_id);
1168     if (debug_file.empty()) {
1169       std::string hex = to_hex(build_id);
1170       xbt_die(
1171         "Missing debug info for %s with build-id %s\n"
1172         "You might want to install the suitable debugging package.\n",
1173         info->file_name.c_str(), hex.c_str());
1174     }
1175
1176     // Load the DWARF info from this file:
1177     XBT_DEBUG("Load DWARF for %s from %s",
1178       info->file_name.c_str(), debug_file.c_str());
1179     fd = open(debug_file.c_str(), O_RDONLY);
1180     if (fd < 0)
1181       xbt_die("Could not open file %s", debug_file.c_str());
1182     Dwarf* dwarf = dwarf_begin(fd, DWARF_C_READ);
1183     if (dwarf == nullptr)
1184       xbt_die("No DWARF info in %s for %s",
1185         debug_file.c_str(), info->file_name.c_str());
1186     read_dwarf_info(info, dwarf);
1187     dwarf_end(dwarf);
1188     close(fd);
1189     return;
1190   }
1191
1192   // TODO, try to find DWARF info using debug-link.
1193   // Is this method really used anywhere?
1194
1195   xbt_die("Debugging information not found for %s\n"
1196     "Try recompiling with -g\n",
1197     info->file_name.c_str());
1198 }
1199
1200 // ***** Functions index
1201
1202 static int MC_compare_frame_index_items(simgrid::mc::FunctionIndexEntry* a,
1203                                         simgrid::mc::FunctionIndexEntry* b)
1204 {
1205   if (a->low_pc < b->low_pc)
1206     return -1;
1207   else if (a->low_pc == b->low_pc)
1208     return 0;
1209   else
1210     return 1;
1211 }
1212
1213 static void MC_make_functions_index(simgrid::mc::ObjectInformation* info)
1214 {
1215   info->functions_index.clear();
1216
1217   for (auto& e : info->subprograms) {
1218     if (e.second.range.begin() == 0)
1219       continue;
1220     simgrid::mc::FunctionIndexEntry entry;
1221     entry.low_pc = (void*) e.second.range.begin();
1222     entry.function = &e.second;
1223     info->functions_index.push_back(entry);
1224   }
1225
1226   info->functions_index.shrink_to_fit();
1227
1228   // Sort the array by low_pc:
1229   std::sort(info->functions_index.begin(), info->functions_index.end(),
1230         [](simgrid::mc::FunctionIndexEntry const& a,
1231           simgrid::mc::FunctionIndexEntry const& b)
1232         {
1233           return a.low_pc < b.low_pc;
1234         });
1235 }
1236
1237 static void MC_post_process_variables(simgrid::mc::ObjectInformation* info)
1238 {
1239   // Someone needs this to be sorted but who?
1240   std::sort(info->global_variables.begin(), info->global_variables.end(),
1241     MC_compare_variable);
1242
1243   for(simgrid::mc::Variable& variable : info->global_variables)
1244     if (variable.type_id)
1245       variable.type = simgrid::util::find_map_ptr(
1246         info->types, variable.type_id);
1247 }
1248
1249 static void mc_post_process_scope(simgrid::mc::ObjectInformation* info, simgrid::mc::Frame* scope)
1250 {
1251
1252   if (scope->tag == DW_TAG_inlined_subroutine) {
1253     // Attach correct namespaced name in inlined subroutine:
1254     auto i = info->subprograms.find(scope->abstract_origin_id);
1255     xbt_assert(i != info->subprograms.end(),
1256       "Could not lookup abstract origin %" PRIx64,
1257       (std::uint64_t) scope->abstract_origin_id);
1258     scope->name = i->second.name;
1259   }
1260
1261   // Direct:
1262   for (simgrid::mc::Variable& variable : scope->variables)
1263     if (variable.type_id)
1264       variable.type = simgrid::util::find_map_ptr(
1265         info->types, variable.type_id);
1266
1267   // Recursive post-processing of nested-scopes:
1268   for (simgrid::mc::Frame& nested_scope : scope->scopes)
1269       mc_post_process_scope(info, &nested_scope);
1270
1271 }
1272
1273 static
1274 simgrid::mc::Type* MC_resolve_type(
1275   simgrid::mc::ObjectInformation* info, unsigned type_id)
1276 {
1277   if (!type_id)
1278     return nullptr;
1279   simgrid::mc::Type* type = simgrid::util::find_map_ptr(info->types, type_id);
1280   if (type == nullptr)
1281     return nullptr;
1282
1283   // We already have the information on the type:
1284   if (type->byte_size != 0)
1285     return type;
1286
1287   // Don't have a name, we can't find a more complete version:
1288   if (type->name.empty())
1289     return type;
1290
1291   // Try to find a more complete description of the type:
1292   // We need to fix in order to support C++.
1293   simgrid::mc::Type** subtype = simgrid::util::find_map_ptr(
1294     info->full_types_by_name, type->name);
1295   if (subtype)
1296     type = *subtype;
1297   return type;
1298 }
1299
1300 static void MC_post_process_types(simgrid::mc::ObjectInformation* info)
1301 {
1302   // Lookup "subtype" field:
1303   for(auto& i : info->types) {
1304     i.second.subtype = MC_resolve_type(info, i.second.type_id);
1305     for (simgrid::mc::Member& member : i.second.members)
1306       member.type = MC_resolve_type(info, member.type_id);
1307   }
1308 }
1309
1310 /** \brief Finds informations about a given shared object/executable */
1311 std::shared_ptr<simgrid::mc::ObjectInformation> MC_find_object_info(
1312   std::vector<simgrid::xbt::VmMap> const& maps, const char *name)
1313 {
1314   std::shared_ptr<simgrid::mc::ObjectInformation> result =
1315     std::make_shared<simgrid::mc::ObjectInformation>();
1316   result->file_name = name;
1317   simgrid::mc::find_object_address(maps, result.get());
1318   MC_dwarf_get_variables(result.get());
1319   MC_post_process_variables(result.get());
1320   MC_post_process_types(result.get());
1321   for (auto& entry : result.get()->subprograms)
1322     mc_post_process_scope(result.get(), &entry.second);
1323   MC_make_functions_index(result.get());
1324   return std::move(result);
1325 }
1326
1327 /*************************************************************************/
1328
1329 void MC_post_process_object_info(simgrid::mc::Process* process, simgrid::mc::ObjectInformation* info)
1330 {
1331   for (auto& i : info->types) {
1332
1333     simgrid::mc::Type* type = &(i.second);
1334     simgrid::mc::Type* subtype = type;
1335     while (subtype->type == DW_TAG_typedef
1336         || subtype->type == DW_TAG_volatile_type
1337         || subtype->type == DW_TAG_const_type)
1338       if (subtype->subtype)
1339         subtype = subtype->subtype;
1340       else
1341         break;
1342
1343     // Resolve full_type:
1344     if (!subtype->name.empty() && subtype->byte_size == 0)
1345       for (auto const& object_info : process->object_infos) {
1346         auto i = object_info->full_types_by_name.find(subtype->name);
1347         if (i != object_info->full_types_by_name.end()
1348             && !i->second->name.empty() && i->second->byte_size) {
1349           type->full_type = i->second;
1350           break;
1351         }
1352       }
1353     else type->full_type = subtype;
1354
1355   }
1356 }
1357
1358 namespace simgrid {
1359 namespace dwarf {
1360
1361 /** Convert a DWARF register into a libunwind register
1362  *
1363  *  DWARF and libunwind does not use the same convention for numbering the
1364  *  registers on some architectures. The function makes the necessary
1365  *  convertion.
1366  */
1367 int dwarf_register_to_libunwind(int dwarf_register)
1368 {
1369 #if defined(__x86_64__)
1370   // It seems for this arch, DWARF and libunwind agree in the numbering:
1371   return dwarf_register;
1372 #elif defined(__i386__)
1373   // Could't find the authoritative source of information for this.
1374   // This is inspired from http://source.winehq.org/source/dlls/dbghelp/cpu_i386.c#L517.
1375   switch (dwarf_register) {
1376   case 0:
1377     return UNW_X86_EAX;
1378   case 1:
1379     return UNW_X86_ECX;
1380   case 2:
1381     return UNW_X86_EDX;
1382   case 3:
1383     return UNW_X86_EBX;
1384   case 4:
1385     return UNW_X86_ESP;
1386   case 5:
1387     return UNW_X86_EBP;
1388   case 6:
1389     return UNW_X86_ESI;
1390   case 7:
1391     return UNW_X86_EDI;
1392   case 8:
1393     return UNW_X86_EIP;
1394   case 9:
1395     return UNW_X86_EFLAGS;
1396   case 10:
1397     return UNW_X86_CS;
1398   case 11:
1399     return UNW_X86_SS;
1400   case 12:
1401     return UNW_X86_DS;
1402   case 13:
1403     return UNW_X86_ES;
1404   case 14:
1405     return UNW_X86_FS;
1406   case 15:
1407     return UNW_X86_GS;
1408   case 16:
1409     return UNW_X86_ST0;
1410   case 17:
1411     return UNW_X86_ST1;
1412   case 18:
1413     return UNW_X86_ST2;
1414   case 19:
1415     return UNW_X86_ST3;
1416   case 20:
1417     return UNW_X86_ST4;
1418   case 21:
1419     return UNW_X86_ST5;
1420   case 22:
1421     return UNW_X86_ST6;
1422   case 23:
1423     return UNW_X86_ST7;
1424   default:
1425     xbt_die("Bad/unknown register number.");
1426   }
1427 #else
1428 #error This architecture is not supported yet for DWARF expression evaluation.
1429 #endif
1430 }
1431
1432 }
1433 }