PR25058 - Better support fn DIEs referring to symbols using DW_AT_ranges
[platform/upstream/libabigail.git] / src / abg-dwarf-reader.cc
1 // -*- Mode: C++ -*-
2 //
3 // Copyright (C) 2013-2019 Red Hat, Inc.
4 //
5 // This file is part of the GNU Application Binary Interface Generic
6 // Analysis and Instrumentation Library (libabigail).  This library is
7 // free software; you can redistribute it and/or modify it under the
8 // terms of the GNU Lesser General Public License as published by the
9 // Free Software Foundation; either version 3, or (at your option) any
10 // later version.
11
12 // This library is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Lesser Public License for more details.
16
17 // You should have received a copy of the GNU Lesser General Public
18 // License along with this program; see the file COPYING-LGPLV3.  If
19 // not, see <http://www.gnu.org/licenses/>.
20 //
21 // Author: Dodji Seketeli
22
23 /// @file
24 ///
25 /// This file contains the definitions of the entry points to
26 /// de-serialize an instance of @ref abigail::corpus from a file in
27 /// elf format, containing dwarf information.
28
29 #include "config.h"
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <fcntl.h>
33 #include <unistd.h>
34 #include <libgen.h>
35 #include <assert.h>
36 #include <limits.h>
37 #include <cstring>
38 #include <cmath>
39 #include <elfutils/libdwfl.h>
40 #include <dwarf.h>
41 #include <algorithm>
42 #include <stack>
43 #include <deque>
44 #include <list>
45 #include <ostream>
46 #include <sstream>
47
48 #include "abg-cxx-compat.h"
49 #include "abg-ir-priv.h"
50 #include "abg-suppression-priv.h"
51 #include "abg-corpus-priv.h"
52
53 #include "abg-internal.h"
54 // <headers defining libabigail's API go under here>
55 ABG_BEGIN_EXPORT_DECLARATIONS
56
57 #include "abg-dwarf-reader.h"
58 #include "abg-sptr-utils.h"
59 #include "abg-tools-utils.h"
60
61 ABG_END_EXPORT_DECLARATIONS
62 // </headers defining libabigail's API>
63
64 #ifndef UINT64_MAX
65 #define UINT64_MAX 0xffffffffffffffff
66 #endif
67
68 using std::string;
69
70 namespace abigail
71 {
72
73 using std::cerr;
74
75 /// The namespace for the DWARF reader.
76 namespace dwarf_reader
77 {
78
79 using abg_compat::dynamic_pointer_cast;
80 using abg_compat::static_pointer_cast;
81 using abg_compat::unordered_map;
82 using abg_compat::unordered_set;
83 using std::stack;
84 using std::deque;
85 using std::list;
86
87 /// Where a DIE comes from. For instance, a DIE can come from the main
88 /// debug info section, the alternate debug info section or from the
89 /// type unit section.
90 enum die_source
91 {
92   NO_DEBUG_INFO_DIE_SOURCE,
93   PRIMARY_DEBUG_INFO_DIE_SOURCE,
94   ALT_DEBUG_INFO_DIE_SOURCE,
95   TYPE_UNIT_DIE_SOURCE,
96   NUMBER_OF_DIE_SOURCES,        // This one must always be the latest
97                                 // enumerator
98 };
99
100 /// Prefix increment operator for @ref die_source.
101 ///
102 /// @param source the die_source to increment.
103 /// @return the incremented source.
104 static die_source&
105 operator++(die_source& source)
106 {
107   source = static_cast<die_source>(source + 1);
108   return source;
109 }
110
111 /// A functor used by @ref dwfl_sptr.
112 struct dwfl_deleter
113 {
114   void
115   operator()(Dwfl* dwfl)
116   {dwfl_end(dwfl);}
117 };//end struct dwfl_deleter
118
119 /// A convenience typedef for a shared pointer to a Dwfl.
120 typedef shared_ptr<Dwfl> dwfl_sptr;
121
122 /// A convenience typedef for a vector of Dwarf_Off.
123 typedef vector<Dwarf_Off> dwarf_offsets_type;
124
125 /// Convenience typedef for a map which key is the offset of a dwarf
126 /// die and which value is the corresponding artefact.
127 typedef unordered_map<Dwarf_Off, type_or_decl_base_sptr> die_artefact_map_type;
128
129 /// Convenience typedef for a map which key is the offset of a dwarf
130 /// die, (given by dwarf_dieoffset()) and which value is the
131 /// corresponding class_decl.
132 typedef unordered_map<Dwarf_Off, class_decl_sptr> die_class_map_type;
133
134 /// Convenience typedef for a map which key is the offset of a dwarf
135 /// die, (given by dwarf_dieoffset()) and which value is the
136 /// corresponding class_or_union_sptr.
137 typedef unordered_map<Dwarf_Off, class_or_union_sptr> die_class_or_union_map_type;
138
139 /// Convenience typedef for a map which key the offset of a dwarf die
140 /// and which value is the corresponding function_decl.
141 typedef unordered_map<Dwarf_Off, function_decl_sptr> die_function_decl_map_type;
142
143 /// Convenience typedef for a map which key is the offset of a dwarf
144 /// die and which value is the corresponding function_type.
145 typedef unordered_map<Dwarf_Off, function_type_sptr> die_function_type_map_type;
146
147 /// Convenience typedef for a map which key is the offset of a
148 /// DW_TAG_compile_unit and the value is the corresponding @ref
149 /// translation_unit_sptr.
150 typedef unordered_map<Dwarf_Off, translation_unit_sptr> die_tu_map_type;
151
152 /// Convenience typedef for a map which key is the offset of a DIE and
153 /// the value is the corresponding qualified name of the DIE.
154 typedef unordered_map<Dwarf_Off, interned_string> die_istring_map_type;
155
156 /// Convenience typedef for a map which is an interned_string and
157 /// which value is a vector of offsets.
158 typedef unordered_map<interned_string,
159                       dwarf_offsets_type,
160                       hash_interned_string>
161 istring_dwarf_offsets_map_type;
162
163 /// Convenience typedef for a map which key is an elf address and
164 /// which value is an elf_symbol_sptr.
165 typedef unordered_map<GElf_Addr, elf_symbol_sptr> addr_elf_symbol_sptr_map_type;
166
167 /// Convenience typedef for a set of ELF addresses.
168 typedef unordered_set<GElf_Addr> address_set_type;
169
170 typedef unordered_set<interned_string, hash_interned_string> istring_set_type;
171
172 /// Convenience typedef for a shared pointer to an @ref address_set_type.
173 typedef shared_ptr<address_set_type> address_set_sptr;
174
175 /// Convenience typedef for a shared pointer to an
176 /// addr_elf_symbol_sptr_map_type.
177 typedef shared_ptr<addr_elf_symbol_sptr_map_type> addr_elf_symbol_sptr_map_sptr;
178
179 /// Convenience typedef for a map that associates an @ref
180 /// interned_string to a @ref function_type_sptr.
181 typedef unordered_map<interned_string,
182                       function_type_sptr,
183                       hash_interned_string> istring_fn_type_map_type;
184
185 /// Convenience typedef for a stack containing the scopes up to the
186 /// current point in the abigail Internal Representation (aka IR) tree
187 /// that is being built.
188 typedef stack<scope_decl*> scope_stack_type;
189
190 /// Convenience typedef for a map which key is a dwarf offset.  The
191 /// value is also a dwarf offset.
192 typedef unordered_map<Dwarf_Off, Dwarf_Off> offset_offset_map_type;
193
194 /// Convenience typedef for a map which key is a string and which
195 /// value is a vector of smart pointer to a class.
196 typedef unordered_map<string, classes_type> string_classes_map;
197
198 /// The abstraction of the place where a partial unit has been
199 /// imported.  This is what the DW_TAG_imported_unit DIE expresses.
200 ///
201 /// This type thus contains:
202 ///     - the offset to which the partial unit is imported
203 ///     - the offset of the imported partial unit.
204 ///     - the offset of the imported partial unit.
205 struct imported_unit_point
206 {
207   Dwarf_Off     offset_of_import;
208   // The boolean below is true iff the imported unit comes from the
209   // alternate debug info file.
210   die_source    imported_unit_die_source;
211   Dwarf_Off     imported_unit_die_off;
212   Dwarf_Off     imported_unit_cu_off;
213   Dwarf_Off     imported_unit_child_off;
214
215   /// Default constructor for @ref the type imported_unit_point.
216   imported_unit_point ()
217     : offset_of_import(),
218       imported_unit_die_source(PRIMARY_DEBUG_INFO_DIE_SOURCE),
219       imported_unit_die_off(),
220       imported_unit_cu_off(),
221       imported_unit_child_off()
222   {}
223
224   /// Constructor of @ref the type imported_unit_point.
225   ///
226   /// @param import_off the offset of the point at which the unit has
227   /// been imported.
228   imported_unit_point (Dwarf_Off import_off)
229     : offset_of_import(import_off),
230       imported_unit_die_source(PRIMARY_DEBUG_INFO_DIE_SOURCE),
231       imported_unit_die_off(),
232       imported_unit_cu_off(),
233       imported_unit_child_off()
234   {}
235
236   /// Constructor of @ref the type imported_unit_point.
237   ///
238   /// @param import_off the offset of the point at which the unit has
239   /// been imported.
240   ///
241   /// @param from where the imported DIE comes from.
242   ///
243   /// @param imported_die the die of the unit that has been imported.
244   imported_unit_point (Dwarf_Off        import_off,
245                        const Dwarf_Die& imported_die,
246                        die_source from)
247     : offset_of_import(import_off),
248       imported_unit_die_source(from),
249       imported_unit_die_off(dwarf_dieoffset
250                             (const_cast<Dwarf_Die*>(&imported_die))),
251       imported_unit_cu_off(),
252       imported_unit_child_off()
253   {
254     Dwarf_Die imported_unit_child;
255
256     dwarf_child(const_cast<Dwarf_Die*>(&imported_die),
257                 &imported_unit_child);
258     imported_unit_child_off =
259       dwarf_dieoffset(const_cast<Dwarf_Die*>(&imported_unit_child));
260
261     Dwarf_Die cu_die_memory;
262     Dwarf_Die *cu_die;
263
264     cu_die = dwarf_diecu(const_cast<Dwarf_Die*>(&imported_unit_child),
265                          &cu_die_memory, 0, 0);
266     imported_unit_cu_off = dwarf_dieoffset(cu_die);
267   }
268 }; // struct imported_unit_point
269
270 /// Convenience typedef for a vector of @ref imported_unit_point.
271 typedef vector<imported_unit_point> imported_unit_points_type;
272
273 /// Convenience typedef for a vector of @ref imported_unit_point.
274 typedef unordered_map<Dwarf_Off, imported_unit_points_type>
275 tu_die_imported_unit_points_map_type;
276
277 /// "Less than" operator for instances of @ref imported_unit_point
278 /// type.
279 ///
280 /// @param the left hand side operand of the "Less than" operator.
281 ///
282 /// @param the right hand side operand of the "Less than" operator.
283 ///
284 /// @return true iff @p l is less than @p r.
285 static bool
286 operator<(const imported_unit_point& l, const imported_unit_point& r)
287 {return l.offset_of_import < r.offset_of_import;}
288
289 static void
290 add_symbol_to_map(const elf_symbol_sptr& sym,
291                   string_elf_symbols_map_type& map);
292
293 static bool
294 find_symbol_table_section(Elf* elf_handle, Elf_Scn*& section);
295
296 static bool
297 get_symbol_versionning_sections(Elf*            elf_handle,
298                                 Elf_Scn*&       versym_section,
299                                 Elf_Scn*&       verdef_section,
300                                 Elf_Scn*&       verneed_section);
301
302 static bool
303 get_parent_die(const read_context&      ctxt,
304                const Dwarf_Die* die,
305                Dwarf_Die&               parent_die,
306                size_t                   where_offset);
307
308 static bool
309 get_scope_die(const read_context&       ctxt,
310               const Dwarf_Die*          die,
311               size_t                    where_offset,
312               Dwarf_Die&                scope_die);
313
314 static bool
315 die_is_anonymous(const Dwarf_Die* die);
316
317 static bool
318 die_is_type(const Dwarf_Die* die);
319
320 static bool
321 die_is_decl(const Dwarf_Die* die);
322
323 static bool
324 die_is_namespace(const Dwarf_Die* die);
325
326 static bool
327 die_is_unspecified(Dwarf_Die* die);
328
329 static bool
330 die_is_void_type(Dwarf_Die* die);
331
332 static bool
333 die_is_pointer_type(const Dwarf_Die* die);
334
335 static bool
336 pointer_or_qual_die_of_anonymous_class_type(const Dwarf_Die* die);
337
338 static bool
339 die_is_reference_type(const Dwarf_Die* die);
340
341 static bool
342 die_is_pointer_or_reference_type(const Dwarf_Die* die);
343
344 static bool
345 die_is_pointer_reference_or_typedef_type(const Dwarf_Die* die);
346
347 static bool
348 die_is_class_type(const Dwarf_Die* die);
349
350 static bool
351 die_is_qualified_type(const Dwarf_Die* die);
352
353 static bool
354 die_is_function_type(const Dwarf_Die *die);
355
356 static bool
357 die_has_object_pointer(const Dwarf_Die* die,
358                        Dwarf_Die& object_pointer);
359
360 static bool
361 die_this_pointer_from_object_pointer(Dwarf_Die* die,
362                                      Dwarf_Die& this_pointer);
363
364 static bool
365 die_this_pointer_is_const(Dwarf_Die* die);
366
367 static bool
368 die_object_pointer_is_for_const_method(Dwarf_Die* die);
369
370 static bool
371 die_is_at_class_scope(const read_context& ctxt,
372                       const Dwarf_Die* die,
373                       size_t where_offset,
374                       Dwarf_Die& class_scope_die);
375 static bool
376 eval_last_constant_dwarf_sub_expr(Dwarf_Op*     expr,
377                                   uint64_t      expr_len,
378                                   int64_t&      value,
379                                   bool& is_tls_address);
380
381 static translation_unit::language
382 dwarf_language_to_tu_language(size_t l);
383
384 static bool
385 die_unsigned_constant_attribute(const Dwarf_Die*        die,
386                                 unsigned                attr_name,
387                                 uint64_t&               cst);
388
389 static bool
390 die_signed_constant_attribute(const Dwarf_Die*die,
391                               unsigned  attr_name,
392                               int64_t&  cst);
393
394 static bool
395 die_constant_attribute(const Dwarf_Die *die,
396                        unsigned attr_name,
397                        array_type_def::subrange_type::bound_value &value);
398
399 static bool
400 die_attribute_has_form(const Dwarf_Die* die,
401                        unsigned attr_name,
402                        unsigned int     form);
403
404 static bool
405 form_is_DW_FORM_strx(unsigned form);
406
407 static bool
408 die_attribute_is_signed(const Dwarf_Die* die, unsigned attr_name);
409
410 static bool
411 die_attribute_is_unsigned(const Dwarf_Die* die, unsigned attr_name);
412
413 static bool
414 die_attribute_has_no_signedness(const Dwarf_Die* die, unsigned attr_name);
415
416 static bool
417 die_address_attribute(Dwarf_Die* die, unsigned attr_name, Dwarf_Addr& result);
418
419 static string
420 die_name(const Dwarf_Die* die);
421
422 static location
423 die_location(const read_context& ctxt, const Dwarf_Die* die);
424
425 static bool
426 die_location_address(Dwarf_Die* die,
427                      Dwarf_Addr&        address,
428                      bool&              is_tls_address);
429
430 static bool
431 die_die_attribute(const Dwarf_Die* die,
432                   unsigned attr_name,
433                   Dwarf_Die& result,
434                   bool look_thru_abstract_origin = true);
435
436 static string
437 get_internal_anonymous_die_prefix_name(const Dwarf_Die *die);
438
439 static string
440 build_internal_anonymous_die_name(const string &base_name,
441                                   size_t anonymous_type_index);
442
443
444 static string
445 get_internal_anonymous_die_name(Dwarf_Die *die,
446                                 size_t anonymous_type_index);
447
448 static string
449 die_qualified_type_name(const read_context& ctxt,
450                         const Dwarf_Die* die,
451                         size_t where);
452
453 static string
454 die_qualified_decl_name(const read_context& ctxt,
455                         const Dwarf_Die* die,
456                         size_t where);
457
458 static string
459 die_qualified_name(const read_context& ctxt,
460                    const Dwarf_Die* die,
461                    size_t where);
462
463 static bool
464 die_qualified_type_name_empty(const read_context& ctxt,
465                               const Dwarf_Die* die, size_t where,
466                               string &qualified_name);
467
468 static void
469 die_return_and_parm_names_from_fn_type_die(const read_context& ctxt,
470                                            const Dwarf_Die* die,
471                                            size_t where_offset,
472                                            bool pretty_print,
473                                            string &return_type_name,
474                                            string &class_name,
475                                            vector<string>& parm_names,
476                                            bool& is_const,
477                                            bool& is_static);
478
479 static string
480 die_function_signature(const read_context& ctxt,
481                        const Dwarf_Die *die,
482                        size_t where_offset);
483
484 static bool
485 die_peel_qual_ptr(Dwarf_Die *die, Dwarf_Die& peeled_die);
486
487 static bool
488 die_function_type_is_method_type(const read_context& ctxt,
489                                  const Dwarf_Die *die,
490                                  size_t where_offset,
491                                  Dwarf_Die& object_pointer_die,
492                                  Dwarf_Die& class_die,
493                                  bool& is_static);
494
495 static string
496 die_pretty_print_type(read_context& ctxt,
497                       const Dwarf_Die* die,
498                       size_t where_offset);
499
500 static string
501 die_pretty_print_decl(read_context& ctxt,
502                       const Dwarf_Die* die,
503                       size_t where_offset);
504
505 static string
506 die_pretty_print(read_context& ctxt,
507                  const Dwarf_Die* die,
508                  size_t where_offset);
509
510 static void
511 maybe_canonicalize_type(const Dwarf_Die* die,
512                         read_context& ctxt);
513
514 static void
515 maybe_canonicalize_type(const type_base_sptr&   t,
516                         read_context&           ctxt);
517
518 static void
519 maybe_canonicalize_type(const Dwarf_Die*        die,
520                         const type_base_sptr&   t,
521                         read_context&           ctxt);
522
523 static uint64_t
524 get_default_array_lower_bound(translation_unit::language l);
525
526 static bool
527 find_lower_bound_in_imported_unit_points(const imported_unit_points_type&,
528                                          Dwarf_Off,
529                                          imported_unit_points_type::const_iterator&);
530
531 static array_type_def::subrange_sptr
532 build_subrange_type(read_context&       ctxt,
533                     const Dwarf_Die*    die,
534                     size_t              where_offset,
535                     bool                associate_type_to_die = true);
536
537 static void
538 build_subranges_from_array_type_die(read_context&                       ctxt,
539                                     const Dwarf_Die*                    die,
540                                     array_type_def::subranges_type&     subranges,
541                                     size_t                              where_offset,
542                                     bool                                associate_type_to_die = true);
543
544 static bool
545 compare_dies(const read_context& ctxt,
546              const Dwarf_Die *l, const Dwarf_Die *r,
547              bool update_canonical_dies_on_the_fly);
548
549 /// Convert an elf symbol type (given by the ELF{32,64}_ST_TYPE
550 /// macros) into an elf_symbol::type value.
551 ///
552 /// Note that this function aborts when given an unexpected value.
553 ///
554 /// @param the symbol type value to convert.
555 ///
556 /// @return the converted value.
557 static elf_symbol::type
558 stt_to_elf_symbol_type(unsigned char stt)
559 {
560   elf_symbol::type t = elf_symbol::NOTYPE_TYPE;
561
562   switch (stt)
563     {
564     case STT_NOTYPE:
565       t = elf_symbol::NOTYPE_TYPE;
566       break;
567     case STT_OBJECT:
568       t = elf_symbol::OBJECT_TYPE;
569       break;
570     case STT_FUNC:
571       t = elf_symbol::FUNC_TYPE;
572       break;
573     case STT_SECTION:
574       t = elf_symbol::SECTION_TYPE;
575       break;
576     case STT_FILE:
577       t = elf_symbol::FILE_TYPE;
578       break;
579     case STT_COMMON:
580       t = elf_symbol::COMMON_TYPE;
581       break;
582     case STT_TLS:
583       t = elf_symbol::TLS_TYPE;
584       break;
585     case STT_GNU_IFUNC:
586       t = elf_symbol::GNU_IFUNC_TYPE;
587       break;
588     default:
589       // An unknown value that probably ought to be supported?  Let's
590       // abort right here rather than yielding garbage.
591       ABG_ASSERT_NOT_REACHED;
592     }
593
594   return t;
595 }
596
597 /// Convert an elf symbol binding (given by the ELF{32,64}_ST_BIND
598 /// macros) into an elf_symbol::binding value.
599 ///
600 /// Note that this function aborts when given an unexpected value.
601 ///
602 /// @param the symbol binding value to convert.
603 ///
604 /// @return the converted value.
605 static elf_symbol::binding
606 stb_to_elf_symbol_binding(unsigned char stb)
607 {
608   elf_symbol::binding b = elf_symbol::GLOBAL_BINDING;
609
610   switch (stb)
611     {
612     case STB_LOCAL:
613       b = elf_symbol::LOCAL_BINDING;
614       break;
615     case STB_GLOBAL:
616       b = elf_symbol::GLOBAL_BINDING;
617       break;
618     case STB_WEAK:
619       b = elf_symbol::WEAK_BINDING;
620       break;
621     case STB_GNU_UNIQUE:
622       b = elf_symbol::GNU_UNIQUE_BINDING;
623       break;
624     default:
625       ABG_ASSERT_NOT_REACHED;
626     }
627
628   return b;
629
630 }
631
632 /// Convert an ELF symbol visiblity given by the symbols ->st_other
633 /// data member as returned by the GELF_ST_VISIBILITY macro into a
634 /// elf_symbol::visiblity value.
635 ///
636 /// @param stv the value of the ->st_other data member of the ELF
637 /// symbol.
638 ///
639 /// @return the converted elf_symbol::visiblity value.
640 static elf_symbol::visibility
641 stv_to_elf_symbol_visibility(unsigned char stv)
642 {
643
644   elf_symbol::visibility v = elf_symbol::DEFAULT_VISIBILITY;
645
646   switch (stv)
647     {
648     case STV_DEFAULT:
649       v = elf_symbol::DEFAULT_VISIBILITY;
650       break;
651     case STV_INTERNAL:
652       v = elf_symbol::INTERNAL_VISIBILITY;
653       break;
654     case STV_HIDDEN:
655       v = elf_symbol::HIDDEN_VISIBILITY;
656       break;
657     case STV_PROTECTED:
658       v = elf_symbol::PROTECTED_VISIBILITY;
659       break;
660     default:
661       ABG_ASSERT_NOT_REACHED;
662     }
663
664   return v;
665 }
666
667 /// Convert the value of the e_machine field of GElf_Ehdr into a
668 /// string.  This is to get a string representing the architecture of
669 /// the elf file at hand.
670 ///
671 /// @param e_machine the value of GElf_Ehdr::e_machine.
672 ///
673 /// @return the string representation of GElf_Ehdr::e_machine.
674 static string
675 e_machine_to_string(GElf_Half e_machine)
676 {
677   string result;
678   switch (e_machine)
679     {
680     case EM_NONE:
681       result = "elf-no-arch";
682       break;
683     case EM_M32:
684       result = "elf-att-we-32100";
685       break;
686     case EM_SPARC:
687       result = "elf-sun-sparc";
688       break;
689     case EM_386:
690       result = "elf-intel-80386";
691       break;
692     case EM_68K:
693       result = "elf-motorola-68k";
694       break;
695     case EM_88K:
696       result = "elf-motorola-88k";
697       break;
698     case EM_860:
699       result = "elf-intel-80860";
700       break;
701     case EM_MIPS:
702       result = "elf-mips-r3000-be";
703       break;
704     case EM_S370:
705       result = "elf-ibm-s370";
706       break;
707     case EM_MIPS_RS3_LE:
708       result = "elf-mips-r3000-le";
709       break;
710     case EM_PARISC:
711       result = "elf-hp-parisc";
712       break;
713     case EM_VPP500:
714       result = "elf-fujitsu-vpp500";
715       break;
716     case EM_SPARC32PLUS:
717       result = "elf-sun-sparc-v8plus";
718       break;
719     case EM_960:
720       result = "elf-intel-80960";
721       break;
722     case EM_PPC:
723       result = "elf-powerpc";
724       break;
725     case EM_PPC64:
726       result = "elf-powerpc-64";
727       break;
728     case EM_S390:
729       result = "elf-ibm-s390";
730       break;
731     case EM_V800:
732       result = "elf-nec-v800";
733       break;
734     case EM_FR20:
735       result = "elf-fujitsu-fr20";
736       break;
737     case EM_RH32:
738       result = "elf-trw-rh32";
739       break;
740     case EM_RCE:
741       result = "elf-motorola-rce";
742       break;
743     case EM_ARM:
744       result = "elf-arm";
745       break;
746     case EM_FAKE_ALPHA:
747       result = "elf-digital-alpha";
748       break;
749     case EM_SH:
750       result = "elf-hitachi-sh";
751       break;
752     case EM_SPARCV9:
753       result = "elf-sun-sparc-v9-64";
754       break;
755     case EM_TRICORE:
756       result = "elf-siemens-tricore";
757       break;
758     case EM_ARC:
759       result = "elf-argonaut-risc-core";
760       break;
761     case EM_H8_300:
762       result = "elf-hitachi-h8-300";
763       break;
764     case EM_H8_300H:
765       result = "elf-hitachi-h8-300h";
766       break;
767     case EM_H8S:
768       result = "elf-hitachi-h8s";
769       break;
770     case EM_H8_500:
771       result = "elf-hitachi-h8-500";
772       break;
773     case EM_IA_64:
774       result = "elf-intel-ia-64";
775       break;
776     case EM_MIPS_X:
777       result = "elf-stanford-mips-x";
778       break;
779     case EM_COLDFIRE:
780       result = "elf-motorola-coldfire";
781       break;
782     case EM_68HC12:
783       result = "elf-motorola-68hc12";
784       break;
785     case EM_MMA:
786       result = "elf-fujitsu-mma";
787       break;
788     case EM_PCP:
789       result = "elf-siemens-pcp";
790       break;
791     case EM_NCPU:
792       result = "elf-sony-ncpu";
793       break;
794     case EM_NDR1:
795       result = "elf-denso-ndr1";
796       break;
797     case EM_STARCORE:
798       result = "elf-motorola-starcore";
799       break;
800     case EM_ME16:
801       result = "elf-toyota-me16";
802       break;
803     case EM_ST100:
804       result = "elf-stm-st100";
805       break;
806     case EM_TINYJ:
807       result = "elf-alc-tinyj";
808       break;
809     case EM_X86_64:
810       result = "elf-amd-x86_64";
811       break;
812     case EM_PDSP:
813       result = "elf-sony-pdsp";
814       break;
815     case EM_FX66:
816       result = "elf-siemens-fx66";
817       break;
818     case EM_ST9PLUS:
819       result = "elf-stm-st9+";
820       break;
821     case EM_ST7:
822       result = "elf-stm-st7";
823       break;
824     case EM_68HC16:
825       result = "elf-motorola-68hc16";
826       break;
827     case EM_68HC11:
828       result = "elf-motorola-68hc11";
829       break;
830     case EM_68HC08:
831       result = "elf-motorola-68hc08";
832       break;
833     case EM_68HC05:
834       result = "elf-motorola-68hc05";
835       break;
836     case EM_SVX:
837       result = "elf-sg-svx";
838       break;
839     case EM_ST19:
840       result = "elf-stm-st19";
841       break;
842     case EM_VAX:
843       result = "elf-digital-vax";
844       break;
845     case EM_CRIS:
846       result = "elf-axis-cris";
847       break;
848     case EM_JAVELIN:
849       result = "elf-infineon-javelin";
850       break;
851     case EM_FIREPATH:
852       result = "elf-firepath";
853       break;
854     case EM_ZSP:
855       result = "elf-lsi-zsp";
856       break;
857     case EM_MMIX:
858       result = "elf-don-knuth-mmix";
859       break;
860     case EM_HUANY:
861       result = "elf-harvard-huany";
862       break;
863     case EM_PRISM:
864       result = "elf-sitera-prism";
865       break;
866     case EM_AVR:
867       result = "elf-atmel-avr";
868       break;
869     case EM_FR30:
870       result = "elf-fujistu-fr30";
871       break;
872     case EM_D10V:
873       result = "elf-mitsubishi-d10v";
874       break;
875     case EM_D30V:
876       result = "elf-mitsubishi-d30v";
877       break;
878     case EM_V850:
879       result = "elf-nec-v850";
880       break;
881     case EM_M32R:
882       result = "elf-mitsubishi-m32r";
883       break;
884     case EM_MN10300:
885       result = "elf-matsushita-mn10300";
886       break;
887     case EM_MN10200:
888       result = "elf-matsushita-mn10200";
889       break;
890     case EM_PJ:
891       result = "elf-picojava";
892       break;
893     case EM_OPENRISC:
894       result = "elf-openrisc-32";
895       break;
896     case EM_ARC_A5:
897       result = "elf-arc-a5";
898       break;
899     case EM_XTENSA:
900       result = "elf-tensilica-xtensa";
901       break;
902
903 #ifdef HAVE_EM_AARCH64_MACRO
904     case EM_AARCH64:
905       result = "elf-arm-aarch64";
906       break;
907 #endif
908
909 #ifdef HAVE_EM_TILEPRO_MACRO
910     case EM_TILEPRO:
911       result = "elf-tilera-tilepro";
912       break;
913 #endif
914
915 #ifdef HAVE_EM_TILEGX_MACRO
916     case EM_TILEGX:
917       result = "elf-tilera-tilegx";
918       break;
919 #endif
920
921     case EM_NUM:
922       result = "elf-last-arch-number";
923       break;
924     case EM_ALPHA:
925       result = "elf-non-official-alpha";
926       break;
927     default:
928       {
929         std::ostringstream o;
930         o << "elf-unknown-arch-value-" << e_machine;
931         result = o.str();
932       }
933       break;
934     }
935   return result;
936 }
937
938 /// The kind of ELF hash table found by the function
939 /// find_hash_table_section_index.
940 enum hash_table_kind
941 {
942   NO_HASH_TABLE_KIND = 0,
943   SYSV_HASH_TABLE_KIND,
944   GNU_HASH_TABLE_KIND
945 };
946
947 /// Get the offset offset of the hash table section.
948 ///
949 /// @param elf_handle the elf handle to use.
950 ///
951 /// @param ht_section_offset this is set to the resulting offset
952 /// of the hash table section.  This is set iff the function returns true.
953 ///
954 /// @param symtab_section_offset the offset of the section of the
955 /// symbol table the hash table refers to.
956 static hash_table_kind
957 find_hash_table_section_index(Elf*      elf_handle,
958                               size_t&   ht_section_index,
959                               size_t&   symtab_section_index)
960 {
961   if (!elf_handle)
962     return NO_HASH_TABLE_KIND;
963
964   GElf_Shdr header_mem, *section_header;
965   bool found_sysv_ht = false, found_gnu_ht = false;
966   for (Elf_Scn* section = elf_nextscn(elf_handle, 0);
967        section != 0;
968        section = elf_nextscn(elf_handle, section))
969     {
970       section_header= gelf_getshdr(section, &header_mem);
971       if (section_header->sh_type != SHT_HASH
972           && section_header->sh_type != SHT_GNU_HASH)
973         continue;
974
975       ht_section_index = elf_ndxscn(section);
976       symtab_section_index = section_header->sh_link;
977
978       if (section_header->sh_type == SHT_HASH)
979         found_sysv_ht = true;
980       else if (section_header->sh_type == SHT_GNU_HASH)
981         found_gnu_ht = true;
982     }
983
984   if (found_gnu_ht)
985     return GNU_HASH_TABLE_KIND;
986   else if (found_sysv_ht)
987     return SYSV_HASH_TABLE_KIND;
988   else
989     return NO_HASH_TABLE_KIND;
990 }
991
992 /// Find the symbol table.
993 ///
994 /// If we are looking at a relocatable or executable file, this
995 /// function will return the .symtab symbol table (of type
996 /// SHT_SYMTAB).  But if we are looking at a DSO it returns the
997 /// .dynsym symbol table (of type SHT_DYNSYM).
998 ///
999 /// @param elf_handle the elf handle to consider.
1000 ///
1001 /// @param symtab the symbol table found.
1002 ///
1003 /// @return true iff the symbol table is found.
1004 static bool
1005 find_symbol_table_section(Elf* elf_handle, Elf_Scn*& symtab)
1006 {
1007   Elf_Scn* section = 0, *dynsym = 0, *sym_tab = 0;
1008   while ((section = elf_nextscn(elf_handle, section)) != 0)
1009     {
1010       GElf_Shdr header_mem, *header;
1011       header = gelf_getshdr(section, &header_mem);
1012       if (header->sh_type == SHT_DYNSYM)
1013         dynsym = section;
1014       else if (header->sh_type == SHT_SYMTAB)
1015         sym_tab = section;
1016     }
1017
1018   if (dynsym || sym_tab)
1019     {
1020       GElf_Ehdr eh_mem;
1021       GElf_Ehdr* elf_header = gelf_getehdr(elf_handle, &eh_mem);
1022       if (elf_header->e_type == ET_REL
1023           || elf_header->e_type == ET_EXEC)
1024         symtab = sym_tab ? sym_tab : dynsym;
1025       else
1026         symtab = dynsym ? dynsym : sym_tab;
1027       return true;
1028     }
1029   return false;
1030 }
1031
1032 /// Find the index (in the section headers table) of the symbol table
1033 /// section.
1034 ///
1035 /// If we are looking at a relocatable or executable file, this
1036 /// function will return the index for the .symtab symbol table (of
1037 /// type SHT_SYMTAB).  But if we are looking at a DSO it returns the
1038 /// index for the .dynsym symbol table (of type SHT_DYNSYM).
1039 ///
1040 /// @param elf_handle the elf handle to use.
1041 ///
1042 /// @param symtab_index the index of the symbol_table, that was found.
1043 ///
1044 /// @return true iff the symbol table section index was found.
1045 static bool
1046 find_symbol_table_section_index(Elf* elf_handle,
1047                                 size_t& symtab_index)
1048 {
1049   Elf_Scn* section = 0;
1050   if (!find_symbol_table_section(elf_handle, section))
1051     return false;
1052
1053   symtab_index = elf_ndxscn(section);
1054   return true;
1055 }
1056
1057 /// Find and return a section by its name and its type.
1058 ///
1059 /// @param elf_handle the elf handle to use.
1060 ///
1061 /// @param name the name of the section.
1062 ///
1063 /// @param section_type the type of the section.  This is the
1064 /// Elf32_Shdr::sh_type (or Elf64_Shdr::sh_type) data member.
1065 /// Examples of values of this parameter are SHT_PROGBITS or SHT_NOBITS.
1066 ///
1067 /// @return the section found, nor nil if none was found.
1068 static Elf_Scn*
1069 find_section(Elf* elf_handle, const string& name, Elf64_Word section_type)
1070 {
1071   size_t section_header_string_index = 0;
1072   if (elf_getshdrstrndx (elf_handle, &section_header_string_index) < 0)
1073     return 0;
1074
1075   Elf_Scn* section = 0;
1076   GElf_Shdr header_mem, *header;
1077   while ((section = elf_nextscn(elf_handle, section)) != 0)
1078     {
1079       header = gelf_getshdr(section, &header_mem);
1080       if (header == NULL || header->sh_type != section_type)
1081       continue;
1082
1083       const char* section_name =
1084         elf_strptr(elf_handle, section_header_string_index, header->sh_name);
1085       if (section_name && name == section_name)
1086         return section;
1087     }
1088
1089   return 0;
1090 }
1091
1092 /// Test if the ELF binary denoted by a given ELF handle is a Linux
1093 /// Kernel Module.
1094 ///
1095 /// @param elf_handle the ELF handle to consider.
1096 ///
1097 /// @return true iff the binary denoted by @p elf_handle is a Linux
1098 /// kernel module.
1099 static bool
1100 binary_is_linux_kernel_module(Elf *elf_handle)
1101 {
1102   return (find_section(elf_handle, ".modinfo", SHT_PROGBITS)
1103           && find_section(elf_handle,
1104                           ".gnu.linkonce.this_module",
1105                           SHT_PROGBITS));
1106 }
1107
1108 /// Test if the ELF binary denoted by a given ELF handle is a Linux
1109 /// Kernel binary (either vmlinux or a kernel module).
1110 ///
1111 /// @param elf_handle the ELF handle to consider.
1112 ///
1113 /// @return true iff the binary denoted by @p elf_handle is a Linux
1114 /// kernel binary
1115 static bool
1116 binary_is_linux_kernel(Elf *elf_handle)
1117 {
1118   return (find_section(elf_handle,
1119                        "__ksymtab_strings",
1120                        SHT_PROGBITS)
1121           || binary_is_linux_kernel_module(elf_handle));
1122 }
1123
1124 /// Find and return the .text section.
1125 ///
1126 /// @param elf_handle the elf handle to use.
1127 ///
1128 /// @return the .text section found.
1129 static Elf_Scn*
1130 find_text_section(Elf* elf_handle)
1131 {return find_section(elf_handle, ".text", SHT_PROGBITS);}
1132
1133 /// Find and return the .bss section.
1134 ///
1135 /// @param elf_handle.
1136 ///
1137 /// @return the .bss section found.
1138 static Elf_Scn*
1139 find_bss_section(Elf* elf_handle)
1140 {return find_section(elf_handle, ".bss", SHT_NOBITS);}
1141
1142 /// Find and return the .rodata section.
1143 ///
1144 /// @param elf_handle.
1145 ///
1146 /// @return the .rodata section found.
1147 static Elf_Scn*
1148 find_rodata_section(Elf* elf_handle)
1149 {return find_section(elf_handle, ".rodata", SHT_PROGBITS);}
1150
1151 /// Find and return the .data section.
1152 ///
1153 /// @param elf_handle the elf handle to use.
1154 ///
1155 /// @return the .data section found.
1156 static Elf_Scn*
1157 find_data_section(Elf* elf_handle)
1158 {return find_section(elf_handle, ".data", SHT_PROGBITS);}
1159
1160 /// Find and return the .data1 section.
1161 ///
1162 /// @param elf_handle the elf handle to use.
1163 ///
1164 /// @return the .data1 section found.
1165 static Elf_Scn*
1166 find_data1_section(Elf* elf_handle)
1167 {return find_section(elf_handle, ".data1", SHT_PROGBITS);}
1168
1169 /// Find the __ksymtab_strings section of a Linux kernel binary.
1170 ///
1171 ///
1172 /// @return the find_ksymtab_strings_section of the linux kernel
1173 /// binary denoted by @p elf_handle, or nil if such a section could
1174 /// not be found.
1175 static Elf_Scn*
1176 find_ksymtab_strings_section(Elf *elf_handle)
1177 {
1178   if (binary_is_linux_kernel(elf_handle))
1179     return find_section(elf_handle, "__ksymtab_strings", SHT_PROGBITS);
1180   return 0;
1181 }
1182
1183 /// Get the address at which a given binary is loaded in memoryâ‹…
1184 ///
1185 /// @param elf_handle the elf handle for the binary to consider.
1186 ///
1187 /// @param load_address the address where the binary is loaded.  This
1188 /// is set by the function iff it returns true.
1189 ///
1190 /// @return true if the function could get the binary load address
1191 /// and assign @p load_address to it.
1192 static bool
1193 get_binary_load_address(Elf *elf_handle,
1194                         GElf_Addr &load_address)
1195 {
1196   GElf_Ehdr eh_mem;
1197   GElf_Ehdr *elf_header = gelf_getehdr(elf_handle, &eh_mem);
1198   size_t num_segments = elf_header->e_phnum;
1199   GElf_Phdr *program_header = 0;
1200   GElf_Addr result;
1201   bool found_loaded_segment = false;
1202   GElf_Phdr ph_mem;
1203
1204   for (unsigned i = 0; i < num_segments; ++i)
1205     {
1206       program_header = gelf_getphdr(elf_handle, i, &ph_mem);
1207       if (program_header && program_header->p_type == PT_LOAD)
1208         {
1209           if (!found_loaded_segment)
1210             {
1211               result = program_header->p_vaddr;
1212               found_loaded_segment = true;
1213             }
1214
1215           if (program_header->p_vaddr < result)
1216             // The resulting load address we want is the lowest
1217             // load address of all the loaded segments.
1218             result = program_header->p_vaddr;
1219         }
1220     }
1221
1222   if (found_loaded_segment)
1223     {
1224       load_address = result;
1225       return true;
1226     }
1227   return false;
1228 }
1229
1230 /// Find the file name of the alternate debug info file.
1231 ///
1232 /// @param elf_module the elf module to consider.
1233 ///
1234 /// @param out parameter.  Is set to the file name of the alternate
1235 /// debug info file, iff this function returns true.
1236 ///
1237 /// @return true iff the location of the alternate debug info file was
1238 /// found.
1239 static bool
1240 find_alt_debug_info_link(Dwfl_Module *elf_module,
1241                          string &alt_file_name)
1242 {
1243   GElf_Addr bias = 0;
1244   Dwarf *dwarf = dwfl_module_getdwarf(elf_module, &bias);
1245   Elf *elf = dwarf_getelf(dwarf);
1246   GElf_Ehdr ehmem, *elf_header;
1247   elf_header = gelf_getehdr(elf, &ehmem);
1248
1249   Elf_Scn* section = 0;
1250   while ((section = elf_nextscn(elf, section)) != 0)
1251     {
1252       GElf_Shdr header_mem, *header;
1253       header = gelf_getshdr(section, &header_mem);
1254       if (header->sh_type != SHT_PROGBITS)
1255         continue;
1256
1257       const char *section_name = elf_strptr(elf,
1258                                             elf_header->e_shstrndx,
1259                                             header->sh_name);
1260
1261       char *alt_name = 0;
1262       char *buildid = 0;
1263       size_t buildid_len = 0;
1264       if (section_name != 0
1265           && strcmp(section_name, ".gnu_debugaltlink") == 0)
1266         {
1267           Elf_Data *data = elf_getdata(section, 0);
1268           if (data != 0 && data->d_size != 0)
1269             {
1270               alt_name = (char*) data->d_buf;
1271               char *end_of_alt_name =
1272                 (char *) memchr(alt_name, '\0', data->d_size);
1273               buildid_len = data->d_size - (end_of_alt_name - alt_name + 1);
1274               if (buildid_len == 0)
1275                 return false;
1276               buildid = end_of_alt_name + 1;
1277             }
1278         }
1279       else
1280         continue;
1281
1282       if (buildid == 0 || alt_name == 0)
1283         return false;
1284
1285       alt_file_name = alt_name;
1286       return true;
1287     }
1288
1289   return false;
1290 }
1291
1292 /// Find alternate debuginfo file of a given "link" under a set of
1293 /// root directories.
1294 ///
1295 /// The link is a string that is read by the function
1296 /// find_alt_debug_info_link().  That link is a path that is relative
1297 /// to a given debug info file, e.g, "../../../.dwz/something.debug".
1298 /// It designates the alternate debug info file associated to a given
1299 /// debug info file.
1300 ///
1301 /// This function will thus try to find the .dwz/something.debug file
1302 /// under some given root directories.
1303 ///
1304 /// @param root_dirs the set of root directories to look from.
1305 ///
1306 /// @param alt_file_name a relative path to the alternate debug info
1307 /// file to look for.
1308 ///
1309 /// @param alt_file_path the resulting absolute path to the alternate
1310 /// debuginfo path denoted by @p alt_file_name and found under one of
1311 /// the directories in @p root_dirs.  This is set iff the function
1312 /// returns true.
1313 ///
1314 /// @return true iff the function found the alternate debuginfo file.
1315 static bool
1316 find_alt_debug_info_path(const vector<char**> root_dirs,
1317                          const string &alt_file_name,
1318                          string &alt_file_path)
1319 {
1320   if (alt_file_name.empty())
1321     return false;
1322
1323   string altfile_name = tools_utils::trim_leading_string(alt_file_name, "../");
1324
1325   for (vector<char**>::const_iterator i = root_dirs.begin();
1326        i != root_dirs.end();
1327        ++i)
1328     if (tools_utils::find_file_under_dir(**i, altfile_name, alt_file_path))
1329       return true;
1330
1331   return false;
1332 }
1333
1334 /// Return the alternate debug info associated to a given main debug
1335 /// info file.
1336 ///
1337 /// @param elf_module the elf module to consider.
1338 ///
1339 /// @param debug_root_dirs a set of root debuginfo directories under
1340 /// which too look for the alternate debuginfo file.
1341 ///
1342 /// @param alt_file_name output parameter.  This is set to the file
1343 /// path of the alternate debug info file associated to @p elf_module.
1344 /// This is set iff the function returns a non-null result.
1345 ///
1346 /// @param alt_fd the file descriptor used to access the alternate
1347 /// debug info.  If this parameter is set by the function, then the
1348 /// caller needs to fclose it, otherwise the file descriptor is going
1349 /// to be leaked.  Note however that on recent versions of elfutils
1350 /// where libdw.h contains the function dwarf_getalt(), this parameter
1351 /// is set to 0, so it doesn't need to be fclosed.
1352 ///
1353 /// Note that the alternate debug info file is a DWARF extension as of
1354 /// DWARF 4 ans is decribed at
1355 /// http://www.dwarfstd.org/ShowIssue.php?issue=120604.1.
1356 ///
1357 /// @return the alternate debuginfo, or null.  If @p alt_fd is
1358 /// non-zero, then the caller of this function needs to call
1359 /// dwarf_end() on the returned alternate debuginfo pointer,
1360 /// otherwise, it's going to be leaked.
1361 static Dwarf*
1362 find_alt_debug_info(Dwfl_Module *elf_module,
1363                     const vector<char**> debug_root_dirs,
1364                     string& alt_file_name,
1365                     int& alt_fd)
1366 {
1367   if (elf_module == 0)
1368     return 0;
1369
1370   Dwarf* result = 0;
1371   find_alt_debug_info_link(elf_module, alt_file_name);
1372
1373 #ifdef LIBDW_HAS_DWARF_GETALT
1374   // We are on recent versions of elfutils where the function
1375   // dwarf_getalt exists, so let's use it.
1376   Dwarf_Addr bias = 0;
1377   Dwarf* dwarf = dwfl_module_getdwarf(elf_module, &bias);
1378   result = dwarf_getalt(dwarf);
1379   alt_fd = 0;
1380 #else
1381   // We are on an old version of elfutils where the function
1382   // dwarf_getalt doesn't exist yet, so let's open code its
1383   // functionality
1384   char *alt_name = 0;
1385   const char *file_name = 0;
1386   void **user_data = 0;
1387   Dwarf_Addr low_addr = 0;
1388   char *alt_file = 0;
1389
1390   file_name = dwfl_module_info(elf_module, &user_data,
1391                                &low_addr, 0, 0, 0, 0, 0);
1392
1393   alt_fd = dwfl_standard_find_debuginfo(elf_module, user_data,
1394                                         file_name, low_addr,
1395                                         alt_name, file_name,
1396                                         0, &alt_file);
1397
1398   result = dwarf_begin(alt_fd, DWARF_C_READ);
1399 #endif
1400
1401   if (result == 0)
1402     {
1403       // So we didn't find the alternate debuginfo file from the
1404       // information that is in the debuginfo file associated to
1405       // elf_module.  Maybe the alternate debuginfo file is located
1406       // under one of the directories in debug_root_dirs.  So let's
1407       // look in there.
1408       string alt_file_path;
1409       if (!find_alt_debug_info_path(debug_root_dirs,
1410                                     alt_file_name,
1411                                     alt_file_path))
1412         return result;
1413
1414       // If we reach this point it means we have found the path to the
1415       // alternate debuginfo file and it's in alt_file_path.  So let's
1416       // open it and read it.
1417       int fd = open(alt_file_path.c_str(), O_RDONLY);
1418       if (fd == -1)
1419         return result;
1420       result = dwarf_begin(fd, DWARF_C_READ);
1421
1422 #ifdef LIBDW_HAS_DWARF_GETALT
1423       Dwarf_Addr bias = 0;
1424       Dwarf* dwarf = dwfl_module_getdwarf(elf_module, &bias);
1425       dwarf_setalt(dwarf, result);
1426 #endif
1427     }
1428
1429   return result;
1430 }
1431
1432 /// Compare a symbol name against another name, possibly demangling
1433 /// the symbol_name before performing the comparison.
1434 ///
1435 /// @param symbol_name the symbol_name to take in account.
1436 ///
1437 /// @param name the second name to take in account.
1438 ///
1439 /// @param demangle if true, demangle @p symbol_name and compare the
1440 /// result of the demangling with @p name.
1441 ///
1442 /// @return true iff symbol_name equals name.
1443 static bool
1444 compare_symbol_name(const string& symbol_name,
1445                     const string& name,
1446                     bool demangle)
1447 {
1448   if (demangle)
1449     {
1450       string m = demangle_cplus_mangled_name(symbol_name);
1451       return m == name;
1452     }
1453   return symbol_name == name;
1454 }
1455
1456 /// Return the SHT_GNU_versym, SHT_GNU_verdef and SHT_GNU_verneed
1457 /// sections that are involved in symbol versionning.
1458 ///
1459 /// @param elf_handle the elf handle to use.
1460 ///
1461 /// @param versym_section the SHT_GNU_versym section found.  If the
1462 /// section wasn't found, this is set to nil.
1463 ///
1464 /// @param verdef_section the SHT_GNU_verdef section found.  If the
1465 /// section wasn't found, this is set to nil.
1466 ///
1467 /// @param verneed_section the SHT_GNU_verneed section found.  If the
1468 /// section wasn't found, this is set to nil.
1469 ///
1470 /// @return true iff at least one of the sections where found.
1471 static bool
1472 get_symbol_versionning_sections(Elf*            elf_handle,
1473                                 Elf_Scn*&       versym_section,
1474                                 Elf_Scn*&       verdef_section,
1475                                 Elf_Scn*&       verneed_section)
1476 {
1477   Elf_Scn* section = NULL;
1478   GElf_Shdr mem;
1479   Elf_Scn* versym = NULL, *verdef = NULL, *verneed = NULL;
1480
1481   while ((section = elf_nextscn(elf_handle, section)) != NULL)
1482     {
1483       GElf_Shdr* h = gelf_getshdr(section, &mem);
1484       if (h->sh_type == SHT_GNU_versym)
1485         versym = section;
1486       else if (h->sh_type == SHT_GNU_verdef)
1487         verdef = section;
1488       else if (h->sh_type == SHT_GNU_verneed)
1489         verneed = section;
1490     }
1491
1492   if (versym || verdef || verneed)
1493     {
1494       // At least one the versionning sections was found.  Return it.
1495       versym_section = versym;
1496       verdef_section = verdef;
1497       verneed_section = verneed;
1498       return true;
1499     }
1500
1501   return false;
1502 }
1503
1504 /// Get the version definition (from the SHT_GNU_verdef section) of a
1505 /// given symbol represented by a pointer to GElf_Versym.
1506 ///
1507 /// @param elf_hande the elf handle to use.
1508 ///
1509 /// @param versym the symbol to get the version definition for.
1510 ///
1511 /// @param verdef_section the SHT_GNU_verdef section.
1512 ///
1513 /// @param version the resulting version definition.  This is set iff
1514 /// the function returns true.
1515 ///
1516 /// @return true upon successful completion, false otherwise.
1517 static bool
1518 get_version_definition_for_versym(Elf*                   elf_handle,
1519                                   GElf_Versym*           versym,
1520                                   Elf_Scn*               verdef_section,
1521                                   elf_symbol::version&   version)
1522 {
1523   Elf_Data* verdef_data = elf_getdata(verdef_section, NULL);
1524   GElf_Verdef verdef_mem;
1525   GElf_Verdef* verdef = gelf_getverdef(verdef_data, 0, &verdef_mem);
1526   size_t vd_offset = 0;
1527
1528   for (;; vd_offset += verdef->vd_next)
1529     {
1530       for (;verdef != 0;)
1531         {
1532           if (verdef->vd_ndx == (*versym & 0x7fff))
1533             // Found the version of the symbol.
1534             break;
1535           vd_offset += verdef->vd_next;
1536           verdef = (verdef->vd_next == 0
1537                     ? 0
1538                     : gelf_getverdef(verdef_data, vd_offset, &verdef_mem));
1539         }
1540
1541       if (verdef != 0)
1542         {
1543           GElf_Verdaux verdaux_mem;
1544           GElf_Verdaux *verdaux = gelf_getverdaux(verdef_data,
1545                                                   vd_offset + verdef->vd_aux,
1546                                                   &verdaux_mem);
1547           GElf_Shdr header_mem;
1548           GElf_Shdr* verdef_section_header = gelf_getshdr(verdef_section,
1549                                                           &header_mem);
1550           size_t verdef_stridx = verdef_section_header->sh_link;
1551           version.str(elf_strptr(elf_handle, verdef_stridx, verdaux->vda_name));
1552           if (*versym & 0x8000)
1553             version.is_default(false);
1554           else
1555             version.is_default(true);
1556           return true;
1557         }
1558       if (!verdef || verdef->vd_next == 0)
1559         break;
1560     }
1561   return false;
1562 }
1563
1564 /// Get the version needed (from the SHT_GNU_verneed section) to
1565 /// resolve an undefined symbol represented by a pointer to
1566 /// GElf_Versym.
1567 ///
1568 /// @param elf_hande the elf handle to use.
1569 ///
1570 /// @param versym the symbol to get the version definition for.
1571 ///
1572 /// @param verneed_section the SHT_GNU_verneed section.
1573 ///
1574 /// @param version the resulting version definition.  This is set iff
1575 /// the function returns true.
1576 ///
1577 /// @return true upon successful completion, false otherwise.
1578 static bool
1579 get_version_needed_for_versym(Elf*                      elf_handle,
1580                               GElf_Versym*              versym,
1581                               Elf_Scn*                  verneed_section,
1582                               elf_symbol::version&      version)
1583 {
1584   if (versym == 0 || elf_handle == 0 || verneed_section == 0)
1585     return false;
1586
1587   size_t vn_offset = 0;
1588   Elf_Data* verneed_data = elf_getdata(verneed_section, NULL);
1589   GElf_Verneed verneed_mem;
1590   GElf_Verneed* verneed = gelf_getverneed(verneed_data, 0, &verneed_mem);
1591
1592   for (;verneed; vn_offset += verneed->vn_next)
1593     {
1594       size_t vna_offset = vn_offset;
1595       GElf_Vernaux vernaux_mem;
1596       GElf_Vernaux *vernaux = gelf_getvernaux(verneed_data,
1597                                               vn_offset + verneed->vn_aux,
1598                                               &vernaux_mem);
1599       for (;vernaux != 0 && verneed;)
1600         {
1601           if (vernaux->vna_other == *versym)
1602             // Found the version of the symbol.
1603             break;
1604           vna_offset += verneed->vn_next;
1605           verneed = (verneed->vn_next == 0
1606                      ? 0
1607                      : gelf_getverneed(verneed_data, vna_offset, &verneed_mem));
1608         }
1609
1610       if (verneed != 0 && vernaux != 0 && vernaux->vna_other == *versym)
1611         {
1612           GElf_Shdr header_mem;
1613           GElf_Shdr* verneed_section_header = gelf_getshdr(verneed_section,
1614                                                            &header_mem);
1615           size_t verneed_stridx = verneed_section_header->sh_link;
1616           version.str(elf_strptr(elf_handle,
1617                                  verneed_stridx,
1618                                  vernaux->vna_name));
1619           if (*versym & 0x8000)
1620             version.is_default(false);
1621           else
1622             version.is_default(true);
1623           return true;
1624         }
1625
1626       if (!verneed || verneed->vn_next == 0)
1627         break;
1628     }
1629   return false;
1630 }
1631
1632 /// Return the version for a symbol that is at a given index in its
1633 /// SHT_SYMTAB section.
1634 ///
1635 /// @param elf_handle the elf handle to use.
1636 ///
1637 /// @param symbol_index the index of the symbol to consider.
1638 ///
1639 /// @param get_def_version if this is true, it means that that we want
1640 /// the version for a defined symbol; in that case, the version is
1641 /// looked for in a section of type SHT_GNU_verdef.  Otherwise, if
1642 /// this parameter is false, this means that we want the version for
1643 /// an undefined symbol; in that case, the version is the needed one
1644 /// for the symbol to be resolved; so the version is looked fo in a
1645 /// section of type SHT_GNU_verneed.
1646 ///
1647 /// @param version the version found for symbol at @p symbol_index.
1648 ///
1649 /// @return true iff a version was found for symbol at index @p
1650 /// symbol_index.
1651 static bool
1652 get_version_for_symbol(Elf*                     elf_handle,
1653                        size_t                   symbol_index,
1654                        bool                     get_def_version,
1655                        elf_symbol::version&     version)
1656 {
1657   Elf_Scn *versym_section = NULL,
1658     *verdef_section = NULL,
1659     *verneed_section = NULL;
1660
1661   if (!get_symbol_versionning_sections(elf_handle,
1662                                        versym_section,
1663                                        verdef_section,
1664                                        verneed_section))
1665     return false;
1666
1667   GElf_Versym versym_mem;
1668   Elf_Data* versym_data = (versym_section)
1669     ? elf_getdata(versym_section, NULL)
1670     : NULL;
1671   GElf_Versym* versym = (versym_data)
1672     ? gelf_getversym(versym_data, symbol_index, &versym_mem)
1673     : NULL;
1674
1675   if (versym == 0 || *versym <= 1)
1676     // I got these value from the code of readelf.c in elfutils.
1677     // Apparently, if the symbol version entry has these values, the
1678     // symbol must be discarded. This is not documented in the
1679     // official specification.
1680     return false;
1681
1682   if (get_def_version)
1683     {
1684       if (*versym == 0x8001)
1685         // I got this value from the code of readelf.c in elfutils
1686         // too.  It's not really documented in the official
1687         // specification.
1688         return false;
1689
1690       if (verdef_section
1691           && get_version_definition_for_versym(elf_handle, versym,
1692                                                verdef_section, version))
1693         return true;
1694     }
1695   else
1696     {
1697       if (verneed_section
1698           && get_version_needed_for_versym(elf_handle, versym,
1699                                            verneed_section, version))
1700         return true;
1701     }
1702
1703   return false;
1704 }
1705
1706 /// Lookup a symbol using the SysV ELF hash table.
1707 ///
1708 /// Note that this function hasn't been tested.  So it hasn't been
1709 /// debugged yet.  IOW, it is not known to work.  Or rather, it's
1710 /// almost like it's surely doesn't work ;-)
1711 ///
1712 /// Use it at your own risks.  :-)
1713 ///
1714 ///@parm env the environment we are operating from.
1715 ///
1716 /// @param elf_handle the elf_handle to use.
1717 ///
1718 /// @param sym_name the symbol name to look for.
1719 ///
1720 /// @param ht_index the index (in the section headers table) of the
1721 /// hash table section to use.
1722 ///
1723 /// @param sym_tab_index the index (in the section headers table) of
1724 /// the symbol table to use.
1725 ///
1726 /// @param demangle if true, demangle @p sym_name before comparing it
1727 /// to names from the symbol table.
1728 ///
1729 /// @param syms_found a vector of symbols found with the name @p
1730 /// sym_name.  table.
1731 static bool
1732 lookup_symbol_from_sysv_hash_tab(const environment*             env,
1733                                  Elf*                           elf_handle,
1734                                  const string&                  sym_name,
1735                                  size_t                 ht_index,
1736                                  size_t                 sym_tab_index,
1737                                  bool                           demangle,
1738                                  vector<elf_symbol_sptr>&       syms_found)
1739 {
1740   Elf_Scn* sym_tab_section = elf_getscn(elf_handle, sym_tab_index);
1741   ABG_ASSERT(sym_tab_section);
1742
1743   Elf_Data* sym_tab_data = elf_getdata(sym_tab_section, 0);
1744   ABG_ASSERT(sym_tab_data);
1745
1746   GElf_Shdr sheader_mem;
1747   GElf_Shdr* sym_tab_section_header = gelf_getshdr(sym_tab_section,
1748                                                    &sheader_mem);
1749   Elf_Scn* hash_section = elf_getscn(elf_handle, ht_index);
1750   ABG_ASSERT(hash_section);
1751
1752   // Poke at the different parts of the hash table and get them ready
1753   // to be used.
1754   unsigned long hash = elf_hash(sym_name.c_str());
1755   Elf_Data* ht_section_data = elf_getdata(hash_section, 0);
1756   Elf32_Word* ht_data = reinterpret_cast<Elf32_Word*>(ht_section_data->d_buf);
1757   size_t nb_buckets = ht_data[0];
1758   size_t nb_chains = ht_data[1];
1759
1760   if (nb_buckets == 0)
1761     // An empty hash table.  Not sure if that is possible, but it
1762     // would mean an empty table of exported symbols.
1763     return false;
1764
1765   //size_t nb_chains = ht_data[1];
1766   Elf32_Word* ht_buckets = &ht_data[2];
1767   Elf32_Word* ht_chains = &ht_buckets[nb_buckets];
1768
1769   // Now do the real work.
1770   size_t bucket = hash % nb_buckets;
1771   size_t symbol_index = ht_buckets[bucket];
1772
1773   GElf_Sym symbol;
1774   const char* sym_name_str;
1775   size_t sym_size;
1776   elf_symbol::type sym_type;
1777   elf_symbol::binding sym_binding;
1778   elf_symbol::visibility sym_visibility;
1779   bool found = false;
1780   Elf_Scn *strings_section = find_ksymtab_strings_section(elf_handle);
1781   size_t strings_ndx = strings_section
1782     ? elf_ndxscn(strings_section)
1783     : 0;
1784
1785   do
1786     {
1787       ABG_ASSERT(gelf_getsym(sym_tab_data, symbol_index, &symbol));
1788       sym_name_str = elf_strptr(elf_handle,
1789                                 sym_tab_section_header->sh_link,
1790                                 symbol.st_name);
1791       if (sym_name_str
1792           && compare_symbol_name(sym_name_str, sym_name, demangle))
1793         {
1794           sym_type = stt_to_elf_symbol_type(GELF_ST_TYPE(symbol.st_info));
1795           sym_binding = stb_to_elf_symbol_binding(GELF_ST_BIND(symbol.st_info));
1796           sym_visibility =
1797             stv_to_elf_symbol_visibility(GELF_ST_VISIBILITY(symbol.st_other));
1798           sym_size = symbol.st_size;
1799           elf_symbol::version ver;
1800           if (get_version_for_symbol(elf_handle, symbol_index,
1801                                      /*get_def_version=*/true, ver))
1802             ABG_ASSERT(!ver.str().empty());
1803           elf_symbol_sptr symbol_found =
1804             elf_symbol::create(env,
1805                                symbol_index,
1806                                sym_size,
1807                                sym_name_str,
1808                                sym_type,
1809                                sym_binding,
1810                                symbol.st_shndx != SHN_UNDEF,
1811                                symbol.st_shndx == SHN_COMMON,
1812                                ver, sym_visibility,
1813                                symbol.st_shndx == strings_ndx);
1814           syms_found.push_back(symbol_found);
1815           found = true;
1816         }
1817       symbol_index = ht_chains[symbol_index];
1818     } while (symbol_index != STN_UNDEF || symbol_index >= nb_chains);
1819
1820   return found;
1821 }
1822
1823 /// Get the size of the elf class, in bytes.
1824 ///
1825 /// @param elf_handle the elf handle to use.
1826 ///
1827 /// @return the size computed.
1828 static char
1829 get_elf_class_size_in_bytes(Elf* elf_handle)
1830 {
1831   char result = 0;
1832   GElf_Ehdr hdr;
1833
1834   ABG_ASSERT(gelf_getehdr(elf_handle, &hdr));
1835   int c = hdr.e_ident[EI_CLASS];
1836
1837   switch (c)
1838     {
1839     case ELFCLASS32:
1840       result = 4;
1841       break;
1842     case ELFCLASS64:
1843       result = 8;
1844       break;
1845     default:
1846       ABG_ASSERT_NOT_REACHED;
1847     }
1848
1849   return result;
1850 }
1851
1852 /// Get a given word of a bloom filter, referred to by the index of
1853 /// the word.  The word size depends on the current elf class and this
1854 /// function abstracts that nicely.
1855 ///
1856 /// @param elf_handle the elf handle to use.
1857 ///
1858 /// @param bloom_filter the bloom filter to consider.
1859 ///
1860 /// @param index the index of the bloom filter to return.
1861 static GElf_Word
1862 bloom_word_at(Elf*              elf_handle,
1863               Elf32_Word*       bloom_filter,
1864               size_t            index)
1865 {
1866   GElf_Word result = 0;
1867   GElf_Ehdr h;
1868   ABG_ASSERT(gelf_getehdr(elf_handle, &h));
1869   int c;
1870   c = h.e_ident[EI_CLASS];
1871
1872   switch(c)
1873     {
1874     case ELFCLASS32:
1875       result = bloom_filter[index];
1876       break ;
1877     case ELFCLASS64:
1878       {
1879         GElf_Word* f= reinterpret_cast<GElf_Word*>(bloom_filter);
1880         result = f[index];
1881       }
1882       break;
1883     default:
1884       abort();
1885     }
1886
1887   return result;
1888 }
1889
1890 /// The abstraction of the gnu elf hash table.
1891 ///
1892 /// The members of this struct are explained at
1893 ///   - https://sourceware.org/ml/binutils/2006-10/msg00377.html
1894 ///   - https://blogs.oracle.com/ali/entry/gnu_hash_elf_sections.
1895 struct gnu_ht
1896 {
1897   size_t nb_buckets;
1898   Elf32_Word* buckets;
1899   Elf32_Word* chain;
1900   size_t first_sym_index;
1901   size_t bf_nwords;
1902   size_t bf_size;
1903   Elf32_Word* bloom_filter;
1904   size_t shift;
1905   size_t sym_count;
1906   Elf_Scn* sym_tab_section;
1907   GElf_Shdr sym_tab_section_header;
1908
1909   gnu_ht()
1910     : nb_buckets(0),
1911       buckets(0),
1912       chain(0),
1913       first_sym_index(0),
1914       bf_nwords(0),
1915       bf_size(0),
1916       bloom_filter(0),
1917       shift(0),
1918       sym_count(0),
1919       sym_tab_section(0)
1920   {}
1921 }; // end struct gnu_ht
1922
1923 /// Setup the members of the gnu hash table.
1924 ///
1925 /// @param elf_handle a handle on the elf file to use.
1926 ///
1927 /// @param ht_index the index  (into the elf section headers table) of
1928 /// the hash table section to use.
1929 ///
1930 /// @param sym_tab_index the index (into the elf section headers
1931 /// table) of the symbol table the gnu hash table is about.
1932 ///
1933 /// @param ht the resulting hash table.
1934 ///
1935 /// @return true iff the hash table @ ht could be setup.
1936 static bool
1937 setup_gnu_ht(Elf* elf_handle,
1938              size_t ht_index,
1939              size_t sym_tab_index,
1940              gnu_ht& ht)
1941 {
1942   ht.sym_tab_section = elf_getscn(elf_handle, sym_tab_index);
1943   ABG_ASSERT(ht.sym_tab_section);
1944   ABG_ASSERT(gelf_getshdr(ht.sym_tab_section, &ht.sym_tab_section_header));
1945   ht.sym_count =
1946     ht.sym_tab_section_header.sh_size / ht.sym_tab_section_header.sh_entsize;
1947   Elf_Scn* hash_section = elf_getscn(elf_handle, ht_index);
1948   ABG_ASSERT(hash_section);
1949
1950   // Poke at the different parts of the hash table and get them ready
1951   // to be used.
1952   Elf_Data* ht_section_data = elf_getdata(hash_section, 0);
1953   Elf32_Word* ht_data = reinterpret_cast<Elf32_Word*>(ht_section_data->d_buf);
1954
1955   ht.nb_buckets = ht_data[0];
1956   if (ht.nb_buckets == 0)
1957     // An empty hash table.  Not sure if that is possible, but it
1958     // would mean an empty table of exported symbols.
1959     return false;
1960   ht.first_sym_index = ht_data[1];
1961   // The number of words used by the bloom filter.  A size of a word
1962   // is ELFCLASS.
1963   ht.bf_nwords = ht_data[2];
1964   // The shift used by the bloom filter code.
1965   ht.shift = ht_data[3];
1966   // The data of the bloom filter proper.
1967   ht.bloom_filter = &ht_data[4];
1968   // The size of the bloom filter in 4 bytes word.  This is going to
1969   // be used to index the 'bloom_filter' above, which is of type
1970   // Elf32_Word*; thus we need that bf_size be expressed in 4 bytes
1971   // words.
1972   ht.bf_size = (get_elf_class_size_in_bytes(elf_handle) / 4) * ht.bf_nwords;
1973   // The buckets of the hash table.
1974   ht.buckets = ht.bloom_filter + ht.bf_size;
1975   // The chain of the hash table.
1976   ht.chain = ht.buckets + ht.nb_buckets;
1977
1978   return true;
1979 }
1980
1981 /// Look into the symbol tables of the underlying elf file and find
1982 /// the symbol we are being asked.
1983 ///
1984 /// This function uses the GNU hash table for the symbol lookup.
1985 ///
1986 /// The reference of for the implementation of this function can be
1987 /// found at:
1988 ///   - https://sourceware.org/ml/binutils/2006-10/msg00377.html
1989 ///   - https://blogs.oracle.com/ali/entry/gnu_hash_elf_sections.
1990 ///
1991 /// @param elf_handle the elf handle to use.
1992 ///
1993 /// @param sym_name the name of the symbol to look for.
1994 ///
1995 /// @param ht_index the index of the hash table header to use.
1996 ///
1997 /// @param sym_tab_index the index of the symbol table header to use
1998 /// with this hash table.
1999 ///
2000 /// @param demangle if true, demangle @p sym_name.
2001 ///
2002 /// @param syms_found the vector of symbols found with the name @p
2003 /// sym_name.
2004 ///
2005 /// @return true if a symbol was actually found.
2006 static bool
2007 lookup_symbol_from_gnu_hash_tab(const environment*              env,
2008                                 Elf*                            elf_handle,
2009                                 const string&                   sym_name,
2010                                 size_t                          ht_index,
2011                                 size_t                          sym_tab_index,
2012                                 bool                            demangle,
2013                                 vector<elf_symbol_sptr>&        syms_found)
2014 {
2015   gnu_ht ht;
2016   if (!setup_gnu_ht(elf_handle, ht_index, sym_tab_index, ht))
2017     return false;
2018
2019   // Now do the real work.
2020
2021   // Compute bloom hashes (GNU hash and second bloom specific hashes).
2022   size_t h1 = elf_gnu_hash(sym_name.c_str());
2023   size_t h2 = h1 >> ht.shift;
2024   // The size of one of the words used in the bloom
2025   // filter, in bits.
2026   int c = get_elf_class_size_in_bytes(elf_handle) * 8;
2027   int n =  (h1 / c) % ht.bf_nwords;
2028   unsigned char bitmask = (1 << (h1 % c)) | (1 << (h2 % c));
2029
2030   // Test if the symbol is *NOT* present in this ELF file.
2031   if ((bloom_word_at(elf_handle, ht.bloom_filter, n) & bitmask) != bitmask)
2032     return false;
2033
2034   size_t i = ht.buckets[h1 % ht.nb_buckets];
2035   if (i == STN_UNDEF)
2036     return false;
2037
2038   Elf32_Word stop_word, *stop_wordp;
2039   elf_symbol::version ver;
2040   GElf_Sym symbol;
2041   const char* sym_name_str;
2042   bool found = false;
2043
2044   elf_symbol::type sym_type;
2045   elf_symbol::binding sym_binding;
2046   elf_symbol::visibility sym_visibility;
2047   Elf_Scn *strings_section = find_ksymtab_strings_section(elf_handle);
2048     size_t strings_ndx = strings_section
2049     ? elf_ndxscn(strings_section)
2050     : 0;
2051
2052   // Let's walk the hash table and record the versions of all the
2053   // symbols which name equal sym_name.
2054   for (i = ht.buckets[h1 % ht.nb_buckets],
2055          stop_wordp = &ht.chain[i - ht.first_sym_index];
2056        i != STN_UNDEF
2057          && (stop_wordp
2058              < ht.chain + (ht.sym_count - ht.first_sym_index));
2059        ++i, ++stop_wordp)
2060     {
2061       stop_word = *stop_wordp;
2062       if ((stop_word & ~ 1)!= (h1 & ~1))
2063         // A given bucket can reference several hashes.  Here we
2064         // stumbled across a hash value different from the one we are
2065         // looking for.  Let's keep walking.
2066         continue;
2067
2068       ABG_ASSERT(gelf_getsym(elf_getdata(ht.sym_tab_section, 0),
2069                          i, &symbol));
2070       sym_name_str = elf_strptr(elf_handle,
2071                                 ht.sym_tab_section_header.sh_link,
2072                                 symbol.st_name);
2073       if (sym_name_str
2074           && compare_symbol_name(sym_name_str, sym_name, demangle))
2075         {
2076           // So we found a symbol (in the symbol table) that equals
2077           // sym_name.  Now lets try to get its version and record it.
2078           sym_type = stt_to_elf_symbol_type(GELF_ST_TYPE(symbol.st_info));
2079           sym_binding = stb_to_elf_symbol_binding(GELF_ST_BIND(symbol.st_info));
2080          sym_visibility =
2081            stv_to_elf_symbol_visibility(GELF_ST_VISIBILITY(symbol.st_other));
2082
2083           if (get_version_for_symbol(elf_handle, i,
2084                                      /*get_def_version=*/true,
2085                                      ver))
2086             ABG_ASSERT(!ver.str().empty());
2087
2088           elf_symbol_sptr symbol_found =
2089             elf_symbol::create(env, i,
2090                                symbol.st_size,
2091                                sym_name_str,
2092                                sym_type, sym_binding,
2093                                symbol.st_shndx != SHN_UNDEF,
2094                                symbol.st_shndx == SHN_COMMON,
2095                                ver, sym_visibility,
2096                                symbol.st_shndx == strings_ndx);
2097           syms_found.push_back(symbol_found);
2098           found = true;
2099         }
2100
2101       if (stop_word & 1)
2102         // The last bit of the stop_word is 1.  That means we need to
2103         // stop here.  We reached the end of the chain of values
2104         // referenced by the hask bucket.
2105         break;
2106     }
2107   return found;
2108 }
2109
2110 /// Look into the symbol tables of the underlying elf file and find
2111 /// the symbol we are being asked.
2112 ///
2113 /// This function uses the elf hash table (be it the GNU hash table or
2114 /// the sysv hash table) for the symbol lookup.
2115 ///
2116 /// @param env the environment we are operating from.
2117 ///
2118 /// @param elf_handle the elf handle to use.
2119 ///
2120 /// @param ht_kind the kind of hash table to use.  This is returned by
2121 /// the function function find_hash_table_section_index.
2122 ///
2123 /// @param ht_index the index (in the section headers table) of the
2124 /// hash table section to use.
2125 ///
2126 /// @param sym_tab_index the index (in section headers table) of the
2127 /// symbol table index to use with this hash table.
2128 ///
2129 /// @param symbol_name the name of the symbol to look for.
2130 ///
2131 /// @param demangle if true, demangle @p sym_name.
2132 ///
2133 /// @param syms_found the symbols that were actually found with the
2134 /// name @p symbol_name.
2135 ///
2136 /// @return true iff the function found the symbol from the elf hash
2137 /// table.
2138 static bool
2139 lookup_symbol_from_elf_hash_tab(const environment*              env,
2140                                 Elf*                            elf_handle,
2141                                 hash_table_kind         ht_kind,
2142                                 size_t                          ht_index,
2143                                 size_t                          symtab_index,
2144                                 const string&                   symbol_name,
2145                                 bool                            demangle,
2146                                 vector<elf_symbol_sptr>&        syms_found)
2147 {
2148   if (elf_handle == 0 || symbol_name.empty())
2149     return false;
2150
2151   if (ht_kind == NO_HASH_TABLE_KIND)
2152     return false;
2153
2154   if (ht_kind == SYSV_HASH_TABLE_KIND)
2155     return lookup_symbol_from_sysv_hash_tab(env,
2156                                             elf_handle, symbol_name,
2157                                             ht_index,
2158                                             symtab_index,
2159                                             demangle,
2160                                             syms_found);
2161   else if (ht_kind == GNU_HASH_TABLE_KIND)
2162     return lookup_symbol_from_gnu_hash_tab(env,
2163                                            elf_handle, symbol_name,
2164                                            ht_index,
2165                                            symtab_index,
2166                                            demangle,
2167                                            syms_found);
2168   return false;
2169 }
2170
2171 /// Lookup a symbol from the symbol table directly.
2172 ///
2173 ///
2174 /// @param env the environment we are operating from.
2175 ///
2176 /// @param elf_handle the elf handle to use.
2177 ///
2178 /// @param sym_name the name of the symbol to look up.
2179 ///
2180 /// @param sym_tab_index the index (in the section headers table) of
2181 /// the symbol table section.
2182 ///
2183 /// @param demangle if true, demangle the names found in the symbol
2184 /// table before comparing them with @p sym_name.
2185 ///
2186 /// @param sym_name_found the actual name of the symbol found.
2187 ///
2188 /// @param sym_type the type of the symbol found.
2189 ///
2190 /// @param sym_binding the binding of the symbol found.
2191 ///
2192 /// @param sym_versions the versions of the symbol found.
2193 ///
2194 /// @return true iff the symbol was found.
2195 static bool
2196 lookup_symbol_from_symtab(const environment*            env,
2197                           Elf*                          elf_handle,
2198                           const string&         sym_name,
2199                           size_t                        sym_tab_index,
2200                           bool                          demangle,
2201                           vector<elf_symbol_sptr>&      syms_found)
2202 {
2203   // TODO: read all of the symbol table, store it in memory in a data
2204   // structure that associates each symbol with its versions and in
2205   // which lookups of a given symbol is fast.
2206   Elf_Scn* sym_tab_section = elf_getscn(elf_handle, sym_tab_index);
2207   ABG_ASSERT(sym_tab_section);
2208
2209   GElf_Shdr header_mem;
2210   GElf_Shdr * sym_tab_header = gelf_getshdr(sym_tab_section,
2211                                             &header_mem);
2212
2213   size_t symcount = sym_tab_header->sh_size / sym_tab_header->sh_entsize;
2214   Elf_Data* symtab = elf_getdata(sym_tab_section, NULL);
2215   GElf_Sym* sym;
2216   char* name_str = 0;
2217   elf_symbol::version ver;
2218   bool found = false;
2219   Elf_Scn *strings_section = find_ksymtab_strings_section(elf_handle);
2220   size_t strings_ndx = strings_section
2221     ? elf_ndxscn(strings_section)
2222     : 0;
2223
2224   for (size_t i = 0; i < symcount; ++i)
2225     {
2226       GElf_Sym sym_mem;
2227       sym = gelf_getsym(symtab, i, &sym_mem);
2228       name_str = elf_strptr(elf_handle,
2229                             sym_tab_header->sh_link,
2230                             sym->st_name);
2231
2232       if (name_str && compare_symbol_name(name_str, sym_name, demangle))
2233         {
2234           elf_symbol::type sym_type =
2235             stt_to_elf_symbol_type(GELF_ST_TYPE(sym->st_info));
2236           elf_symbol::binding sym_binding =
2237             stb_to_elf_symbol_binding(GELF_ST_BIND(sym->st_info));
2238           elf_symbol::visibility sym_visibility =
2239             stv_to_elf_symbol_visibility(GELF_ST_VISIBILITY(sym->st_other));
2240           bool sym_is_defined = sym->st_shndx != SHN_UNDEF;
2241           bool sym_is_common = sym->st_shndx == SHN_COMMON;
2242
2243           if (get_version_for_symbol(elf_handle, i,
2244                                      /*get_def_version=*/sym_is_defined,
2245                                      ver))
2246             ABG_ASSERT(!ver.str().empty());
2247           elf_symbol_sptr symbol_found =
2248             elf_symbol::create(env, i, sym->st_size,
2249                                name_str, sym_type,
2250                                sym_binding, sym_is_defined,
2251                                sym_is_common, ver, sym_visibility,
2252                                sym->st_shndx == strings_ndx);
2253           syms_found.push_back(symbol_found);
2254           found = true;
2255         }
2256     }
2257
2258   if (found)
2259     return true;
2260
2261   return false;
2262 }
2263
2264 /// Look into the symbol tables of the underlying elf file and see
2265 /// if we find a given symbol.
2266 ///
2267 /// @param env the environment we are operating from.
2268 ///
2269 /// @param symbol_name the name of the symbol to look for.
2270 ///
2271 /// @param demangle if true, try to demangle the symbol name found in
2272 /// the symbol table before comparing it to @p symbol_name.
2273 ///
2274 /// @param syms_found the list of symbols found, with the name @p
2275 /// symbol_name.
2276 ///
2277 /// @param sym_type this is set to the type of the symbol found.  This
2278 /// shall b a standard elf.h value for symbol types, that is SHT_OBJECT,
2279 /// STT_FUNC, STT_IFUNC, etc ...
2280 ///
2281 /// Note that this parameter is set iff the function returns true.
2282 ///
2283 /// @param sym_binding this is set to the binding of the symbol found.
2284 /// This is a standard elf.h value of the symbol binding kind, that
2285 /// is, STB_LOCAL, STB_GLOBAL, or STB_WEAK.
2286 ///
2287 /// @param symbol_versions the versions of the symbol @p symbol_name,
2288 /// if it was found.
2289 ///
2290 /// @return true iff a symbol with the name @p symbol_name was found.
2291 static bool
2292 lookup_symbol_from_elf(const environment*               env,
2293                        Elf*                             elf_handle,
2294                        const string&                    symbol_name,
2295                        bool                             demangle,
2296                        vector<elf_symbol_sptr>& syms_found)
2297 {
2298   size_t hash_table_index = 0, symbol_table_index = 0;
2299   hash_table_kind ht_kind = NO_HASH_TABLE_KIND;
2300
2301   if (!demangle)
2302     ht_kind = find_hash_table_section_index(elf_handle,
2303                                             hash_table_index,
2304                                             symbol_table_index);
2305
2306   if (ht_kind == NO_HASH_TABLE_KIND)
2307     {
2308       if (!find_symbol_table_section_index(elf_handle, symbol_table_index))
2309         return false;
2310
2311       return lookup_symbol_from_symtab(env,
2312                                        elf_handle,
2313                                        symbol_name,
2314                                        symbol_table_index,
2315                                        demangle,
2316                                        syms_found);
2317     }
2318
2319   return lookup_symbol_from_elf_hash_tab(env,
2320                                          elf_handle,
2321                                          ht_kind,
2322                                          hash_table_index,
2323                                          symbol_table_index,
2324                                          symbol_name,
2325                                          demangle,
2326                                          syms_found);
2327 }
2328
2329 /// Look into the symbol tables of the underlying elf file and see if
2330 /// we find a given public (global or weak) symbol of function type.
2331 ///
2332 /// @param env the environment we are operating from.
2333 ///
2334 /// @param elf_handle the elf handle to use for the query.
2335 ///
2336 /// @param symbol_name the function symbol to look for.
2337 ///
2338 /// @param func_syms the vector of public functions symbols found, if
2339 /// any.
2340 ///
2341 /// @return true iff the symbol was found.
2342 static bool
2343 lookup_public_function_symbol_from_elf(const environment*               env,
2344                                        Elf*                             elf_handle,
2345                                        const string&                    symbol_name,
2346                                        vector<elf_symbol_sptr>& func_syms)
2347 {
2348   vector<elf_symbol_sptr> syms_found;
2349   bool found = false;
2350
2351   if (lookup_symbol_from_elf(env, elf_handle, symbol_name,
2352                              /*demangle=*/false, syms_found))
2353     {
2354       for (vector<elf_symbol_sptr>::const_iterator i = syms_found.begin();
2355            i != syms_found.end();
2356            ++i)
2357         {
2358           elf_symbol::type type = (*i)->get_type();
2359           elf_symbol::binding binding = (*i)->get_binding();
2360
2361           if ((type == elf_symbol::FUNC_TYPE
2362                || type == elf_symbol::GNU_IFUNC_TYPE
2363                || type == elf_symbol::COMMON_TYPE)
2364               && (binding == elf_symbol::GLOBAL_BINDING
2365                   || binding == elf_symbol::WEAK_BINDING))
2366             {
2367               func_syms.push_back(*i);
2368               found = true;
2369             }
2370         }
2371     }
2372
2373   return found;
2374 }
2375
2376 /// Look into the symbol tables of the underlying elf file and see if
2377 /// we find a given public (global or weak) symbol of variable type.
2378 ///
2379 /// @param env the environment we are operating from.
2380 ///
2381 /// @param elf the elf handle to use for the query.
2382 ///
2383 /// @param symname the variable symbol to look for.
2384 ///
2385 /// @param var_syms the vector of public variable symbols found, if any.
2386 ///
2387 /// @return true iff symbol @p symname was found.
2388 static bool
2389 lookup_public_variable_symbol_from_elf(const environment*               env,
2390                                        Elf*                             elf,
2391                                        const string&                    symname,
2392                                        vector<elf_symbol_sptr>& var_syms)
2393 {
2394   vector<elf_symbol_sptr> syms_found;
2395   bool found = false;
2396
2397   if (lookup_symbol_from_elf(env, elf, symname, /*demangle=*/false, syms_found))
2398     {
2399       for (vector<elf_symbol_sptr>::const_iterator i = syms_found.begin();
2400            i != syms_found.end();
2401            ++i)
2402         if ((*i)->is_variable()
2403             && ((*i)->get_binding() == elf_symbol::GLOBAL_BINDING
2404                 || (*i)->get_binding() == elf_symbol::WEAK_BINDING))
2405           {
2406             var_syms.push_back(*i);
2407             found = true;
2408           }
2409     }
2410
2411   return found;
2412 }
2413
2414 /// Get data tag information of an ELF file by looking up into its
2415 /// dynamic segment
2416 ///
2417 /// @param elf the elf handle to use for the query.
2418 ///
2419 /// @param dt_tag data tag to look for in dynamic segment
2420 /// @param dt_tag_data vector of found information for a given @p data_tag
2421 ///
2422 /// @return true iff data tag @p data_tag was found
2423
2424 bool
2425 lookup_data_tag_from_dynamic_segment(Elf*                       elf,
2426                                      Elf64_Sxword               data_tag,
2427                                      vector<string>&            dt_tag_data)
2428 {
2429   size_t num_prog_headers = 0;
2430   bool found = false;
2431   if (elf_getphdrnum(elf, &num_prog_headers) < 0)
2432     return found;
2433
2434   // Cycle through each program header.
2435   for (size_t i = 0; i < num_prog_headers; ++i)
2436     {
2437       GElf_Phdr phdr_mem;
2438       GElf_Phdr *phdr = gelf_getphdr(elf, i, &phdr_mem);
2439       if (phdr == NULL || phdr->p_type != PT_DYNAMIC)
2440         continue;
2441
2442       // Poke at the dynamic segment like a section, so that we can
2443       // get its section header information; also we'd like to read
2444       // the data of the segment by using elf_getdata() but that
2445       // function needs a Elf_Scn data structure to act on.
2446       // Elfutils doesn't really have any particular function to
2447       // access segment data, other than the functions used to
2448       // access section data.
2449       Elf_Scn *dynamic_section = gelf_offscn(elf, phdr->p_offset);
2450       GElf_Shdr  shdr_mem;
2451       GElf_Shdr *dynamic_section_header = gelf_getshdr(dynamic_section,
2452                                                        &shdr_mem);
2453       if (dynamic_section_header == NULL
2454           || dynamic_section_header->sh_type != SHT_DYNAMIC)
2455         continue;
2456
2457       // Get data of the dynamic segment (seen as a section).
2458       Elf_Data *data = elf_getdata(dynamic_section, NULL);
2459       if (data == NULL)
2460         continue;
2461
2462       // Get the index of the section headers string table.
2463       size_t string_table_index = 0;
2464       ABG_ASSERT (elf_getshdrstrndx(elf, &string_table_index) >= 0);
2465
2466       size_t dynamic_section_header_entry_size = gelf_fsize(elf,
2467                                                             ELF_T_DYN, 1,
2468                                                             EV_CURRENT);
2469
2470       GElf_Shdr link_mem;
2471       GElf_Shdr *link =
2472         gelf_getshdr(elf_getscn(elf,
2473                                 dynamic_section_header->sh_link),
2474                      &link_mem);
2475       ABG_ASSERT(link != NULL);
2476
2477       size_t num_dynamic_section_entries =
2478         dynamic_section_header->sh_size / dynamic_section_header_entry_size;
2479
2480       // Now walk through all the DT_* data tags that are in the
2481       // segment/section
2482       for (size_t j = 0; j < num_dynamic_section_entries; ++j)
2483         {
2484           GElf_Dyn dynamic_section_mem;
2485           GElf_Dyn *dynamic_section = gelf_getdyn(data,
2486                                                   j,
2487                                                   &dynamic_section_mem);
2488           if (dynamic_section->d_tag == data_tag)
2489             {
2490               dt_tag_data.push_back(elf_strptr(elf,
2491                                                dynamic_section_header->sh_link,
2492                                                dynamic_section->d_un.d_val));
2493               found = true;
2494             }
2495         }
2496     }
2497   return found;
2498 }
2499
2500 /// Convert the type of ELF file into @ref elf_type.
2501 ///
2502 /// @param elf the elf handle to use for the query.
2503 ///
2504 /// @return the @ref elf_type for a given elf type.
2505 static elf_type
2506 elf_file_type(Elf* elf)
2507 {
2508   GElf_Ehdr ehdr_mem;
2509   GElf_Ehdr *header = gelf_getehdr (elf, &ehdr_mem);
2510   vector<string> dt_debug_data;
2511
2512   switch (header->e_type)
2513     {
2514     case ET_DYN:
2515       if (lookup_data_tag_from_dynamic_segment(elf, DT_DEBUG, dt_debug_data))
2516         return ELF_TYPE_PI_EXEC;
2517       else
2518         return ELF_TYPE_DSO;
2519     case ET_EXEC:
2520       return ELF_TYPE_EXEC;
2521     case ET_REL:
2522       return ELF_TYPE_RELOCATABLE;
2523     default:
2524       return ELF_TYPE_UNKNOWN;
2525     }
2526 }
2527
2528 // ---------------------------------------
2529 // <location expression evaluation types>
2530 // ---------------------------------------
2531
2532 /// An abstraction of a value representing the result of the
2533 /// evaluation of a dwarf expression.  This is abstraction represents
2534 /// a partial view on the possible values because we are only
2535 /// interested in extracting the latest and longuest constant
2536 /// sub-expression of a given dwarf expression.
2537 class expr_result
2538 {
2539   bool is_const_;
2540   int64_t const_value_;
2541
2542 public:
2543   expr_result()
2544     : is_const_(true),
2545       const_value_(0)
2546   {}
2547
2548   expr_result(bool is_const)
2549     : is_const_(is_const),
2550       const_value_(0)
2551   {}
2552
2553   explicit expr_result(int64_t v)
2554     :is_const_(true),
2555      const_value_(v)
2556   {}
2557
2558   /// @return true if the value is a constant.  Otherwise, return
2559   /// false, meaning the value represents a quantity for which we need
2560   /// inferior (a running program) state to determine the value.
2561   bool
2562   is_const() const
2563   {return is_const_;}
2564
2565
2566   /// @param f a flag saying if the value is set to a constant or not.
2567   void
2568   is_const(bool f)
2569   {is_const_ = f;}
2570
2571   /// Get the current constant value iff this represents a
2572   /// constant.
2573   ///
2574   /// @param value the out parameter.  Is set to the constant value of
2575   /// the @ref expr_result.  This is set iff the function return true.
2576   ///
2577   ///@return true if this has a constant value, false otherwise.
2578   bool
2579   const_value(int64_t& value)
2580   {
2581     if (is_const())
2582       {
2583         value = const_value_;
2584         return true;
2585       }
2586     return false;
2587   }
2588
2589   /// Getter of the constant value of the current @ref expr_result.
2590   ///
2591   /// Note that the current @ref expr_result must be constant,
2592   /// otherwise the current process is aborted.
2593   ///
2594   /// @return the constant value of the current @ref expr_result.
2595   int64_t
2596   const_value() const
2597   {
2598     ABG_ASSERT(is_const());
2599     return const_value_;
2600   }
2601
2602   operator int64_t() const
2603   {return const_value();}
2604
2605   expr_result&
2606   operator=(const int64_t v)
2607   {
2608     const_value_ = v;
2609     return *this;
2610   }
2611
2612   bool
2613   operator==(const expr_result& o) const
2614   {return const_value_ == o.const_value_ && is_const_ == o.is_const_;}
2615
2616   bool
2617   operator>=(const expr_result& o) const
2618   {return const_value_ >= o.const_value_;}
2619
2620   bool
2621   operator<=(const expr_result& o) const
2622   {return const_value_ <= o.const_value_;}
2623
2624   bool
2625   operator>(const expr_result& o) const
2626   {return const_value_ > o.const_value_;}
2627
2628   bool
2629   operator<(const expr_result& o) const
2630   {return const_value_ < o.const_value_;}
2631
2632   expr_result
2633   operator+(const expr_result& v) const
2634   {
2635     expr_result r(*this);
2636     r.const_value_ += v.const_value_;
2637     r.is_const_ = r.is_const_ && v.is_const_;
2638     return r;
2639   }
2640
2641   expr_result&
2642   operator+=(int64_t v)
2643   {
2644     const_value_ += v;
2645     return *this;
2646   }
2647
2648   expr_result
2649   operator-(const expr_result& v) const
2650   {
2651     expr_result r(*this);
2652     r.const_value_ -= v.const_value_;
2653     r.is_const_ = r.is_const_ && v.is_const_;
2654     return r;
2655   }
2656
2657   expr_result
2658   operator%(const expr_result& v) const
2659   {
2660     expr_result r(*this);
2661     r.const_value_ %= v.const_value_;
2662     r.is_const_ = r.is_const_ && v.is_const();
2663     return r;
2664   }
2665
2666   expr_result
2667   operator*(const expr_result& v) const
2668   {
2669     expr_result r(*this);
2670     r.const_value_ *= v.const_value_;
2671     r.is_const_ = r.is_const_ && v.is_const();
2672     return r;
2673   }
2674
2675   expr_result
2676   operator|(const expr_result& v) const
2677   {
2678     expr_result r(*this);
2679     r.const_value_ |= v.const_value_;
2680     r.is_const_ = r.is_const_ && v.is_const_;
2681     return r;
2682   }
2683
2684   expr_result
2685   operator^(const expr_result& v) const
2686   {
2687     expr_result r(*this);
2688     r.const_value_ ^= v.const_value_;
2689     r.is_const_ = r.is_const_ && v.is_const_;
2690     return r;
2691   }
2692
2693   expr_result
2694   operator>>(const expr_result& v) const
2695   {
2696     expr_result r(*this);
2697     r.const_value_ = r.const_value_ >> v.const_value_;
2698     r.is_const_ = r.is_const_ && v.is_const_;
2699     return r;
2700   }
2701
2702   expr_result
2703   operator<<(const expr_result& v) const
2704   {
2705     expr_result r(*this);
2706     r.const_value_ = r.const_value_ << v.const_value_;
2707     r.is_const_ = r.is_const_ && v.is_const_;
2708     return r;
2709   }
2710
2711   expr_result
2712   operator~() const
2713   {
2714     expr_result r(*this);
2715     r.const_value_ = ~r.const_value_;
2716     return r;
2717   }
2718
2719   expr_result
2720   neg() const
2721   {
2722     expr_result r(*this);
2723     r.const_value_ = -r.const_value_;
2724     return r;
2725   }
2726
2727   expr_result
2728   abs() const
2729   {
2730     expr_result r = *this;
2731     r.const_value_ = std::abs(static_cast<long double>(r.const_value()));
2732     return r;
2733   }
2734
2735   expr_result
2736   operator&(const expr_result& o)
2737   {
2738     expr_result r(*this);
2739     r.const_value_ &= o.const_value_;
2740     r.is_const_ = r.is_const_ && o.is_const_;
2741     return r;
2742   }
2743
2744   expr_result
2745   operator/(const expr_result& o)
2746   {
2747     expr_result r(*this);
2748     r.is_const_ = r.is_const_ && o.is_const_;
2749     return r.const_value() / o.const_value();
2750   }
2751 };// class end expr_result;
2752
2753 /// A class that implements a stack of @ref expr_result, to be used in
2754 /// the engine evaluating DWARF expressions.
2755 class expr_result_stack_type
2756 {
2757   vector<expr_result> elems_;
2758
2759 public:
2760
2761   expr_result_stack_type()
2762   {elems_.reserve(4);}
2763
2764   expr_result&
2765   operator[](unsigned i)
2766   {
2767     unsigned s = elems_.size();
2768     ABG_ASSERT(s > i);
2769     return elems_[s - 1 -i];
2770   }
2771
2772   const expr_result&
2773   operator[](unsigned i) const
2774   {return const_cast<expr_result_stack_type*>(this)->operator[](i);}
2775
2776   unsigned
2777   size() const
2778   {return elems_.size();}
2779
2780   vector<expr_result>::reverse_iterator
2781   begin()
2782   {return elems_.rbegin();}
2783
2784   const vector<expr_result>::reverse_iterator
2785   begin() const
2786   {return const_cast<expr_result_stack_type*>(this)->begin();}
2787
2788   vector<expr_result>::reverse_iterator
2789   end()
2790   {return elems_.rend();}
2791
2792   const vector<expr_result>::reverse_iterator
2793   end() const
2794   {return const_cast<expr_result_stack_type*>(this)->end();}
2795
2796   expr_result&
2797   front()
2798   {return elems_.back();}
2799
2800   const expr_result&
2801   front() const
2802   {return const_cast<expr_result_stack_type*>(this)->front();}
2803
2804   void
2805   push_front(expr_result e)
2806   {elems_.push_back(e);}
2807
2808   expr_result
2809   pop_front()
2810   {
2811     expr_result r = front();
2812     elems_.pop_back();
2813     return r;
2814   }
2815
2816   void
2817   erase(vector<expr_result>::reverse_iterator i)
2818   {elems_.erase(--i.base());}
2819
2820   void
2821   clear()
2822   {elems_.clear();}
2823 }; // end class expr_result_stack_type
2824
2825 /// Abstraction of the evaluation context of a dwarf expression.
2826 struct dwarf_expr_eval_context
2827 {
2828   expr_result accum;
2829   expr_result_stack_type stack;
2830   // Is set to true if the result of the expression that got evaluated
2831   // is a TLS address.
2832   bool set_tls_addr;
2833
2834   dwarf_expr_eval_context()
2835     : accum(/*is_const=*/false),
2836       set_tls_addr(false)
2837   {
2838     stack.push_front(expr_result(true));
2839   }
2840
2841   void
2842   reset()
2843   {
2844     stack.clear();
2845     stack.push_front(expr_result(true));
2846     accum = expr_result(false);
2847     set_tls_addr = false;
2848   }
2849
2850   /// Set a flag to to tell that the result of the expression that got
2851   /// evaluated is a TLS address.
2852   ///
2853   /// @param f true iff the result of the expression that got
2854   /// evaluated is a TLS address, false otherwise.
2855   void
2856   set_tls_address(bool f)
2857   {set_tls_addr = f;}
2858
2859   /// Getter for the flag that tells if the result of the expression
2860   /// that got evaluated is a TLS address.
2861   ///
2862   /// @return true iff the result of the expression that got evaluated
2863   /// is a TLS address.
2864   bool
2865   set_tls_address() const
2866   {return set_tls_addr;}
2867
2868   expr_result
2869   pop()
2870   {
2871     expr_result r = stack.front();
2872     stack.pop_front();
2873     return r;
2874   }
2875
2876   void
2877   push(const expr_result& v)
2878   {stack.push_front(v);}
2879 };//end class dwarf_expr_eval_context
2880
2881 // ---------------------------------------
2882 // </location expression evaluation types>
2883 // ---------------------------------------
2884
2885 /// An enum for the diffent kinds of linux kernel specific symbol
2886 /// tables.
2887 enum kernel_symbol_table_kind
2888 {
2889   /// This is for an undefined kind of kernel symbol table.
2890   KERNEL_SYMBOL_TABLE_KIND_UNDEFINED,
2891
2892   /// The __ksymtab symbol table.
2893   KERNEL_SYMBOL_TABLE_KIND_KSYMTAB,
2894
2895   /// The __ksymtab_gpl symbol table.
2896   KERNEL_SYMBOL_TABLE_KIND_KSYMTAB_GPL
2897 };
2898
2899 /// An enum which specifies the format of the kernel symbol table
2900 /// (__ksymtab or __ksymtab_gpl).
2901 enum ksymtab_format
2902 {
2903   /// This enumerator means that no __ksymtab format has been
2904   /// determined yet.
2905   UNDEFINED_KSYMTAB_FORMAT,
2906
2907   /// Before Linux v4.19, the format of the __ksymtab (and the
2908   /// __ksymtab_gpl) section was the following.
2909   ///
2910   /// It's an array of entries.  Each entry describes a symbol.  Each
2911   /// entry is made of two words.  each is of the word size of the
2912   /// architecture. (8-bytes on a 64 bits arch and 4-bytes on a 32
2913   /// bits arch) The first word is the address of a symbol.  The
2914   /// second one is the address of a static global variable symbol
2915   /// which value is the string representing the symbol name.  That
2916   /// string is in the __ksymtab_strings section.
2917   ///
2918   /// So we are mostly interested in the symbol address part of each
2919   /// entry.
2920   ///
2921   /// Thus this enumerator means that we have the pre v4.19 __ksymtab
2922   /// section format.
2923   PRE_V4_19_KSYMTAB_FORMAT,
2924
2925   /// Since, Linux v4.19, the format of the __ksymtab section has
2926   /// changed.  The commit that changed is
2927   /// https://github.com/torvalds/linux/commit/7290d58095712a89f845e1bca05334796dd49ed2.
2928   ///
2929   /// The __ksymtab and __ksymtab_gpl sections each are an array of
2930   /// entries.  Each entry describes a symbol.  Each entry is made of
2931   /// two words.  Each word is 4-bytes length.  The first word is the
2932   /// 'place-relative' address of a symbol.  The second one is the
2933   /// 'place-relative' address of a static global variable symbol
2934   /// which value is the string representing the symbol name.  That
2935   /// string is in the __ksymtab_strings section.
2936   ///
2937   /// Below is the description of what a "place-relative address"
2938   /// means.  For that, we are going to define the meaning of four
2939   /// values: 'N', 'S', 'O', and 'A'.
2940   ///
2941   /// *** 'N' and '0' ***
2942   /// Suppose 'N' is the value of the number stored at offset 'O' (big
2943   /// oh, not zero) in the __ksymtab section.
2944   ///
2945   /// *** 'S'***
2946   /// That N designates a symbol in the symtab section which value is
2947   /// S.  So S is the symbol value (in the .symtab symbol table)
2948   /// referred to by the number N found at offset 'O'.
2949   ///
2950   /// *** 'A' ***
2951   /// Also, suppose the __ksymtab section will be loaded at memory
2952   /// address A, as indicated by the 'address' field of the section
2953   /// header describing the __ksymtab section.
2954   ///
2955   /// So here is the formula that gives us S, from N:
2956   ///
2957   ///     S = N + O + A.
2958   ///
2959   /// Storing addresses this way does away with the need to have
2960   /// relocations for the __ksymtab section.  So in effect, vmlinux
2961   /// binaries implementing this new format of __ksymtab won't have
2962   /// any .rela__ksymtab relocation section for the __ksymtab section
2963   /// in particular (nor any relocation section at all).
2964   ///
2965   ///
2966   /// Note that we are mostly interested in the symbol address part of
2967   /// each entry.
2968   V4_19_KSYMTAB_FORMAT
2969 }; // end enum ksymtab_format
2970
2971 /// The context used to build ABI corpus from debug info in DWARF
2972 /// format.
2973 ///
2974 /// This context is to be created by create_read_context().  It's then
2975 /// passed to all the routines that read specific dwarf bits as they
2976 /// get some important data from it.
2977 ///
2978 /// When a new data member is added to this context, it must be
2979 /// initiliazed by the read_context::initiliaze() function.  So please
2980 /// do not forget.
2981 class read_context
2982 {
2983 public:
2984   struct options_type
2985   {
2986     environment*        env;
2987     bool                load_in_linux_kernel_mode;
2988     bool                load_all_types;
2989     bool                ignore_symbol_table;
2990     bool                show_stats;
2991     bool                do_log;
2992
2993     options_type()
2994       : env(),
2995         load_in_linux_kernel_mode(),
2996         load_all_types(),
2997         ignore_symbol_table(),
2998         show_stats(),
2999         do_log()
3000     {}
3001   };// read_context::options_type
3002
3003   /// A set of containers that contains one container per kind of @ref
3004   /// die_source.  This allows to associate DIEs to things, depending
3005   /// on the source of the DIE.
3006   template <typename ContainerType>
3007   class die_source_dependant_container_set
3008   {
3009     ContainerType primary_debug_info_container_;
3010     ContainerType alt_debug_info_container_;
3011     ContainerType type_unit_container_;
3012
3013   public:
3014
3015     /// Getter for the container associated to DIEs coming from a
3016     /// given @ref die_source.
3017     ///
3018     /// @param source the die_source for which we want the container.
3019     ///
3020     /// @return the container that associates DIEs coming from @p
3021     /// source to something.
3022     ContainerType&
3023     get_container(die_source source)
3024     {
3025       ContainerType *result = 0;
3026       switch (source)
3027         {
3028         case PRIMARY_DEBUG_INFO_DIE_SOURCE:
3029           result = &primary_debug_info_container_;
3030           break;
3031         case ALT_DEBUG_INFO_DIE_SOURCE:
3032           result = &alt_debug_info_container_;
3033           break;
3034         case TYPE_UNIT_DIE_SOURCE:
3035           result = &type_unit_container_;
3036           break;
3037         case NO_DEBUG_INFO_DIE_SOURCE:
3038         case NUMBER_OF_DIE_SOURCES:
3039           ABG_ASSERT_NOT_REACHED;
3040         }
3041       return *result;
3042     }
3043
3044     /// Getter for the container associated to DIEs coming from a
3045     /// given @ref die_source.
3046     ///
3047     /// @param source the die_source for which we want the container.
3048     ///
3049     /// @return the container that associates DIEs coming from @p
3050     /// source to something.
3051     const ContainerType&
3052     get_container(die_source source) const
3053     {
3054       return const_cast<die_source_dependant_container_set*>(this)->
3055         get_container(source);
3056     }
3057
3058     /// Getter for the container associated to DIEs coming from the
3059     /// same source as a given DIE.
3060     ///
3061     /// @param ctxt the read context to consider.
3062     ///
3063     /// @param die the DIE which should have the same source as the
3064     /// source of the container we want.
3065     ///
3066     /// @return the container that associates DIEs coming from the
3067     /// same source as @p die.
3068     ContainerType&
3069     get_container(const read_context& ctxt, const Dwarf_Die *die)
3070     {
3071       die_source source = NO_DEBUG_INFO_DIE_SOURCE;
3072       ABG_ASSERT(ctxt.get_die_source(die, source));
3073       return get_container(source);
3074     }
3075
3076     /// Getter for the container associated to DIEs coming from the
3077     /// same source as a given DIE.
3078     ///
3079     /// @param ctxt the read context to consider.
3080     ///
3081     /// @param die the DIE which should have the same source as the
3082     /// source of the container we want.
3083     ///
3084     /// @return the container that associates DIEs coming from the
3085     /// same source as @p die.
3086     const ContainerType&
3087     get_container(const read_context& ctxt, const Dwarf_Die *die) const
3088     {
3089       return const_cast<die_source_dependant_container_set*>(this)->
3090         get_container(ctxt, die);
3091     }
3092
3093     /// Clear the container set.
3094     void
3095     clear()
3096     {
3097       primary_debug_info_container_.clear();
3098       alt_debug_info_container_.clear();
3099       type_unit_container_.clear();
3100     }
3101   }; // end die_dependant_container_set
3102
3103   suppr::suppressions_type      supprs_;
3104   unsigned short                dwarf_version_;
3105   Dwfl_Callbacks                offline_callbacks_;
3106   // The set of directories under which to look for debug info.
3107   vector<char**>                debug_info_root_paths_;
3108   dwfl_sptr                     handle_;
3109   Dwarf*                        dwarf_;
3110   // The alternate debug info.  Alternate debug info sections are a
3111   // DWARF extension as of DWARF4 and are described at
3112   // http://www.dwarfstd.org/ShowIssue.php?issue=120604.1.  Below are
3113   // the file desctor used to access the alternate debug info
3114   // sections, and the representation of the DWARF debug info.  Both
3115   // need to be freed after we are done using them, with fclose and
3116   // dwarf_end.
3117   int                           alt_fd_;
3118   Dwarf*                        alt_dwarf_;
3119   string                        alt_debug_info_path_;
3120   // The address range of the offline elf file we are looking at.
3121   Dwfl_Module*                  elf_module_;
3122   mutable Elf*                  elf_handle_;
3123   string                        elf_path_;
3124   mutable Elf_Scn*              bss_section_;
3125   mutable Elf_Scn*              text_section_;
3126   mutable Elf_Scn*              rodata_section_;
3127   mutable Elf_Scn*              data_section_;
3128   mutable Elf_Scn*              data1_section_;
3129   mutable Elf_Scn*              symtab_section_;
3130   // The "Official procedure descriptor section, aka .opd", used in
3131   // ppc64 elf v1 binaries.  This section contains the procedure
3132   // descriptors on that platform.
3133   Elf_Scn*                      opd_section_;
3134   /// The format of the special __ksymtab section from the linux
3135   /// kernel binary.
3136   mutable ksymtab_format        ksymtab_format_;
3137   /// The size of one entry of the __ksymtab section.
3138   mutable size_t                ksymtab_entry_size_;
3139   /// The number of entries in the __ksymtab section.
3140   mutable size_t                nb_ksymtab_entries_;
3141   /// The number of entries in the __ksymtab_gpl section.
3142   mutable size_t                nb_ksymtab_gpl_entries_;
3143   /// The special __ksymtab and __ksymtab_gpl sections from linux
3144   /// kernel or module binaries.  The former is used to store
3145   /// references to symbols exported using the EXPORT_SYMBOL macro
3146   /// from the linux kernel.  The latter is used to store references
3147   /// to symbols exported using the EXPORT_SYMBOL_GPL macro from the
3148   /// linux kernel.
3149   Elf_Scn*                      ksymtab_section_;
3150   Elf_Scn*                      ksymtab_reloc_section_;
3151   Elf_Scn*                      ksymtab_gpl_section_;
3152   Elf_Scn*                      ksymtab_gpl_reloc_section_;
3153   Elf_Scn*                      ksymtab_strings_section_;
3154   Elf_Scn*                      versym_section_;
3155   Elf_Scn*                      verdef_section_;
3156   Elf_Scn*                      verneed_section_;
3157   bool                          symbol_versionning_sections_loaded_;
3158   bool                          symbol_versionning_sections_found_;
3159   Dwarf_Die*                    cur_tu_die_;
3160   mutable dwarf_expr_eval_context       dwarf_expr_eval_context_;
3161   // A set of maps (one per kind of die source) that associates a decl
3162   // string representation with the DIEs (offsets) representing that
3163   // decl.
3164   mutable die_source_dependant_container_set<istring_dwarf_offsets_map_type>
3165   decl_die_repr_die_offsets_maps_;
3166   // A set of maps (one per kind of die source) that associates a type
3167   // string representation with the DIEs (offsets) representing that
3168   // type.
3169   mutable die_source_dependant_container_set<istring_dwarf_offsets_map_type>
3170   type_die_repr_die_offsets_maps_;
3171   mutable die_source_dependant_container_set<die_istring_map_type>
3172   die_qualified_name_maps_;
3173   mutable die_source_dependant_container_set<die_istring_map_type>
3174   die_pretty_repr_maps_;
3175   mutable die_source_dependant_container_set<die_istring_map_type>
3176   die_pretty_type_repr_maps_;
3177   // A set of maps (one per kind of die source) that associates the
3178   // offset of a decl die to its corresponding decl artifact.
3179   mutable die_source_dependant_container_set<die_artefact_map_type>
3180   decl_die_artefact_maps_;
3181   // A set of maps (one per kind of die source) that associates the
3182   // offset of a type die to its corresponding type artifact.
3183   mutable die_source_dependant_container_set<die_artefact_map_type>
3184   type_die_artefact_maps_;
3185   /// A set of vectors (one per kind of die source) that associates
3186   /// the offset of a type DIE to the offset of its canonical DIE.
3187   mutable die_source_dependant_container_set<offset_offset_map_type>
3188   canonical_type_die_offsets_;
3189   /// A set of vectors (one per kind of die source) that associates
3190   /// the offset of a decl DIE to the offset of its canonical DIE.
3191   mutable die_source_dependant_container_set<offset_offset_map_type>
3192   canonical_decl_die_offsets_;
3193   /// A map that associates a function type representations to
3194   /// function types, inside a translation unit.
3195   mutable istring_fn_type_map_type per_tu_repr_to_fn_type_maps_;
3196
3197   die_class_or_union_map_type   die_wip_classes_map_;
3198   die_class_or_union_map_type   alternate_die_wip_classes_map_;
3199   die_class_or_union_map_type   type_unit_die_wip_classes_map_;
3200   die_function_type_map_type    die_wip_function_types_map_;
3201   die_function_type_map_type    alternate_die_wip_function_types_map_;
3202   die_function_type_map_type    type_unit_die_wip_function_types_map_;
3203   die_function_decl_map_type    die_function_with_no_symbol_map_;
3204   vector<Dwarf_Off>             types_to_canonicalize_;
3205   vector<Dwarf_Off>             alt_types_to_canonicalize_;
3206   vector<Dwarf_Off>             type_unit_types_to_canonicalize_;
3207   vector<type_base_sptr>        extra_types_to_canonicalize_;
3208   string_classes_map            decl_only_classes_map_;
3209   die_tu_map_type               die_tu_map_;
3210   corpus_group_sptr             cur_corpus_group_;
3211   corpus_sptr                   cur_corpus_;
3212   translation_unit_sptr cur_tu_;
3213   scope_decl_sptr               nil_scope_;
3214   scope_stack_type              scope_stack_;
3215   offset_offset_map_type        primary_die_parent_map_;
3216   // A map that associates each tu die to a vector of unit import
3217   // points, in the main debug info
3218   tu_die_imported_unit_points_map_type tu_die_imported_unit_points_map_;
3219   // A map that associates each tu die to a vector of unit import
3220   // points, in the alternate debug info
3221   tu_die_imported_unit_points_map_type alt_tu_die_imported_unit_points_map_;
3222   tu_die_imported_unit_points_map_type type_units_tu_die_imported_unit_points_map_;
3223   // A DIE -> parent map for DIEs coming from the alternate debug info
3224   // file.
3225   offset_offset_map_type        alternate_die_parent_map_;
3226   offset_offset_map_type        type_section_die_parent_map_;
3227   list<var_decl_sptr>           var_decls_to_add_;
3228   addr_elf_symbol_sptr_map_sptr fun_addr_sym_map_;
3229   // On PPC64, the function entry point address is different from the
3230   // GElf_Sym::st_value value, which is the address of the descriptor
3231   // of the function.  The map below thus associates the address of
3232   // the entry point to the function symbol.  If we are not on ppc64,
3233   // then this map ought to be empty.  Only the fun_addr_sym_map_ is
3234   // used in that case.  On ppc64, though, both maps are used.
3235   addr_elf_symbol_sptr_map_sptr fun_entry_addr_sym_map_;
3236   string_elf_symbols_map_sptr   fun_syms_;
3237   addr_elf_symbol_sptr_map_sptr var_addr_sym_map_;
3238   string_elf_symbols_map_sptr   var_syms_;
3239   string_elf_symbols_map_sptr   undefined_fun_syms_;
3240   string_elf_symbols_map_sptr   undefined_var_syms_;
3241   address_set_sptr              linux_exported_fn_syms_;
3242   address_set_sptr              linux_exported_var_syms_;
3243   address_set_sptr              linux_exported_gpl_fn_syms_;
3244   address_set_sptr              linux_exported_gpl_var_syms_;
3245   vector<string>                dt_needed_;
3246   string                        dt_soname_;
3247   string                        elf_architecture_;
3248   corpus::exported_decls_builder* exported_decls_builder_;
3249   options_type                  options_;
3250   read_context();
3251
3252 public:
3253
3254   /// Constructor of read_context.
3255   ///
3256   /// @param elf_path the path to the elf file the context is to be
3257   /// used for.
3258   ///
3259   /// @param debug_info_root_paths a vector of pointers to the path to
3260   /// the root directory under which the debug info is to be found for
3261   /// @p elf_path.  Leave this empty if the debug info is not in a
3262   /// split file.
3263   ///
3264   /// @param environment the environment used by the current context.
3265   /// This environment contains resources needed by the reader and by
3266   /// the types and declarations that are to be created later.  Note
3267   /// that ABI artifacts that are to be compared all need to be
3268   /// created within the same environment.
3269   ///
3270   /// Please also note that the life time of this environment object
3271   /// must be greater than the life time of the resulting @ref
3272   /// read_context the context uses resources that are allocated in
3273   /// the environment.
3274   ///
3275   /// @param load_all_types if set to false only the types that are
3276   /// reachable from publicly exported declarations (of functions and
3277   /// variables) are read.  If set to true then all types found in the
3278   /// debug information are loaded.
3279   ///
3280   /// @param linux_kernel_mode if set to true, then consider the special
3281   /// linux kernel symbol tables when determining if a symbol is
3282   /// exported or not.
3283   read_context(const string&    elf_path,
3284                const vector<char**>& debug_info_root_paths,
3285                ir::environment* environment,
3286                bool             load_all_types,
3287                bool             linux_kernel_mode)
3288   {
3289     initialize(elf_path, debug_info_root_paths, environment,
3290                load_all_types, linux_kernel_mode);
3291   }
3292
3293   /// Initializer of read_context.
3294   ///
3295   /// @param elf_path the path to the elf file the context is to be
3296   /// used for.
3297   ///
3298   /// @param debug_info_root_paths a vector of pointers to the path to
3299   /// the root directory under which the debug info is to be found for
3300   /// @p elf_path.  Leave this empty if the debug info is not in a
3301   /// split file.
3302   ///
3303   /// @param environment the environment used by the current context.
3304   /// This environment contains resources needed by the reader and by
3305   /// the types and declarations that are to be created later.  Note
3306   /// that ABI artifacts that are to be compared all need to be
3307   /// created within the same environment.
3308   ///
3309   /// Please also note that the life time of this environment object
3310   /// must be greater than the life time of the resulting @ref
3311   /// read_context the context uses resources that are allocated in
3312   /// the environment.
3313   ///
3314   /// @param load_all_types if set to false only the types that are
3315   /// reachable from publicly exported declarations (of functions and
3316   /// variables) are read.  If set to true then all types found in the
3317   /// debug information are loaded.
3318   ///
3319   /// @param linux_kernel_mode if set to true, then consider the
3320   /// special linux kernel symbol tables when determining if a symbol
3321   /// is exported or not.
3322   void
3323   initialize(const string&      elf_path,
3324              const vector<char**>& debug_info_root_paths,
3325              ir::environment* environment,
3326              bool               load_all_types,
3327              bool               linux_kernel_mode)
3328   {
3329     dwarf_version_ = 0;
3330     dwarf_ = 0;
3331     handle_.reset();
3332     alt_fd_ = 0;
3333     alt_dwarf_ = 0;
3334     elf_module_ = 0;
3335     elf_handle_ = 0;
3336     elf_path_ = elf_path;
3337     bss_section_ = 0;
3338     text_section_ = 0;
3339     rodata_section_ = 0;
3340     data_section_ = 0;
3341     data1_section_ = 0;
3342     symtab_section_ = 0;
3343     opd_section_ = 0;
3344     ksymtab_format_ = UNDEFINED_KSYMTAB_FORMAT;
3345     ksymtab_entry_size_ = 0;
3346     nb_ksymtab_entries_ = 0;
3347     nb_ksymtab_gpl_entries_ = 0;
3348     ksymtab_section_ = 0;
3349     ksymtab_reloc_section_ = 0;
3350     ksymtab_gpl_section_ = 0;
3351     ksymtab_gpl_reloc_section_ = 0;
3352     ksymtab_strings_section_ = 0;
3353     versym_section_ = 0;
3354     verdef_section_ = 0;
3355     verneed_section_ = 0;
3356     symbol_versionning_sections_loaded_ = 0;
3357     symbol_versionning_sections_found_ = 0;
3358     cur_tu_die_ =  0;
3359     exported_decls_builder_ = 0;
3360
3361     clear_alt_debug_info_data();
3362
3363     supprs_.clear();
3364     decl_die_repr_die_offsets_maps_.clear();
3365     type_die_repr_die_offsets_maps_.clear();
3366     die_qualified_name_maps_.clear();
3367     die_pretty_repr_maps_.clear();
3368     die_pretty_type_repr_maps_.clear();
3369     decl_die_artefact_maps_.clear();
3370     type_die_artefact_maps_.clear();
3371     canonical_type_die_offsets_.clear();
3372     canonical_decl_die_offsets_.clear();
3373     die_wip_classes_map_.clear();
3374     alternate_die_wip_classes_map_.clear();
3375     type_unit_die_wip_classes_map_.clear();
3376     die_wip_function_types_map_.clear();
3377     alternate_die_wip_function_types_map_.clear();
3378     type_unit_die_wip_function_types_map_.clear();
3379     die_function_with_no_symbol_map_.clear();
3380     types_to_canonicalize_.clear();
3381     alt_types_to_canonicalize_.clear();
3382     type_unit_types_to_canonicalize_.clear();
3383     extra_types_to_canonicalize_.clear();
3384     decl_only_classes_map_.clear();
3385     die_tu_map_.clear();
3386     cur_corpus_group_.reset();
3387     cur_corpus_.reset();
3388     cur_tu_.reset();
3389     primary_die_parent_map_.clear();
3390     tu_die_imported_unit_points_map_.clear();
3391     alt_tu_die_imported_unit_points_map_.clear();
3392     type_units_tu_die_imported_unit_points_map_.clear();
3393     alternate_die_parent_map_.clear();
3394     type_section_die_parent_map_.clear();
3395     var_decls_to_add_.clear();
3396     fun_addr_sym_map_.reset();
3397     fun_entry_addr_sym_map_.reset();
3398     fun_syms_.reset();
3399     var_addr_sym_map_.reset();
3400     var_syms_.reset();
3401     undefined_fun_syms_.reset();
3402     undefined_var_syms_.reset();
3403     linux_exported_fn_syms_.reset();
3404     linux_exported_var_syms_.reset();
3405     linux_exported_gpl_fn_syms_.reset();
3406     linux_exported_gpl_var_syms_.reset();
3407     dt_needed_.clear();
3408     dt_soname_.clear();
3409     elf_architecture_.clear();
3410
3411     clear_per_translation_unit_data();
3412
3413     memset(&offline_callbacks_, 0, sizeof(offline_callbacks_));
3414     create_default_dwfl(debug_info_root_paths);
3415     options_.env = environment;
3416     options_.load_in_linux_kernel_mode = linux_kernel_mode;
3417     options_.load_all_types = load_all_types;
3418     load_in_linux_kernel_mode(linux_kernel_mode);
3419   }
3420
3421   /// Clear the resources related to the alternate DWARF data.
3422   void
3423   clear_alt_debug_info_data()
3424   {
3425     if (alt_fd_)
3426       {
3427         close(alt_fd_);
3428         alt_fd_ = 0;
3429         if (alt_dwarf_)
3430           {
3431             dwarf_end(alt_dwarf_);
3432             alt_dwarf_ = 0;
3433           }
3434         alt_debug_info_path_.clear();
3435       }
3436   }
3437
3438   /// Detructor of the @ref read_context type.
3439   ~read_context()
3440   {
3441     clear_alt_debug_info_data();
3442   }
3443
3444   /// Clear the data that is relevant only for the current translation
3445   /// unit being read.  The rest of the data is relevant for the
3446   /// entire ABI corpus.
3447   void
3448   clear_per_translation_unit_data()
3449   {
3450     while (!scope_stack().empty())
3451       scope_stack().pop();
3452     var_decls_to_re_add_to_tree().clear();
3453     per_tu_repr_to_fn_type_maps().clear();
3454   }
3455
3456   /// Clear the data that is relevant for the current corpus being
3457   /// read.
3458   void
3459   clear_per_corpus_data()
3460   {
3461     die_qualified_name_maps_.clear();
3462     die_pretty_repr_maps_.clear();
3463     die_pretty_type_repr_maps_.clear();
3464     clear_types_to_canonicalize();
3465   }
3466
3467   /// Getter of the options of the read context.
3468   ///
3469   /// @return the options of the read context.
3470   options_type&
3471   options()
3472   {return options_;}
3473
3474   /// Getter of the options of the read context.
3475   ///
3476   /// @return the options of the read context.
3477   const options_type&
3478   options() const
3479   {return options_;}
3480
3481   /// Getter of the options of the read context.
3482   ///
3483   /// @return the options of the read context.
3484   void
3485   options(const options_type& o)
3486   {options_ = o;}
3487
3488   /// Getter for the current environment.
3489   ///
3490   /// @return the current environment.
3491   const ir::environment*
3492   env() const
3493   {return options_.env;}
3494
3495   /// Getter for the current environment.
3496   ///
3497   /// @return the current environment.
3498   ir::environment*
3499   env()
3500   {return options_.env;}
3501
3502   /// Setter for the current environment.
3503   ///
3504   /// @param env the new current environment.
3505   void
3506   env(ir::environment* env)
3507   {options_.env = env;}
3508
3509   /// Getter of the suppression specifications to be used during
3510   /// ELF/DWARF parsing.
3511   ///
3512   /// @return the suppression specifications.
3513   const suppr::suppressions_type&
3514   get_suppressions() const
3515   {return supprs_;}
3516
3517   /// Getter of the suppression specifications to be used during
3518   /// ELF/DWARF parsing.
3519   ///
3520   /// @return the suppression specifications.
3521   suppr::suppressions_type&
3522   get_suppressions()
3523   {return supprs_;}
3524
3525   /// Getter for the callbacks of the Dwarf Front End library of
3526   /// elfutils that is used by this reader to read dwarf.
3527   ///
3528   /// @return the callbacks.
3529   const Dwfl_Callbacks*
3530   offline_callbacks() const
3531   {return &offline_callbacks_;}
3532
3533   /// Getter for the callbacks of the Dwarf Front End library of
3534   /// elfutils that is used by this reader to read dwarf.
3535   /// @returnthe callbacks
3536   Dwfl_Callbacks*
3537   offline_callbacks()
3538   {return &offline_callbacks_;}
3539
3540   /// Constructor for a default Dwfl handle that knows how to load debug
3541   /// info from a library or executable elf file.
3542   ///
3543   /// @param debug_info_root_paths a vector of pointers to the root
3544   /// path under which to look for the debug info of the elf files
3545   /// that are later handled by the Dwfl.  This is for cases where the
3546   /// debug info is split into a different file from the binary we
3547   /// want to inspect.  On Red Hat compatible systems, this root path
3548   /// is usually /usr/lib/debug by default.  If this argument is set
3549   /// to the empty set, then "./debug" and /usr/lib/debug will be
3550   /// searched for sub-directories containing the debug info file.
3551   /// Note that for now, elfutils wants this path to be absolute
3552   /// otherwise things just don't work and the debug info is not
3553   /// found.
3554   ///
3555   /// @return the constructed Dwfl handle.
3556   void
3557   create_default_dwfl(const vector<char**>& debug_info_root_paths)
3558   {
3559     offline_callbacks()->find_debuginfo = dwfl_standard_find_debuginfo;
3560     offline_callbacks()->section_address = dwfl_offline_section_address;
3561     offline_callbacks()->debuginfo_path =
3562       debug_info_root_paths.empty() ? 0 : debug_info_root_paths.front();
3563     handle_.reset(dwfl_begin(offline_callbacks()),
3564                   dwfl_deleter());
3565     debug_info_root_paths_ = debug_info_root_paths;
3566   }
3567
3568   unsigned short
3569   dwarf_version() const
3570   {return dwarf_version_;}
3571
3572   void
3573   dwarf_version(unsigned short v)
3574   {dwarf_version_ = v;}
3575
3576   /// Getter for a smart pointer to a handle on the dwarf front end
3577   /// library that we use to read dwarf.
3578   ///
3579   /// @return the dwfl handle.
3580   dwfl_sptr
3581   dwfl_handle() const
3582   {return handle_;}
3583
3584   /// Setter for a smart pointer to a handle on the dwarf front end
3585   /// library that we use to read dwarf.
3586   ///
3587   /// @param h the new dwfl handle.
3588   void
3589   dwfl_handle(dwfl_sptr& h)
3590   {handle_ = h;}
3591
3592   Dwfl_Module*
3593   elf_module() const
3594   {return elf_module_;}
3595
3596   /// Return the ELF descriptor for the binary we are analizing.
3597   ///
3598   /// @return a pointer to the Elf descriptor representing the binary
3599   /// we are analizing.
3600   Elf*
3601   elf_handle() const
3602   {
3603     if (elf_handle_ == 0)
3604       {
3605         if (elf_module())
3606           {
3607             GElf_Addr bias = 0;
3608             elf_handle_ = dwfl_module_getelf(elf_module(), &bias);
3609           }
3610       }
3611     return elf_handle_;
3612   }
3613
3614   /// Return the ELF descriptor used for DWARF access.
3615   ///
3616   /// This can be the same as read_context::elf_handle() above, if the
3617   /// DWARF info is in the same ELF file as the one of the binary we
3618   /// are analizing.  It is different if e.g, the debug info is split
3619   /// from the ELF file we are analizing.
3620   ///
3621   /// @return a pointer to the ELF descriptor used to access debug
3622   /// info.
3623   Elf*
3624   dwarf_elf_handle() const
3625   {return dwarf_getelf(dwarf());}
3626
3627   /// Test if the debug information is in a separate ELF file wrt the
3628   /// main ELF file of the program (application or shared library) we
3629   /// are analizing.
3630   ///
3631   /// @return true if the debug information is in a separate ELF file
3632   /// compared to the main ELF file of the program (application or
3633   /// shared library) that we are looking at.
3634   bool
3635   dwarf_is_splitted() const
3636   {return dwarf_elf_handle() != elf_handle();}
3637
3638   /// Add paths to the set of paths under which to look for split
3639   /// debuginfo files.
3640   ///
3641   /// @param debug_info_root_paths the paths to add.
3642   void
3643   add_debug_info_root_paths(const vector<char **>& debug_info_root_paths)
3644   {
3645     debug_info_root_paths_.insert(debug_info_root_paths_.end(),
3646                                   debug_info_root_paths.begin(),
3647                                   debug_info_root_paths.end());
3648   }
3649
3650   /// Add a path to the set of paths under which to look for split
3651   /// debuginfo files.
3652   ///
3653   /// @param debug_info_root_path the path to add.
3654   void
3655   add_debug_info_root_path(char** debug_info_root_path)
3656   {debug_info_root_paths_.push_back(debug_info_root_path);}
3657
3658   /// Find the alternate debuginfo file associated to a given elf file.
3659   ///
3660   /// @param elf_module represents the elf file to consider.
3661   ///
3662   /// @param alt_file_name the resulting path to the alternate
3663   /// debuginfo file found.  This is set iff the function returns a
3664   /// non-nil value.
3665   Dwarf*
3666   find_alt_debug_info(Dwfl_Module *elf_module,
3667                       string& alt_file_name,
3668                       int& alt_fd)
3669   {
3670     Dwarf *result = 0;
3671     result = dwarf_reader::find_alt_debug_info(elf_module,
3672                                                debug_info_root_paths_,
3673                                                alt_file_name, alt_fd);
3674     return result;
3675   }
3676
3677   /// Load the debug info associated with an elf file that is at a
3678   /// given path.
3679   ///
3680   /// @return a pointer to the DWARF debug info pointer upon
3681   /// successful debug info loading, NULL otherwise.
3682   Dwarf*
3683   load_debug_info()
3684   {
3685     if (!dwfl_handle())
3686       return 0;
3687
3688     if (dwarf_)
3689       return dwarf_;
3690
3691     elf_module_ =
3692       dwfl_report_offline(dwfl_handle().get(),
3693                           basename(const_cast<char*>(elf_path().c_str())),
3694                           elf_path().c_str(),
3695                           -1);
3696     dwfl_report_end(dwfl_handle().get(), 0, 0);
3697
3698     Dwarf_Addr bias = 0;
3699     dwarf_ = dwfl_module_getdwarf(elf_module_, &bias);
3700     // Look for split debuginfo files under multiple possible
3701     // debuginfo roots.
3702     for (vector<char**>::const_iterator i = debug_info_root_paths_.begin();
3703          dwarf_ == 0 && i != debug_info_root_paths_.end();
3704          ++i)
3705       {
3706         offline_callbacks()->debuginfo_path = *i;
3707         dwarf_ = dwfl_module_getdwarf(elf_module_, &bias);
3708       }
3709
3710     if (!alt_dwarf_)
3711       alt_dwarf_ = find_alt_debug_info(elf_module_,
3712                                        alt_debug_info_path_,
3713                                        alt_fd_);
3714
3715     return dwarf_;
3716   }
3717
3718   /// Return the main debug info we are looking at.
3719   ///
3720   /// @return the main debug info.
3721   Dwarf*
3722   dwarf() const
3723   {return dwarf_;}
3724
3725   /// Return the alternate debug info we are looking at.
3726   ///
3727   /// Note that "alternate debug info sections" is a GNU extension as
3728   /// of DWARF4 and is described at
3729   /// http://www.dwarfstd.org/ShowIssue.php?issue=120604.1
3730   ///
3731   /// @return the alternate debug info.
3732   Dwarf*
3733   alt_dwarf() const
3734   {return alt_dwarf_;}
3735
3736   /// Return the correct debug info, depending on the DIE source we
3737   /// are looking at.
3738   ///
3739   /// @param source the DIE source to consider.
3740   ///
3741   /// @return the right debug info, depending on @p source.
3742   Dwarf*
3743   dwarf_per_die_source(die_source source) const
3744   {
3745     Dwarf *result = 0;
3746     switch(source)
3747       {
3748       case PRIMARY_DEBUG_INFO_DIE_SOURCE:
3749       case TYPE_UNIT_DIE_SOURCE:
3750         result = dwarf();
3751         break;
3752       case ALT_DEBUG_INFO_DIE_SOURCE:
3753         result = alt_dwarf();
3754         break;
3755       case NO_DEBUG_INFO_DIE_SOURCE:
3756       case NUMBER_OF_DIE_SOURCES:
3757         ABG_ASSERT_NOT_REACHED;
3758       }
3759     return result;
3760   }
3761
3762   /// Return the path to the alternate debug info as contained in the
3763   /// .gnu_debugaltlink section of the main elf file.
3764   ///
3765   /// Note that "alternate debug info sections" is a GNU extension as
3766   /// of DWARF4 and is described at
3767   /// http://www.dwarfstd.org/ShowIssue.php?issue=120604.1
3768   ///
3769   /// @return the path to the alternate debug info file, or an empty
3770   /// path if no alternate debug info file is associated.
3771   const string&
3772   alt_debug_info_path() const
3773   {return alt_debug_info_path_;}
3774
3775   /// Return the path to the ELF path we are reading.
3776   ///
3777   /// @return the elf path.
3778   const string&
3779   elf_path() const
3780   {return elf_path_;}
3781
3782   /// Return the bss section of the ELF file we are reading.
3783   ///
3784   /// The first time this function is called, the ELF file is scanned
3785   /// to look for the section we are looking for.  Once the section is
3786   /// found, it's cached.
3787   ///
3788   /// Subsequent calls to this function just return the cached
3789   /// version.
3790   ///
3791   /// @return the bss section.
3792   Elf_Scn*
3793   bss_section() const
3794   {
3795     if (!bss_section_)
3796       bss_section_ = find_bss_section(elf_handle());
3797     return bss_section_;
3798   }
3799
3800   /// Return the text section of the ELF file we are reading.
3801   ///
3802   /// The first time this function is called, the ELF file is scanned
3803   /// to look for the section we are looking for.  Once the section is
3804   /// found, it's cached.
3805   ///
3806   /// Subsequent calls to this function just return the cached
3807   /// version.
3808   ///
3809   /// return the text section.
3810   Elf_Scn*
3811   text_section() const
3812   {
3813     if (!text_section_)
3814       text_section_ = find_text_section(elf_handle());
3815     return text_section_;
3816   }
3817
3818   /// Return the rodata section of the ELF file we are reading.
3819   ///
3820   /// The first time this function is called, the ELF file is scanned
3821   /// to look for the section we are looking for.  Once the section is
3822   /// found, it's cached.
3823   ///
3824   /// Subsequent calls to this function just return the cached
3825   /// version.
3826   ///
3827   /// return the rodata section.
3828   Elf_Scn*
3829   rodata_section() const
3830   {
3831     if (!rodata_section_)
3832       rodata_section_ =find_rodata_section(elf_handle());
3833     return rodata_section_;
3834   }
3835
3836   /// Return the data section of the ELF file we are reading.
3837   ///
3838   /// The first time this function is called, the ELF file is scanned
3839   /// to look for the section we are looking for.  Once the section is
3840   /// found, it's cached.
3841   ///
3842   /// Subsequent calls to this function just return the cached
3843   /// version.
3844   ///
3845   /// return the data section.
3846   Elf_Scn*
3847   data_section() const
3848   {
3849     if (!data_section_)
3850       data_section_ = find_data_section(elf_handle());
3851     return data_section_;
3852   }
3853
3854   /// Return the data1 section of the ELF file we are reading.
3855   ///
3856   /// The first time this function is called, the ELF file is scanned
3857   /// to look for the section we are looking for.  Once the section is
3858   /// found, it's cached.
3859   ///
3860   /// Subsequent calls to this function just return the cached
3861   /// version.
3862   ///
3863   /// return the data1 section.
3864   Elf_Scn*
3865   data1_section() const
3866   {
3867     if (!data1_section_)
3868       data1_section_ = find_data1_section(elf_handle());
3869     return data1_section_;
3870   }
3871
3872   const Dwarf_Die*
3873   cur_tu_die() const
3874   {return cur_tu_die_;}
3875
3876   void
3877   cur_tu_die(Dwarf_Die* cur_tu_die)
3878   {cur_tu_die_ = cur_tu_die;}
3879
3880   dwarf_expr_eval_context&
3881   dwarf_expr_eval_ctxt() const
3882   {return dwarf_expr_eval_context_;}
3883
3884   /// Getter of the maps set that associates a representation of a
3885   /// decl DIE to a vector of offsets of DIEs having that representation.
3886   ///
3887   /// @return the maps set that associates a representation of a decl
3888   /// DIE to a vector of offsets of DIEs having that representation.
3889   const die_source_dependant_container_set<istring_dwarf_offsets_map_type>&
3890   decl_die_repr_die_offsets_maps() const
3891   {return decl_die_repr_die_offsets_maps_;}
3892
3893   /// Getter of the maps set that associates a representation of a
3894   /// decl DIE to a vector of offsets of DIEs having that representation.
3895   ///
3896   /// @return the maps set that associates a representation of a decl
3897   /// DIE to a vector of offsets of DIEs having that representation.
3898   die_source_dependant_container_set<istring_dwarf_offsets_map_type>&
3899   decl_die_repr_die_offsets_maps()
3900   {return decl_die_repr_die_offsets_maps_;}
3901
3902   /// Getter of the maps set that associate a representation of a type
3903   /// DIE to a vector of offsets of DIEs having that representation.
3904   ///
3905   /// @return the maps set that associate a representation of a type
3906   /// DIE to a vector of offsets of DIEs having that representation.
3907   const die_source_dependant_container_set<istring_dwarf_offsets_map_type>&
3908   type_die_repr_die_offsets_maps() const
3909   {return type_die_repr_die_offsets_maps_;}
3910
3911   /// Getter of the maps set that associate a representation of a type
3912   /// DIE to a vector of offsets of DIEs having that representation.
3913   ///
3914   /// @return the maps set that associate a representation of a type
3915   /// DIE to a vector of offsets of DIEs having that representation.
3916   die_source_dependant_container_set<istring_dwarf_offsets_map_type>&
3917   type_die_repr_die_offsets_maps()
3918   {return type_die_repr_die_offsets_maps_;}
3919
3920
3921   /// Compute the offset of the canonical DIE of a given DIE.
3922   ///
3923   /// @param die the DIE to consider.
3924   ///
3925   /// @param canonical_die_offset out parameter.  This is set to the
3926   /// resulting canonical DIE that was computed.
3927   ///
3928   /// @param die_as_type if yes, it means @p die has to be considered
3929   /// as a type.
3930   void
3931   compute_canonical_die_offset(const Dwarf_Die *die,
3932                                Dwarf_Off &canonical_die_offset,
3933                                bool die_as_type) const
3934   {
3935     offset_offset_map_type &canonical_dies =
3936       die_as_type
3937       ? const_cast<read_context*>(this)->canonical_type_die_offsets_.
3938       get_container(*this, die)
3939       : const_cast<read_context*>(this)->canonical_decl_die_offsets_.
3940       get_container(*this, die);
3941
3942     Dwarf_Die canonical_die;
3943     compute_canonical_die(die, canonical_dies, canonical_die, die_as_type);
3944
3945     canonical_die_offset = dwarf_dieoffset(&canonical_die);
3946   }
3947
3948   /// Compute (find) the canonical DIE of a given DIE.
3949   ///
3950   /// @param die the DIE to consider.
3951   ///
3952   /// @param canonical_dies the vector in which the canonical dies ar
3953   /// stored.  The index of each element is the offset of the DIE we
3954   /// want the canonical DIE for.  And the value of the element at
3955   /// that index is the canonical DIE offset we are looking for.
3956   ///
3957   /// @param canonical_die_offset out parameter.  This is set to the
3958   /// resulting canonical DIE that was computed.
3959   ///
3960   /// @param die_as_type if yes, it means @p die has to be considered
3961   /// as a type.
3962   void
3963   compute_canonical_die(const Dwarf_Die *die,
3964                         offset_offset_map_type& canonical_dies,
3965                         Dwarf_Die &canonical_die,
3966                         bool die_as_type) const
3967   {
3968     die_source source;
3969     ABG_ASSERT(get_die_source(die, source));
3970
3971     Dwarf_Off die_offset = dwarf_dieoffset(const_cast<Dwarf_Die*>(die));
3972
3973     compute_canonical_die(die_offset, source,
3974                           canonical_dies,
3975                           canonical_die, die_as_type);
3976   }
3977
3978   /// Compute (find) the canonical DIE of a given DIE.
3979   ///
3980   /// @param die_offset the offset of the DIE to consider.
3981   ///
3982   /// @param source the source of the DIE to consider.
3983   ///
3984   /// @param canonical_dies the vector in which the canonical dies ar
3985   /// stored.  The index of each element is the offset of the DIE we
3986   /// want the canonical DIE for.  And the value of the element at
3987   /// that index is the canonical DIE offset we are looking for.
3988   ///
3989   /// @param canonical_die_offset out parameter.  This is set to the
3990   /// resulting canonical DIE that was computed.
3991   ///
3992   /// @param die_as_type if yes, it means @p die has to be considered
3993   /// as a type.
3994   void
3995   compute_canonical_die(Dwarf_Off die_offset,
3996                         die_source source,
3997                         offset_offset_map_type& canonical_dies,
3998                         Dwarf_Die &canonical_die,
3999                         bool die_as_type) const
4000   {
4001     // The map that associates the string representation of 'die'
4002     // with a vector of offsets of potentially equivalent DIEs.
4003     istring_dwarf_offsets_map_type& map =
4004       die_as_type
4005       ? (const_cast<read_context*>(this)->
4006          type_die_repr_die_offsets_maps().get_container(source))
4007       : (const_cast<read_context*>(this)->
4008          decl_die_repr_die_offsets_maps().get_container(source));
4009
4010     Dwarf_Die die;
4011     ABG_ASSERT(dwarf_offdie(dwarf_per_die_source(source), die_offset, &die));
4012
4013     // The variable repr is the the string representation of 'die'.
4014     //
4015     // Even if die_as_type is true -- which means that 'die' is said
4016     // to be considered as a type -- we always consider a
4017     // DW_TAG_subprogram DIE as a decl here, as far as its string
4018     // representation is concerned.
4019     interned_string name =
4020       (die_as_type)
4021       ? get_die_pretty_type_representation(&die, /*where=*/0)
4022       : get_die_pretty_representation(&die, /*where=*/0);
4023
4024     Dwarf_Off canonical_die_offset = 0;
4025     istring_dwarf_offsets_map_type::iterator i = map.find(name);
4026     if (i == map.end())
4027       {
4028         dwarf_offsets_type offsets;
4029         offsets.push_back(die_offset);
4030         map[name] = offsets;
4031         set_canonical_die_offset(canonical_dies, die_offset, die_offset);
4032         get_die_from_offset(source, die_offset, &canonical_die);
4033         return;
4034       }
4035
4036     if (odr_is_relevant(&die))
4037       {
4038         // ODR is relevant for this DIE.  In this case, all types with
4039         // the same name are considered equivalent.  So the array
4040         // i->second shoud only have on element.  If not, then
4041         // the DIEs referenced in the array should all compare equal.
4042         // Otherwise, this is an ODR violation.  In any case, return
4043         // the first element of the array.
4044         // ABG_ASSERT(i->second.size() == 1);
4045         canonical_die_offset = i->second.front();
4046         get_die_from_offset(source, canonical_die_offset, &canonical_die);
4047         set_canonical_die_offset(canonical_dies, die_offset, die_offset);
4048         return;
4049       }
4050
4051     Dwarf_Off cur_die_offset;
4052     Dwarf_Die potential_canonical_die;
4053     for (dwarf_offsets_type::const_iterator o = i->second.begin();
4054          o != i->second.end();
4055          ++o)
4056       {
4057         cur_die_offset = *o;
4058         get_die_from_offset(source, cur_die_offset, &potential_canonical_die);
4059         if (compare_dies(*this, &die, &potential_canonical_die,
4060                          /*update_canonical_dies_on_the_fly=*/false))
4061           {
4062             canonical_die_offset = cur_die_offset;
4063             set_canonical_die_offset(canonical_dies, die_offset,
4064                                      canonical_die_offset);
4065             get_die_from_offset(source, canonical_die_offset, &canonical_die);
4066             return;
4067           }
4068       }
4069
4070     canonical_die_offset = die_offset;
4071     i->second.push_back(die_offset);
4072     set_canonical_die_offset(canonical_dies, die_offset, die_offset);
4073     get_die_from_offset(source, canonical_die_offset, &canonical_die);
4074   }
4075
4076   /// Getter of the canonical DIE of a given DIE.
4077   ///
4078   /// @param die the DIE to consider.
4079   ///
4080   /// @param canonical_die output parameter.  Is set to the resuling
4081   /// canonical die, if this function returns true.
4082   ///
4083   /// @param where the offset of the logical DIE we are supposed to be
4084   /// calling this function from.  If set to zero this means this is
4085   /// to be ignored.
4086   ///
4087   /// @param die_as_type if set to yes, it means @p die is to be
4088   /// considered as a type DIE.
4089   ///
4090   /// @return true iff a canonical DIE was found for @p die.
4091   bool
4092   get_canonical_die(const Dwarf_Die *die,
4093                     Dwarf_Die &canonical_die,
4094                     size_t where,
4095                     bool die_as_type) const
4096   {
4097     die_source source;
4098     ABG_ASSERT(get_die_source(die, source));
4099
4100     offset_offset_map_type &canonical_dies =
4101       die_as_type
4102       ? const_cast<read_context*>(this)->canonical_type_die_offsets_.
4103       get_container(source)
4104       : const_cast<read_context*>(this)->canonical_decl_die_offsets_.
4105       get_container(source);
4106
4107     Dwarf_Off die_offset = dwarf_dieoffset(const_cast<Dwarf_Die*>(die));
4108     if (Dwarf_Off canonical_die_offset =
4109         get_canonical_die_offset(canonical_dies, die_offset))
4110       {
4111         get_die_from_offset(source, canonical_die_offset, &canonical_die);
4112         return true;
4113       }
4114
4115     // The map that associates the string representation of 'die'
4116     // with a vector of offsets of potentially equivalent DIEs.
4117     istring_dwarf_offsets_map_type& map =
4118       die_as_type
4119       ? (const_cast<read_context*>(this)->
4120          type_die_repr_die_offsets_maps().get_container(*this, die))
4121       : (const_cast<read_context*>(this)->
4122          decl_die_repr_die_offsets_maps().get_container(*this, die));
4123
4124     // The variable repr is the the string representation of 'die'.
4125     //
4126     // Even if die_as_type is true -- which means that 'die' is said
4127     // to be considered as a type -- we always consider a
4128     // DW_TAG_subprogram DIE as a decl here, as far as its string
4129     // representation is concerned.
4130     interned_string name =
4131       (die_as_type /*&& dwarf_tag(die) != DW_TAG_subprogram*/)
4132       ? get_die_pretty_type_representation(die, where)
4133       : get_die_pretty_representation(die, where);
4134
4135     istring_dwarf_offsets_map_type::iterator i = map.find(name);
4136     if (i == map.end())
4137       return false;
4138
4139     if (odr_is_relevant(die))
4140       {
4141         // ODR is relevant for this DIE.  In this case, all types with
4142         // the same name are considered equivalent.  So the array
4143         // i->second shoud only have on element.  If not, then
4144         // the DIEs referenced in the array should all compare equal.
4145         // Otherwise, this is an ODR violation.  In any case, return
4146         // the first element of the array.
4147         // ABG_ASSERT(i->second.size() == 1);
4148         Dwarf_Off canonical_die_offset = i->second.front();
4149         get_die_from_offset(source, canonical_die_offset, &canonical_die);
4150         set_canonical_die_offset(canonical_dies,
4151                                  die_offset,
4152                                  canonical_die_offset);
4153         return true;
4154       }
4155
4156     Dwarf_Off cur_die_offset;
4157     for (dwarf_offsets_type::const_iterator o = i->second.begin();
4158          o != i->second.end();
4159          ++o)
4160       {
4161         cur_die_offset = *o;
4162         get_die_from_offset(source, cur_die_offset, &canonical_die);
4163         // compare die and canonical_die.
4164         if (compare_dies(*this, die, &canonical_die,
4165                          /*update_canonical_dies_on_the_fly=*/true))
4166           {
4167             set_canonical_die_offset(canonical_dies,
4168                                      die_offset,
4169                                      cur_die_offset);
4170             return true;
4171           }
4172       }
4173
4174     return false;
4175   }
4176
4177   /// Retrieve the canonical DIE of a given DIE.
4178   ///
4179   /// The canonical DIE is a DIE that is structurally equivalent to
4180   /// this one.
4181   ///
4182   /// Note that this function caches the canonical DIE that was
4183   /// computed.  Subsequent invocations of this function on the same
4184   /// DIE return the same cached DIE.
4185   ///
4186   /// @param die the DIE to get a canonical type for.
4187   ///
4188   /// @param canonical_die the resulting canonical DIE.
4189   ///
4190   /// @param where the offset of the logical DIE we are supposed to be
4191   /// calling this function from.  If set to zero this means this is
4192   /// to be ignored.
4193   ///
4194   /// @param die_as_type if true, consider DIE is a type.
4195   ///
4196   /// @return true if an *existing* canonical DIE was found.
4197   /// Otherwise, @p die is considered as being a canonical DIE for
4198   /// itself. @p canonical_die is thus set to the canonical die in
4199   /// either cases.
4200   bool
4201   get_or_compute_canonical_die(const Dwarf_Die* die,
4202                                Dwarf_Die& canonical_die,
4203                                size_t where,
4204                                bool die_as_type) const
4205   {
4206     die_source source;
4207     ABG_ASSERT(get_die_source(die, source));
4208
4209     offset_offset_map_type &canonical_dies =
4210       die_as_type
4211       ? const_cast<read_context*>(this)->canonical_type_die_offsets_.
4212       get_container(source)
4213       : const_cast<read_context*>(this)->canonical_decl_die_offsets_.
4214       get_container(source);
4215
4216     Dwarf_Off initial_die_offset = dwarf_dieoffset(const_cast<Dwarf_Die*>(die));
4217
4218     if (Dwarf_Off canonical_die_offset =
4219         get_canonical_die_offset(canonical_dies,
4220                                  initial_die_offset))
4221       {
4222         get_die_from_offset(source, canonical_die_offset, &canonical_die);
4223         return true;
4224       }
4225
4226     // The map that associates the string representation of 'die'
4227     // with a vector of offsets of potentially equivalent DIEs.
4228     istring_dwarf_offsets_map_type& map =
4229       die_as_type
4230       ? (const_cast<read_context*>(this)->
4231          type_die_repr_die_offsets_maps().get_container(*this, die))
4232       : (const_cast<read_context*>(this)->
4233          decl_die_repr_die_offsets_maps().get_container(*this, die));
4234
4235     // The variable repr is the the string representation of 'die'.
4236     //
4237     // Even if die_as_type is true -- which means that 'die' is said
4238     // to be considered as a type -- we always consider a
4239     // DW_TAG_subprogram DIE as a decl here, as far as its string
4240     // representation is concerned.
4241     interned_string name =
4242       (die_as_type)
4243       ? get_die_pretty_type_representation(die, where)
4244       : get_die_pretty_representation(die, where);
4245
4246     istring_dwarf_offsets_map_type::iterator i = map.find(name);
4247     if (i == map.end())
4248       {
4249         dwarf_offsets_type offsets;
4250         offsets.push_back(initial_die_offset);
4251         map[name] = offsets;
4252         get_die_from_offset(source, initial_die_offset, &canonical_die);
4253         set_canonical_die_offset(canonical_dies,
4254                                  initial_die_offset,
4255                                  initial_die_offset);
4256         return false;
4257       }
4258
4259     if (odr_is_relevant(die))
4260       {
4261         // ODR is relevant for this DIE.  In this case, all types with
4262         // the same name are considered equivalent.  So the array
4263         // i->second shoud only have on element.  If not, then
4264         // the DIEs referenced in the array should all compare equal.
4265         // Otherwise, this is an ODR violation.  In any case, return
4266         // the first element of the array.
4267         // ABG_ASSERT(i->second.size() == 1);
4268         Dwarf_Off die_offset = i->second.front();
4269         get_die_from_offset(source, die_offset, &canonical_die);
4270         set_canonical_die_offset(canonical_dies,
4271                                  initial_die_offset,
4272                                  die_offset);
4273         return true;
4274       }
4275
4276     // walk i->second without any iterator (using a while loop rather
4277     // than a for loop) because compare_dies might add new content to
4278     // the end of the i->second vector during the walking.
4279     dwarf_offsets_type::size_type n = 0, s = i->second.size();
4280     while (n < s)
4281       {
4282         Dwarf_Off die_offset = i->second[n];
4283         get_die_from_offset(source, die_offset, &canonical_die);
4284         // compare die and canonical_die.
4285         if (compare_dies(*this, die, &canonical_die,
4286                          /*update_canonical_dies_on_the_fly=*/true))
4287           {
4288             set_canonical_die_offset(canonical_dies,
4289                                      initial_die_offset,
4290                                      die_offset);
4291             return true;
4292           }
4293         ++n;
4294       }
4295
4296     // We didn't find a canonical DIE for 'die'.  So let's consider
4297     // that it is its own canonical DIE.
4298     get_die_from_offset(source, initial_die_offset, &canonical_die);
4299     i->second.push_back(initial_die_offset);
4300     set_canonical_die_offset(canonical_dies,
4301                              initial_die_offset,
4302                              initial_die_offset);
4303
4304     return false;
4305   }
4306
4307   /// Get the source of the DIE.
4308   ///
4309   /// The function returns an enumerator value saying if the DIE comes
4310   /// from the .debug_info section of the primary debug info file, the
4311   /// .debug_info section of the alternate debug info file, or the
4312   /// .debug_types section.
4313   ///
4314   /// @param die the DIE to get the source of.
4315   ///
4316   /// @param source out parameter.  The function sets this parameter
4317   /// to the source of the DIE @p iff it returns true.
4318   ///
4319   /// @return true iff the source of the DIE could be determined and
4320   /// returned.
4321   bool
4322   get_die_source(const Dwarf_Die *die, die_source &source) const
4323   {
4324     ABG_ASSERT(die);
4325     return get_die_source(*die, source);
4326   }
4327
4328   /// Get the source of the DIE.
4329   ///
4330   /// The function returns an enumerator value saying if the DIE comes
4331   /// from the .debug_info section of the primary debug info file, the
4332   /// .debug_info section of the alternate debug info file, or the
4333   /// .debug_types section.
4334   ///
4335   /// @param die the DIE to get the source of.
4336   ///
4337   /// @param source out parameter.  The function sets this parameter
4338   /// to the source of the DIE @p iff it returns true.
4339   ///
4340   /// @return true iff the source of the DIE could be determined and
4341   /// returned.
4342   bool
4343   get_die_source(const Dwarf_Die &die, die_source &source) const
4344   {
4345     Dwarf_Die cu_die;
4346     Dwarf_Die cu_kind;
4347     uint8_t address_size = 0, offset_size = 0;
4348     if (!dwarf_diecu(const_cast<Dwarf_Die*>(&die),
4349                      &cu_die, &address_size,
4350                      &offset_size))
4351       return false;
4352
4353     Dwarf_Half version = 0;
4354     Dwarf_Off abbrev_offset = 0;
4355     uint64_t type_signature = 0;
4356     Dwarf_Off type_offset = 0;
4357     if (!dwarf_cu_die(cu_die.cu, &cu_kind,
4358                       &version, &abbrev_offset,
4359                       &address_size, &offset_size,
4360                       &type_signature, &type_offset))
4361       return false;
4362
4363     int tag = dwarf_tag(&cu_kind);
4364
4365     if (tag == DW_TAG_compile_unit
4366         || tag == DW_TAG_partial_unit)
4367       {
4368         Dwarf *die_dwarf = dwarf_cu_getdwarf(cu_die.cu);
4369         if (dwarf() == die_dwarf)
4370           source = PRIMARY_DEBUG_INFO_DIE_SOURCE;
4371         else if (alt_dwarf() == die_dwarf)
4372           source = ALT_DEBUG_INFO_DIE_SOURCE;
4373         else
4374           ABG_ASSERT_NOT_REACHED;
4375       }
4376     else if (tag == DW_TAG_type_unit)
4377       source = TYPE_UNIT_DIE_SOURCE;
4378     else
4379       return false;
4380
4381     return true;
4382   }
4383
4384   /// Getter for the DIE designated by an offset.
4385   ///
4386   /// @param source the source of the DIE to get.
4387   ///
4388   /// @param offset the offset of the DIE to get.
4389   ///
4390   /// @param die the resulting DIE.  The pointer has to point to an
4391   /// allocated memory region.
4392   void
4393   get_die_from_offset(die_source source, Dwarf_Off offset, Dwarf_Die *die) const
4394   {
4395     if (source == TYPE_UNIT_DIE_SOURCE)
4396       ABG_ASSERT(dwarf_offdie_types(dwarf_per_die_source(source), offset, die));
4397     else
4398       ABG_ASSERT(dwarf_offdie(dwarf_per_die_source(source), offset, die));
4399   }
4400
4401 public:
4402
4403   /// Add an entry to the relevant die->decl map.
4404   ///
4405   /// @param die the DIE to add the the map.
4406   ///
4407   /// @param decl the decl to consider.
4408   ///
4409   /// @param where_offset where in the DIE stream we logically are.
4410   ///
4411   /// @param do_associate_by_repr if true then this function
4412   /// associates the representation string of @p die with the
4413   /// declaration @p decl, in a corpus-wide manner.  That is, in the
4414   /// entire current corpus, there is going to be just one declaration
4415   /// associated with a DIE of the string representation of @p die.
4416   ///
4417   /// @param do_associate_by_repr_per_tu if true, then this function
4418   /// associates the representation string of @p die with the
4419   /// declaration @p decl in a translation unit wide manner.  That is,
4420   /// in the entire current translation unit, there is going to be
4421   /// just one declaration associated with a DIE of the string
4422   /// representation of @p die.
4423   void
4424   associate_die_to_decl(Dwarf_Die* die,
4425                         decl_base_sptr decl,
4426                         size_t where_offset,
4427                         bool do_associate_by_repr = false)
4428   {
4429     die_source source;
4430     ABG_ASSERT(get_die_source(die, source));
4431
4432     die_artefact_map_type& m =
4433       decl_die_artefact_maps().get_container(source);
4434
4435     size_t die_offset;
4436     if (do_associate_by_repr)
4437       {
4438         Dwarf_Die equiv_die;
4439         get_or_compute_canonical_die(die, equiv_die, where_offset,
4440                                      /*die_as_type=*/false);
4441         die_offset = dwarf_dieoffset(&equiv_die);
4442       }
4443     else
4444       die_offset = dwarf_dieoffset(die);
4445
4446     m[die_offset] = decl;
4447   }
4448
4449 public:
4450
4451   /// Lookup the decl for a given DIE.
4452   ///
4453   /// The returned decl is either the decl of the DIE that as the
4454   /// exact offset @p die_offset
4455   /// die_offset, or
4456   /// give
4457   ///
4458   /// @param die_offset the offset of the DIE to consider.
4459   ///
4460   /// @param source where the DIE represented by @p die_offset comes
4461   /// from.
4462   ///
4463   /// Note that "alternate debug info sections" is a GNU extension as
4464   /// of DWARF4 and is described at
4465   /// http://www.dwarfstd.org/ShowIssue.php?issue=120604.1
4466   ///
4467   /// @return the resulting decl, or null if no decl is associated to
4468   /// the DIE represented by @p die_offset.
4469   decl_base_sptr
4470   lookup_decl_from_die_offset(Dwarf_Off die_offset, die_source source)
4471   {
4472     decl_base_sptr result =
4473       is_decl(lookup_artifact_from_die_offset(die_offset, source,
4474                                               /*die_as_type=*/false));
4475
4476     return result;
4477   }
4478
4479   /// Get the qualified name of a given DIE.
4480   ///
4481   /// If the name of the DIE was already computed before just return
4482   /// that name from a cache.  Otherwise, build the name, cache it and
4483   /// return it.
4484   ///
4485   /// @param die the DIE to consider.
4486   ///
4487   /// @param where_offset where in the DIE stream we logically are.
4488   ///
4489   /// @return the interned string representing the qualified name of
4490   /// @p die.
4491   interned_string
4492   get_die_qualified_name(Dwarf_Die *die, size_t where_offset)
4493   {
4494     ABG_ASSERT(die);
4495     die_istring_map_type& map =
4496       die_qualified_name_maps_.get_container(*this, die);
4497
4498     size_t die_offset = dwarf_dieoffset(die);
4499     die_istring_map_type::const_iterator i = map.find(die_offset);
4500
4501     if (i == map.end())
4502       {
4503         read_context& ctxt  = *const_cast<read_context*>(this);
4504         string qualified_name = die_qualified_name(ctxt, die, where_offset);
4505         interned_string istr = env()->intern(qualified_name);
4506         map[die_offset] = istr;
4507         return istr;
4508       }
4509
4510     return i->second;
4511   }
4512
4513   /// Get the qualified name of a given DIE.
4514   ///
4515   /// If the name of the DIE was already computed before just return
4516   /// that name from a cache.  Otherwise, build the name, cache it and
4517   /// return it.
4518   ///
4519   /// @param die the DIE to consider.
4520   ///
4521   /// @param where_offset where in the DIE stream we logically are.
4522   ///
4523   /// @return the interned string representing the qualified name of
4524   /// @p die.
4525   interned_string
4526   get_die_qualified_name(Dwarf_Die *die, size_t where_offset) const
4527   {
4528     return const_cast<read_context*>(this)->
4529       get_die_qualified_name(die, where_offset);
4530   }
4531
4532   /// Get the qualified name of a given DIE which is considered to be
4533   /// the DIE for a type.
4534   ///
4535   /// For instance, for a DW_TAG_subprogram DIE, this function
4536   /// computes the name of the function *type* that corresponds to the
4537   /// function.
4538   ///
4539   /// If the name of the DIE was already computed before just return
4540   /// that name from a cache.  Otherwise, build the name, cache it and
4541   /// return it.
4542   ///
4543   /// @param die the DIE to consider.
4544   ///
4545   /// @param where_offset where in the DIE stream we logically are.
4546   ///
4547   /// @return the interned string representing the qualified name of
4548   /// @p die.
4549   interned_string
4550   get_die_qualified_type_name(const Dwarf_Die *die, size_t where_offset) const
4551   {
4552     ABG_ASSERT(die);
4553
4554     // The name of the translation unit die is "".
4555     if (die == cur_tu_die())
4556       return env()->intern("");
4557
4558     die_istring_map_type& map =
4559       die_qualified_name_maps_.get_container(*const_cast<read_context*>(this),
4560                                              die);
4561
4562     size_t die_offset = dwarf_dieoffset(const_cast<Dwarf_Die*>(die));
4563     die_istring_map_type::const_iterator i =
4564       map.find(die_offset);
4565
4566     if (i == map.end())
4567       {
4568         read_context& ctxt  = *const_cast<read_context*>(this);
4569         string qualified_name;
4570         int tag = dwarf_tag(const_cast<Dwarf_Die*>(die));
4571         if ((tag == DW_TAG_structure_type
4572              || tag == DW_TAG_class_type
4573              || tag == DW_TAG_union_type)
4574             && die_is_anonymous(die))
4575           {
4576             location l = die_location(*this, die);
4577             qualified_name = l ? l.expand() : "noloc";
4578             qualified_name = "unnamed-at-" + qualified_name;
4579           }
4580         else
4581           qualified_name =
4582             die_qualified_type_name(ctxt, die, where_offset);
4583
4584         interned_string istr = env()->intern(qualified_name);
4585         map[die_offset] = istr;
4586         return istr;
4587       }
4588
4589     return i->second;
4590   }
4591
4592   /// Get the pretty representation of a DIE that represents a type.
4593   ///
4594   /// For instance, for the DW_TAG_subprogram, this function computes
4595   /// the pretty representation of the type of the function, not the
4596   /// pretty representation of the function declaration.
4597   ///
4598   /// Once the pretty representation is computed, it's stored in a
4599   /// cache.  Subsequent invocations of this function on the same DIE
4600   /// will yield the cached name.
4601   ///
4602   /// @param die the DIE to consider.
4603   ///
4604   /// @param where_offset where in the DIE stream we logically are.
4605   ///
4606   /// @return the interned_string that represents the pretty
4607   /// representation.
4608   interned_string
4609   get_die_pretty_type_representation(const Dwarf_Die *die,
4610                                      size_t where_offset) const
4611   {
4612     ABG_ASSERT(die);
4613     die_istring_map_type& map =
4614       die_pretty_type_repr_maps_.get_container(*const_cast<read_context*>(this),
4615                                                die);
4616
4617     size_t die_offset = dwarf_dieoffset(const_cast<Dwarf_Die*>(die));
4618     die_istring_map_type::const_iterator i = map.find(die_offset);
4619
4620     if (i == map.end())
4621       {
4622         read_context& ctxt = *const_cast<read_context*>(this);
4623         string pretty_representation =
4624           die_pretty_print_type(ctxt, die, where_offset);
4625         interned_string istr = env()->intern(pretty_representation);
4626         map[die_offset] = istr;
4627         return istr;
4628       }
4629
4630     return i->second;
4631   }
4632
4633   /// Get the pretty representation of a DIE.
4634   ///
4635   /// Once the pretty representation is computed, it's stored in a
4636   /// cache.  Subsequent invocations of this function on the same DIE
4637   /// will yield the cached name.
4638   ///
4639   /// @param die the DIE to consider.
4640   ///
4641   /// @param where_offset where in the DIE stream we logically are.
4642   ///
4643   /// @return the interned_string that represents the pretty
4644   /// representation.
4645   interned_string
4646   get_die_pretty_representation(const Dwarf_Die *die, size_t where_offset) const
4647   {
4648     ABG_ASSERT(die);
4649
4650     die_istring_map_type& map =
4651       die_pretty_repr_maps_.get_container(*const_cast<read_context*>(this),
4652                                           die);
4653
4654     size_t die_offset = dwarf_dieoffset(const_cast<Dwarf_Die*>(die));
4655     die_istring_map_type::const_iterator i = map.find(die_offset);
4656
4657     if (i == map.end())
4658       {
4659         read_context& ctxt = *const_cast<read_context*>(this);
4660         string pretty_representation =
4661           die_pretty_print(ctxt, die, where_offset);
4662         interned_string istr = env()->intern(pretty_representation);
4663         map[die_offset] = istr;
4664         return istr;
4665       }
4666
4667     return i->second;
4668   }
4669
4670   /// Lookup the artifact that was built to represent a type that has
4671   /// the same pretty representation as the type denoted by a given
4672   /// DIE.
4673   ///
4674   /// Note that the DIE must have previously been associated with the
4675   /// artifact using the functions associate_die_to_decl or
4676   /// associate_die_to_type.
4677   ///
4678   /// Also, note that the scope of the lookup is the current ABI
4679   /// corpus.
4680   ///
4681   /// @param die the DIE to consider.
4682   ///
4683   /// @param where_offset where in the DIE stream we logically are.
4684   ///
4685   /// @return the type artifact found.
4686   type_or_decl_base_sptr
4687   lookup_type_artifact_from_die(Dwarf_Die *die) const
4688   {
4689     type_or_decl_base_sptr artifact =
4690       lookup_artifact_from_die(die, /*type_as_die=*/true);
4691     if (function_decl_sptr fn = is_function_decl(artifact))
4692       return fn->get_type();
4693     return artifact;
4694   }
4695
4696   /// Lookup the artifact that was built to represent a type or a
4697   /// declaration that has the same pretty representation as the type
4698   /// denoted by a given DIE.
4699   ///
4700   /// Note that the DIE must have previously been associated with the
4701   /// artifact using the functions associate_die_to_decl or
4702   /// associate_die_to_type.
4703   ///
4704   /// Also, note that the scope of the lookup is the current ABI
4705   /// corpus.
4706   ///
4707   /// @param die the DIE to consider.
4708   ///
4709   /// @param where_offset where in the DIE stream we logically are.
4710   ///
4711   /// @param die_as_type if true, it means the DIE is to be considered
4712   /// as a type.
4713   ///
4714   /// @return the artifact found.
4715   type_or_decl_base_sptr
4716   lookup_artifact_from_die(const Dwarf_Die *die, bool die_as_type = false) const
4717   {
4718     Dwarf_Die equiv_die;
4719     if (!get_or_compute_canonical_die(die, equiv_die, /*where=*/0, die_as_type))
4720       return type_or_decl_base_sptr();
4721
4722     const die_artefact_map_type& m =
4723       die_as_type
4724       ? type_die_artefact_maps().get_container(*this, &equiv_die)
4725       : decl_die_artefact_maps().get_container(*this, &equiv_die);
4726
4727     size_t die_offset = dwarf_dieoffset(&equiv_die);
4728     die_artefact_map_type::const_iterator i = m.find(die_offset);
4729
4730     if (i == m.end())
4731       return type_or_decl_base_sptr();
4732     return i->second;
4733   }
4734
4735   /// Lookup the artifact that was built to represent a type or a
4736   /// declaration that has the same pretty representation as the type
4737   /// denoted by the offset of a given DIE.
4738   ///
4739   /// Note that the DIE must have previously been associated with the
4740   /// artifact using either associate_die_to_decl or
4741   /// associate_die_to_type.
4742   ///
4743   /// Also, note that the scope of the lookup is the current ABI
4744   /// corpus.
4745   ///
4746   /// @param die the DIE to consider.
4747   ///
4748   /// @param where_offset where in the DIE stream we logically are.
4749   ///
4750   /// @param die_as_type if true, it means the DIE is to be considered
4751   /// as a type.
4752   ///
4753   /// @return the artifact found.
4754   type_or_decl_base_sptr
4755   lookup_artifact_from_die_offset(Dwarf_Off die_offset,
4756                                   die_source source,
4757                                   bool die_as_type = false) const
4758   {
4759     const die_artefact_map_type& m =
4760       die_as_type
4761       ? type_die_artefact_maps().get_container(source)
4762       : decl_die_artefact_maps().get_container(source);
4763
4764     die_artefact_map_type::const_iterator i = m.find(die_offset);
4765     if (i == m.end())
4766       return type_or_decl_base_sptr();
4767     return i->second;
4768   }
4769
4770   /// Get the language used to generate a given DIE.
4771   ///
4772   /// @param die the DIE to consider.
4773   ///
4774   /// @param lang the resulting language.
4775   ///
4776   /// @return true iff the language of the DIE was found.
4777   bool
4778   get_die_language(const Dwarf_Die *die, translation_unit::language &lang) const
4779   {
4780     Dwarf_Die cu_die;
4781     ABG_ASSERT(dwarf_diecu(const_cast<Dwarf_Die*>(die), &cu_die, 0, 0));
4782
4783     uint64_t l = 0;
4784     if (!die_unsigned_constant_attribute(&cu_die, DW_AT_language, l))
4785       return false;
4786
4787     lang = dwarf_language_to_tu_language(l);
4788     return true;
4789   }
4790
4791   /// Test if a given DIE originates from a program written in the C
4792   /// language.
4793   ///
4794   /// @param die the DIE to consider.
4795   ///
4796   /// @return true iff @p die originates from a program in the C
4797   /// language.
4798   bool
4799   die_is_in_c(const Dwarf_Die *die) const
4800   {
4801     translation_unit::language l = translation_unit::LANG_UNKNOWN;
4802     if (!get_die_language(die, l))
4803       return false;
4804     return is_c_language(l);
4805   }
4806
4807   /// Test if a given DIE originates from a program written in the C++
4808   /// language.
4809   ///
4810   /// @param die the DIE to consider.
4811   ///
4812   /// @return true iff @p die originates from a program in the C++
4813   /// language.
4814   bool
4815   die_is_in_cplus_plus(const Dwarf_Die *die) const
4816   {
4817     translation_unit::language l = translation_unit::LANG_UNKNOWN;
4818     if (!get_die_language(die, l))
4819       return false;
4820     return is_cplus_plus_language(l);
4821   }
4822
4823   /// Test if a given DIE originates from a program written either in
4824   /// C or C++.
4825   ///
4826   /// @param die the DIE to consider.
4827   ///
4828   /// @return true iff @p die originates from a program written either in
4829   /// C or C++.
4830   bool
4831   die_is_in_c_or_cplusplus(const Dwarf_Die *die) const
4832   {
4833     translation_unit::language l = translation_unit::LANG_UNKNOWN;
4834     if (!get_die_language(die, l))
4835       return false;
4836     return (is_cplus_plus_language(l) || is_c_language(l));
4837   }
4838
4839   /// Check if we can assume the One Definition Rule[1] to be relevant
4840   /// for the current translation unit.
4841   ///
4842   /// [1]: https://en.wikipedia.org/wiki/One_Definition_Rule
4843   ///
4844   /// At the moment this returns true if the current translation unit
4845   /// is in C++ language.  In that case, it's relevant to assume that
4846   /// we use optimizations based on the ODR.
4847   bool
4848   odr_is_relevant() const
4849   {return odr_is_relevant(cur_transl_unit()->get_language());}
4850
4851   /// Check if we can assume the One Definition Rule[1] to be relevant
4852   /// for a given language.
4853   ///
4854   /// [1]: https://en.wikipedia.org/wiki/One_Definition_Rule
4855   ///
4856   /// At the moment this returns true if the language considered
4857   /// is C++, Java or Ada.
4858   bool
4859   odr_is_relevant(translation_unit::language l) const
4860   {
4861     return (is_cplus_plus_language(l)
4862             || is_java_language(l)
4863             || is_ada_language(l));
4864   }
4865
4866   /// Check if we can assume the One Definition Rule to be relevant
4867   /// for a given DIE.
4868   ///
4869   /// @param die the DIE to consider.
4870   ///
4871   /// @return true if the ODR is relevant for @p die.
4872   bool
4873   odr_is_relevant(Dwarf_Off die_offset, die_source source) const
4874   {
4875     Dwarf_Die die;
4876     ABG_ASSERT(dwarf_offdie(dwarf_per_die_source(source), die_offset, &die));
4877     return odr_is_relevant(&die);
4878   }
4879
4880   /// Check if we can assume the One Definition Rule to be relevant
4881   /// for a given DIE.
4882   ///
4883   /// @param die the DIE to consider.
4884   ///
4885   /// @return true if the ODR is relevant for @p die.
4886   bool
4887   odr_is_relevant(const Dwarf_Die *die) const
4888   {
4889     translation_unit::language lang;
4890     if (!get_die_language(die, lang))
4891       return odr_is_relevant();
4892
4893     return odr_is_relevant(lang);
4894   }
4895
4896   /// Getter for the maps set that associates a decl DIE offset to an
4897   /// artifact.
4898   ///
4899   /// @return the maps set that associates a decl DIE offset to an
4900   /// artifact.
4901   die_source_dependant_container_set<die_artefact_map_type>&
4902   decl_die_artefact_maps()
4903   {return decl_die_artefact_maps_;}
4904
4905   /// Getter for the maps set that associates a decl DIE offset to an
4906   /// artifact.
4907   ///
4908   /// @return the maps set that associates a decl DIE offset to an
4909   /// artifact.
4910   const die_source_dependant_container_set<die_artefact_map_type>&
4911   decl_die_artefact_maps() const
4912   {return decl_die_artefact_maps_;}
4913
4914   /// Getter for the maps set that associates a type DIE offset to an
4915   /// artifact.
4916   ///
4917   /// @return the maps set that associates a type DIE offset to an
4918   /// artifact.
4919   die_source_dependant_container_set<die_artefact_map_type>&
4920   type_die_artefact_maps()
4921   {return type_die_artefact_maps_;}
4922
4923   /// Getter for the maps set that associates a type DIE offset to an
4924   /// artifact.
4925   ///
4926   /// @return the maps set that associates a type DIE offset to an
4927   /// artifact.
4928   const die_source_dependant_container_set<die_artefact_map_type>&
4929   type_die_artefact_maps() const
4930   {return type_die_artefact_maps_;}
4931
4932   /// Getter of the maps that associates function type representations
4933   /// to function types, inside a translation unit.
4934   ///
4935   /// @return the maps that associates function type representations
4936   /// to function types, inside a translation unit.
4937   istring_fn_type_map_type&
4938   per_tu_repr_to_fn_type_maps()
4939   {return per_tu_repr_to_fn_type_maps_;}
4940
4941   /// Getter of the maps that associates function type representations
4942   /// to function types, inside a translation unit.
4943   ///
4944   /// @return the maps that associates function type representations
4945   /// to function types, inside a translation unit.
4946   const istring_fn_type_map_type&
4947   per_tu_repr_to_fn_type_maps() const
4948   {return per_tu_repr_to_fn_type_maps_;}
4949
4950   /// Associate the representation of a function type DIE to a given
4951   /// function type, inside the current translation unit.
4952   ///
4953   /// @param die the DIE to associate to the function type, using its
4954   /// representation.
4955   ///
4956   /// @param fn_type the function type to associate to @p die.
4957   void
4958   associate_die_repr_to_fn_type_per_tu(const Dwarf_Die *die,
4959                                        const function_type_sptr &fn_type)
4960   {
4961     if (!die_is_function_type(die))
4962       return;
4963
4964     interned_string repr =
4965       get_die_pretty_type_representation(die, /*where=*/0);
4966     ABG_ASSERT(!repr.empty());
4967
4968     per_tu_repr_to_fn_type_maps()[repr]= fn_type;
4969   }
4970
4971   /// Lookup the function type associated to a given function type
4972   /// DIE, in the current translation unit.
4973   ///
4974   /// @param die the DIE of function type to consider.
4975   ///
4976   /// @return the @ref function_type_sptr associated to @p die, or nil
4977   /// of no function_type is associated to @p die.
4978   function_type_sptr
4979   lookup_fn_type_from_die_repr_per_tu(const Dwarf_Die *die)
4980   {
4981     if (!die_is_function_type(die))
4982       return function_type_sptr();
4983
4984     interned_string repr =
4985       get_die_pretty_representation(die, /*where=*/0);
4986     ABG_ASSERT(!repr.empty());
4987
4988     istring_fn_type_map_type::const_iterator i =
4989       per_tu_repr_to_fn_type_maps().find(repr);
4990
4991     if (i == per_tu_repr_to_fn_type_maps().end())
4992       return function_type_sptr();
4993
4994     return i->second;
4995   }
4996
4997   /// Set the canonical DIE offset of a given DIE.
4998   ///
4999   /// @param canonical_dies the vector that holds canonical DIEs.
5000   ///
5001   /// @param die_offset the offset of the DIE to set the canonical DIE
5002   /// for.
5003   ///
5004   /// @param canonical_die_offset the canonical DIE offset to
5005   /// associate to @p die_offset.
5006   void
5007   set_canonical_die_offset(offset_offset_map_type &canonical_dies,
5008                            Dwarf_Off die_offset,
5009                            Dwarf_Off canonical_die_offset) const
5010   {
5011     canonical_dies[die_offset] = canonical_die_offset;}
5012
5013   /// Set the canonical DIE offset of a given DIE.
5014   ///
5015   ///
5016   /// @param die_offset the offset of the DIE to set the canonical DIE
5017   /// for.
5018   ///
5019   /// @param source the source of the DIE denoted by @p die_offset.
5020   ///
5021   /// @param canonical_die_offset the canonical DIE offset to
5022   /// associate to @p die_offset.
5023   ///
5024   /// @param die_as_type if true, it means that @p die_offset has to
5025   /// be considered as a type.
5026   void
5027   set_canonical_die_offset(Dwarf_Off die_offset,
5028                            die_source source,
5029                            Dwarf_Off canonical_die_offset,
5030                            bool die_as_type) const
5031   {
5032     offset_offset_map_type &canonical_dies =
5033       die_as_type
5034       ? const_cast<read_context*>(this)->canonical_type_die_offsets_.
5035       get_container(source)
5036       : const_cast<read_context*>(this)->canonical_decl_die_offsets_.
5037       get_container(source);
5038
5039     set_canonical_die_offset(canonical_dies,
5040                              die_offset,
5041                              canonical_die_offset);
5042   }
5043
5044   /// Set the canonical DIE offset of a given DIE.
5045   ///
5046   ///
5047   /// @param die the DIE to set the canonical DIE for.
5048   ///
5049   /// @param canonical_die_offset the canonical DIE offset to
5050   /// associate to @p die_offset.
5051   ///
5052   /// @param die_as_type if true, it means that @p die has to be
5053   /// considered as a type.
5054   void
5055   set_canonical_die_offset(const Dwarf_Die *die,
5056                            Dwarf_Off canonical_die_offset,
5057                            bool die_as_type) const
5058   {
5059     die_source source;
5060     ABG_ASSERT(get_die_source(die, source));
5061
5062     Dwarf_Off die_offset = dwarf_dieoffset(const_cast<Dwarf_Die*>(die));
5063
5064     set_canonical_die_offset(die_offset, source,
5065                              canonical_die_offset,
5066                              die_as_type);
5067   }
5068
5069   /// Get the canonical DIE offset of a given DIE.
5070   ///
5071   /// @param canonical_dies the vector that contains canonical DIES.
5072   ///
5073   /// @param die_offset the offset of the DIE to consider.
5074   ///
5075   /// @return the canonical of the DIE denoted by @p die_offset, or
5076   /// zero if no canonical DIE was found.
5077   Dwarf_Off
5078   get_canonical_die_offset(offset_offset_map_type &canonical_dies,
5079                            Dwarf_Off die_offset) const
5080   {
5081     offset_offset_map_type::const_iterator it = canonical_dies.find(die_offset);
5082     if (it == canonical_dies.end())
5083       return 0;
5084     return it->second;
5085   }
5086
5087   /// Get the canonical DIE offset of a given DIE.
5088   ///
5089   /// @param die_offset the offset of the DIE to consider.
5090   ///
5091   /// @param source the source of the DIE denoted by @p die_offset.
5092   ///
5093   /// @param die_as_type if true, it means that @p is to be considered
5094   /// as a type DIE.
5095   ///
5096   /// @return the canonical of the DIE denoted by @p die_offset, or
5097   /// zero if no canonical DIE was found.
5098   Dwarf_Off
5099   get_canonical_die_offset(Dwarf_Off die_offset,
5100                            die_source source,
5101                            bool die_as_type) const
5102   {
5103     offset_offset_map_type &canonical_dies =
5104       die_as_type
5105       ? const_cast<read_context*>(this)->canonical_type_die_offsets_.
5106       get_container(source)
5107       : const_cast<read_context*>(this)->canonical_decl_die_offsets_.
5108       get_container(source);
5109
5110     return get_canonical_die_offset(canonical_dies, die_offset);
5111   }
5112
5113   /// Associate a DIE (representing a type) to the type that it
5114   /// represents.
5115   ///
5116   /// @param die the DIE to consider.
5117   ///
5118   /// @param type the type to associate the DIE to.
5119   ///
5120   /// @param where_offset where in the DIE stream we logically are.
5121   void
5122   associate_die_to_type(const Dwarf_Die *die,
5123                         type_base_sptr  type,
5124                         size_t          where)
5125   {
5126     if (!type)
5127       return;
5128
5129     Dwarf_Die equiv_die;
5130     get_or_compute_canonical_die(die, equiv_die, where, /*die_as_type=*/true);
5131
5132     die_artefact_map_type& m =
5133       type_die_artefact_maps().get_container(*this, &equiv_die);
5134
5135     size_t die_offset = dwarf_dieoffset(&equiv_die);
5136     m[die_offset] = type;
5137   }
5138
5139   /// Lookup the type associated to a given DIE.
5140   ///
5141   /// Note that the DIE must have been associated to type by a
5142   /// previous invocation of the function
5143   /// read_context::associate_die_to_type().
5144   ///
5145   /// @param die the DIE to consider.
5146   ///
5147   /// @return the type associated to the DIE or NULL if no type is
5148   /// associated to the DIE.
5149   type_base_sptr
5150   lookup_type_from_die(const Dwarf_Die* die) const
5151   {
5152     type_or_decl_base_sptr artifact =
5153       lookup_artifact_from_die(die, /*die_as_type=*/true);
5154     if (function_decl_sptr fn = is_function_decl(artifact))
5155       return fn->get_type();
5156     return is_type(artifact);
5157   }
5158
5159   /// Lookup the type associated to a DIE at a given offset, from a
5160   /// given source.
5161   ///
5162   /// Note that the DIE must have been associated to type by a
5163   /// previous invocation of the function
5164   /// read_context::associate_die_to_type().
5165   ///
5166   /// @param die_offset the offset of the DIE to consider.
5167   ///
5168   /// @param source the source of the DIE to consider.
5169   ///
5170   /// @return the type associated to the DIE or NULL if no type is
5171   /// associated to the DIE.
5172   type_base_sptr
5173   lookup_type_from_die_offset(size_t die_offset, die_source source) const
5174   {
5175     type_base_sptr result;
5176     const die_artefact_map_type& m =
5177       type_die_artefact_maps().get_container(source);
5178     die_artefact_map_type::const_iterator i = m.find(die_offset);
5179     if (i != m.end())
5180       {
5181         if (function_decl_sptr fn = is_function_decl(i->second))
5182           return fn->get_type();
5183         result = is_type(i->second);
5184       }
5185
5186     if (!result)
5187       {
5188         // Maybe we are looking for a class type being constructed?
5189         const die_class_or_union_map_type& m = die_wip_classes_map(source);
5190         die_class_or_union_map_type::const_iterator i = m.find(die_offset);
5191
5192         if (i != m.end())
5193           result = i->second;
5194       }
5195
5196     if (!result)
5197       {
5198         // Maybe we are looking for a function type being constructed?
5199         const die_function_type_map_type& m =
5200           die_wip_function_types_map(source);
5201         die_function_type_map_type::const_iterator i = m.find(die_offset);
5202
5203         if (i != m.end())
5204           result = i->second;
5205       }
5206
5207     return result;
5208   }
5209
5210   /// Getter of a map that associates a die that represents a
5211   /// class/struct with the declaration of the class, while the class
5212   /// is being constructed.
5213   ///
5214   /// @param source where the DIE is from.
5215   ///
5216   /// @return the map that associates a DIE to the class that is being
5217   /// built.
5218   const die_class_or_union_map_type&
5219   die_wip_classes_map(die_source source) const
5220   {return const_cast<read_context*>(this)->die_wip_classes_map(source);}
5221
5222   /// Getter of a map that associates a die that represents a
5223   /// class/struct with the declaration of the class, while the class
5224   /// is being constructed.
5225   ///
5226   /// @param source where the DIE comes from.
5227   ///
5228   /// @return the map that associates a DIE to the class that is being
5229   /// built.
5230   die_class_or_union_map_type&
5231   die_wip_classes_map(die_source source)
5232   {
5233     switch (source)
5234       {
5235       case PRIMARY_DEBUG_INFO_DIE_SOURCE:
5236         break;
5237       case ALT_DEBUG_INFO_DIE_SOURCE:
5238         return alternate_die_wip_classes_map_;
5239       case TYPE_UNIT_DIE_SOURCE:
5240         return type_unit_die_wip_classes_map_;
5241       case NO_DEBUG_INFO_DIE_SOURCE:
5242       case NUMBER_OF_DIE_SOURCES:
5243         ABG_ASSERT_NOT_REACHED;
5244       }
5245     return die_wip_classes_map_;
5246   }
5247
5248   /// Getter for a map that associates a die (that represents a
5249   /// function type) whith a function type, while the function type is
5250   /// being constructed (WIP == work in progress).
5251   ///
5252   /// @param source where the DIE comes from.n
5253   ///
5254   /// @return the map of wip function types.
5255   const die_function_type_map_type&
5256   die_wip_function_types_map(die_source source) const
5257   {return const_cast<read_context*>(this)->die_wip_function_types_map(source);}
5258
5259   /// Getter for a map that associates a die (that represents a
5260   /// function type) whith a function type, while the function type is
5261   /// being constructed (WIP == work in progress).
5262   ///
5263   /// @param source where DIEs of the map come from.
5264   ///
5265   /// @return the map of wip function types.
5266   die_function_type_map_type&
5267   die_wip_function_types_map(die_source source)
5268   {
5269     switch (source)
5270       {
5271       case PRIMARY_DEBUG_INFO_DIE_SOURCE:
5272         break;
5273       case ALT_DEBUG_INFO_DIE_SOURCE:
5274         return alternate_die_wip_function_types_map_;
5275       case TYPE_UNIT_DIE_SOURCE:
5276         return type_unit_die_wip_function_types_map_;
5277       case NO_DEBUG_INFO_DIE_SOURCE:
5278       case NUMBER_OF_DIE_SOURCES:
5279         ABG_ASSERT_NOT_REACHED;
5280       }
5281     return die_wip_function_types_map_;
5282   }
5283
5284   /// Getter for a map that associates a die with a function decl
5285   /// which has a linkage name but no elf symbol yet.
5286   ///
5287   /// This is to fixup function decls with linkage names, but with no
5288   /// link to their underlying elf symbol.  There are some DIEs like
5289   /// that in DWARF sometimes, especially when the compiler optimizes
5290   /// stuff aggressively.
5291   die_function_decl_map_type&
5292   die_function_decl_with_no_symbol_map()
5293   {return die_function_with_no_symbol_map_;}
5294
5295   /// Return true iff a given offset is for the DIE of a class that is
5296   /// being built, but that is not fully built yet.  WIP == "work in
5297   /// progress".
5298   ///
5299   /// @param offset the DIE offset to consider.
5300   ///
5301   /// @param source where the DIE of the map come from.
5302   ///
5303   /// @return true iff @p offset is the offset of the DIE of a class
5304   /// that is being currently built.
5305   bool
5306   is_wip_class_die_offset(Dwarf_Off offset, die_source source) const
5307   {
5308     die_class_or_union_map_type::const_iterator i =
5309       die_wip_classes_map(source).find(offset);
5310     return (i != die_wip_classes_map(source).end());
5311   }
5312
5313   /// Return true iff a given offset is for the DIE of a function type
5314   /// that is being built at the moment, but is not fully built yet.
5315   /// WIP == work in progress.
5316   ///
5317   /// @param offset DIE offset to consider.
5318   ///
5319   /// @param source where the DIE comes from.
5320   ///
5321   /// @return true iff @p offset is the offset of the DIE of a
5322   /// function type that is being currently built.
5323   bool
5324   is_wip_function_type_die_offset(Dwarf_Off offset, die_source source) const
5325   {
5326     die_function_type_map_type::const_iterator i =
5327       die_wip_function_types_map(source).find(offset);
5328     return (i != die_wip_function_types_map(source).end());
5329   }
5330
5331   /// Getter for the map of declaration-only classes that are to be
5332   /// resolved to their definition classes by the end of the corpus
5333   /// loading.
5334   ///
5335   /// @return a map of string -> vector of classes where the key is
5336   /// the fully qualified name of the class and the value is the
5337   /// vector of declaration-only class.
5338   const string_classes_map&
5339   declaration_only_classes() const
5340   {return decl_only_classes_map_;}
5341
5342   /// Getter for the map of declaration-only classes that are to be
5343   /// resolved to their definition classes by the end of the corpus
5344   /// loading.
5345   ///
5346   /// @return a map of string -> vector of classes where the key is
5347   /// the fully qualified name of the class and the value is the
5348   /// vector of declaration-only class.
5349   string_classes_map&
5350   declaration_only_classes()
5351   {return decl_only_classes_map_;}
5352
5353   /// If a given class is a declaration-only class then stash it on
5354   /// the side so that at the end of the corpus reading we can resolve
5355   /// it to its definition.
5356   ///
5357   /// @param klass the class to consider.
5358   void
5359   maybe_schedule_declaration_only_class_for_resolution(class_decl_sptr& klass)
5360   {
5361     if (klass->get_is_declaration_only()
5362         && klass->get_definition_of_declaration() == 0)
5363       {
5364         string qn = klass->get_qualified_name();
5365         string_classes_map::iterator record =
5366           declaration_only_classes().find(qn);
5367         if (record == declaration_only_classes().end())
5368           declaration_only_classes()[qn].push_back(klass);
5369         else
5370           record->second.push_back(klass);
5371       }
5372   }
5373
5374   /// Test if a given declaration-only class has been scheduled for
5375   /// resolution to a defined class.
5376   ///
5377   /// @param klass the class to consider for the test.
5378   ///
5379   /// @return true iff @p klass is a declaration-only class and if
5380   /// it's been scheduled for resolution to a defined class.
5381   bool
5382   is_decl_only_class_scheduled_for_resolution(class_decl_sptr& klass)
5383   {
5384     if (klass->get_is_declaration_only())
5385       return (declaration_only_classes().find(klass->get_qualified_name())
5386               != declaration_only_classes().end());
5387
5388     return false;
5389   }
5390
5391   /// Walk the declaration-only classes that have been found during
5392   /// the building of the corpus and resolve them to their definitions.
5393   void
5394   resolve_declaration_only_classes()
5395   {
5396     vector<string> resolved_classes;
5397
5398     for (string_classes_map::iterator i =
5399            declaration_only_classes().begin();
5400          i != declaration_only_classes().end();
5401          ++i)
5402       {
5403         bool to_resolve = false;
5404         for (classes_type::iterator j = i->second.begin();
5405              j != i->second.end();
5406              ++j)
5407           if ((*j)->get_is_declaration_only()
5408               && ((*j)->get_definition_of_declaration() == 0))
5409             to_resolve = true;
5410
5411         if (!to_resolve)
5412           {
5413             resolved_classes.push_back(i->first);
5414             continue;
5415           }
5416
5417         // Now, for each decl-only class that have the current name
5418         // 'i->first', let's try to poke at the fully defined class
5419         // that is defined in the same translation unit as the
5420         // declaration.
5421         //
5422         // If we find one class (defined in the TU of the declaration)
5423         // that defines the declaration, then the declaration can be
5424         // resolved to that class.
5425         //
5426         // If no defining class is found in the TU of the declaration,
5427         // then there are possibly three cases to consider:
5428         //
5429         //   1/ There is exactly one class that defines the
5430         //   declaration and that class is defined in another TU.  In
5431         //   this case, the declaration is resolved to that
5432         //   definition.
5433         //
5434         //   2/ There are more than one class that define that
5435         //   declaration and none of them is defined in the TU of the
5436         //   declaration.  In this case, the declaration is left
5437         //   unresolved.
5438         //
5439         //   3/ No class defines the declaration.  In this case, the
5440         //   declaration is left unresoved.
5441
5442         // So get the classes that might define the current
5443         // declarations which name is i->first.
5444         const type_base_wptrs_type *classes =
5445           lookup_class_types(i->first, *current_corpus());
5446         if (!classes)
5447           continue;
5448
5449         unordered_map<string, class_decl_sptr> per_tu_class_map;
5450         for (type_base_wptrs_type::const_iterator c = classes->begin();
5451              c != classes->end();
5452              ++c)
5453           {
5454             class_decl_sptr klass = is_class_type(type_base_sptr(*c));
5455             ABG_ASSERT(klass);
5456
5457             klass = is_class_type(look_through_decl_only_class(klass));
5458             if (klass->get_is_declaration_only())
5459               continue;
5460
5461             string tu_path = klass->get_translation_unit()->get_absolute_path();
5462             if (tu_path.empty())
5463               continue;
5464
5465             // Build a map that associates the translation unit path
5466             // to the class (that potentially defines the declarations
5467             // that we consider) that are defined in that translation unit.
5468             per_tu_class_map[tu_path] = klass;
5469           }
5470
5471         if (!per_tu_class_map.empty())
5472           {
5473             // Walk the declarations to resolve and resolve them
5474             // either to the definitions that are in the same TU as
5475             // the declaration, or to the definition found elsewhere,
5476             // if there is only one such definition.
5477             for (classes_type::iterator j = i->second.begin();
5478                  j != i->second.end();
5479                  ++j)
5480               {
5481                 if ((*j)->get_is_declaration_only()
5482                     && ((*j)->get_definition_of_declaration() == 0))
5483                   {
5484                     string tu_path =
5485                       (*j)->get_translation_unit()->get_absolute_path();
5486                     unordered_map<string, class_decl_sptr>::const_iterator e =
5487                       per_tu_class_map.find(tu_path);
5488                     if (e != per_tu_class_map.end())
5489                       (*j)->set_definition_of_declaration(e->second);
5490                     else if (per_tu_class_map.size() == 1)
5491                       (*j)->set_definition_of_declaration
5492                         (per_tu_class_map.begin()->second);
5493                   }
5494               }
5495             resolved_classes.push_back(i->first);
5496           }
5497       }
5498
5499     size_t num_decl_only_classes = declaration_only_classes().size(),
5500       num_resolved = resolved_classes.size();
5501     if (show_stats())
5502       cerr << "resolved " << num_resolved
5503            << " class declarations out of "
5504            << num_decl_only_classes
5505            << "\n";
5506
5507     for (vector<string>::const_iterator i = resolved_classes.begin();
5508          i != resolved_classes.end();
5509          ++i)
5510       declaration_only_classes().erase(*i);
5511
5512     for (string_classes_map::iterator i = declaration_only_classes().begin();
5513          i != declaration_only_classes().end();
5514          ++i)
5515       {
5516         if (show_stats())
5517           {
5518             if (i == declaration_only_classes().begin())
5519               cerr << "Here are the "
5520                    << num_decl_only_classes - num_resolved
5521                    << " unresolved class declarations:\n";
5522             else
5523               cerr << "    " << i->first << "\n";
5524           }
5525       }
5526   }
5527
5528   /// Some functions described by DWARF may have their linkage name
5529   /// set, but no link to their actual underlying elf symbol.  When
5530   /// these are virtual member functions, comparing the enclosing type
5531   /// against another one which has its underlying symbol properly set
5532   /// might lead to spurious type changes.
5533   ///
5534   /// If the corpus contains a symbol with the same name as the
5535   /// linkage name of the function, then set up the link between the
5536   /// function and its underlying symbol.
5537   ///
5538   /// Note that for the moment, only virtual member functions are
5539   /// fixed up like this.  This is because they really are the only
5540   /// fuctions of functions that can affect types (in spurious ways).
5541   void
5542   fixup_functions_with_no_symbols()
5543   {
5544     corpus_sptr corp = current_corpus();
5545     if (!corp)
5546       return;
5547
5548     die_function_decl_map_type &fns_with_no_symbol =
5549       die_function_decl_with_no_symbol_map();
5550
5551     if (do_log())
5552       cerr << fns_with_no_symbol.size()
5553            << " functions to fixup, potentially\n";
5554
5555     for (die_function_decl_map_type::iterator i = fns_with_no_symbol.begin();
5556          i != fns_with_no_symbol.end();
5557          ++i)
5558       if (elf_symbol_sptr sym =
5559           corp->lookup_function_symbol(i->second->get_linkage_name()))
5560         {
5561           ABG_ASSERT(is_member_function(i->second));
5562           ABG_ASSERT(get_member_function_is_virtual(i->second));
5563           i->second->set_symbol(sym);
5564           if (do_log())
5565             cerr << "fixed up '"
5566                  << i->second->get_pretty_representation()
5567                  << "' with symbol '"
5568                  << sym->get_id_string()
5569                  << "'\n";
5570         }
5571
5572     fns_with_no_symbol.clear();
5573   }
5574
5575   /// Return a reference to the vector containing the offsets of the
5576   /// types that need late canonicalizing.
5577   ///
5578   /// @param source whe DIEs referred to by the offsets contained in
5579   /// the vector to return are from.
5580   vector<Dwarf_Off>&
5581   types_to_canonicalize(die_source source)
5582   {
5583     switch (source)
5584       {
5585       case PRIMARY_DEBUG_INFO_DIE_SOURCE:
5586         break;
5587       case ALT_DEBUG_INFO_DIE_SOURCE:
5588         return alt_types_to_canonicalize_;
5589       case TYPE_UNIT_DIE_SOURCE:
5590         return type_unit_types_to_canonicalize_;
5591       case NO_DEBUG_INFO_DIE_SOURCE:
5592       case NUMBER_OF_DIE_SOURCES:
5593         ABG_ASSERT_NOT_REACHED;
5594       }
5595     return types_to_canonicalize_;
5596   }
5597
5598   /// Return a reference to the vector containing the offsets of the
5599   /// types that need late canonicalizing.
5600   ///
5601   /// @param source where the DIEs referred to by the offset in the
5602   /// returned vector are from.
5603   const vector<Dwarf_Off>&
5604   types_to_canonicalize(die_source source) const
5605   {return const_cast<read_context*>(this)->types_to_canonicalize(source);}
5606
5607   /// Return a reference to the vector containing the types created
5608   /// during the binary analysis but that are not tied to a given
5609   /// DWARF DIE.
5610   ///
5611   /// @return reference to the vector containing the types created
5612   /// during the binary analysis but that are not tied to a given
5613   /// DWARF DIE.
5614   const vector<type_base_sptr>&
5615   extra_types_to_canonicalize() const
5616   {return extra_types_to_canonicalize_;}
5617
5618   /// Clear the containers holding types to canonicalize.
5619   void
5620   clear_types_to_canonicalize()
5621   {
5622     types_to_canonicalize_.clear();
5623     alt_types_to_canonicalize_.clear();
5624     type_unit_types_to_canonicalize_.clear();
5625     extra_types_to_canonicalize_.clear();
5626   }
5627
5628   /// Put the offset of a DIE representing a type on a side vector so
5629   /// that when the reading of the debug info of the current
5630   /// translation unit is done, we can get back to the type DIE and
5631   /// from there, to the type it's associated to, and then
5632   /// canonicalize it.  This what we call late canonicalization.
5633   ///
5634   /// @param die the type DIE to schedule for late type
5635   /// canonicalization.
5636   void
5637   schedule_type_for_late_canonicalization(const Dwarf_Die *die)
5638   {
5639     Dwarf_Off o;
5640     die_source source;
5641
5642     Dwarf_Die equiv_die;
5643     ABG_ASSERT(get_canonical_die(die, equiv_die,
5644                                   /*where=*/0,
5645                                  /*die_as_type=*/true));
5646
5647     ABG_ASSERT(get_die_source(&equiv_die, source));
5648     o = dwarf_dieoffset(&equiv_die);
5649
5650     const die_artefact_map_type& m =
5651       type_die_artefact_maps().get_container(*this, die);
5652
5653     die_artefact_map_type::const_iterator i = m.find(o);
5654     ABG_ASSERT(i != m.end());
5655
5656     // Then really do the scheduling.
5657     types_to_canonicalize(source).push_back(o);
5658   }
5659
5660   /// Types that were created but not tied to a particular DIE, must
5661   /// be scheduled for late canonicalization using this method.
5662   ///
5663   /// @param t the type to schedule for late canonicalization.
5664   void
5665   schedule_type_for_late_canonicalization(const type_base_sptr &t)
5666   {
5667     extra_types_to_canonicalize_.push_back(t);
5668   }
5669
5670   /// Canonicalize types which DIE offsets are stored in vectors on
5671   /// the side.  This is a sub-routine of
5672   /// read_context::perform_late_type_canonicalizing().
5673   ///
5674   /// @param source where the DIE of the types to canonicalize are
5675   /// from.
5676   void
5677   canonicalize_types_scheduled(die_source source)
5678   {
5679     tools_utils::timer cn_timer;
5680     if (do_log())
5681       {
5682         cerr << "going to canonicalize types";
5683         corpus_sptr c = current_corpus();
5684         if (c)
5685           cerr << " of corpus " << current_corpus()->get_path();
5686         cerr << " (DIEs source: " << source << ")\n";
5687         cn_timer.start();
5688       }
5689
5690     if (!types_to_canonicalize(source).empty())
5691       {
5692         tools_utils::timer single_type_cn_timer;
5693         size_t total = types_to_canonicalize(source).size();
5694         if (do_log())
5695           cerr << total << " types to canonicalize\n";
5696         for (size_t i = 0; i < total; ++i)
5697           {
5698             Dwarf_Off element = types_to_canonicalize(source)[i];
5699             type_base_sptr t =
5700               lookup_type_from_die_offset(element, source);
5701             ABG_ASSERT(t);
5702             if (do_log())
5703               {
5704                 cerr << "canonicalizing type "
5705                      << get_pretty_representation(t, false)
5706                      << " [" << i + 1 << "/" << total << "]";
5707                 if (corpus_sptr c = current_corpus())
5708                   cerr << "@" << c->get_path();
5709                 cerr << " ...";
5710                 single_type_cn_timer.start();
5711               }
5712             canonicalize(t);
5713             if (do_log())
5714               {
5715                 cerr << " DONE";
5716                 single_type_cn_timer.stop();
5717                 cerr << ":" <<single_type_cn_timer << "\n";
5718               }
5719           }
5720
5721         // Now canonicalize types that were created but not tied to
5722         // any DIE.
5723         if (!extra_types_to_canonicalize().empty())
5724           {
5725             tools_utils::timer single_type_cn_timer;
5726             size_t total = extra_types_to_canonicalize().size();
5727             if (do_log())
5728               cerr << total << " extra types to canonicalize\n";
5729             size_t i = 1;
5730             for (vector<type_base_sptr>::const_iterator it =
5731                    extra_types_to_canonicalize().begin();
5732                  it != extra_types_to_canonicalize().end();
5733                  ++it, ++i)
5734               {
5735                 if (do_log())
5736                   {
5737                     cerr << "canonicalizing extra type "
5738                          << get_pretty_representation(*it, false)
5739                          << " [" << i << "/" << total << "]";
5740                     if (corpus_sptr c = current_corpus())
5741                       cerr << "@" << c->get_path();
5742                     cerr << " ...";
5743                     single_type_cn_timer.start();
5744                   }
5745                 canonicalize(*it);
5746                 if (do_log())
5747                   {
5748                     single_type_cn_timer.stop();
5749                     cerr << "DONE:"
5750                          << single_type_cn_timer
5751                          << "\n";
5752                   }
5753               }
5754           }
5755       }
5756
5757     if (do_log())
5758       {
5759         cn_timer.stop();
5760         cerr << "finished canonicalizing types";
5761         corpus_sptr c = current_corpus();
5762         if (c)
5763           cerr << " of corpus " << current_corpus()->get_path();
5764         cerr << " (DIEs source: "
5765              << source << "):"
5766              << cn_timer
5767              << "\n";
5768       }
5769   }
5770
5771   /// Compute the number of canonicalized and missed types in the late
5772   /// canonicalization phase.
5773   ///
5774   /// @param source where the DIEs of the canonicalized types are
5775   /// from.
5776   ///
5777   /// @param canonicalized the number of types that got canonicalized
5778   /// is added to the value already present in this parameter.
5779   ///
5780   /// @param missed the number of types scheduled for late
5781   /// canonicalization and which couldn't be canonicalized (for a
5782   /// reason) is added to the value already present in this parameter.
5783   void
5784   add_late_canonicalized_types_stats(die_source source,
5785                                      size_t&            canonicalized,
5786                                      size_t&            missed) const
5787   {
5788     for (vector<Dwarf_Off>::const_iterator i =
5789            types_to_canonicalize(source).begin();
5790          i != types_to_canonicalize(source).end();
5791          ++i)
5792       {
5793         type_base_sptr t = lookup_type_from_die_offset(*i, source);
5794         if (t->get_canonical_type())
5795           ++canonicalized;
5796         else
5797           ++missed;
5798       }
5799   }
5800
5801   /// Compute the number of canonicalized and missed types in the late
5802   /// canonicalization phase.
5803   ///
5804   /// @param canonicalized the number of types that got canonicalized
5805   /// is added to the value already present in this parameter.
5806   ///
5807   /// @param missed the number of types scheduled for late
5808   /// canonicalization and which couldn't be canonicalized (for a
5809   /// reason) is added to the value already present in this parameter.
5810   void
5811   add_late_canonicalized_types_stats(size_t& canonicalized,
5812                                      size_t& missed) const
5813   {
5814     for (die_source source = PRIMARY_DEBUG_INFO_DIE_SOURCE;
5815          source < NUMBER_OF_DIE_SOURCES;
5816          ++source)
5817       add_late_canonicalized_types_stats(source, canonicalized, missed);
5818   }
5819
5820   // Look at the types that need to be canonicalized after the
5821   // translation unit has been constructed and canonicalize them.
5822   void
5823   perform_late_type_canonicalizing()
5824   {
5825     for (die_source source = PRIMARY_DEBUG_INFO_DIE_SOURCE;
5826          source < NUMBER_OF_DIE_SOURCES;
5827          ++source)
5828       canonicalize_types_scheduled(source);
5829
5830     if (show_stats())
5831       {
5832         size_t num_canonicalized = 0, num_missed = 0, total = 0;
5833         add_late_canonicalized_types_stats(num_canonicalized,
5834                                            num_missed);
5835         total = num_canonicalized + num_missed;
5836         cerr << "binary: "
5837              << elf_path()
5838              << "\n";
5839         cerr << "    # late canonicalized types: "
5840              << num_canonicalized
5841              << " (" << num_canonicalized * 100 / total << "%)\n"
5842              << "    # missed canonicalization opportunities: "
5843              << num_missed
5844              << " (" << num_missed * 100 / total << "%)\n";
5845       }
5846
5847   }
5848
5849   const die_tu_map_type&
5850   die_tu_map() const
5851   {return die_tu_map_;}
5852
5853   die_tu_map_type&
5854   die_tu_map()
5855   {return die_tu_map_;}
5856
5857   /// Getter for the map that associates a translation unit DIE to the
5858   /// vector of imported unit points that it contains.
5859   ///
5860   /// @param source where the DIEs are from.
5861   ///
5862   /// @return the map.
5863   const tu_die_imported_unit_points_map_type&
5864   tu_die_imported_unit_points_map(die_source source) const
5865   {return const_cast<read_context*>(this)->tu_die_imported_unit_points_map(source);}
5866
5867   /// Getter for the map that associates a translation unit DIE to the
5868   /// vector of imported unit points that it contains.
5869   ///
5870   /// @param source where the DIEs are from.
5871   ///
5872   /// @return the map.
5873   tu_die_imported_unit_points_map_type&
5874   tu_die_imported_unit_points_map(die_source source)
5875   {
5876     switch (source)
5877       {
5878       case PRIMARY_DEBUG_INFO_DIE_SOURCE:
5879         break;
5880       case ALT_DEBUG_INFO_DIE_SOURCE:
5881         return alt_tu_die_imported_unit_points_map_;
5882       case TYPE_UNIT_DIE_SOURCE:
5883         return type_units_tu_die_imported_unit_points_map_;
5884       case NO_DEBUG_INFO_DIE_SOURCE:
5885       case NUMBER_OF_DIE_SOURCES:
5886         // We cannot reach this point.
5887         ABG_ASSERT_NOT_REACHED;
5888       }
5889     return tu_die_imported_unit_points_map_;
5890   }
5891
5892   /// Getter of the current corpus being constructed.
5893   ///
5894   /// @return the current corpus.
5895   const corpus_sptr
5896   current_corpus() const
5897   {return cur_corpus_;}
5898
5899   /// Getter of the current corpus being constructed.
5900   ///
5901   /// @return the current corpus.
5902   corpus_sptr
5903   current_corpus()
5904   {return cur_corpus_;}
5905
5906   /// Setter of the current corpus being constructed.
5907   ///
5908   /// @param c the new corpus.
5909   void
5910   current_corpus(const corpus_sptr& c)
5911   {
5912     if (c)
5913       cur_corpus_ = c;
5914   }
5915
5916   /// Reset the current corpus being constructed.
5917   ///
5918   /// This actually deletes the current corpus being constructed.
5919   void
5920   reset_current_corpus()
5921   {cur_corpus_.reset();}
5922
5923   /// Getter of the current corpus group being constructed.
5924   ///
5925   /// @return current the current corpus being constructed, if any, or
5926   /// nil.
5927   const corpus_group_sptr
5928   current_corpus_group() const
5929   {return cur_corpus_group_;}
5930
5931   /// Getter of the current corpus group being constructed.
5932   ///
5933   /// @return current the current corpus being constructed, if any, or
5934   /// nil.
5935   corpus_group_sptr
5936   current_corpus_group()
5937   {return cur_corpus_group_;}
5938
5939   /// Setter of the current corpus group being constructed.
5940   ///
5941   /// @param g the new corpus group.
5942   void
5943   current_corpus_group(const corpus_group_sptr& g)
5944   {
5945     if (g)
5946       cur_corpus_group_ = g;
5947   }
5948
5949   /// Test if there is a corpus group being built.
5950   ///
5951   /// @return if there is a corpus group being built, false otherwise.
5952   bool
5953   has_corpus_group() const
5954   {return bool(cur_corpus_group_);}
5955
5956   /// Return the main corpus from the current corpus group, if any.
5957   ///
5958   /// @return the main corpus of the current corpus group, if any, nil
5959   /// if no corpus group is being constructed.
5960   corpus_sptr
5961   main_corpus_from_current_group()
5962   {
5963     if (cur_corpus_group_)
5964       return cur_corpus_group_->get_main_corpus();
5965     return corpus_sptr();
5966   }
5967
5968   /// Return the main corpus from the current corpus group, if any.
5969   ///
5970   /// @return the main corpus of the current corpus group, if any, nil
5971   /// if no corpus group is being constructed.
5972   const corpus_sptr
5973   main_corpus_from_current_group() const
5974   {return const_cast<read_context*>(this)->main_corpus_from_current_group();}
5975
5976   /// Test if the current corpus being built is the main corpus of the
5977   /// current corpus group.
5978   ///
5979   /// @return return true iff the current corpus being built is the
5980   /// main corpus of the current corpus group.
5981   bool
5982   current_corpus_is_main_corpus_from_current_group() const
5983   {
5984     corpus_sptr main_corpus = main_corpus_from_current_group();
5985
5986     if (main_corpus && main_corpus.get() == cur_corpus_.get())
5987       return true;
5988
5989     return false;
5990   }
5991
5992   /// Return true if the current corpus is part of a corpus group
5993   /// being built and if it's not the main corpus of the group.
5994   ///
5995   /// For instance, this would return true if we are loading a linux
5996   /// kernel *module* that is part of the current corpus group that is
5997   /// being built.  In this case, it means we should re-use types
5998   /// coming from the "vmlinux" binary that is the main corpus of the
5999   /// group.
6000   ///
6001   /// @return the corpus group the current corpus belongs to, if the
6002   /// current corpus is part of a corpus group being built. Nil otherwise.
6003   corpus_sptr
6004   should_reuse_type_from_corpus_group() const
6005   {
6006     if (has_corpus_group() && is_c_language(cur_transl_unit()->get_language()))
6007       if (corpus_sptr main_corpus = main_corpus_from_current_group())
6008         if (!current_corpus_is_main_corpus_from_current_group())
6009           return current_corpus_group();
6010
6011     return corpus_sptr();
6012   }
6013
6014   /// Get the map that associates each DIE to its parent DIE.  This is
6015   /// for DIEs coming from the main debug info sections.
6016   ///
6017   /// @param source where the DIEs in the map come from.
6018   ///
6019   /// @return the DIE -> parent map.
6020   const offset_offset_map_type&
6021   die_parent_map(die_source source) const
6022   {return const_cast<read_context*>(this)->die_parent_map(source);}
6023
6024   /// Get the map that associates each DIE to its parent DIE.  This is
6025   /// for DIEs coming from the main debug info sections.
6026   ///
6027   /// @param source where the DIEs in the map come from.
6028   ///
6029   /// @return the DIE -> parent map.
6030   offset_offset_map_type&
6031   die_parent_map(die_source source)
6032   {
6033     switch (source)
6034       {
6035       case PRIMARY_DEBUG_INFO_DIE_SOURCE:
6036         break;
6037       case ALT_DEBUG_INFO_DIE_SOURCE:
6038         return alternate_die_parent_map_;
6039       case TYPE_UNIT_DIE_SOURCE:
6040         return type_section_die_parent_map();
6041       case NO_DEBUG_INFO_DIE_SOURCE:
6042       case NUMBER_OF_DIE_SOURCES:
6043         ABG_ASSERT_NOT_REACHED;
6044       }
6045     return primary_die_parent_map_;
6046   }
6047
6048   const offset_offset_map_type&
6049   type_section_die_parent_map() const
6050   {return type_section_die_parent_map_;}
6051
6052   offset_offset_map_type&
6053   type_section_die_parent_map()
6054   {return type_section_die_parent_map_;}
6055
6056   /// Getter of the current translation unit.
6057   ///
6058   /// @return the current translation unit being constructed.
6059   const translation_unit_sptr&
6060   cur_transl_unit() const
6061   {return cur_tu_;}
6062
6063   /// Getter of the current translation unit.
6064   ///
6065   /// @return the current translation unit being constructed.
6066   translation_unit_sptr&
6067   cur_transl_unit()
6068   {return cur_tu_;}
6069
6070   /// Setter of the current translation unit.
6071   ///
6072   /// @param tu the current translation unit being constructed.
6073   void
6074   cur_transl_unit(translation_unit_sptr tu)
6075   {
6076     if (tu)
6077       cur_tu_ = tu;
6078   }
6079
6080   /// Return the global scope of the current translation unit.
6081   ///
6082   /// @return the global scope of the current translation unit.
6083   const scope_decl_sptr&
6084   global_scope() const
6085   {return cur_transl_unit()->get_global_scope();}
6086
6087   /// Return a scope that is nil.
6088   ///
6089   /// @return a scope that is nil.
6090   const scope_decl_sptr&
6091   nil_scope() const
6092   {return nil_scope_;}
6093
6094   const scope_stack_type&
6095   scope_stack() const
6096   {return scope_stack_;}
6097
6098   scope_stack_type&
6099   scope_stack()
6100   {return scope_stack_;}
6101
6102   scope_decl*
6103   current_scope()
6104   {
6105     if (scope_stack().empty())
6106       {
6107         if (cur_transl_unit())
6108           scope_stack().push(cur_transl_unit()->get_global_scope().get());
6109       }
6110     return scope_stack().top();
6111   }
6112
6113   list<var_decl_sptr>&
6114   var_decls_to_re_add_to_tree()
6115   {return var_decls_to_add_;}
6116
6117   /// Return the type of the current elf file.
6118   ///
6119   /// @return the type of the current elf file.
6120   elf_type
6121   get_elf_file_type()
6122   {
6123     return elf_file_type(elf_handle());
6124   }
6125
6126   /// The section containing the symbol table from the current ELF
6127   /// file.
6128   ///
6129   /// Note that after it's first invocation, this function caches the
6130   /// symbol table that it found.  Subsequent invocations just return
6131   /// the cached symbol table section.
6132   ///
6133   /// @return the symbol table section if found
6134   Elf_Scn*
6135   find_symbol_table_section() const
6136   {
6137     if (!symtab_section_)
6138       dwarf_reader::find_symbol_table_section(elf_handle(),
6139                                               const_cast<read_context*>(this)->symtab_section_);
6140     return symtab_section_;
6141   }
6142
6143   /// Return the "Official Procedure descriptors section."  This
6144   /// section is named .opd, and is usually present only on PPC64
6145   /// ELFv1 binaries.
6146   ///
6147   /// @return the .opd section, if found.  Return nil otherwise.
6148   Elf_Scn*
6149   find_opd_section() const
6150   {
6151     if (!opd_section_)
6152       const_cast<read_context*>(this)->opd_section_=
6153         find_section(elf_handle(), ".opd", SHT_PROGBITS);
6154     return opd_section_;
6155   }
6156
6157   /// Return the __ksymtab section of a linux kernel ELF file (either
6158   /// a vmlinux binary or a kernel module).
6159   ///
6160   /// @return the __ksymtab section if found, nil otherwise.
6161   Elf_Scn*
6162   find_ksymtab_section() const
6163   {
6164     if (!ksymtab_section_)
6165       const_cast<read_context*>(this)->ksymtab_section_ =
6166         find_section(elf_handle(), "__ksymtab", SHT_PROGBITS);
6167     return ksymtab_section_;
6168   }
6169
6170   /// Return the .rel{a,}__ksymtab section of a linux kernel ELF file (either
6171   /// a vmlinux binary or a kernel module).
6172   ///
6173   /// @return the .rel{a,}__ksymtab section if found, nil otherwise.
6174   Elf_Scn*
6175   find_ksymtab_reloc_section() const
6176   {
6177     if (!ksymtab_reloc_section_)
6178       {
6179         Elf_Scn *sec = find_section(elf_handle(), ".rela__ksymtab", SHT_RELA);
6180         if (!sec)
6181           sec = find_section(elf_handle(), ".rel__ksymtab", SHT_REL);
6182         const_cast<read_context*>(this)->ksymtab_reloc_section_ = sec;
6183       }
6184     return ksymtab_reloc_section_;
6185   }
6186
6187   /// Return the __ksymtab_gpl section of a linux kernel ELF file
6188   /// (either a vmlinux binary or a kernel module).
6189   ///
6190   /// @return the __ksymtab_gpl section if found, nil otherwise.
6191   Elf_Scn*
6192   find_ksymtab_gpl_section() const
6193   {
6194     if (!ksymtab_gpl_section_)
6195       const_cast<read_context*>(this)->ksymtab_gpl_section_ =
6196         find_section(elf_handle(), "__ksymtab_gpl", SHT_PROGBITS);
6197     return ksymtab_gpl_section_;
6198   }
6199
6200   /// Return the .rel{a,}__ksymtab_gpl section of a linux kernel ELF file
6201   /// (either a vmlinux binary or a kernel module).
6202   ///
6203   /// @return the .rel{a,}__ksymtab_gpl section if found, nil otherwise.
6204   Elf_Scn*
6205   find_ksymtab_gpl_reloc_section() const
6206   {
6207     if (!ksymtab_gpl_reloc_section_)
6208       {
6209         Elf_Scn *sec = find_section(elf_handle(), ".rela__ksymtab_gpl", SHT_RELA);
6210         if (!sec)
6211           sec = find_section(elf_handle(), ".rel__ksymtab_gpl", SHT_REL);
6212         const_cast<read_context*>(this)->ksymtab_gpl_reloc_section_ = sec;
6213       }
6214     return ksymtab_gpl_reloc_section_;
6215   }
6216
6217   /// Return the __ksymtab_strings section of a linux kernel ELF file
6218   /// (either a vmlinux binary or a kernel module).
6219   ///
6220   /// @return the __ksymtab_strings section if found, nil otherwise.
6221   Elf_Scn*
6222   find_ksymtab_strings_section() const
6223   {
6224     if (!ksymtab_strings_section_)
6225       const_cast<read_context*>(this)->ksymtab_strings_section_ =
6226         dwarf_reader::find_ksymtab_strings_section(elf_handle());
6227     return ksymtab_strings_section_;
6228   }
6229
6230   /// Return either a __ksymtab or a __ksymtab_gpl section, in case
6231   /// only the __ksymtab_gpl exists.
6232   ///
6233   /// @return the __ksymtab section if it exists, or the
6234   /// __ksymtab_gpl; or NULL if neither is found.
6235   Elf_Scn*
6236   find_any_ksymtab_section() const
6237   {
6238     Elf_Scn *result = find_ksymtab_section();
6239     if (!result)
6240       result = find_ksymtab_gpl_section();
6241     return result;
6242   }
6243
6244   /// Return either a .rel{a,}__ksymtab or a .rel{a,}__ksymtab_gpl section
6245   ///
6246   /// @return the .rel{a,}__ksymtab section if it exists, or the
6247   /// .rel{a,}__ksymtab_gpl; or NULL if neither is found.
6248   Elf_Scn*
6249   find_any_ksymtab_reloc_section() const
6250   {
6251     Elf_Scn *result = find_ksymtab_reloc_section();
6252     if (!result)
6253       result = find_ksymtab_gpl_reloc_section();
6254     return result;
6255   }
6256
6257   /// Return the SHT_GNU_versym, SHT_GNU_verdef and SHT_GNU_verneed
6258   /// sections that are involved in symbol versionning.
6259   ///
6260   /// @param versym_section the SHT_GNU_versym section found.
6261   ///
6262   /// @param verdef_section the SHT_GNU_verdef section found.
6263   ///
6264   /// @param verneed_section the SHT_GNU_verneed section found.
6265   ///
6266   /// @return true iff the sections where found.
6267   bool
6268   get_symbol_versionning_sections(Elf_Scn*&     versym_section,
6269                                   Elf_Scn*&     verdef_section,
6270                                   Elf_Scn*&     verneed_section)
6271   {
6272     if (!symbol_versionning_sections_loaded_)
6273       {
6274         symbol_versionning_sections_found_ =
6275           dwarf_reader::get_symbol_versionning_sections(elf_handle(),
6276                                                         versym_section_,
6277                                                         verdef_section_,
6278                                                         verneed_section_);
6279         symbol_versionning_sections_loaded_ = true;
6280       }
6281
6282     versym_section = versym_section_;
6283     verdef_section = verdef_section_;
6284     verneed_section = verneed_section_;
6285     return symbol_versionning_sections_found_;
6286   }
6287
6288   /// Return the version for a symbol that is at a given index in its
6289   /// SHT_SYMTAB section.
6290   ///
6291   /// The first invocation of this function caches the results and
6292   /// subsequent invocations just return the cached results.
6293   ///
6294   /// @param symbol_index the index of the symbol to consider.
6295   ///
6296   /// @param get_def_version if this is true, it means that that we want
6297   /// the version for a defined symbol; in that case, the version is
6298   /// looked for in a section of type SHT_GNU_verdef.  Otherwise, if
6299   /// this parameter is false, this means that we want the version for
6300   /// an undefined symbol; in that case, the version is the needed one
6301   /// for the symbol to be resolved; so the version is looked fo in a
6302   /// section of type SHT_GNU_verneed.
6303   ///
6304   /// @param version the version found for symbol at @p symbol_index.
6305   ///
6306   /// @return true iff a version was found for symbol at index @p
6307   /// symbol_index.
6308   bool
6309   get_version_for_symbol(size_t         symbol_index,
6310                          bool                   get_def_version,
6311                          elf_symbol::version&   version)
6312   {
6313     Elf_Scn *versym_section = NULL,
6314       *verdef_section = NULL,
6315       *verneed_section = NULL;
6316
6317     if (!get_symbol_versionning_sections(versym_section,
6318                                          verdef_section,
6319                                          verneed_section))
6320       return false;
6321
6322     GElf_Versym versym_mem;
6323     Elf_Data* versym_data = (versym_section)
6324       ? elf_getdata(versym_section, NULL)
6325       : NULL;
6326     GElf_Versym* versym = (versym_data)
6327       ? gelf_getversym(versym_data, symbol_index, &versym_mem)
6328       : NULL;
6329
6330     if (versym == 0 || *versym <= 1)
6331       // I got these value from the code of readelf.c in elfutils.
6332       // Apparently, if the symbol version entry has these values, the
6333       // symbol must be discarded. This is not documented in the
6334       // official specification.
6335       return false;
6336
6337     if (get_def_version)
6338       {
6339         if (*versym == 0x8001)
6340           // I got this value from the code of readelf.c in elfutils
6341           // too.  It's not really documented in the official
6342           // specification.
6343           return false;
6344
6345         if (verdef_section
6346             && get_version_definition_for_versym(elf_handle(), versym,
6347                                                  verdef_section, version))
6348           return true;
6349       }
6350     else
6351       {
6352         if (verneed_section
6353             && get_version_needed_for_versym(elf_handle(), versym,
6354                                              verneed_section, version))
6355           return true;
6356       }
6357
6358     return false;
6359   }
6360
6361   /// Look into the symbol tables of the underlying elf file and see
6362   /// if we find a given symbol.
6363   ///
6364   /// @param symbol_name the name of the symbol to look for.
6365   ///
6366   /// @param demangle if true, demangle the symbols found in the symbol
6367   /// tables.
6368   ///
6369   /// @param syms the vector of symbols with the name @p symbol_name
6370   /// that were found.
6371   ///
6372   /// @return true iff the symbol was found.
6373   bool
6374   lookup_symbol_from_elf(const string&                  symbol_name,
6375                          bool                           demangle,
6376                          vector<elf_symbol_sptr>&       syms) const
6377   {
6378     return dwarf_reader::lookup_symbol_from_elf(env(),
6379                                                 elf_handle(),
6380                                                 symbol_name,
6381                                                 demangle,
6382                                                 syms);
6383   }
6384
6385   /// Lookup an elf symbol, referred to by its index, from the .symtab
6386   /// section.
6387   ///
6388   /// The resulting symbol returned is an instance of a GElf_Sym, from
6389   /// the libelf library.
6390   ///
6391   /// @param symbol_index the index of the symbol to look up.
6392   ///
6393   /// @param elf_sym out parameter.  This is set to the resulting ELF
6394   /// symbol iff the function returns TRUE, meaning the symbol was
6395   /// found.
6396   ///
6397   /// @return TRUE iff the symbol was found.
6398   bool
6399   lookup_native_elf_symbol_from_index(size_t symbol_index, GElf_Sym &elf_sym)
6400   {
6401     Elf_Scn* symtab_section = find_symbol_table_section();
6402     if (!symtab_section)
6403       return false;
6404
6405     Elf_Data* symtab = elf_getdata(symtab_section, 0);
6406     ABG_ASSERT(symtab);
6407
6408     if (!gelf_getsym(symtab, symbol_index, &elf_sym))
6409       return false;
6410
6411     return true;
6412   }
6413
6414   /// Given the index of a symbol into the symbol table of an ELF
6415   /// file, look the symbol up, build an instace of @ref elf_symbol
6416   /// and return it.
6417   ///
6418   /// @param symbol_index the index of the symbol into the symbol
6419   /// table of the current elf file.
6420   ///
6421   /// @return the elf symbol found or nil if none was found.
6422   elf_symbol_sptr
6423   lookup_elf_symbol_from_index(size_t symbol_index)
6424   {
6425     GElf_Sym s;
6426     elf_symbol_sptr result =
6427       lookup_elf_symbol_from_index(symbol_index, s);
6428     return result;
6429   }
6430
6431   /// Lookup an ELF symbol given its index into the .symtab section.
6432   ///
6433   /// This function returns both the native symbol (from libelf) and
6434   /// the @p abigail::ir::elf_symbol instance, which is the
6435   /// libabigail-specific representation of the symbol.
6436   ///
6437   /// @param symbol_index the index of the symbol to look for.
6438   ///
6439   /// @param native_sym output parameter.  This is set to the native
6440   /// ELF symbol found iff the function returns a non-nil value.
6441   ///
6442   /// @return an instance of libabigail::ir::elf_symbol representing
6443   /// the ELF symbol found, iff one was found.  Otherwise, returns
6444   /// nil.
6445   elf_symbol_sptr
6446   lookup_elf_symbol_from_index(size_t symbol_index,
6447                                GElf_Sym &native_sym)
6448   {
6449     if (!lookup_native_elf_symbol_from_index(symbol_index, native_sym))
6450       return elf_symbol_sptr();
6451
6452     Elf_Scn* symtab_section = find_symbol_table_section();
6453     if (!symtab_section)
6454       return elf_symbol_sptr();
6455
6456     GElf_Shdr header_mem;
6457     GElf_Shdr* symtab_sheader = gelf_getshdr(symtab_section,
6458                                              &header_mem);
6459
6460     Elf_Data* symtab = elf_getdata(symtab_section, 0);
6461     ABG_ASSERT(symtab);
6462
6463     bool sym_is_defined = native_sym.st_shndx != SHN_UNDEF;
6464     bool sym_is_common = native_sym.st_shndx == SHN_COMMON; // this occurs in
6465                                                             // relocatable
6466                                                             // files.
6467     const char* name_str = elf_strptr(elf_handle(),
6468                                       symtab_sheader->sh_link,
6469                                       native_sym.st_name);
6470     if (name_str == 0)
6471       name_str = "";
6472
6473     elf_symbol::version ver;
6474     get_version_for_symbol(symbol_index,
6475                            sym_is_defined,
6476                            ver);
6477
6478     elf_symbol::visibility vis =
6479       stv_to_elf_symbol_visibility(GELF_ST_VISIBILITY(native_sym.st_other));
6480
6481     Elf_Scn *strings_section = find_ksymtab_strings_section();
6482     size_t strings_ndx = strings_section
6483       ? elf_ndxscn(strings_section)
6484       : 0;
6485
6486     elf_symbol_sptr sym =
6487       elf_symbol::create(env(), symbol_index, native_sym.st_size,
6488                          name_str, stt_to_elf_symbol_type
6489                          (GELF_ST_TYPE(native_sym.st_info)),
6490                          stb_to_elf_symbol_binding
6491                          (GELF_ST_BIND(native_sym.st_info)),
6492                          sym_is_defined, sym_is_common, ver, vis,
6493                          native_sym.st_shndx == strings_ndx);
6494     return sym;
6495   }
6496
6497   /// Read 8 bytes and convert their value into an uint64_t.
6498   ///
6499   /// @param bytes the array of bytes to read the next 8 bytes from.
6500   /// Note that this array must be at least 8 bytes long.
6501   ///
6502   /// @param result where to store the resuting uint64_t that was read.
6503   ///
6504   /// @param is_big_endian if true, read the 8 bytes in Big Endian
6505   /// mode, otherwise, read them in Little Endian.
6506   ///
6507   /// @param true if the 8 bytes could be read, false otherwise.
6508   bool
6509   read_uint64_from_array_of_bytes(const uint8_t *bytes,
6510                                   bool                  is_big_endian,
6511                                   uint64_t              &result) const
6512   {
6513     return read_int_from_array_of_bytes(bytes, 8, is_big_endian, result);
6514   }
6515
6516   /// Read N bytes and convert their value into an integer type T.
6517   ///
6518   /// Note that N cannot be bigger than 8 for now. The type passed needs to be
6519   /// at least of the size of number_of_bytes.
6520   ///
6521   /// @param bytes the array of bytes to read the next 8 bytes from.
6522   /// Note that this array must be at least 8 bytes long.
6523   ///
6524   /// @param number_of_bytes the number of bytes to read.  This number
6525   /// cannot be bigger than 8.
6526   ///
6527   /// @param is_big_endian if true, read the 8 bytes in Big Endian
6528   /// mode, otherwise, read them in Little Endian.
6529   ///
6530   /// @param result where to store the resuting integer that was read.
6531   ///
6532   ///
6533   /// @param true if the 8 bytes could be read, false otherwise.
6534   template<typename T>
6535   bool
6536   read_int_from_array_of_bytes(const uint8_t    *bytes,
6537                                unsigned char    number_of_bytes,
6538                                bool             is_big_endian,
6539                                T                &result) const
6540   {
6541     if (!bytes)
6542       return false;
6543
6544     ABG_ASSERT(number_of_bytes <= 8);
6545     ABG_ASSERT(number_of_bytes <= sizeof(T));
6546
6547     T res = 0;
6548
6549     const uint8_t *cur = bytes;
6550     if (is_big_endian)
6551       {
6552         // In Big Endian, the most significant byte is at the lowest
6553         // address.
6554         const uint8_t* msb = cur;
6555         res = *msb;
6556
6557         // Now read the remaining least significant bytes.
6558         for (uint i = 1; i < number_of_bytes; ++i)
6559           res = (res << 8) | ((T)msb[i]);
6560       }
6561     else
6562       {
6563         // In Little Endian, the least significant byte is at the
6564         // lowest address.
6565         const uint8_t* lsb = cur;
6566         res = *lsb;
6567         // Now read the remaining most significant bytes.
6568         for (uint i = 1; i < number_of_bytes; ++i)
6569           res = res | (((T)lsb[i]) << i * 8);
6570       }
6571
6572     result = res;
6573     return true;
6574   }
6575
6576   /// Lookup the address of the function entry point that corresponds
6577   /// to the address of a given function descriptor.
6578   ///
6579   /// On PPC64, a function pointer is the address of a function
6580   /// descriptor.  Function descriptors are located in the .opd
6581   /// section.  Each function descriptor is a triplet of three
6582   /// addresses, each one on 64 bits.  Among those three address only
6583   /// the first one is of any interest to us: the address of the entry
6584   /// point of the function.
6585   ///
6586   /// This function returns the address of the entry point of the
6587   /// function whose descriptor's address is given.
6588   ///
6589   /// http://refspecs.linuxfoundation.org/ELF/ppc64/PPC-elf64abi.html#FUNC-DES
6590   ///
6591   /// https://www.ibm.com/developerworks/community/blogs/5894415f-be62-4bc0-81c5-3956e82276f3/entry/deeply_understand_64_bit_powerpc_elf_abi_function_descriptors?lang=en
6592   ///
6593   /// @param fn_desc_address the address of the function descriptor to
6594   /// consider.
6595   ///
6596   /// @return the address of the entry point of the function whose
6597   /// descriptor has the address @p fn_desc_address.  If there is no
6598   /// .opd section (e.g because we are not on ppc64) or more generally
6599   /// if the function descriptor could not be found then this function
6600   /// just returns the address of the fuction descriptor.
6601   GElf_Addr
6602   lookup_ppc64_elf_fn_entry_point_address(GElf_Addr fn_desc_address) const
6603   {
6604     if (!elf_handle())
6605       return fn_desc_address;
6606
6607     if (!elf_architecture_is_ppc64())
6608       return fn_desc_address;
6609
6610     bool is_big_endian = elf_architecture_is_big_endian();
6611
6612     Elf_Scn *opd_section = find_opd_section();
6613     if (!opd_section)
6614       return fn_desc_address;
6615
6616     GElf_Shdr header_mem;
6617     // The section header of the .opd section.
6618     GElf_Shdr *opd_sheader = gelf_getshdr(opd_section, &header_mem);
6619
6620     // The offset of the function descriptor entry, in the .opd
6621     // section.
6622     size_t fn_desc_offset = fn_desc_address - opd_sheader->sh_addr;
6623     Elf_Data *elf_data = elf_rawdata(opd_section, 0);
6624
6625     // Ensure that the opd_section has at least 8 bytes, starting from
6626     // the offset we want read the data from.
6627     if (elf_data->d_size <= fn_desc_offset + 8)
6628       return fn_desc_address;
6629
6630     // A pointer to the data of the .opd section, that we can actually
6631     // do something with.
6632     uint8_t * bytes = (uint8_t*) elf_data->d_buf;
6633
6634     // The resulting address we are looking for is going to be formed
6635     // in this variable.
6636     GElf_Addr result = 0;
6637     ABG_ASSERT(read_uint64_from_array_of_bytes(bytes + fn_desc_offset,
6638                                            is_big_endian, result));
6639
6640     return result;
6641   }
6642
6643   /// Given the address of the beginning of a function, lookup the
6644   /// symbol of the function, build an instance of @ref elf_symbol out
6645   /// of it and return it.
6646   ///
6647   /// @param symbol_start_addr the address of the beginning of the
6648   /// function to consider.
6649   ///
6650   /// @param sym the resulting symbol.  This is set iff the function
6651   /// returns true.
6652   ///
6653   /// @return the elf symbol found at address @p symbol_start_addr, or
6654   /// nil if none was found.
6655   elf_symbol_sptr
6656   lookup_elf_fn_symbol_from_address(GElf_Addr symbol_start_addr) const
6657   {
6658     addr_elf_symbol_sptr_map_type::const_iterator i,
6659       nil = fun_entry_addr_sym_map().end();
6660
6661     if ((i = fun_entry_addr_sym_map().find(symbol_start_addr)) == nil)
6662       return elf_symbol_sptr();
6663
6664     return i->second;
6665   }
6666
6667   /// Given the address of a global variable, lookup the symbol of the
6668   /// variable, build an instance of @ref elf_symbol out of it and
6669   /// return it.
6670   ///
6671   /// @param symbol_start_addr the address of the beginning of the
6672   /// variable to consider.
6673   ///
6674   /// @param the symbol found, iff the function returns true.
6675   ///
6676   /// @return the elf symbol found or nil if none was found.
6677   elf_symbol_sptr
6678   lookup_elf_var_symbol_from_address(GElf_Addr symbol_start_addr) const
6679   {
6680     addr_elf_symbol_sptr_map_type::const_iterator i,
6681       nil = var_addr_sym_map().end();
6682
6683     if ((i = var_addr_sym_map().find(symbol_start_addr)) == nil)
6684       return elf_symbol_sptr();
6685
6686     return i->second;
6687   }
6688
6689   /// Lookup an elf symbol, knowing its address.
6690   ///
6691   /// This function first looks for a function symbol having this
6692   /// address; if it doesn't find any, then it looks for a variable
6693   /// symbol.
6694   ///
6695   /// @param symbol_addr the address of the symbol of the symbol we
6696   /// are looking for.  Note that the address is a relative offset
6697   /// starting from the beginning of the .text section.  Addresses
6698   /// that are presen in the symbol table (the one named .symtab).
6699   ///
6700   /// @return the elf symbol if found, or nil otherwise.
6701   elf_symbol_sptr
6702   lookup_elf_symbol_from_address(GElf_Addr symbol_addr) const
6703   {
6704     elf_symbol_sptr result = lookup_elf_fn_symbol_from_address(symbol_addr);
6705     if (!result)
6706       result = lookup_elf_var_symbol_from_address(symbol_addr);
6707     return result;
6708   }
6709
6710   /// Look in the symbol tables of the underying elf file and see if
6711   /// we find a symbol of a given name of function type.
6712   ///
6713   /// @param sym_name the name of the symbol to look for.
6714   ///
6715   /// @param syms the public function symbols that were found, with
6716   /// the name @p sym_name.
6717   ///
6718   /// @return true iff the symbol was found.
6719   bool
6720   lookup_public_function_symbol_from_elf(const string&                  sym_name,
6721                                          vector<elf_symbol_sptr>&       syms)
6722   {
6723     return dwarf_reader::lookup_public_function_symbol_from_elf(env(),
6724                                                                 elf_handle(),
6725                                                                 sym_name,
6726                                                                 syms);
6727   }
6728
6729   /// Look in the symbol tables of the underying elf file and see if
6730   /// we find a symbol of a given name of variable type.
6731   ///
6732   /// @param sym_name the name of the symbol to look for.
6733   ///
6734   /// @param syms the variable symbols that were found, with the name
6735   /// @p sym_name.
6736   ///
6737   /// @return true iff the symbol was found.
6738   bool
6739   lookup_public_variable_symbol_from_elf(const string&            sym_name,
6740                                          vector<elf_symbol_sptr>& syms)
6741   {
6742     return dwarf_reader::lookup_public_variable_symbol_from_elf(env(),
6743                                                                 elf_handle(),
6744                                                                 sym_name,
6745                                                                 syms);
6746   }
6747
6748   /// Test if a given function symbol has been exported.
6749   ///
6750   /// @param symbol_address the address of the symbol we are looking
6751   /// for.  Note that this address must be a relative offset from the
6752   /// beginning of the .text section, just like the kind of addresses
6753   /// that are present in the .symtab section.
6754   ///
6755   /// @returnthe elf symbol if found, or nil otherwise.
6756   elf_symbol_sptr
6757   function_symbol_is_exported(GElf_Addr symbol_address) const
6758   {
6759     elf_symbol_sptr symbol = lookup_elf_fn_symbol_from_address(symbol_address);
6760     if (!symbol)
6761       return symbol;
6762
6763     if (!symbol->is_public())
6764       return elf_symbol_sptr();
6765
6766     address_set_sptr set;
6767     bool looking_at_linux_kernel_binary =
6768       load_in_linux_kernel_mode() && is_linux_kernel_binary();
6769
6770     if (looking_at_linux_kernel_binary)
6771       {
6772         if ((set = linux_exported_fn_syms()))
6773           {
6774             if (set->find(symbol_address) != set->end())
6775               return symbol;
6776           }
6777         if ((set = linux_exported_gpl_fn_syms()))
6778           {
6779             if (set->find(symbol_address) != set->end())
6780               return symbol;
6781           }
6782         return elf_symbol_sptr();
6783       }
6784
6785     return symbol;
6786   }
6787
6788   /// Test if a given variable symbol has been exported.
6789   ///
6790   /// @param symbol_address the address of the symbol we are looking
6791   /// for.  Note that this address must be a relative offset from the
6792   /// beginning of the .text section, just like the kind of addresses
6793   /// that are present in the .symtab section.
6794   ///
6795   /// @returnthe elf symbol if found, or nil otherwise.
6796   elf_symbol_sptr
6797   variable_symbol_is_exported(GElf_Addr symbol_address) const
6798   {
6799     elf_symbol_sptr symbol = lookup_elf_var_symbol_from_address(symbol_address);
6800     if (!symbol)
6801       return symbol;
6802
6803     if (!symbol->is_public())
6804       return elf_symbol_sptr();
6805
6806     address_set_sptr set;
6807     bool looking_at_linux_kernel_binary =
6808       load_in_linux_kernel_mode() && is_linux_kernel_binary();
6809
6810     if (looking_at_linux_kernel_binary)
6811       {
6812         if ((set = linux_exported_var_syms()))
6813           {
6814             if (set->find(symbol_address) != set->end())
6815               return symbol;
6816           }
6817         if ((set = linux_exported_gpl_var_syms()))
6818           {
6819             if (set->find(symbol_address) != set->end())
6820               return symbol;
6821           }
6822         return elf_symbol_sptr();
6823       }
6824
6825     return symbol;
6826   }
6827
6828   /// Getter for the map of function address -> symbol.
6829   ///
6830   /// @return the function address -> symbol map.
6831   const addr_elf_symbol_sptr_map_sptr
6832   fun_addr_sym_map_sptr() const
6833   {
6834     maybe_load_symbol_maps();
6835     return fun_addr_sym_map_;
6836   }
6837
6838   /// Getter for the map of function address -> symbol.
6839   ///
6840   /// @return the function address -> symbol map.
6841   addr_elf_symbol_sptr_map_sptr
6842   fun_addr_sym_map_sptr()
6843   {
6844     maybe_load_symbol_maps();
6845     return fun_addr_sym_map_;
6846   }
6847
6848   /// Getter for the map of function symbol address -> function symbol
6849   /// index.
6850   ///
6851   /// @return the map.  Note that this initializes the map once when
6852   /// its nedded.
6853   const addr_elf_symbol_sptr_map_type&
6854   fun_addr_sym_map() const
6855   {
6856     maybe_load_symbol_maps();
6857     return *fun_addr_sym_map_;
6858   }
6859
6860   /// Getter for the map of function symbol address -> function symbol
6861   /// index.
6862   ///
6863   /// @return the map.  Note that this initializes the map once when
6864   /// its nedded.
6865   addr_elf_symbol_sptr_map_type&
6866   fun_addr_sym_map()
6867   {
6868     maybe_load_symbol_maps();
6869     return *fun_addr_sym_map_;
6870   }
6871
6872   /// Getter for a pointer to the map that associates the address of
6873   /// an entry point of a function with the symbol of that function.
6874   ///
6875   /// Note that on non-"PPC64 ELFv1" binaries, this map is the same as
6876   /// the one that assciates the address of a function with the symbol
6877   /// of that function.
6878   ///
6879   /// @return a pointer to the map that associates the address of an
6880   /// entry point of a function with the symbol of that function.
6881   addr_elf_symbol_sptr_map_sptr&
6882   fun_entry_addr_sym_map_sptr()
6883   {
6884     if (!fun_entry_addr_sym_map_ && !fun_addr_sym_map_)
6885       maybe_load_symbol_maps();
6886     if (elf_architecture_is_ppc64())
6887       return fun_entry_addr_sym_map_;
6888     return fun_addr_sym_map_;
6889   }
6890
6891   /// Getter for a pointer to the map that associates the address of
6892   /// an entry point of a function with the symbol of that function.
6893   ///
6894   /// Note that on non-"PPC64 ELFv1" binaries, this map is the same as
6895   /// the one that assciates the address of a function with the symbol
6896   /// of that function.
6897   ///
6898   /// @return a pointer to the map that associates the address of an
6899   /// entry point of a function with the symbol of that function.
6900   const addr_elf_symbol_sptr_map_sptr&
6901   fun_entry_addr_sym_map_sptr() const
6902   {return const_cast<read_context*>(this)->fun_entry_addr_sym_map_sptr();}
6903
6904
6905   /// Getter for the map that associates the address of an entry point
6906   /// of a function with the symbol of that function.
6907   ///
6908   /// Note that on non-"PPC64 ELFv1" binaries, this map is the same as
6909   /// the one that assciates the address of a function with the symbol
6910   /// of that function.
6911   ///
6912   /// @return the map that associates the address of an entry point of
6913   /// a function with the symbol of that function.
6914   addr_elf_symbol_sptr_map_type&
6915   fun_entry_addr_sym_map()
6916   {return *fun_entry_addr_sym_map_sptr();}
6917
6918   /// Getter for the map that associates the address of an entry point
6919   /// of a function with the symbol of that function.
6920   ///
6921   /// Note that on non-"PPC64 ELFv1" binaries, this map is the same as
6922   /// the one that assciates the address of a function with the symbol
6923   /// of that function.
6924   ///
6925   /// @return the map that associates the address of an entry point of
6926   /// a function with the symbol of that function.
6927   const addr_elf_symbol_sptr_map_type&
6928   fun_entry_addr_sym_map() const
6929   { return *fun_entry_addr_sym_map_sptr();}
6930
6931   /// Getter for the map of function symbols (name -> sym).
6932   ///
6933   /// @return a shared pointer to the map of function symbols.
6934   const string_elf_symbols_map_sptr&
6935   fun_syms_sptr() const
6936   {
6937     maybe_load_symbol_maps();
6938     return fun_syms_;
6939   }
6940
6941   /// Getter for the map of function symbols (name -> sym).
6942   ///
6943   /// @return a shared pointer to the map of function symbols.
6944   string_elf_symbols_map_sptr&
6945   fun_syms_sptr()
6946   {
6947     maybe_load_symbol_maps();
6948     return fun_syms_;
6949   }
6950
6951   /// Getter for the map of function symbols (name -> sym).
6952   ///
6953   /// @return a reference to the map of function symbols.
6954   const string_elf_symbols_map_type&
6955   fun_syms() const
6956   {
6957     maybe_load_symbol_maps();
6958     return *fun_syms_;
6959   }
6960
6961   /// Getter for the map of function symbols (name -> sym).
6962   ///
6963   /// @return a reference to the map of function symbols.
6964   string_elf_symbols_map_type&
6965   fun_syms()
6966   {
6967     maybe_load_symbol_maps();
6968     return *fun_syms_;
6969   }
6970
6971   /// Getter for the map of variable symbols (name -> sym)
6972   ///
6973   /// @return a shared pointer to the map of variable symbols.
6974   const string_elf_symbols_map_sptr
6975   var_syms_sptr() const
6976   {
6977     maybe_load_symbol_maps();
6978     return var_syms_;
6979   }
6980
6981   /// Getter for the map of variable symbols (name -> sym)
6982   ///
6983   /// @return a shared pointer to the map of variable symbols.
6984   string_elf_symbols_map_sptr
6985   var_syms_sptr()
6986   {
6987     maybe_load_symbol_maps();
6988     return var_syms_;
6989   }
6990
6991   /// Getter for the map of variable symbols (name -> sym)
6992   ///
6993   /// @return a reference to the map of variable symbols.
6994   const string_elf_symbols_map_type&
6995   var_syms() const
6996   {
6997     maybe_load_symbol_maps();
6998     return *var_syms_;
6999   }
7000
7001   /// Getter for the map of variable symbols (name -> sym)
7002   ///
7003   /// @return a reference to the map of variable symbols.
7004   string_elf_symbols_map_type&
7005   var_syms()
7006   {
7007     maybe_load_symbol_maps();
7008     return *var_syms_;
7009   }
7010
7011   /// Getter for the map of undefined function symbols (name -> vector
7012   /// of symbols).
7013   ///
7014   /// @return a (smart) pointer to the map of undefined function
7015   /// symbols.
7016   const string_elf_symbols_map_sptr&
7017   undefined_fun_syms_sptr() const
7018   {
7019     maybe_load_symbol_maps();
7020     return undefined_fun_syms_;
7021   }
7022
7023   /// Getter for the map of undefined function symbols (name -> vector
7024   /// of symbols).
7025   ///
7026   /// @return a (smart) pointer to the map of undefined function
7027   /// symbols.
7028   string_elf_symbols_map_sptr&
7029   undefined_fun_syms_sptr()
7030   {
7031     maybe_load_symbol_maps();
7032     return undefined_fun_syms_;
7033   }
7034
7035   /// Getter for the map of undefined function symbols (name -> vector
7036   /// of symbols).
7037   ///
7038   /// @return a reference to the map of undefined function symbols.
7039   const string_elf_symbols_map_type&
7040   undefined_fun_syms() const
7041   {
7042     maybe_load_symbol_maps();
7043     return *undefined_fun_syms_;
7044   }
7045
7046   /// Getter for the map of undefined function symbols (name -> vector
7047   /// of symbols).
7048   ///
7049   /// @return a reference to the map of undefined function symbols.
7050   string_elf_symbols_map_type&
7051   undefined_fun_syms()
7052   {
7053     maybe_load_symbol_maps();
7054     return *undefined_fun_syms_;
7055   }
7056
7057   /// Getter for the map of undefined variable symbols (name -> vector
7058   /// of symbols).
7059   ///
7060   /// @return a (smart) pointer to the map of undefined variable
7061   /// symbols.
7062   const string_elf_symbols_map_sptr&
7063   undefined_var_syms_sptr() const
7064   {
7065     maybe_load_symbol_maps();
7066     return undefined_var_syms_;
7067   }
7068
7069   /// Getter for the map of undefined variable symbols (name -> vector
7070   /// of symbols).
7071   ///
7072   /// @return a (smart) pointer to the map of undefined variable
7073   /// symbols.
7074   string_elf_symbols_map_sptr&
7075   undefined_var_syms_sptr()
7076   {
7077     maybe_load_symbol_maps();
7078     return undefined_var_syms_;
7079   }
7080
7081   /// Getter for the map of undefined variable symbols (name -> vector
7082   /// of symbols).
7083   ///
7084   /// @return a reference to the map of undefined variable symbols.
7085   const string_elf_symbols_map_type&
7086   undefined_var_syms() const
7087   {
7088     maybe_load_symbol_maps();
7089     return *undefined_var_syms_;
7090   }
7091
7092   /// Getter for the map of undefined variable symbols (name -> vector
7093   /// of symbols).
7094   ///
7095   /// @return a reference to the map of undefined variable symbols.
7096   string_elf_symbols_map_type&
7097   undefined_var_syms()
7098   {
7099     maybe_load_symbol_maps();
7100     return *undefined_var_syms_;
7101   }
7102
7103   /// Getter for the set of addresses of function symbols that are
7104   /// explicitely exported, for a linux kernel (module) binary.  These
7105   /// are the addresses of function symbols present in the __ksymtab
7106   /// section
7107   address_set_sptr&
7108   linux_exported_fn_syms()
7109   {return linux_exported_fn_syms_;}
7110
7111   /// Getter for the set of addresses of functions that are
7112   /// explicitely exported, for a linux kernel (module) binary.  These
7113   /// are the addresses of function symbols present in the __ksymtab
7114   /// section.
7115   ///
7116   /// @return the set of addresses of exported function symbols.
7117   const address_set_sptr&
7118   linux_exported_fn_syms() const
7119   {return const_cast<read_context*>(this)->linux_exported_fn_syms();}
7120
7121   /// Create an empty set of addresses of functions exported from a
7122   /// linux kernel (module) binary, or return the one that already
7123   /// exists.
7124   ///
7125   /// @return the set of addresses of exported function symbols.
7126   address_set_sptr&
7127   create_or_get_linux_exported_fn_syms()
7128   {
7129     if (!linux_exported_fn_syms_)
7130       linux_exported_fn_syms_.reset(new address_set_type);
7131     return linux_exported_fn_syms_;
7132   }
7133
7134   /// Getter for the set of addresses of v ariables that are
7135   /// explicitely exported, for a linux kernel (module) binary.  These
7136   /// are the addresses of variable symbols present in the __ksymtab
7137   /// section.
7138   ///
7139   /// @return the set of addresses of exported variable symbols.
7140   address_set_sptr&
7141   linux_exported_var_syms()
7142   {return linux_exported_var_syms_;}
7143
7144   /// Getter for the set of addresses of variables that are
7145   /// explicitely exported, for a linux kernel (module) binary.  These
7146   /// are the addresses of variable symbols present in the __ksymtab
7147   /// section.
7148   ///
7149   /// @return the set of addresses of exported variable symbols.
7150   const address_set_sptr&
7151   linux_exported_var_syms() const
7152   {return const_cast<read_context*>(this)->linux_exported_var_syms();}
7153
7154
7155   /// Create an empty set of addresses of variables exported from a
7156   /// linux kernel (module) binary, or return the one that already
7157   /// exists.
7158   ///
7159   /// @return the set of addresses of exported variable symbols.
7160   address_set_sptr&
7161   create_or_get_linux_exported_var_syms()
7162   {
7163     if (!linux_exported_var_syms_)
7164       linux_exported_var_syms_.reset(new address_set_type);
7165     return linux_exported_var_syms_;
7166   }
7167
7168
7169   /// Getter for the set of addresses of function symbols that are
7170   /// explicitely exported as GPL, for a linux kernel (module) binary.
7171   /// These are the addresses of function symbols present in the
7172   /// __ksymtab_gpl section.
7173   address_set_sptr&
7174   linux_exported_gpl_fn_syms()
7175   {return linux_exported_gpl_fn_syms_;}
7176
7177   /// Getter for the set of addresses of function symbols that are
7178   /// explicitely exported as GPL, for a linux kernel (module) binary.
7179   /// These are the addresses of function symbols present in the
7180   /// __ksymtab_gpl section.
7181   const address_set_sptr&
7182   linux_exported_gpl_fn_syms() const
7183   {return const_cast<read_context*>(this)->linux_exported_gpl_fn_syms();}
7184
7185   /// Create an empty set of addresses of GPL functions exported from
7186   /// a linux kernel (module) binary, or return the one that already
7187   /// exists.
7188   ///
7189   /// @return the set of addresses of exported function symbols.
7190   address_set_sptr&
7191   create_or_get_linux_exported_gpl_fn_syms()
7192   {
7193     if (!linux_exported_gpl_fn_syms_)
7194       linux_exported_gpl_fn_syms_.reset(new address_set_type);
7195     return linux_exported_gpl_fn_syms_;
7196   }
7197
7198   /// Getter for the set of addresses of variable symbols that are
7199   /// explicitely exported as GPL, for a linux kernel (module) binary.
7200   /// These are the addresses of variable symbols present in the
7201   /// __ksymtab_gpl section.
7202   address_set_sptr&
7203   linux_exported_gpl_var_syms()
7204   {return linux_exported_gpl_var_syms_;}
7205
7206   /// Getter for the set of addresses of variable symbols that are
7207   /// explicitely exported as GPL, for a linux kernel (module) binary.
7208   /// These are the addresses of variable symbols present in the
7209   /// __ksymtab_gpl section.
7210   const address_set_sptr&
7211   linux_exported_gpl_var_syms() const
7212   {return const_cast<read_context*>(this)->linux_exported_gpl_var_syms();}
7213
7214   /// Create an empty set of addresses of GPL variables exported from
7215   /// a linux kernel (module) binary, or return the one that already
7216   /// exists.
7217   ///
7218   /// @return the set of addresses of exported variable symbols.
7219   address_set_sptr&
7220   create_or_get_linux_exported_gpl_var_syms()
7221   {
7222     if (!linux_exported_gpl_var_syms_)
7223       linux_exported_gpl_var_syms_.reset(new address_set_type);
7224     return linux_exported_gpl_var_syms_;
7225   }
7226
7227   /// Getter for the ELF dt_needed tag.
7228   const vector<string>&
7229   dt_needed() const
7230   {return dt_needed_;}
7231
7232   /// Getter for the ELF dt_soname tag.
7233   const string&
7234   dt_soname() const
7235   {return dt_soname_;}
7236
7237   /// Getter for the ELF architecture of the current file.
7238   const string&
7239   elf_architecture() const
7240   {return elf_architecture_;}
7241
7242   /// Return the size of a word for the current architecture.
7243   /// @return the size of a word.
7244   unsigned char
7245   architecture_word_size() const
7246   {
7247     unsigned char word_size = 0;
7248     GElf_Ehdr eh_mem;
7249     GElf_Ehdr* elf_header = gelf_getehdr(elf_handle(), &eh_mem);
7250     if (elf_header->e_ident[EI_CLASS] == ELFCLASS32)
7251       word_size = 4;
7252     else if (elf_header->e_ident[EI_CLASS] == ELFCLASS64)
7253       word_size = 8;
7254     else
7255       ABG_ASSERT_NOT_REACHED;
7256     return word_size;
7257   }
7258
7259   /// Test if the architecture of the current binary is ppc64.
7260   ///
7261   /// @return true iff the architecture of the current binary is ppc64.
7262   bool
7263   elf_architecture_is_ppc64() const
7264   {
7265     GElf_Ehdr eh_mem;
7266     GElf_Ehdr* elf_header = gelf_getehdr(elf_handle(), &eh_mem);
7267
7268     return (elf_header && elf_header->e_machine == EM_PPC64);
7269   }
7270
7271   /// Test if the endianness of the current binary is Big Endian.
7272   ///
7273   /// https://en.wikipedia.org/wiki/Endianness.
7274   ///
7275   /// @return true iff the current binary is Big Endian.
7276   bool
7277   elf_architecture_is_big_endian() const
7278   {
7279     GElf_Ehdr eh_mem;
7280     GElf_Ehdr* elf_header = gelf_getehdr(elf_handle(), &eh_mem);
7281
7282     bool is_big_endian = (elf_header->e_ident[EI_DATA] == ELFDATA2MSB);
7283
7284     if (!is_big_endian)
7285       ABG_ASSERT(elf_header->e_ident[EI_DATA] == ELFDATA2LSB);
7286
7287     return is_big_endian;
7288   }
7289
7290   /// Test if the current elf file being read is an executable.
7291   ///
7292   /// @return true iff the current elf file being read is an
7293   /// executable.
7294   bool
7295   current_elf_file_is_executable() const
7296   {
7297     GElf_Ehdr eh_mem;
7298     GElf_Ehdr* elf_header = gelf_getehdr(elf_handle(), &eh_mem);
7299     return elf_header->e_type == ET_EXEC;
7300   }
7301
7302   /// Test if the current elf file being read is a dynamic shared
7303   /// object.
7304   ///
7305   /// @return true iff the current elf file being read is a
7306   /// dynamic shared object.
7307   bool
7308   current_elf_file_is_dso() const
7309   {
7310     GElf_Ehdr eh_mem;
7311     GElf_Ehdr* elf_header = gelf_getehdr(elf_handle(), &eh_mem);
7312     return elf_header->e_type == ET_DYN;
7313   }
7314
7315   /// Getter for the map of global variables symbol address -> global
7316   /// variable symbol index.
7317   ///
7318   /// @return the map.  Note that this initializes the map once when
7319   /// its nedded.
7320   const addr_elf_symbol_sptr_map_type&
7321   var_addr_sym_map() const
7322   {return const_cast<read_context*>(this)->var_addr_sym_map();}
7323
7324   /// Getter for the map of global variables symbol address -> global
7325   /// variable symbol index.
7326   ///
7327   /// @return the map.  Note that this initializes the map once when
7328   /// its nedded.
7329   addr_elf_symbol_sptr_map_type&
7330   var_addr_sym_map()
7331   {
7332     if (!var_addr_sym_map_)
7333       maybe_load_symbol_maps();
7334     return *var_addr_sym_map_;
7335   }
7336
7337   /// Load the maps address -> function symbol, address -> variable
7338   /// symbol and the maps of function and variable undefined symbols.
7339   ///
7340   /// @param load_fun_map whether to load the address to function map.
7341   ///
7342   /// @param load_var_map whether to laod the address to variable map.
7343   ///
7344   /// @param load_undefined_fun_map whether to load the undefined
7345   /// function map.
7346   ///
7347   /// @param load_undefined_var_map whether to laod the undefined
7348   /// variable map.
7349   ///
7350   /// @return return true iff the maps have be loaded.
7351   bool
7352   load_symbol_maps_from_symtab_section(bool load_fun_map,
7353                                        bool load_var_map,
7354                                        bool load_undefined_fun_map,
7355                                        bool load_undefined_var_map)
7356   {
7357     Elf_Scn* symtab_section = find_symbol_table_section();
7358     if (!symtab_section)
7359       return false;
7360
7361     GElf_Shdr header_mem;
7362     GElf_Shdr* symtab_sheader = gelf_getshdr(symtab_section,
7363                                              &header_mem);
7364     size_t nb_syms = symtab_sheader->sh_size / symtab_sheader->sh_entsize;
7365
7366     Elf_Data* symtab = elf_getdata(symtab_section, 0);
7367     ABG_ASSERT(symtab);
7368
7369     GElf_Ehdr elf_header;
7370     ABG_ASSERT(gelf_getehdr(elf_handle(), &elf_header));
7371
7372     bool is_ppc64 = elf_architecture_is_ppc64();
7373
7374     for (size_t i = 0; i < nb_syms; ++i)
7375       {
7376         GElf_Sym* sym, sym_mem;
7377         sym = gelf_getsym(symtab, i, &sym_mem);
7378         ABG_ASSERT(sym);
7379
7380         if ((load_fun_map || load_undefined_fun_map)
7381             && (GELF_ST_TYPE(sym->st_info) == STT_FUNC
7382                 || GELF_ST_TYPE(sym->st_info) == STT_GNU_IFUNC))
7383           {
7384             elf_symbol_sptr symbol = lookup_elf_symbol_from_index(i);
7385             ABG_ASSERT(symbol);
7386             ABG_ASSERT(symbol->is_function());
7387
7388
7389             if (load_fun_map && symbol->is_public())
7390               {
7391                 {
7392                   string_elf_symbols_map_type::iterator it =
7393                     fun_syms_->find(symbol->get_name());
7394                   if (it == fun_syms_->end())
7395                     {
7396                       (*fun_syms_)[symbol->get_name()] = elf_symbols();
7397                       it = fun_syms_->find(symbol->get_name());
7398                     }
7399                   string name = symbol->get_name();
7400                   it->second.push_back(symbol);
7401                 }
7402
7403                 {
7404                   GElf_Addr symbol_value =
7405                     maybe_adjust_et_rel_sym_addr_to_abs_addr(sym);
7406
7407                   addr_elf_symbol_sptr_map_type::const_iterator it =
7408                     fun_addr_sym_map_->find(symbol_value);
7409                   if (it == fun_addr_sym_map_->end())
7410                     (*fun_addr_sym_map_)[symbol_value] = symbol;
7411                   else //if (sym->st_value != 0)
7412                     it->second->get_main_symbol()->add_alias(symbol);
7413
7414                   if (is_ppc64)
7415                     {
7416                       // For ppc64 ELFv1 binaries, we need to build a
7417                       // function entry point address -> function
7418                       // symbol map.  This is in addition to the
7419                       // function pointer -> symbol map.  This is
7420                       // because on ppc64 ELFv1, a function pointer is
7421                       // different from a function entry point
7422                       // address.
7423                       //
7424                       // On ppc64 ELFv1, the DWARF DIE of a function
7425                       // references the address of the entry point of
7426                       // the function symbol; whereas the value of the
7427                       // function symbol is the function pointer.  As
7428                       // these addresses are different, if I we want
7429                       // to get to the symbol of a function from its
7430                       // entry point address (as referenced by DWARF
7431                       // function DIEs) we must have the two maps I
7432                       // mentionned right above.
7433                       //
7434                       // In other words, we need a map that associates
7435                       // a function enty point address with the symbol
7436                       // of that function, to be able to get the
7437                       // function symbol that corresponds to a given
7438                       // function DIE, on ppc64.
7439                       //
7440                       // The value of the function pointer (the value
7441                       // of the symbol) usually refers to the offset
7442                       // of a table in the .opd section.  But
7443                       // sometimes, for a symbol named "foo", the
7444                       // corresponding symbol named ".foo" (note the
7445                       // dot before foo) which value is the entry
7446                       // point address of the function; that entry
7447                       // point address refers to a region in the .text
7448                       // section.
7449                       //
7450                       // So we are only interested in values of the
7451                       // symbol that are in the .opd section.
7452                       GElf_Addr fn_desc_addr = sym->st_value;
7453                       GElf_Addr fn_entry_point_addr =
7454                         lookup_ppc64_elf_fn_entry_point_address(fn_desc_addr);
7455                       addr_elf_symbol_sptr_map_type::const_iterator it2 =
7456                         fun_entry_addr_sym_map().find(fn_entry_point_addr);
7457
7458                       if (it2 == fun_entry_addr_sym_map().end())
7459                         fun_entry_addr_sym_map()[fn_entry_point_addr] = symbol;
7460                       else if (address_is_in_opd_section(fn_desc_addr))
7461                         {
7462                           // Either
7463                           //
7464                           // 'symbol' must have been registered as an
7465                           // alias for it2->second->get_main_symbol(),
7466                           // right before the "if (ppc64)" statement.
7467                           //
7468                           // Or
7469                           //
7470                           // if the name of 'symbol' is foo, then the
7471                           // name of it2->second is ".foo".  That is,
7472                           // foo is the name of the symbol when it
7473                           // refers to the function descriptor in the
7474                           // .opd section and ".foo" is an internal
7475                           // name for the address of the entry point
7476                           // of foo.
7477                           //
7478                           // In the latter case, we just want to keep
7479                           // a refernce to "foo" as .foo is an
7480                           // internal name.
7481
7482                           bool two_symbols_alias =
7483                             it2->second->get_main_symbol()->does_alias(*symbol);
7484                           bool symbol_is_foo_and_prev_symbol_is_dot_foo =
7485                             (it2->second->get_name()
7486                              == string(".") + symbol->get_name());
7487
7488                           ABG_ASSERT(two_symbols_alias
7489                                  || symbol_is_foo_and_prev_symbol_is_dot_foo);
7490
7491                           if (symbol_is_foo_and_prev_symbol_is_dot_foo)
7492                             // Let's just keep a reference of the
7493                             // symbol that the user sees in the source
7494                             // code (the one named foo).  The symbol
7495                             // which name is prefixed with a "dot" is
7496                             // an artificial one.
7497                             fun_entry_addr_sym_map()[fn_entry_point_addr] = symbol;
7498                         }
7499                     }
7500                 }
7501               }
7502             else if (load_undefined_fun_map && !symbol->is_defined())
7503               {
7504                 string_elf_symbols_map_type::iterator it =
7505                   undefined_fun_syms_->find(symbol->get_name());
7506                 if (it == undefined_fun_syms_->end())
7507                   {
7508                     (*undefined_fun_syms_)[symbol->get_name()] = elf_symbols();
7509                     it = undefined_fun_syms_->find(symbol->get_name());
7510                   }
7511                 it->second.push_back(symbol);
7512               }
7513           }
7514         else if ((load_var_map || load_undefined_var_map)
7515                  && (GELF_ST_TYPE(sym->st_info) == STT_OBJECT
7516                      || GELF_ST_TYPE(sym->st_info) == STT_TLS)
7517                  // If the symbol is for an OBJECT, the index of the
7518                  // section it refers to cannot be absolute.
7519                  // Otherwise that OBJECT is not a variable.
7520                  && (sym->st_shndx != SHN_ABS
7521                      || GELF_ST_TYPE(sym->st_info) != STT_OBJECT ))
7522           {
7523             elf_symbol_sptr symbol = lookup_elf_symbol_from_index(i);
7524             ABG_ASSERT(symbol);
7525             ABG_ASSERT(symbol->is_variable());
7526
7527             if (load_var_map && symbol->is_public())
7528               {
7529                 {
7530                   string_elf_symbols_map_type::iterator it =
7531                     var_syms_->find(symbol->get_name());
7532                   if (it == var_syms_->end())
7533                     {
7534                       (*var_syms_)[symbol->get_name()] = elf_symbols();
7535                       it = var_syms_->find(symbol->get_name());
7536                     }
7537                   string name = symbol->get_name();
7538                   it->second.push_back(symbol);
7539                 }
7540
7541                 if (symbol->is_common_symbol())
7542                   {
7543                     string_elf_symbols_map_type::iterator it =
7544                       var_syms_->find(symbol->get_name());
7545                     ABG_ASSERT(it != var_syms_->end());
7546                     const elf_symbols& common_sym_instances = it->second;
7547                     ABG_ASSERT(!common_sym_instances.empty());
7548                     if (common_sym_instances.size() > 1)
7549                       {
7550                         elf_symbol_sptr main_common_sym =
7551                           common_sym_instances[0];
7552                         ABG_ASSERT(main_common_sym->get_name()
7553                                == symbol->get_name());
7554                         ABG_ASSERT(main_common_sym->is_common_symbol());
7555                         ABG_ASSERT(symbol.get() != main_common_sym.get());
7556                         main_common_sym->add_common_instance(symbol);
7557                       }
7558                   }
7559                 else
7560                   {
7561                     GElf_Addr symbol_value =
7562                       maybe_adjust_et_rel_sym_addr_to_abs_addr(sym);
7563                     addr_elf_symbol_sptr_map_type::const_iterator it =
7564                       var_addr_sym_map_->find(symbol_value);
7565                     if (it == var_addr_sym_map_->end())
7566                       (*var_addr_sym_map_)[symbol_value] = symbol;
7567                     else
7568                       it->second->get_main_symbol()->add_alias(symbol);
7569                   }
7570               }
7571             else if (load_undefined_var_map && !symbol->is_defined())
7572               {
7573                 string_elf_symbols_map_type::iterator it =
7574                   undefined_var_syms_->find(symbol->get_name());
7575                 if (it == undefined_var_syms_->end())
7576                   {
7577                     (*undefined_var_syms_)[symbol->get_name()] = elf_symbols();
7578                     it = undefined_var_syms_->find(symbol->get_name());
7579                   }
7580                 it->second.push_back(symbol);
7581               }
7582           }
7583       }
7584     return true;
7585   }
7586
7587   /// Try reading the first __ksymtab section entry as if it is in the
7588   /// pre-v4_19 format and lookup a symbol from the .symbol section to
7589   /// see if that succeeds.  If it does, then we can assume the
7590   /// __ksymtab section is in the pre-v4_19 format.
7591   ///
7592   /// @return the symbol resulting from the lookup of the symbol
7593   /// address we got from reading the first entry of the ksymtab
7594   /// section assuming the pre-v4.19 format.  If nil, it means the
7595   /// __ksymtab section is not in the pre-v4.19 format.
7596   elf_symbol_sptr
7597   try_reading_first_ksymtab_entry_using_pre_v4_19_format() const
7598   {
7599     Elf_Scn *section = find_any_ksymtab_section();
7600     Elf_Data *elf_data = elf_rawdata(section, 0);
7601     uint8_t *bytes = reinterpret_cast<uint8_t*>(elf_data->d_buf);
7602     bool is_big_endian = elf_architecture_is_big_endian();
7603     elf_symbol_sptr symbol;
7604     unsigned char symbol_value_size = architecture_word_size();
7605
7606     GElf_Addr symbol_address = 0, adjusted_symbol_address = 0;
7607     ABG_ASSERT(read_int_from_array_of_bytes(bytes,
7608                                             symbol_value_size,
7609                                             is_big_endian,
7610                                             symbol_address));
7611     adjusted_symbol_address = maybe_adjust_fn_sym_address(symbol_address);
7612     symbol = lookup_elf_symbol_from_address(adjusted_symbol_address);
7613     return symbol;
7614   }
7615
7616   /// Try reading the first __ksymtab section entry as if it is in the
7617   /// v4_19 format and lookup a symbol from the .symbol section to see
7618   /// if that succeeds.  If it does, then we can assume the __ksymtab
7619   /// section is in the v4_19 format.
7620   ///
7621   /// @return the symbol resulting from the lookup of the symbol
7622   /// address we got from reading the first entry of the ksymtab
7623   /// section assuming the v4.19 format.  If nil, it means the
7624   /// __ksymtab section is not in the v4.19 format.
7625   elf_symbol_sptr
7626   try_reading_first_ksymtab_entry_using_v4_19_format() const
7627   {
7628     Elf_Scn *section = find_any_ksymtab_section();
7629     Elf_Data *elf_data = elf_rawdata(section, 0);
7630     uint8_t *bytes = reinterpret_cast<uint8_t*>(elf_data->d_buf);
7631     bool is_big_endian = elf_architecture_is_big_endian();
7632     elf_symbol_sptr symbol;
7633
7634     int32_t offset = 0;
7635     const unsigned char symbol_value_size = sizeof(offset);
7636     GElf_Addr symbol_address = 0, adjusted_symbol_address = 0;
7637     ABG_ASSERT(read_int_from_array_of_bytes(bytes,
7638                                             symbol_value_size,
7639                                             is_big_endian,
7640                                             offset));
7641     GElf_Shdr mem;
7642     GElf_Shdr *section_header = gelf_getshdr(section, &mem);
7643     symbol_address = offset + section_header->sh_addr;
7644
7645     adjusted_symbol_address = maybe_adjust_fn_sym_address(symbol_address);
7646     symbol = lookup_elf_symbol_from_address(adjusted_symbol_address);
7647     return symbol;
7648   }
7649
7650   /// Try to determine the format of the __ksymtab and __ksymtab_gpl
7651   /// sections of Linux kernel modules.
7652   ///
7653   /// This is important because we need to know the format of these
7654   /// sections to be able to read from them.
7655   ///
7656   /// @return the format the __ksymtab[_gpl] sections.
7657   enum ksymtab_format
7658   get_ksymtab_format_module() const
7659   {
7660     Elf_Scn *section = find_any_ksymtab_reloc_section();
7661
7662     ABG_ASSERT(section);
7663
7664     // Libdwfl has a weird quirk where, in the process of obtaining an Elf
7665     // descriptor via dwfl_module_getelf(), it will apply all relocations it
7666     // knows how to and it will zero the relocation info after applying it. If
7667     // the .rela__ksymtab* section contained only simple (absolute) relocations,
7668     // they will have been all applied and sh_size will be 0. For arches that
7669     // support relative ksymtabs, simple relocations only appear in pre-4.19
7670     // kernel modules.
7671     GElf_Shdr section_mem;
7672     GElf_Shdr *section_shdr = gelf_getshdr(section, &section_mem);
7673     if (section_shdr->sh_size == 0)
7674       return PRE_V4_19_KSYMTAB_FORMAT;
7675
7676     bool is_relasec = (section_shdr->sh_type == SHT_RELA);
7677
7678     // If we still have a normal non-zeroed relocation section, we can guess
7679     // what format the ksymtab is in depending on what types of relocs it
7680     // contains.
7681
7682     uint64_t type;
7683     Elf_Data *section_data = elf_getdata(section, 0);
7684     if (is_relasec)
7685       {
7686         GElf_Rela rela;
7687         gelf_getrela(section_data, 0, &rela);
7688         type = GELF_R_TYPE(rela.r_info);
7689       }
7690     else
7691       {
7692         GElf_Rel rel;
7693         gelf_getrel(section_data, 0, &rel);
7694         type = GELF_R_TYPE(rel.r_info);
7695       }
7696
7697     // Sigh, I dislike the arch-dependent code here, but this seems to be a
7698     // reliable heuristic for kernel modules for now. Relative ksymtabs only
7699     // supported on x86 and arm64 as of v4.19.
7700     ksymtab_format format;
7701     switch (type)
7702       {
7703       case R_X86_64_64: // Same as R_386_32, fallthrough
7704 #ifdef HAVE_R_AARCH64_ABS64_MACRO
7705       case R_AARCH64_ABS64:
7706 #endif
7707         format = PRE_V4_19_KSYMTAB_FORMAT;
7708         break;
7709       case R_X86_64_PC32: // Same as R_386_PC32, fallthrough
7710 #ifdef HAVE_R_AARCH64_PREL32_MACRO
7711       case R_AARCH64_PREL32:
7712 #endif
7713         format = V4_19_KSYMTAB_FORMAT;
7714         break;
7715       default:
7716         // Fall back to other methods of determining the ksymtab format.
7717         format = UNDEFINED_KSYMTAB_FORMAT;
7718         break;
7719       }
7720     return format;
7721   }
7722
7723   /// Determine the format of the __ksymtab and __ksymtab_gpl
7724   /// sections.
7725   ///
7726   /// This is important because we need the know the format of these
7727   /// sections to be able to read from them.
7728   ///
7729   /// @return the format the __ksymtab[_gpl] sections.
7730   enum ksymtab_format
7731   get_ksymtab_format() const
7732   {
7733     if (!find_any_ksymtab_section())
7734       ksymtab_format_ = UNDEFINED_KSYMTAB_FORMAT;
7735     else
7736       {
7737         if (ksymtab_format_ == UNDEFINED_KSYMTAB_FORMAT)
7738           {
7739             // Since Linux kernel modules are relocatable, we can first try
7740             // using a heuristic based on relocations to guess the ksymtab format.
7741             if (is_linux_kernel_module())
7742              {
7743                ksymtab_format_ = get_ksymtab_format_module();
7744                if (ksymtab_format_ != UNDEFINED_KSYMTAB_FORMAT)
7745                   return ksymtab_format_;
7746              }
7747
7748             // If it's not a kernel module or we couldn't determine its format
7749             // with relocations, fall back to the heuristics below.
7750
7751             // OK this is a dirty little heuristic to determine the
7752             // format of the ksymtab section.
7753             //
7754             // We try to read the first ksymtab entry assuming a
7755             // pre-v4.19 format.  If that succeeds then we are in the
7756             // pr-v4.19 format.  Otherwise, try reading it assuming a
7757             // v4.19 format.  For now, we just support
7758             // PRE_V4_19_KSYMTAB_FORMAT and V4_19_KSYMTAB_FORMAT.
7759             if (try_reading_first_ksymtab_entry_using_pre_v4_19_format())
7760               ksymtab_format_ = PRE_V4_19_KSYMTAB_FORMAT;
7761             else if (try_reading_first_ksymtab_entry_using_v4_19_format())
7762               ksymtab_format_ = V4_19_KSYMTAB_FORMAT;
7763             else
7764               // If a new format emerges, then we need to add its
7765               // support above.
7766               ABG_ASSERT_NOT_REACHED;
7767           }
7768       }
7769     return ksymtab_format_;
7770   }
7771
7772   /// Getter of the size of the symbol value part of an entry of the
7773   /// ksymtab section.
7774   ///
7775   /// @return the size of the symbol value part of the entry of the
7776   /// ksymtab section.
7777   unsigned char
7778   get_ksymtab_symbol_value_size() const
7779   {
7780     unsigned char result = 0;
7781     ksymtab_format format = get_ksymtab_format();
7782     if (format == UNDEFINED_KSYMTAB_FORMAT)
7783       ;
7784     else if (format == PRE_V4_19_KSYMTAB_FORMAT)
7785       result = architecture_word_size();
7786     else if (format == V4_19_KSYMTAB_FORMAT)
7787       result = 4;
7788     else
7789       ABG_ASSERT_NOT_REACHED;
7790
7791     return result;
7792   }
7793
7794   /// Getter of the size of one entry of the ksymtab section.
7795   ///
7796   /// @return the size of one entry of the ksymtab section.
7797   unsigned char
7798   get_ksymtab_entry_size() const
7799   {
7800     if (ksymtab_entry_size_ == 0)
7801       // The entry size if 2 *  symbol_value_size.
7802       ksymtab_entry_size_ = 2 * get_ksymtab_symbol_value_size();
7803
7804     return ksymtab_entry_size_;
7805   }
7806
7807   /// Getter of the number of entries that are present in the ksymtab
7808   /// section.
7809   ///
7810   /// @return the number of entries that are present in the ksymtab
7811   /// section.
7812   size_t
7813   get_nb_ksymtab_entries() const
7814   {
7815     if (nb_ksymtab_entries_ == 0)
7816       {
7817         Elf_Scn *section = find_ksymtab_section();
7818         if (section)
7819           {
7820             GElf_Shdr header_mem;
7821             GElf_Shdr *section_header = gelf_getshdr(section, &header_mem);
7822             size_t entry_size = get_ksymtab_entry_size();
7823             ABG_ASSERT(entry_size);
7824             nb_ksymtab_entries_ = section_header->sh_size / entry_size;
7825           }
7826       }
7827     return nb_ksymtab_entries_;
7828   }
7829
7830   /// Getter of the number of entries that are present in the
7831   /// ksymtab_gpl section.
7832   ///
7833   /// @return the number of entries that are present in the
7834   /// ksymtab_gpl section.
7835   size_t
7836   get_nb_ksymtab_gpl_entries()
7837   {
7838     if (nb_ksymtab_gpl_entries_ == 0)
7839       {
7840         Elf_Scn *section = find_ksymtab_gpl_section();
7841         if (section)
7842           {
7843             GElf_Shdr header_mem;
7844             GElf_Shdr *section_header = gelf_getshdr(section, &header_mem);
7845             size_t entry_size = get_ksymtab_entry_size();
7846             ABG_ASSERT(entry_size);
7847             nb_ksymtab_gpl_entries_ = section_header->sh_size / entry_size;
7848           }
7849       }
7850     return nb_ksymtab_gpl_entries_;
7851   }
7852
7853   /// Populate the symbol map by reading exported symbols from the
7854   /// ksymtab directly.
7855   ///
7856   /// @param section the ksymtab section to read from
7857   ///
7858   /// @param exported_fns_set the set of exported functions
7859   ///
7860   /// @param exported_vars_set the set of exported variables
7861   ///
7862   /// @param nb_entries the number of ksymtab entries to read
7863   ///
7864   /// @return true upon successful completion, false otherwise.
7865   bool
7866   populate_symbol_map_from_ksymtab(Elf_Scn *section,
7867                                    address_set_sptr exported_fns_set,
7868                                    address_set_sptr exported_vars_set,
7869                                    size_t nb_entries)
7870   {
7871     // The data of the section.
7872     Elf_Data *elf_data = elf_rawdata(section, 0);
7873
7874     // An array-of-bytes view of the elf data above.  Something we can
7875     // actually program with.  Phew.
7876     uint8_t *bytes = reinterpret_cast<uint8_t*>(elf_data->d_buf);
7877
7878     // This is where to store an address of a symbol that we read from
7879     // the section.
7880     GElf_Addr symbol_address = 0, adjusted_symbol_address = 0;
7881
7882     // So the section is an array of entries.  Each entry describes a
7883     // symbol.  Each entry is made of two words.
7884     //
7885     // The first word is the address of a symbol.  The second one is
7886     // the address of a static global variable symbol which value is
7887     // the string representing the symbol name.  That string is in the
7888     // __ksymtab_strings section.  Here, we are only interested in the
7889     // first entry.
7890     //
7891     // Lets thus walk the array of entries, and let's read just the
7892     // symbol address part of each entry.
7893     bool is_big_endian = elf_architecture_is_big_endian();
7894     elf_symbol_sptr symbol;
7895     unsigned char symbol_value_size = get_ksymtab_symbol_value_size();
7896
7897     for (size_t i = 0, entry_offset = 0;
7898          i < nb_entries;
7899          ++i, entry_offset = get_ksymtab_entry_size() * i)
7900       {
7901         symbol_address = 0;
7902         ABG_ASSERT(read_int_from_array_of_bytes(&bytes[entry_offset],
7903                                                 symbol_value_size,
7904                                                 is_big_endian,
7905                                                 symbol_address));
7906
7907         // Starting from linux kernel v4.19, it can happen that the
7908         // address value read from the ksymtab[_gpl] section might
7909         // need some decoding to get the real symbol address that has
7910         // a meaning in the .symbol section.
7911         symbol_address =
7912           maybe_adjust_sym_address_from_v4_19_ksymtab(symbol_address,
7913                                                       entry_offset, section);
7914
7915         // We might also want to adjust the symbol address, depending
7916         // on if we are looking at an ET_REL, an executable or a
7917         // shared object binary.
7918         adjusted_symbol_address = maybe_adjust_fn_sym_address(symbol_address);
7919
7920         if (adjusted_symbol_address == 0)
7921           // The resulting symbol address is zero, not sure this
7922           // valid; ignore it.
7923           continue;
7924
7925         // OK now the symbol address should be in a suitable form to
7926         // be used to look the symbol up in the usual .symbol section
7927         // (aka ELF symbol table).
7928         symbol = lookup_elf_symbol_from_address(adjusted_symbol_address);
7929         if (!symbol)
7930           {
7931             adjusted_symbol_address =
7932               maybe_adjust_var_sym_address(symbol_address);
7933             symbol = lookup_elf_symbol_from_address(adjusted_symbol_address);
7934             if (!symbol)
7935               // This must be a symbol that is of type neither FUNC
7936               // (function) nor OBJECT (variable).  There are for intance,
7937               // symbols of type 'NOTYPE' in the ksymtab symbol table.  I
7938               // am not sure what those are.
7939               continue;
7940           }
7941
7942         address_set_sptr set;
7943         if (symbol->is_function())
7944           {
7945             ABG_ASSERT(lookup_elf_fn_symbol_from_address
7946                        (adjusted_symbol_address));
7947             set = exported_fns_set;
7948           }
7949         else if (symbol->is_variable())
7950           {
7951             ABG_ASSERT(lookup_elf_var_symbol_from_address
7952                        (adjusted_symbol_address));
7953             set = exported_vars_set;
7954           }
7955         else
7956           ABG_ASSERT_NOT_REACHED;
7957         set->insert(adjusted_symbol_address);
7958       }
7959     return true;
7960   }
7961
7962   /// Populate the symbol map by extracting the exported symbols from a
7963   /// ksymtab rela section.
7964   ///
7965   /// @param section the ksymtab section to read from
7966   ///
7967   /// @param exported_fns_set the set of exported functions
7968   ///
7969   /// @param exported_vars_set the set of exported variables
7970   ///
7971   /// @return true upon successful completion, false otherwise.
7972   bool
7973   populate_symbol_map_from_ksymtab_reloc(Elf_Scn *reloc_section,
7974                                          address_set_sptr exported_fns_set,
7975                                          address_set_sptr exported_vars_set)
7976   {
7977     GElf_Shdr reloc_section_mem;
7978     GElf_Shdr *reloc_section_shdr = gelf_getshdr(reloc_section,
7979                                                  &reloc_section_mem);
7980     size_t reloc_count =
7981       reloc_section_shdr->sh_size / reloc_section_shdr->sh_entsize;
7982
7983     Elf_Data *reloc_section_data = elf_getdata(reloc_section, 0);
7984
7985     bool is_relasec = (reloc_section_shdr->sh_type == SHT_RELA);
7986     elf_symbol_sptr symbol;
7987     GElf_Sym native_symbol;
7988     for (unsigned int i = 0; i < reloc_count; i++)
7989       {
7990         if (is_relasec)
7991           {
7992             GElf_Rela rela;
7993             gelf_getrela(reloc_section_data, i, &rela);
7994             symbol = lookup_elf_symbol_from_index(GELF_R_SYM(rela.r_info),
7995                                                   native_symbol);
7996           }
7997         else
7998           {
7999             GElf_Rel rel;
8000             gelf_getrel(reloc_section_data, i, &rel);
8001             symbol = lookup_elf_symbol_from_index(GELF_R_SYM(rel.r_info),
8002                                                   native_symbol);
8003           }
8004
8005         ABG_ASSERT(symbol);
8006
8007         // If the symbol is a linux string constant then ignore it.
8008         if (symbol->get_is_linux_string_cst())
8009           continue;
8010
8011         if (!symbol->is_function() && !symbol->is_variable())
8012           {
8013             if (do_log())
8014               {
8015                 if (symbol->get_type() == elf_symbol::NOTYPE_TYPE)
8016                   cerr << "skipping NOTYPE symbol "
8017                        << symbol->get_name()
8018                        << " shndx: "
8019                        << symbol->get_index()
8020                        << " @"
8021                        << elf_path()
8022                        << "\n";
8023                 else if (symbol->get_type() == elf_symbol::SECTION_TYPE)
8024                   cerr << "skipping SECTION symbol "
8025                        << "shndx: "
8026                        << symbol->get_index()
8027                        << " @"
8028                        << elf_path()
8029                        << "\n";
8030                }
8031             continue;
8032           }
8033
8034         // If we are looking at an ET_REL (relocatable) binary, then
8035         // the symbol value of native_symbol is relative to the
8036         // section that symbol is defined in.  We need to translate it
8037         // into an absolute (okay, binary-relative, rather) address.
8038         GElf_Addr symbol_address =
8039           maybe_adjust_et_rel_sym_addr_to_abs_addr (&native_symbol);
8040
8041         address_set_sptr set;
8042         if (symbol->is_function())
8043           {
8044             ABG_ASSERT(lookup_elf_fn_symbol_from_address(symbol_address));
8045             set = exported_fns_set;
8046           }
8047         else if (symbol->is_variable())
8048           {
8049             ABG_ASSERT(lookup_elf_var_symbol_from_address(symbol_address));
8050             set = exported_vars_set;
8051           }
8052         else
8053           ABG_ASSERT_NOT_REACHED;
8054         set->insert(symbol_address);
8055       }
8056     return true;
8057   }
8058
8059   /// Load a given kernel symbol table.
8060   ///
8061   /// One can thus retrieve the resulting symbols by using the
8062   /// accessors read_context::linux_exported_fn_syms(),
8063   /// read_context::linux_exported_var_syms(),
8064   /// read_context::linux_exported_gpl_fn_syms(), or
8065   /// read_context::linux_exported_gpl_var_syms().
8066   ///
8067   /// @param kind the kind of kernel symbol table to load.
8068   ///
8069   /// @return true upon successful completion, false otherwise.
8070   bool
8071   load_kernel_symbol_table(kernel_symbol_table_kind kind)
8072   {
8073     size_t nb_entries = 0;
8074     Elf_Scn *section = 0, *reloc_section = 0;
8075     address_set_sptr linux_exported_fns_set, linux_exported_vars_set;
8076
8077     switch (kind)
8078       {
8079       case KERNEL_SYMBOL_TABLE_KIND_UNDEFINED:
8080         break;
8081       case KERNEL_SYMBOL_TABLE_KIND_KSYMTAB:
8082         section = find_ksymtab_section();
8083         reloc_section = find_ksymtab_reloc_section();
8084         nb_entries = get_nb_ksymtab_entries();
8085         linux_exported_fns_set = create_or_get_linux_exported_fn_syms();
8086         linux_exported_vars_set = create_or_get_linux_exported_var_syms();
8087         break;
8088       case KERNEL_SYMBOL_TABLE_KIND_KSYMTAB_GPL:
8089         section = find_ksymtab_gpl_section();
8090         reloc_section = find_ksymtab_gpl_reloc_section();
8091         nb_entries = get_nb_ksymtab_gpl_entries();
8092         linux_exported_fns_set = create_or_get_linux_exported_gpl_fn_syms();
8093         linux_exported_vars_set = create_or_get_linux_exported_gpl_var_syms();
8094         break;
8095       }
8096
8097     if (!linux_exported_vars_set
8098         || !linux_exported_fns_set
8099         || !section
8100         || !nb_entries)
8101       return false;
8102
8103     ksymtab_format format = get_ksymtab_format();
8104
8105     // Although pre-v4.19 kernel modules can have a relocation section for the
8106     // __ksymtab section, libdwfl zeroes the rela section after applying
8107     // "simple" absolute relocations via dwfl_module_getelf(). For v4.19 and
8108     // above, we get PC-relative relocations so dwfl_module_getelf() doesn't
8109     // apply those relocations and we're safe to read the relocation section to
8110     // determine which exported symbols are in the ksymtab.
8111     if (!reloc_section || format == PRE_V4_19_KSYMTAB_FORMAT)
8112       return populate_symbol_map_from_ksymtab(section, linux_exported_fns_set,
8113                                               linux_exported_vars_set,
8114                                               nb_entries);
8115     else
8116       return populate_symbol_map_from_ksymtab_reloc(reloc_section,
8117                                                     linux_exported_fns_set,
8118                                                     linux_exported_vars_set);
8119   }
8120
8121   /// Load the special __ksymtab section. This is for linux kernel
8122   /// (module) files.
8123   ///
8124   /// @return true upon successful completion, false otherwise.
8125   bool
8126   load_ksymtab_symbols()
8127   {
8128     return load_kernel_symbol_table(KERNEL_SYMBOL_TABLE_KIND_KSYMTAB);
8129   }
8130
8131   /// Load the special __ksymtab_gpl section. This is for linux kernel
8132   /// (module) files.
8133   ///
8134   /// @return true upon successful completion, false otherwise.
8135   bool
8136   load_ksymtab_gpl_symbols()
8137   {
8138     return load_kernel_symbol_table(KERNEL_SYMBOL_TABLE_KIND_KSYMTAB_GPL);
8139   }
8140
8141   /// Load linux kernel (module) specific exported symbol sections.
8142   ///
8143   /// @return true upon successful completion, false otherwise.
8144   bool
8145   load_linux_specific_exported_symbol_maps()
8146   {
8147     bool loaded = false;
8148     if (!linux_exported_fn_syms_
8149         || !linux_exported_var_syms_)
8150       loaded |= load_ksymtab_symbols();
8151
8152     if (!linux_exported_gpl_fn_syms_
8153         || !linux_exported_gpl_var_syms_)
8154       loaded |= load_ksymtab_gpl_symbols();
8155
8156     return loaded;
8157   }
8158
8159   /// Load the maps of function symbol address -> function symbol,
8160   /// global variable symbol address -> variable symbol and also the
8161   /// maps of function and variable undefined symbols.
8162   ///
8163   /// All these maps are loaded only if they are not loaded already.
8164   ///
8165   /// @return true iff everything went fine.
8166   bool
8167   load_symbol_maps()
8168   {
8169     bool load_fun_map = !fun_addr_sym_map_ ;
8170     bool load_var_map = !var_addr_sym_map_;
8171     bool load_undefined_fun_map = !undefined_fun_syms_;
8172     bool load_undefined_var_map = !undefined_var_syms_;
8173
8174     if (!fun_syms_)
8175       fun_syms_.reset(new string_elf_symbols_map_type);
8176
8177     if (!fun_addr_sym_map_)
8178       fun_addr_sym_map_.reset(new addr_elf_symbol_sptr_map_type);
8179
8180     if (!fun_entry_addr_sym_map_ && elf_architecture_is_ppc64())
8181       fun_entry_addr_sym_map_.reset(new addr_elf_symbol_sptr_map_type);
8182
8183     if (!var_syms_)
8184       var_syms_.reset(new string_elf_symbols_map_type);
8185
8186     if (!var_addr_sym_map_)
8187       var_addr_sym_map_.reset(new addr_elf_symbol_sptr_map_type);
8188
8189     if (!undefined_fun_syms_)
8190       undefined_fun_syms_.reset(new string_elf_symbols_map_type);
8191
8192     if (!undefined_var_syms_)
8193       undefined_var_syms_.reset(new string_elf_symbols_map_type);
8194
8195     if (!options_.ignore_symbol_table)
8196       {
8197         if (load_symbol_maps_from_symtab_section(load_fun_map,
8198                                                  load_var_map,
8199                                                  load_undefined_fun_map,
8200                                                  load_undefined_var_map))
8201           {
8202             if (load_in_linux_kernel_mode() && is_linux_kernel_binary())
8203               return load_linux_specific_exported_symbol_maps();
8204             return true;
8205           }
8206         return false;
8207       }
8208     return true;
8209   }
8210
8211   /// Return true if an address is in the ".opd" section that is
8212   /// present on the ppc64 platform.
8213   ///
8214   /// @param addr the address to consider.
8215   ///
8216   /// @return true iff @p addr is designates a word that is in the
8217   /// ".opd" section.
8218   bool
8219   address_is_in_opd_section(Dwarf_Addr addr)
8220   {
8221     Elf_Scn * opd_section = find_opd_section();
8222     if (!opd_section)
8223       return false;
8224     if (address_is_in_section(addr, opd_section))
8225       return true;
8226     return false;
8227   }
8228
8229   /// Load the symbol maps if necessary.
8230   ///
8231   /// @return true iff the symbol maps has been loaded by this
8232   /// invocation.
8233   bool
8234   maybe_load_symbol_maps() const
8235   {
8236     if (!fun_addr_sym_map_
8237         || !var_addr_sym_map_
8238         || !fun_syms_
8239         || !var_syms_
8240         || !undefined_fun_syms_
8241         || !undefined_var_syms_)
8242       return const_cast<read_context*>(this)->load_symbol_maps();
8243     return false;
8244   }
8245
8246   /// Load the DT_NEEDED and DT_SONAME elf TAGS.
8247   ///
8248   void
8249   load_dt_soname_and_needed()
8250   {
8251     lookup_data_tag_from_dynamic_segment(elf_handle(), DT_NEEDED, dt_needed_);
8252
8253     vector<string> dt_tag_data;
8254     lookup_data_tag_from_dynamic_segment(elf_handle(), DT_SONAME, dt_tag_data);
8255     if (!dt_tag_data.empty())
8256       dt_soname_ = dt_tag_data[0];
8257   }
8258
8259   /// Read the string representing the architecture of the current ELF
8260   /// file.
8261   void
8262   load_elf_architecture()
8263   {
8264     if (!elf_handle())
8265       return;
8266
8267     GElf_Ehdr eh_mem;
8268     GElf_Ehdr* elf_header = gelf_getehdr(elf_handle(), &eh_mem);
8269
8270     elf_architecture_ = e_machine_to_string(elf_header->e_machine);
8271   }
8272
8273   /// Load various ELF data.
8274   ///
8275   /// This function loads ELF data that are not symbol maps or debug
8276   /// info.  That is, things like various tags, elf architecture and
8277   /// so on.
8278   void
8279   load_elf_properties()
8280   {
8281     load_dt_soname_and_needed();
8282     load_elf_architecture();
8283   }
8284
8285   /// Convert the value of the symbol address part of a post V4.19
8286   /// ksymtab entry (that contains place-relative addresses) into its
8287   /// corresponding symbol value in the .symtab section.  The value of
8288   /// the symbol in .symtab equals to addr_offset + address-of-ksymtab
8289   /// + addr.
8290   ///
8291   /// @param addr the address read from the ksymtab section.
8292   ///
8293   /// @param addr_offset the offset at which @p addr was read.
8294   ///
8295   /// @param ksymtab_section the kymstab section @p addr was read
8296   /// from.
8297   GElf_Addr
8298   maybe_adjust_sym_address_from_v4_19_ksymtab(GElf_Addr addr,
8299                                               size_t addr_offset,
8300                                               Elf_Scn *ksymtab_section) const
8301   {
8302     GElf_Addr result = addr;
8303
8304     if (get_ksymtab_format() == V4_19_KSYMTAB_FORMAT)
8305       {
8306         int32_t offset = addr;
8307         GElf_Shdr mem;
8308         GElf_Shdr *section_header = gelf_getshdr(ksymtab_section, &mem);
8309         result = offset + section_header->sh_addr + addr_offset;
8310       }
8311
8312     return result;
8313   }
8314
8315   /// This is a sub-routine of maybe_adjust_fn_sym_address and
8316   /// maybe_adjust_var_sym_address.
8317   ///
8318   /// Given an address that we got by looking at some debug
8319   /// information (e.g, a symbol's address referred to by a DWARF
8320   /// TAG), If the ELF file we are interested in is a shared library
8321   /// or an executable, then adjust the address to be coherent with
8322   /// where the executable (or shared library) is loaded.  That way,
8323   /// the address can be used to look for symbols in the executable or
8324   /// shared library.
8325   ///
8326   /// @return the adjusted address, or the same address as @p addr if
8327   /// it didn't need any adjustment.
8328   Dwarf_Addr
8329   maybe_adjust_address_for_exec_or_dyn(Dwarf_Addr addr) const
8330   {
8331     if (addr == 0)
8332       return addr;
8333
8334     GElf_Ehdr eh_mem;
8335     GElf_Ehdr *elf_header = gelf_getehdr(elf_handle(), &eh_mem);
8336
8337     if (elf_header->e_type == ET_DYN || elf_header->e_type == ET_EXEC)
8338       {
8339         Dwarf_Addr dwarf_elf_load_address = 0, elf_load_address = 0;
8340         ABG_ASSERT(get_binary_load_address(dwarf_elf_handle(),
8341                                            dwarf_elf_load_address));
8342         ABG_ASSERT(get_binary_load_address(elf_handle(),
8343                                            elf_load_address));
8344         if (dwarf_is_splitted()
8345             && (dwarf_elf_load_address != elf_load_address))
8346           // This means that in theory the DWARF and the executable are
8347           // not loaded at the same address.  And addr is meaningful
8348           // only in the context of the DWARF.
8349           //
8350           // So let's transform addr into an offset relative to where
8351           // the DWARF is loaded, and let's add that relative offset
8352           // to the load address of the executable.  That way, addr
8353           // becomes meaningful in the context of the executable and
8354           // can thus be used to compare against the address of
8355           // symbols of the executable, for instance.
8356           addr = addr - dwarf_elf_load_address + elf_load_address;
8357       }
8358
8359     return addr;
8360   }
8361
8362   /// For a relocatable (*.o) elf file, this function expects an
8363   /// absolute address, representing a function symbol.  It then
8364   /// extracts the address of the .text section from the symbol
8365   /// absolute address to get the relative address of the function
8366   /// from the beginning of the .text section.
8367   ///
8368   /// For executable or shared library, this function expects an
8369   /// address of a function symbol that was retrieved by looking at a
8370   /// DWARF "file".  The function thus adjusts the address to make it
8371   /// be meaningful in the context of the ELF file.
8372   ///
8373   /// In both cases, the address can then be compared against the
8374   /// st_value field of a function symbol from the ELF file.
8375   ///
8376   /// @param addr an adress for a function symbol that was retrieved
8377   /// from a DWARF file.
8378   ///
8379   /// @return the (possibly) adjusted address, or just @p addr if no
8380   /// adjustment took place.
8381   Dwarf_Addr
8382   maybe_adjust_fn_sym_address(Dwarf_Addr addr) const
8383   {
8384     if (addr == 0)
8385       return addr;
8386
8387     Elf* elf = elf_handle();
8388     GElf_Ehdr eh_mem;
8389     GElf_Ehdr* elf_header = gelf_getehdr(elf, &eh_mem);
8390
8391     if (elf_header->e_type == ET_REL)
8392       // We are looking at a relocatable file.  In this case, we don't
8393       // do anything because:
8394       //
8395       // 1/ the addresses from DWARF are absolute (relative to the
8396       // beginning of the relocatable file)
8397       //
8398       // 2/ The ELF symbol addresses that we store in our lookup
8399       // tables are translated from section-related to absolute as
8400       // well.  So we don't have anything to do at this point for
8401       // ET_REL files.
8402       ;
8403     else
8404       addr = maybe_adjust_address_for_exec_or_dyn(addr);
8405
8406     return addr;
8407   }
8408
8409   /// Translate a section-relative symbol address (i.e, symbol value)
8410   /// into an absolute symbol address by adding the address of the
8411   /// section the symbol belongs to, to the address value.
8412   ///
8413   /// This is useful when looking at symbol values coming from
8414   /// relocatable files (of ET_REL kind).  If the binary is not
8415   /// ET_REL, then the function does nothing and returns the input
8416   /// address unchanged.
8417   ///
8418   /// @param addr the symbol address to possibly translate.
8419   ///
8420   /// @param section the section the symbol which value is @p addr
8421   /// belongs to.
8422   ///
8423   /// @return the section-relative address, translated into an
8424   /// absolute address, if @p section is an ET_REL binary.  Otherwise,
8425   /// return @p addr, unchanged.
8426   GElf_Addr
8427   maybe_adjust_et_rel_sym_addr_to_abs_addr(GElf_Addr addr, Elf_Scn *section)
8428   {
8429     if (section == 0)
8430       return addr;
8431
8432     Elf* elf = elf_handle();
8433     GElf_Ehdr elf_header;
8434
8435     if (!gelf_getehdr(elf, &elf_header))
8436       return addr;
8437
8438     if (elf_header.e_type != ET_REL)
8439       return addr;
8440
8441     GElf_Shdr section_header;
8442     if (!gelf_getshdr(section, &section_header))
8443       return addr;
8444
8445     return addr + section_header.sh_addr;
8446   }
8447
8448   /// Translate a section-relative symbol address (i.e, symbol value)
8449   /// into an absolute symbol address by adding the address of the
8450   /// section the symbol belongs to, to the address value.
8451   ///
8452   /// This is useful when looking at symbol values coming from
8453   /// relocatable files (of ET_REL kind).  If the binary is not
8454   /// ET_REL, then the function does nothing and returns the input
8455   /// address unchanged.
8456   ///
8457   /// @param sym the symbol whose address to possibly needs to be
8458   /// translated.
8459   ///
8460   /// @return the section-relative address, translated into an
8461   /// absolute address, if @p sym is from an ET_REL binary.
8462   /// Otherwise, return the address of @p sym, unchanged.
8463   GElf_Addr
8464   maybe_adjust_et_rel_sym_addr_to_abs_addr(GElf_Sym *sym)
8465   {
8466     Elf_Scn *symbol_section = elf_getscn(elf_handle(), sym->st_shndx);
8467     ABG_ASSERT(symbol_section);
8468     GElf_Addr result = sym->st_value;
8469     result = maybe_adjust_et_rel_sym_addr_to_abs_addr(result, symbol_section);
8470     return result;
8471   }
8472
8473   /// Test if a given address is in a given section.
8474   ///
8475   /// @param addr the address to consider.
8476   ///
8477   /// @param section the section to consider.
8478   bool
8479   address_is_in_section(Dwarf_Addr addr, Elf_Scn* section) const
8480   {
8481     if (!section)
8482       return false;
8483
8484     GElf_Shdr sheader_mem;
8485     GElf_Shdr* sheader = gelf_getshdr(section, &sheader_mem);
8486
8487     if (sheader->sh_addr <= addr && addr <= sheader->sh_addr + sheader->sh_size)
8488       return true;
8489
8490     return false;
8491   }
8492
8493   /// Get the section which a global variable address comes from.
8494   ///
8495   /// @param var_addr the address for the variable.
8496   ///
8497   /// @return the ELF section the @p var_addr comes from, or nil if no
8498   /// section was found for that variable address.
8499   Elf_Scn*
8500   get_data_section_for_variable_address(Dwarf_Addr var_addr) const
8501   {
8502     // There are several potential 'data sections" from which a
8503     // variable address can come from: .data, .data1 and .rodata.
8504     // Let's try to try them all in sequence.
8505
8506     Elf_Scn* data_scn = bss_section();
8507     if (!address_is_in_section(var_addr, data_scn))
8508       {
8509         data_scn = data_section();
8510         if (!address_is_in_section(var_addr, data_scn))
8511           {
8512             data_scn = data1_section();
8513             if (!address_is_in_section(var_addr, data_scn))
8514               {
8515                 data_scn = rodata_section();
8516                 if (!address_is_in_section(var_addr, data_scn))
8517                   return 0;
8518               }
8519           }
8520       }
8521     return data_scn;
8522   }
8523
8524   /// For a relocatable (*.o) elf file, this function expects an
8525   /// absolute address, representing a global variable symbol.  It
8526   /// then extracts the address of the {.data,.data1,.rodata,.bss}
8527   /// section from the symbol absolute address to get the relative
8528   /// address of the variable from the beginning of the data section.
8529   ///
8530   /// For executable or shared library, this function expects an
8531   /// address of a variable symbol that was retrieved by looking at a
8532   /// DWARF "file".  The function thus adjusts the address to make it
8533   /// be meaningful in the context of the ELF file.
8534   ///
8535   /// In both cases, the address can then be compared against the
8536   /// st_value field of a function symbol from the ELF file.
8537   ///
8538   /// @param addr an address for a global variable symbol that was
8539   /// retrieved from a DWARF file.
8540   ///
8541   /// @return the (possibly) adjusted address, or just @p addr if no
8542   /// adjustment took place.
8543   Dwarf_Addr
8544   maybe_adjust_var_sym_address(Dwarf_Addr addr) const
8545   {
8546     Elf* elf = elf_handle();
8547     GElf_Ehdr eh_mem;
8548     GElf_Ehdr* elf_header = gelf_getehdr(elf, &eh_mem);
8549
8550     if (elf_header->e_type == ET_REL)
8551       // We are looking at a relocatable file.  In this case, we don't
8552       // do anything because:
8553       //
8554       // 1/ the addresses from DWARF are absolute (relative to the
8555       // beginning of the relocatable file)
8556       //
8557       // 2/ The ELF symbol addresses that we store in our lookup
8558       // tables are translated from section-related to absolute as
8559       // well.  So we don't have anything to do at this point for
8560       // ET_REL files.
8561       ;
8562     else
8563       addr = maybe_adjust_address_for_exec_or_dyn(addr);
8564
8565     return addr;
8566   }
8567
8568   /// Get the first exported function address in the set of addresses
8569   /// referred to by the DW_AT_ranges attribute of a given DIE.
8570   ///
8571   /// @param die the DIE we are considering.
8572   ///
8573   /// @param address output parameter.  This is set to the first
8574   /// address found in the sequence pointed to by the DW_AT_ranges
8575   /// attribute found on the DIE @p die, iff the function returns
8576   /// true.  Otherwise, no value is set into this output parameter.
8577   ///
8578   /// @return true iff the DIE @p die does have a DW_AT_ranges
8579   /// attribute and an address of an exported function was found in
8580   /// its sequence value.
8581   bool
8582   get_first_exported_fn_address_from_DW_AT_ranges(Dwarf_Die* die,
8583                                                   Dwarf_Addr& address) const
8584   {
8585     Dwarf_Addr base;
8586     Dwarf_Addr end_addr;
8587     ptrdiff_t offset = 0;
8588
8589     do
8590       {
8591         Dwarf_Addr addr, fn_addr;
8592         if ((offset = dwarf_ranges(die, offset, &base, &addr, &end_addr)) >= 0)
8593           {
8594             fn_addr = maybe_adjust_fn_sym_address(addr);
8595             if (function_symbol_is_exported(fn_addr))
8596               {
8597                 address = fn_addr;
8598                 return true;
8599               }
8600           }
8601       } while (offset > 0);
8602     return false;
8603   }
8604
8605   /// Get the address of the function.
8606   ///
8607   /// The address of the function is considered to be the value of the
8608   /// DW_AT_low_pc attribute, possibly adjusted (in relocatable files
8609   /// only) to not point to an absolute address anymore, but rather to
8610   /// the address of the function inside the .text segment.
8611   ///
8612   /// @param function_die the die of the function to consider.
8613   ///
8614   /// @param address the resulting address iff the function returns
8615   /// true.
8616   ///
8617   /// @return true if the function address was found.
8618   bool
8619   get_function_address(Dwarf_Die* function_die, Dwarf_Addr& address) const
8620   {
8621     if (!die_address_attribute(function_die, DW_AT_low_pc, address))
8622       // So no DW_AT_low_pc was found.  Let's see if the function DIE
8623       // has got a DW_AT_ranges attribute instead.  If it does, the
8624       // first address of the set of addresses represented by the
8625       // value of that DW_AT_ranges represents the function (symbol)
8626       // address we are looking for.
8627       if (!get_first_exported_fn_address_from_DW_AT_ranges(function_die,
8628                                                            address))
8629         return false;
8630
8631     address = maybe_adjust_fn_sym_address(address);
8632     return true;
8633   }
8634
8635   /// Get the address of the global variable.
8636   ///
8637   /// The address of the global variable is considered to be the value
8638   /// of the DW_AT_location attribute, possibly adjusted (in
8639   /// relocatable files only) to not point to an absolute address
8640   /// anymore, but rather to the address of the global variable inside
8641   /// the data segment.
8642   ///
8643   /// @param variable_die the die of the function to consider.
8644   ///
8645   /// @param address the resulting address iff this function returns
8646   /// true.
8647   ///
8648   /// @return true if the variable address was found.
8649   bool
8650   get_variable_address(Dwarf_Die*       variable_die,
8651                        Dwarf_Addr&      address) const
8652   {
8653     bool is_tls_address = false;
8654     if (!die_location_address(variable_die, address, is_tls_address))
8655       return false;
8656     if (!is_tls_address)
8657       address = maybe_adjust_var_sym_address(address);
8658     return true;
8659   }
8660
8661   /// Tests if a suppression specification can match ABI artifacts
8662   /// coming from the binary being analyzed.
8663   ///
8664   /// This tests if the suppression matches the soname of and binary
8665   /// name of the ELF binary being analyzed.
8666   ///
8667   /// @param s the suppression specification to consider.
8668   bool
8669   suppression_can_match(const suppr::suppression_base& s) const
8670   {
8671     if (s.priv_->matches_soname(dt_soname())
8672         && s.priv_->matches_binary_name(elf_path()))
8673       return true;
8674     return false;
8675   }
8676
8677   /// Test whether if a given function suppression matches a function
8678   /// designated by a regular expression that describes its linkage
8679   /// name (symbol name).
8680   ///
8681   /// @param s the suppression specification to evaluate to see if it
8682   /// matches a given function linkage name
8683   ///
8684   /// @param fn_linkage_name the linkage name of the function of interest.
8685   ///
8686   /// @return true iff the suppression specification @p s matches the
8687   /// function whose linkage name is @p fn_linkage_name.
8688   bool
8689   suppression_matches_function_sym_name(const suppr::function_suppression_sptr& s,
8690                                         const string& fn_linkage_name) const
8691   {
8692     if (!s)
8693       return false;
8694     return suppression_matches_function_sym_name(*s,fn_linkage_name);
8695   }
8696
8697   /// Test whether if a given function suppression matches a function
8698   /// designated by a regular expression that describes its linkage
8699   /// name (symbol name).
8700   ///
8701   /// @param s the suppression specification to evaluate to see if it
8702   /// matches a given function linkage name
8703   ///
8704   /// @param fn_linkage_name the linkage name of the function of interest.
8705   ///
8706   /// @return true iff the suppression specification @p s matches the
8707   /// function whose linkage name is @p fn_linkage_name.
8708   bool
8709   suppression_matches_function_sym_name(const suppr::function_suppression& s,
8710                                         const string& fn_linkage_name) const
8711   {
8712     if (!suppression_can_match(s))
8713       return false;
8714
8715     return suppr::suppression_matches_function_sym_name(s, fn_linkage_name);
8716   }
8717
8718   /// Test whether if a given function suppression matches a function
8719   /// designated by a regular expression that describes its name.
8720   ///
8721   /// @param s the suppression specification to evaluate to see if it
8722   /// matches a given function name.
8723   ///
8724   /// @param fn_name the name of the function of interest.  Note that
8725   /// this name must be *non* qualified.
8726   ///
8727   /// @return true iff the suppression specification @p s matches the
8728   /// function whose name is @p fn_name.
8729   bool
8730   suppression_matches_function_name(const suppr::function_suppression_sptr& s,
8731                                     const string& fn_name) const
8732   {
8733     if (!s)
8734       return false;
8735     return suppression_matches_function_name(*s, fn_name);
8736   }
8737
8738   /// Test whether if a given function suppression matches a function
8739   /// designated by a regular expression that describes its name.
8740   ///
8741   /// @param s the suppression specification to evaluate to see if it
8742   /// matches a given function name.
8743   ///
8744   /// @param fn_name the name of the function of interest.  Note that
8745   /// this name must be *non* qualified.
8746   ///
8747   /// @return true iff the suppression specification @p s matches the
8748   /// function whose name is @p fn_name.
8749   bool
8750   suppression_matches_function_name(const suppr::function_suppression& s,
8751                                     const string& fn_name) const
8752   {
8753     if (!suppression_can_match(s))
8754       return false;
8755
8756     return suppr::suppression_matches_function_name(s, fn_name);
8757   }
8758
8759   /// Test whether if a given variable suppression specification
8760   /// matches a variable denoted by its name.
8761   ///
8762   /// @param s the variable suppression specification to consider.
8763   ///
8764   /// @param var_name the name of the variable to consider.
8765   ///
8766   /// @return true iff the suppression specification @p s matches the
8767   /// variable whose name is @p var_name.
8768   bool
8769   suppression_matches_variable_name(const suppr::variable_suppression& s,
8770                                     const string& var_name) const
8771   {
8772     if (!suppression_can_match(s))
8773       return false;
8774
8775     return suppr::suppression_matches_variable_name(s, var_name);
8776   }
8777
8778   /// Test whether if a given variable suppression specification
8779   /// matches a variable denoted by its linkage name.
8780   ///
8781   /// @param s the variable suppression specification to consider.
8782   ///
8783   /// @param var_linkage_name the linkage name of the variable to consider.
8784   ///
8785   /// @return true iff variable suppression specification @p s matches
8786   /// the variable denoted by linkage name @p var_linkage_name.
8787   bool
8788   suppression_matches_variable_sym_name(const suppr::variable_suppression& s,
8789                                         const string& var_linkage_name) const
8790   {
8791     if (!suppression_can_match(s))
8792       return false;
8793
8794     return suppr::suppression_matches_variable_sym_name(s, var_linkage_name);
8795   }
8796
8797   /// Test if a given type suppression specification matches a type
8798   /// designated by its name and location.
8799   ///
8800   /// @param s the suppression specification to consider.
8801   ///
8802   /// @param type_name the fully qualified type name to consider.
8803   ///
8804   /// @param type_location the type location to consider.
8805   ///
8806   /// @return true iff the type suppression specification matches a
8807   /// type of a given name and location.
8808   bool
8809   suppression_matches_type_name_or_location(const suppr::type_suppression& s,
8810                                             const string& type_name,
8811                                             const location& type_location) const
8812   {
8813     if (!suppression_can_match(s))
8814       return false;
8815
8816     return suppr::suppression_matches_type_name_or_location(s, type_name,
8817                                                             type_location);
8818   }
8819
8820   /// Test if a type suppression specification matches the name of a
8821   /// type within a given scope.
8822   ///
8823   /// @param s the type suppression specification to consider.
8824   ///
8825   /// @param type_scope the type scope to consider.
8826   ///
8827   /// @param type the type to consider.
8828   ///
8829   /// @return true iff the type suppression specification matches a
8830   /// the name of type @p type.
8831   bool
8832   suppression_matches_type_name(const suppr::type_suppression&  s,
8833                                 const scope_decl*               type_scope,
8834                                 const type_base_sptr&           type) const
8835   {
8836     if (!suppression_can_match(s))
8837       return false;
8838     return suppr::suppression_matches_type_name(s, type_scope, type);
8839   }
8840
8841   /// Getter of the exported decls builder object.
8842   ///
8843   /// @return the exported decls builder.
8844   corpus::exported_decls_builder*
8845   exported_decls_builder()
8846   {return exported_decls_builder_;}
8847
8848   /// Setter of the exported decls builder object.
8849   ///
8850   /// Note that this @ref read_context is not responsible for the live
8851   /// time of the exported_decls_builder object.  The corpus is.
8852   ///
8853   /// @param b the new builder.
8854   void
8855   exported_decls_builder(corpus::exported_decls_builder* b)
8856   {exported_decls_builder_ = b;}
8857
8858   /// Getter of the "load_all_types" flag.  This flag tells if all the
8859   /// types (including those not reachable by public declarations) are
8860   /// to be read and represented in the final ABI corpus.
8861   ///
8862   /// @return the load_all_types flag.
8863   bool
8864   load_all_types() const
8865   {return options_.load_all_types;}
8866
8867   /// Setter of the "load_all_types" flag.  This flag tells if all the
8868   /// types (including those not reachable by public declarations) are
8869   /// to be read and represented in the final ABI corpus.
8870   ///
8871   /// @param f the new load_all_types flag.
8872   void
8873   load_all_types(bool f)
8874   {options_.load_all_types = f;}
8875
8876   bool
8877   load_in_linux_kernel_mode() const
8878   {return options_.load_in_linux_kernel_mode;}
8879
8880   void
8881   load_in_linux_kernel_mode(bool f)
8882   {options_.load_in_linux_kernel_mode = f;}
8883
8884   /// Guess if the current binary is a Linux Kernel or a Linux Kernel module.
8885   ///
8886   /// To guess that, the function looks for the presence of the
8887   /// special "__ksymtab_strings" section in the binary.
8888   ///
8889   bool
8890   is_linux_kernel_binary() const
8891   {
8892     return find_section(elf_handle(), "__ksymtab_strings", SHT_PROGBITS)
8893            || is_linux_kernel_module();
8894   }
8895
8896   /// Guess if the current binary is a Linux Kernel module.
8897   ///
8898   /// To guess that, the function looks for the presence of the special
8899   /// ".modinfo" and ".gnu.linkonce.this_module" sections in the binary.
8900   ///
8901   bool
8902   is_linux_kernel_module() const
8903   {
8904     return find_section(elf_handle(), ".modinfo", SHT_PROGBITS)
8905            && find_section(elf_handle(), ".gnu.linkonce.this_module", SHT_PROGBITS);
8906   }
8907
8908   /// Getter of the "show_stats" flag.
8909   ///
8910   /// This flag tells if we should emit statistics about various
8911   /// internal stuff.
8912   ///
8913   /// @return the value of the flag.
8914   bool
8915   show_stats() const
8916   {return options_.show_stats;}
8917
8918   /// Setter of the "show_stats" flag.
8919   ///
8920   /// This flag tells if we should emit statistics about various
8921   /// internal stuff.
8922   ///
8923   /// @param f the value of the flag.
8924   void
8925   show_stats(bool f)
8926   {options_.show_stats = f;}
8927
8928   /// Getter of the "do_log" flag.
8929   ///
8930   /// This flag tells if we should log about various internal
8931   /// details.
8932   ///
8933   /// return the "do_log" flag.
8934   bool
8935   do_log() const
8936   {return options_.do_log;}
8937
8938   /// Setter of the "do_log" flag.
8939   ///
8940   /// This flag tells if we should log about various internal details.
8941   ///
8942   /// @param f the new value of the flag.
8943   void
8944   do_log(bool f)
8945   {options_.do_log = f;}
8946
8947   /// If a given function decl is suitable for the set of exported
8948   /// functions of the current corpus, this function adds it to that
8949   /// set.
8950   ///
8951   /// @param fn the function to consider for inclusion into the set of
8952   /// exported functions of the current corpus.
8953   void
8954   maybe_add_fn_to_exported_decls(function_decl* fn)
8955   {
8956     if (fn)
8957       if (corpus::exported_decls_builder* b = exported_decls_builder())
8958         b->maybe_add_fn_to_exported_fns(fn);
8959   }
8960
8961   /// If a given variable decl is suitable for the set of exported
8962   /// variables of the current corpus, this variable adds it to that
8963   /// set.
8964   ///
8965   /// @param fn the variable to consider for inclusion into the set of
8966   /// exported variables of the current corpus.
8967   void
8968   maybe_add_var_to_exported_decls(var_decl* var)
8969   {
8970     if (var)
8971       if (corpus::exported_decls_builder* b = exported_decls_builder())
8972         b->maybe_add_var_to_exported_vars(var);
8973   }
8974
8975   /// Walk the DIEs under a given die and for each child, populate the
8976   /// die -> parent map to record the child -> parent relationship
8977   /// that
8978   /// exists between the child and the given die.
8979   ///
8980   /// The function also builds the vector of places where units are
8981   /// imported.
8982   ///
8983   /// This is done recursively as for each child DIE, this function
8984   /// walks its children as well.
8985   ///
8986   /// @param die the DIE whose children to walk recursively.
8987   ///
8988   /// @param source where the DIE @p die comes from.
8989   ///
8990   /// @param imported_units a vector containing all the offsets of the
8991   /// points where unit have been imported, under @p die.
8992   void
8993   build_die_parent_relations_under(Dwarf_Die*                   die,
8994                                    die_source                   source,
8995                                    imported_unit_points_type &  imported_units)
8996   {
8997     if (!die)
8998       return;
8999
9000     offset_offset_map_type& parent_of = die_parent_map(source);
9001
9002     Dwarf_Die child;
9003     if (dwarf_child(die, &child) != 0)
9004       return;
9005
9006     do
9007       {
9008         parent_of[dwarf_dieoffset(&child)] = dwarf_dieoffset(die);
9009         if (dwarf_tag(&child) == DW_TAG_imported_unit)
9010           {
9011             Dwarf_Die imported_unit;
9012             if (die_die_attribute(&child, DW_AT_import, imported_unit))
9013               {
9014                 die_source imported_unit_die_source = NO_DEBUG_INFO_DIE_SOURCE;
9015                 ABG_ASSERT(get_die_source(imported_unit, imported_unit_die_source));
9016                 imported_units.push_back
9017                   (imported_unit_point(dwarf_dieoffset(&child),
9018                                        imported_unit,
9019                                        imported_unit_die_source));
9020               }
9021           }
9022         build_die_parent_relations_under(&child, source, imported_units);
9023       }
9024     while (dwarf_siblingof(&child, &child) == 0);
9025
9026   }
9027
9028   /// Determine if we do have to build a DIE -> parent map, depending
9029   /// on a given language.
9030   ///
9031   /// Some languages like C++, Ada etc, do have the concept of
9032   /// namespace and yet, the DIE data structure doesn't provide us
9033   /// with a way to get the parent namespace of a given DIE.  So for
9034   /// those languages, we need to build a DIE -> parent map so that we
9035   /// can get the namespace DIE (or more generally the scope DIE) of a given
9036   /// DIE as we need it.
9037   ///
9038   /// But then some more basic languages like C or assembly don't have
9039   /// that need.
9040   ///
9041   /// This function, depending on the language, tells us if we need to
9042   /// build the DIE -> parent map or not.
9043   ///
9044   /// @param lang the language to consider.
9045   ///
9046   /// @return true iff we need to build the DIE -> parent map for this
9047   /// language.
9048   bool
9049   do_we_build_die_parent_maps(translation_unit::language lang)
9050   {
9051     if (is_c_language(lang))
9052       return false;
9053
9054     switch (lang)
9055       {
9056       case translation_unit::LANG_UNKNOWN:
9057 #ifdef HAVE_DW_LANG_Mips_Assembler_enumerator
9058       case translation_unit::LANG_Mips_Assembler:
9059 #endif
9060         return false;
9061       default:
9062         break;
9063       }
9064     return true;
9065   }
9066
9067   /// Walk all the DIEs accessible in the debug info (and in the
9068   /// alternate debug info as well) and build maps representing the
9069   /// relationship DIE -> parent.  That is, make it so that we can get
9070   /// the parent for a given DIE.
9071   ///
9072   /// Note that the goal of this map is to be able to get the parent
9073   /// of a given DIE. This is to mainly to handle namespaces.  For instance,
9074   /// when we get a DIE of a type, and we want to build an internal
9075   /// representation for it, we need to get its fully qualified name.
9076   /// For that, we need to know what is the parent DIE of that type
9077   /// DIE, so that we can know what the namespace of that type is.
9078   ///
9079   /// Note that as the C language doesn't have namespaces (all types
9080   /// are defined in the same global namespace), this function doesn't
9081   /// build the DIE -> parent map if the current translation unit
9082   /// comes from C.  This saves time on big C ELF files with a lot of
9083   /// DIEs.
9084   void
9085   build_die_parent_maps()
9086   {
9087     bool we_do_have_to_build_die_parent_map = false;
9088     uint8_t address_size = 0;
9089     size_t header_size = 0;
9090     // Get the DIE of the current translation unit, look at it to get
9091     // its language. If that language is in C, then all types are in
9092     // the global namespace so we don't need to build the DIE ->
9093     // parent map.  So we dont build it in that case.
9094     for (Dwarf_Off offset = 0, next_offset = 0;
9095          (dwarf_next_unit(dwarf(), offset, &next_offset, &header_size,
9096                           NULL, NULL, &address_size, NULL, NULL, NULL) == 0);
9097          offset = next_offset)
9098       {
9099         Dwarf_Off die_offset = offset + header_size;
9100         Dwarf_Die cu;
9101         if (!dwarf_offdie(dwarf(), die_offset, &cu))
9102           continue;
9103
9104         uint64_t l = 0;
9105         die_unsigned_constant_attribute(&cu, DW_AT_language, l);
9106         translation_unit::language lang = dwarf_language_to_tu_language(l);
9107         if (do_we_build_die_parent_maps(lang))
9108           we_do_have_to_build_die_parent_map = true;
9109       }
9110
9111     if (!we_do_have_to_build_die_parent_map)
9112       return;
9113
9114     // Build the DIE -> parent relation for DIEs coming from the
9115     // .debug_info section in the alternate debug info file.
9116     die_source source = ALT_DEBUG_INFO_DIE_SOURCE;
9117     for (Dwarf_Off offset = 0, next_offset = 0;
9118          (dwarf_next_unit(alt_dwarf(), offset, &next_offset, &header_size,
9119                           NULL, NULL, &address_size, NULL, NULL, NULL) == 0);
9120          offset = next_offset)
9121       {
9122         Dwarf_Off die_offset = offset + header_size;
9123         Dwarf_Die cu;
9124         if (!dwarf_offdie(alt_dwarf(), die_offset, &cu))
9125           continue;
9126         cur_tu_die(&cu);
9127
9128         imported_unit_points_type& imported_units =
9129           tu_die_imported_unit_points_map(source)[die_offset] =
9130           imported_unit_points_type();
9131         build_die_parent_relations_under(&cu, source, imported_units);
9132       }
9133
9134     // Build the DIE -> parent relation for DIEs coming from the
9135     // .debug_info section of the main debug info file.
9136     source = PRIMARY_DEBUG_INFO_DIE_SOURCE;
9137     address_size = 0;
9138     header_size = 0;
9139     for (Dwarf_Off offset = 0, next_offset = 0;
9140          (dwarf_next_unit(dwarf(), offset, &next_offset, &header_size,
9141                           NULL, NULL, &address_size, NULL, NULL, NULL) == 0);
9142          offset = next_offset)
9143       {
9144         Dwarf_Off die_offset = offset + header_size;
9145         Dwarf_Die cu;
9146         if (!dwarf_offdie(dwarf(), die_offset, &cu))
9147           continue;
9148         cur_tu_die(&cu);
9149         imported_unit_points_type& imported_units =
9150           tu_die_imported_unit_points_map(source)[die_offset] =
9151           imported_unit_points_type();
9152         build_die_parent_relations_under(&cu, source, imported_units);
9153       }
9154
9155     // Build the DIE -> parent relation for DIEs coming from the
9156     // .debug_types section.
9157     source = TYPE_UNIT_DIE_SOURCE;
9158     address_size = 0;
9159     header_size = 0;
9160     uint64_t type_signature = 0;
9161     Dwarf_Off type_offset;
9162     for (Dwarf_Off offset = 0, next_offset = 0;
9163          (dwarf_next_unit(dwarf(), offset, &next_offset, &header_size,
9164                           NULL, NULL, &address_size, NULL,
9165                           &type_signature, &type_offset) == 0);
9166          offset = next_offset)
9167       {
9168         Dwarf_Off die_offset = offset + header_size;
9169         Dwarf_Die cu;
9170
9171         if (!dwarf_offdie_types(dwarf(), die_offset, &cu))
9172           continue;
9173         cur_tu_die(&cu);
9174         imported_unit_points_type& imported_units =
9175           tu_die_imported_unit_points_map(source)[die_offset] =
9176           imported_unit_points_type();
9177         build_die_parent_relations_under(&cu, source, imported_units);
9178       }
9179   }
9180 };// end class read_context.
9181
9182 static type_or_decl_base_sptr
9183 build_ir_node_from_die(read_context&    ctxt,
9184                        Dwarf_Die*       die,
9185                        scope_decl*      scope,
9186                        bool             called_from_public_decl,
9187                        size_t           where_offset,
9188                        bool             is_required_decl_spec = false);
9189
9190 static type_or_decl_base_sptr
9191 build_ir_node_from_die(read_context&    ctxt,
9192                        Dwarf_Die*       die,
9193                        bool             called_from_public_decl,
9194                        size_t           where_offset);
9195
9196 static class_decl_sptr
9197 add_or_update_class_type(read_context&  ctxt,
9198                          Dwarf_Die*     die,
9199                          scope_decl*    scope,
9200                          bool           is_struct,
9201                          class_decl_sptr  klass,
9202                          bool           called_from_public_decl,
9203                          size_t         where_offset);
9204
9205 static union_decl_sptr
9206 add_or_update_union_type(read_context&  ctxt,
9207                          Dwarf_Die*     die,
9208                          scope_decl*    scope,
9209                          union_decl_sptr  union_type,
9210                          bool           called_from_public_decl,
9211                          size_t         where_offset);
9212
9213 static decl_base_sptr
9214 build_ir_node_for_void_type(read_context& ctxt);
9215
9216 static function_decl_sptr
9217 build_function_decl(read_context&       ctxt,
9218                     Dwarf_Die*          die,
9219                     size_t              where_offset,
9220                     function_decl_sptr  fn);
9221
9222 static bool
9223 function_is_suppressed(const read_context& ctxt,
9224                        const scope_decl* scope,
9225                        Dwarf_Die *function_die);
9226
9227 static function_decl_sptr
9228 build_or_get_fn_decl_if_not_suppressed(read_context&    ctxt,
9229                                        scope_decl       *scope,
9230                                        Dwarf_Die        *die,
9231                                        size_t   where_offset,
9232                                        function_decl_sptr f = function_decl_sptr());
9233
9234 static var_decl_sptr
9235 build_var_decl(read_context&    ctxt,
9236                Dwarf_Die        *die,
9237                size_t           where_offset,
9238                var_decl_sptr    result = var_decl_sptr());
9239
9240 static var_decl_sptr
9241 build_or_get_var_decl_if_not_suppressed(read_context&   ctxt,
9242                                         scope_decl      *scope,
9243                                         Dwarf_Die       *die,
9244                                         size_t  where_offset,
9245                                         var_decl_sptr   res = var_decl_sptr(),
9246                                         bool is_required_decl_spec = false);
9247 static bool
9248 variable_is_suppressed(const read_context& ctxt,
9249                        const scope_decl* scope,
9250                        Dwarf_Die *variable_die,
9251                        bool is_required_decl_spec = false);
9252
9253 static void
9254 finish_member_function_reading(Dwarf_Die*                die,
9255                                const function_decl_sptr& f,
9256                                const class_or_union_sptr& klass,
9257                                read_context&             ctxt);
9258
9259 /// Setter of the debug info root path for a dwarf reader context.
9260 ///
9261 /// @param ctxt the dwarf reader context to consider.
9262 ///
9263 /// @param path the new debug info root path.  This must be a pointer to a
9264 /// character string which life time should be greater than the life
9265 /// time of the read context.
9266 void
9267 set_debug_info_root_path(read_context& ctxt, char** path)
9268 {ctxt.offline_callbacks()->debuginfo_path = path;}
9269
9270 /// Setter of the debug info root path for a dwarf reader context.
9271 ///
9272 /// @param ctxt the dwarf reader context to consider.
9273 ///
9274 /// @return a pointer to the debug info root path.
9275 ///
9276 /// time of the read context.
9277 char**
9278 get_debug_info_root_path(read_context& ctxt)
9279 {return ctxt.offline_callbacks()->debuginfo_path;}
9280
9281 /// Getter of the "show_stats" flag.
9282 ///
9283 /// This flag tells if we should emit statistics about various
9284 /// internal stuff.
9285 ///
9286 /// @param ctx the read context to consider for this flag.
9287 ///
9288 /// @return the value of the flag.
9289 bool
9290 get_show_stats(read_context& ctxt)
9291 {return ctxt.show_stats();}
9292
9293 /// Setter of the "show_stats" flag.
9294 ///
9295 /// This flag tells if we should emit statistics about various
9296 /// internal stuff.
9297 ///
9298 /// @param ctxt the read context to consider for this flag.
9299 ///
9300 /// @param f the value of the flag.
9301 void
9302 set_show_stats(read_context& ctxt, bool f)
9303 {ctxt.show_stats(f);}
9304
9305 /// Setter of the "do_log" flag.
9306 ///
9307 /// This flag tells if we should emit verbose logs for various
9308 /// internal things related to DWARF reading.
9309 ///
9310 /// @param ctxt the DWARF reading context to consider.
9311 ///
9312 /// @param f the new value of the flag.
9313 void
9314 set_do_log(read_context& ctxt, bool f)
9315 {ctxt.do_log(f);}
9316
9317 /// Setter of the "set_ignore_symbol_table" flag.
9318 ///
9319 /// This flag tells if we should load information about ELF symbol
9320 /// tables.  Not loading the symbol tables is a speed optimization
9321 /// that is done when the set of symbols we care about is provided
9322 /// off-hand.  This is the case when we are supposed to analyze a
9323 /// Linux kernel binary.  In that case, because we have the white list
9324 /// of functions/variable symbols we care about, we don't need to
9325 /// analyze the symbol table; things are thus faster in that case.
9326 ///
9327 /// By default, the symbol table is analyzed so this boolean is set to
9328 /// false.
9329 ///
9330 /// @param ctxt the read context to consider.
9331 ///
9332 /// @param f the new value of the flag.
9333 void
9334 set_ignore_symbol_table(read_context &ctxt, bool f)
9335 {ctxt.options_.ignore_symbol_table = f;}
9336
9337 /// Getter of the "set_ignore_symbol_table" flag.
9338 ///
9339 /// This flag tells if we should load information about ELF symbol
9340 /// tables.  Not loading the symbol tables is a speed optimization
9341 /// that is done when the set of symbols we care about is provided
9342 /// off-hand.  This is the case when we are supposed to analyze a
9343 /// Linux kernel binary.  In that case, because we have the white list
9344 /// of functions/variable symbols we care about, we don't need to
9345 /// analyze the symbol table; things are thus faster in that case.
9346 ///
9347 /// By default, the symbol table is analyzed so this boolean is set to
9348 /// false.
9349 ///
9350 /// @param ctxt the read context to consider.
9351 ///
9352 /// @return the value of the flag.
9353 bool
9354 get_ignore_symbol_table(const read_context& ctxt)
9355 {return ctxt.options_.ignore_symbol_table;}
9356
9357 /// Test if a given DIE is anonymous
9358 ///
9359 /// @param die the DIE to consider.
9360 ///
9361 /// @return true iff @p die is anonymous.
9362 static bool
9363 die_is_anonymous(const Dwarf_Die* die)
9364 {
9365   Dwarf_Attribute attr;
9366   if (!dwarf_attr_integrate(const_cast<Dwarf_Die*>(die), DW_AT_name, &attr))
9367     return true;
9368   return false;
9369 }
9370
9371 /// Get the value of an attribute that is supposed to be a string, or
9372 /// an empty string if the attribute could not be found.
9373 ///
9374 /// @param die the DIE to get the attribute value from.
9375 ///
9376 /// @param attr_name the attribute name.  Must come from dwarf.h and
9377 /// be an enumerator representing an attribute like, e.g, DW_AT_name.
9378 ///
9379 /// @return the string representing the value of the attribute, or an
9380 /// empty string if no string attribute could be found.
9381 static string
9382 die_string_attribute(const Dwarf_Die* die, unsigned attr_name)
9383 {
9384   if (!die)
9385     return "";
9386
9387   Dwarf_Attribute attr;
9388   if (!dwarf_attr_integrate(const_cast<Dwarf_Die*>(die), attr_name, &attr))
9389     return "";
9390
9391   const char* str = dwarf_formstring(&attr);
9392   return str ? str : "";
9393 }
9394
9395 /// Get the value of an attribute that is supposed to be an unsigned
9396 /// constant.
9397 ///
9398 /// @param die the DIE to read the information from.
9399 ///
9400 /// @param attr_name the DW_AT_* name of the attribute.  Must come
9401 /// from dwarf.h and be an enumerator representing an attribute like,
9402 /// e.g, DW_AT_decl_line.
9403 ///
9404 ///@param cst the output parameter that is set to the value of the
9405 /// attribute @p attr_name.  This parameter is set iff the function
9406 /// return true.
9407 ///
9408 /// @return true if there was an attribute of the name @p attr_name
9409 /// and with a value that is a constant, false otherwise.
9410 static bool
9411 die_unsigned_constant_attribute(const Dwarf_Die*        die,
9412                                 unsigned        attr_name,
9413                                 uint64_t&       cst)
9414 {
9415   if (!die)
9416     return false;
9417
9418   Dwarf_Attribute attr;
9419   Dwarf_Word result = 0;
9420   if (!dwarf_attr_integrate(const_cast<Dwarf_Die*>(die), attr_name, &attr)
9421       || dwarf_formudata(&attr, &result))
9422     return false;
9423
9424   cst = result;
9425   return true;
9426 }
9427
9428 /// Read a signed constant value from a given attribute.
9429 ///
9430 /// The signed constant expected must be of form DW_FORM_sdata.
9431 ///
9432 /// @param die the DIE to get the attribute from.
9433 ///
9434 /// @param attr_name the attribute name.
9435 ///
9436 /// @param cst the resulting signed constant read.
9437 ///
9438 /// @return true iff a signed constant attribute of the name @p
9439 /// attr_name was found on the DIE @p die.
9440 static bool
9441 die_signed_constant_attribute(const Dwarf_Die *die,
9442                               unsigned  attr_name,
9443                               int64_t&  cst)
9444 {
9445   if (!die)
9446     return false;
9447
9448   Dwarf_Attribute attr;
9449   Dwarf_Sword result = 0;
9450   if (!dwarf_attr_integrate(const_cast<Dwarf_Die*>(die), attr_name, &attr)
9451       || dwarf_formsdata(&attr, &result))
9452     return false;
9453
9454   cst = result;
9455   return true;
9456 }
9457
9458 /// Read the value of a constant attribute that is either signed or
9459 /// unsigned into a array_type_def::subrange_type::bound_value value.
9460 ///
9461 /// The bound_value instance will capture the actual signedness of the
9462 /// read attribute.
9463 ///
9464 /// @param die the DIE from which to read the value of the attribute.
9465 ///
9466 /// @param attr_name the attribute name to consider.
9467 ///
9468 /// @param value the resulting value read from attribute @p attr_name
9469 /// on DIE @p die.
9470 ///
9471 /// @return true iff DIE @p die has an attribute named @p attr_name
9472 /// with a constant value.
9473 static bool
9474 die_constant_attribute(const Dwarf_Die *die,
9475                        unsigned attr_name,
9476                        array_type_def::subrange_type::bound_value &value)
9477 {
9478   if (die_attribute_is_unsigned(die, attr_name)
9479       || die_attribute_has_no_signedness(die, attr_name))
9480     {
9481       uint64_t l = 0;
9482       if (!die_unsigned_constant_attribute(die, attr_name, l))
9483         return false;
9484       value.set_unsigned(l);
9485     }
9486   else
9487     {
9488       int64_t l = 0;
9489       if (!die_signed_constant_attribute(die, attr_name, l))
9490         return false;
9491       value.set_signed(l);
9492     }
9493   return true;
9494 }
9495
9496 /// Test if a given attribute on a DIE has a particular form.
9497 ///
9498 /// @param die the DIE to consider.
9499 ///
9500 /// @param attr_name the attribute name to consider on DIE @p die.
9501 ///
9502 /// @param attr_form the attribute form that we expect attribute @p
9503 /// attr_name has on DIE @p die.
9504 ///
9505 /// @return true iff the attribute named @p attr_name on DIE @p die
9506 /// has the form @p attr_form.
9507 static bool
9508 die_attribute_has_form(const Dwarf_Die  *die,
9509                        unsigned attr_name,
9510                        unsigned int     attr_form)
9511 {
9512   Dwarf_Attribute attr;
9513   if (!dwarf_attr_integrate(const_cast<Dwarf_Die*>(die), attr_name, &attr))
9514     return false;
9515
9516   return dwarf_hasform(&attr, attr_form);
9517 }
9518
9519 /// Test if a given DWARF form is DW_FORM_strx{1,4}.
9520 ///
9521 /// Unfortunaly, the DW_FORM_strx{1,4} are enumerators of an untagged
9522 /// enum in dwarf.h so we have to use an unsigned int for the form,
9523 /// grrr.
9524 ///
9525 /// @param form the form to consider.
9526 ///
9527 /// @return true iff @p form is DW_FORM_strx{1,4}.
9528 static bool
9529 form_is_DW_FORM_strx(unsigned form)
9530 {
9531   if (form)
9532     {
9533 #if defined HAVE_DW_FORM_strx1          \
9534   && defined HAVE_DW_FORM_strx2 \
9535   && defined HAVE_DW_FORM_strx3 \
9536   && defined HAVE_DW_FORM_strx4
9537       if (form == DW_FORM_strx1
9538           || form == DW_FORM_strx2
9539           || form == DW_FORM_strx3
9540           ||form == DW_FORM_strx4)
9541         return true;
9542 #endif
9543     }
9544   return false;
9545 }
9546
9547 /// Test if a given DIE attribute is signed.
9548 ///
9549 /// @param die the DIE to consider.
9550 ///
9551 /// @param attr_name the attribute name to consider.
9552 ///
9553 /// @return true iff the attribute named @p attr_name on DIE @p die is
9554 /// signed.
9555 static bool
9556 die_attribute_is_signed(const Dwarf_Die* die, unsigned attr_name)
9557 {
9558   if (die_attribute_has_form(die, attr_name, DW_FORM_sdata))
9559     return true;
9560   return false;
9561 }
9562
9563 /// Test if a given DIE attribute is unsigned.
9564 ///
9565 /// @param die the DIE to consider.
9566 ///
9567 /// @param attr_name the attribute name to consider.
9568 ///
9569 /// @return true iff the attribute named @p attr_name on DIE @p die is
9570 /// unsigned.
9571 static bool
9572 die_attribute_is_unsigned(const Dwarf_Die* die, unsigned attr_name)
9573 {
9574   if (die_attribute_has_form(die, attr_name, DW_FORM_udata))
9575     return true;
9576   return false;
9577 }
9578
9579 /// Test if a given DIE attribute is neither explicitely signed nor
9580 /// unsigned.  Usually this is the case for attribute of the form
9581 /// DW_FORM_data*.
9582 ///
9583 /// @param die the DIE to consider.
9584 ///
9585 /// @param attr_name the name of the attribute to consider.
9586 ///
9587 /// @return true iff the attribute named @p attr_name of DIE @p die is
9588 /// neither specifically signed nor unsigned.
9589 static bool
9590 die_attribute_has_no_signedness(const Dwarf_Die *die, unsigned attr_name)
9591 {
9592   return (!die_attribute_is_unsigned(die, attr_name)
9593           && !die_attribute_is_signed(die, attr_name));
9594 }
9595
9596 /// Get the value of a DIE attribute; that value is meant to be a
9597 /// flag.
9598 ///
9599 /// @param die the DIE to get the attribute from.
9600 ///
9601 /// @param attr_name the DW_AT_* name of the attribute.  Must come
9602 /// from dwarf.h and be an enumerator representing an attribute like,
9603 /// e.g, DW_AT_external.
9604 ///
9605 /// @param flag the output parameter to store the flag value into.
9606 /// This is set iff the function returns true.
9607 ///
9608 /// @return true if the DIE has a flag attribute named @p attr_name,
9609 /// false otherwise.
9610 static bool
9611 die_flag_attribute(Dwarf_Die* die, unsigned attr_name, bool& flag)
9612 {
9613   Dwarf_Attribute attr;
9614   bool f = false;
9615   if (!dwarf_attr_integrate(die, attr_name, &attr)
9616       || dwarf_formflag(&attr, &f))
9617     return false;
9618
9619   flag = f;
9620   return true;
9621 }
9622
9623 /// Get the mangled name from a given DIE.
9624 ///
9625 /// @param die the DIE to read the mangled name from.
9626 ///
9627 /// @return the mangled name if it's present in the DIE, or just an
9628 /// empty string if it's not.
9629 static string
9630 die_linkage_name(const Dwarf_Die* die)
9631 {
9632   if (!die)
9633     return "";
9634
9635   string linkage_name = die_string_attribute(die, DW_AT_linkage_name);
9636   if (linkage_name.empty())
9637     linkage_name = die_string_attribute(die, DW_AT_MIPS_linkage_name);
9638   return linkage_name;
9639 }
9640
9641 /// Get the file path that is the value of the DW_AT_decl_file
9642 /// attribute on a given DIE, if the DIE is a decl DIE having that
9643 /// attribute.
9644 ///
9645 /// @param die the DIE to consider.
9646 ///
9647 /// @return a string containing the file path that is the logical
9648 /// value of the DW_AT_decl_file attribute.  If the DIE @p die
9649 /// doesn't have a DW_AT_decl_file attribute, then the return value is
9650 /// just an empty string.
9651 static string
9652 die_decl_file_attribute(const Dwarf_Die* die)
9653 {
9654   if (!die)
9655     return "";
9656
9657   const char* str = dwarf_decl_file(const_cast<Dwarf_Die*>(die));
9658
9659   return str ? str : "";
9660 }
9661
9662 /// Get the value of an attribute which value is supposed to be a
9663 /// reference to a DIE.
9664 ///
9665 /// @param die the DIE to read the value from.
9666 ///
9667 /// @param die_is_in_alt_di true if @p die comes from alternate debug
9668 /// info sections.
9669 ///
9670 /// @param attr_name the DW_AT_* attribute name to read.
9671 ///
9672 /// @param result the DIE resulting from reading the attribute value.
9673 /// This is set iff the function returns true.
9674 ///
9675 /// @param look_thru_abstract_origin if yes, the function looks
9676 /// through the possible DW_AT_abstract_origin attribute all the way
9677 /// down to the initial DIE that is cloned and look on that DIE to see
9678 /// if it has the @p attr_name attribute.
9679 ///
9680 /// @return true if the DIE @p die contains an attribute named @p
9681 /// attr_name that is a DIE reference, false otherwise.
9682 static bool
9683 die_die_attribute(const Dwarf_Die* die,
9684                   unsigned attr_name,
9685                   Dwarf_Die& result,
9686                   bool look_thru_abstract_origin)
9687 {
9688   Dwarf_Attribute attr;
9689   if (look_thru_abstract_origin)
9690     {
9691       if (!dwarf_attr_integrate(const_cast<Dwarf_Die*>(die), attr_name, &attr))
9692         return false;
9693     }
9694   else
9695     {
9696       if (!dwarf_attr(const_cast<Dwarf_Die*>(die), attr_name, &attr))
9697         return false;
9698     }
9699   bool r = dwarf_formref_die(&attr, &result);
9700   return r;
9701 }
9702
9703 /// Read and return a DW_FORM_addr attribute from a given DIE.
9704 ///
9705 /// @param die the DIE to consider.
9706 ///
9707 /// @param attr_name the name of the DW_FORM_addr attribute to read
9708 /// the value from.
9709 ///
9710 /// @param the resulting address.
9711 ///
9712 /// @return true iff the attribute could be read, was of the expected
9713 /// DW_FORM_addr and could thus be translated into the @p result.
9714 static bool
9715 die_address_attribute(Dwarf_Die* die, unsigned attr_name, Dwarf_Addr& result)
9716 {
9717   Dwarf_Attribute attr;
9718   if (!dwarf_attr_integrate(die, attr_name, &attr))
9719     return false;
9720   return dwarf_formaddr(&attr, &result) == 0;
9721 }
9722
9723 /// Returns the source location associated with a decl DIE.
9724 ///
9725 /// @param ctxt the @ref read_context to use.
9726 ///
9727 /// @param die the DIE the read the source location from.
9728 ///
9729 /// @return the location associated with @p die.
9730 static location
9731 die_location(const read_context& ctxt, const Dwarf_Die* die)
9732 {
9733   if (!die)
9734     return location();
9735
9736   string file = die_decl_file_attribute(die);
9737   uint64_t line = 0;
9738   die_unsigned_constant_attribute(die, DW_AT_decl_line, line);
9739
9740   if (!file.empty() && line != 0)
9741     {
9742       translation_unit_sptr tu = ctxt.cur_transl_unit();
9743       location l = tu->get_loc_mgr().create_new_location(file, line, 1);
9744       return l;
9745     }
9746   return location();
9747 }
9748
9749 /// Return a copy of the name of a DIE.
9750 ///
9751 /// @param die the DIE to consider.
9752 ///
9753 /// @return a copy of the name of the DIE.
9754 static string
9755 die_name(const Dwarf_Die* die)
9756 {
9757   string name = die_string_attribute(die, DW_AT_name);
9758   return name;
9759 }
9760
9761 /// Return the location, the name and the mangled name of a given DIE.
9762 ///
9763 /// @param ctxt the read context to use.
9764 ///
9765 /// @param die the DIE to read location and names from.
9766 ///
9767 /// @param loc the location output parameter to set.
9768 ///
9769 /// @param name the name output parameter to set.
9770 ///
9771 /// @param linkage_name the linkage_name output parameter to set.
9772 static void
9773 die_loc_and_name(const read_context&    ctxt,
9774                  Dwarf_Die*             die,
9775                  location&              loc,
9776                  string&                name,
9777                  string&                linkage_name)
9778 {
9779   loc = die_location(ctxt, die);
9780   name = die_name(die);
9781   linkage_name = die_linkage_name(die);
9782 }
9783
9784 /// Get the size of a (type) DIE as the value for the parameter
9785 /// DW_AT_byte_size or DW_AT_bit_size.
9786 ///
9787 /// @param die the DIE to read the information from.
9788 ///
9789 /// @param size the resulting size in bits.  This is set iff the
9790 /// function return true.
9791 ///
9792 /// @return true if the size attribute was found.
9793 static bool
9794 die_size_in_bits(const Dwarf_Die* die, uint64_t& size)
9795 {
9796   if (!die)
9797     return false;
9798
9799   uint64_t byte_size = 0, bit_size = 0;
9800
9801   if (!die_unsigned_constant_attribute(die, DW_AT_byte_size, byte_size))
9802     {
9803       if (!die_unsigned_constant_attribute(die, DW_AT_bit_size, bit_size))
9804         return false;
9805     }
9806   else
9807     bit_size = byte_size * 8;
9808
9809   size = bit_size;
9810
9811   return true;
9812 }
9813
9814 /// Get the access specifier (from the DW_AT_accessibility attribute
9815 /// value) of a given DIE.
9816 ///
9817 /// @param die the DIE to consider.
9818 ///
9819 /// @param access the resulting access.  This is set iff the function
9820 /// returns true.
9821 ///
9822 /// @return bool if the DIE contains the DW_AT_accessibility die.
9823 static bool
9824 die_access_specifier(Dwarf_Die * die, access_specifier& access)
9825 {
9826   if (!die)
9827     return false;
9828
9829   uint64_t a = 0;
9830   if (!die_unsigned_constant_attribute(die, DW_AT_accessibility, a))
9831     return false;
9832
9833   access_specifier result = private_access;
9834
9835   switch (a)
9836     {
9837     case private_access:
9838       result = private_access;
9839       break;
9840
9841     case protected_access:
9842       result = protected_access;
9843       break;
9844
9845     case public_access:
9846       result = public_access;
9847       break;
9848
9849     default:
9850       break;
9851     }
9852
9853   access = result;
9854   return true;
9855 }
9856
9857 /// Test whether a given DIE represents a decl that is public.  That
9858 /// is, one with the DW_AT_external attribute set.
9859 ///
9860 /// @param die the DIE to consider for testing.
9861 ///
9862 /// @return true if a DW_AT_external attribute is present and its
9863 /// value is set to the true; return false otherwise.
9864 static bool
9865 die_is_public_decl(Dwarf_Die* die)
9866 {
9867   bool is_public = false;
9868   die_flag_attribute(die, DW_AT_external, is_public);
9869   return is_public;
9870 }
9871
9872 /// Test whether a given DIE represents a declaration-only DIE.
9873 ///
9874 /// That is, if the DIE has the DW_AT_declaration flag set.
9875 ///
9876 /// @param die the DIE to consider.
9877 //
9878 /// @return true if a DW_AT_declaration is present, false otherwise.
9879 static bool
9880 die_is_declaration_only(Dwarf_Die* die)
9881 {
9882   bool is_declaration_only = false;
9883   die_flag_attribute(die, DW_AT_declaration, is_declaration_only);
9884   return is_declaration_only;
9885 }
9886
9887 /// Tests whether a given DIE is artificial.
9888 ///
9889 /// @param die the test to test for.
9890 ///
9891 /// @return true if the DIE is artificial, false otherwise.
9892 static bool
9893 die_is_artificial(Dwarf_Die* die)
9894 {
9895   bool is_artificial;
9896   return die_flag_attribute(die, DW_AT_artificial, is_artificial);
9897 }
9898
9899 ///@return true if a tag represents a type, false otherwise.
9900 ///
9901 ///@param tag the tag to consider.
9902 static bool
9903 is_type_tag(unsigned tag)
9904 {
9905   bool result = false;
9906
9907   switch (tag)
9908     {
9909     case DW_TAG_array_type:
9910     case DW_TAG_class_type:
9911     case DW_TAG_enumeration_type:
9912     case DW_TAG_pointer_type:
9913     case DW_TAG_reference_type:
9914     case DW_TAG_string_type:
9915     case DW_TAG_structure_type:
9916     case DW_TAG_subroutine_type:
9917     case DW_TAG_typedef:
9918     case DW_TAG_union_type:
9919     case DW_TAG_ptr_to_member_type:
9920     case DW_TAG_set_type:
9921     case DW_TAG_subrange_type:
9922     case DW_TAG_base_type:
9923     case DW_TAG_const_type:
9924     case DW_TAG_file_type:
9925     case DW_TAG_packed_type:
9926     case DW_TAG_thrown_type:
9927     case DW_TAG_volatile_type:
9928     case DW_TAG_restrict_type:
9929     case DW_TAG_interface_type:
9930     case DW_TAG_unspecified_type:
9931     case DW_TAG_shared_type:
9932     case DW_TAG_rvalue_reference_type:
9933       result = true;
9934       break;
9935
9936     default:
9937       result = false;
9938       break;
9939     }
9940
9941   return result;
9942 }
9943
9944 /// Test if a given DIE is a type to be canonicalized.  note that a
9945 /// function DIE (DW_TAG_subprogram) is considered to be a
9946 /// canonicalize-able type too because we can consider that DIE as
9947 /// being the type of the function, as well as the function decl
9948 /// itself.
9949 ///
9950 /// @param tag the tag of the DIE to consider.
9951 ///
9952 /// @return true iff the DIE of tag @p tag is a canonicalize-able DIE.
9953 static bool
9954 is_canonicalizeable_type_tag(unsigned tag)
9955 {
9956   bool result = false;
9957
9958   switch (tag)
9959     {
9960     case DW_TAG_array_type:
9961     case DW_TAG_class_type:
9962     case DW_TAG_enumeration_type:
9963     case DW_TAG_pointer_type:
9964     case DW_TAG_reference_type:
9965     case DW_TAG_structure_type:
9966     case DW_TAG_subroutine_type:
9967     case DW_TAG_subprogram:
9968     case DW_TAG_typedef:
9969     case DW_TAG_union_type:
9970     case DW_TAG_base_type:
9971     case DW_TAG_const_type:
9972     case DW_TAG_volatile_type:
9973     case DW_TAG_restrict_type:
9974     case DW_TAG_rvalue_reference_type:
9975       result = true;
9976       break;
9977
9978     default:
9979       result = false;
9980       break;
9981     }
9982
9983   return result;
9984 }
9985
9986 /// Test if a DIE tag represents a declaration.
9987 ///
9988 /// @param tag the DWARF tag to consider.
9989 ///
9990 /// @return true iff @p tag is for a declaration.
9991 static bool
9992 is_decl_tag(unsigned tag)
9993 {
9994   switch (tag)
9995     {
9996     case DW_TAG_formal_parameter:
9997     case DW_TAG_imported_declaration:
9998     case DW_TAG_member:
9999     case DW_TAG_unspecified_parameters:
10000     case DW_TAG_subprogram:
10001     case DW_TAG_variable:
10002     case DW_TAG_namespace:
10003     case DW_TAG_GNU_template_template_param:
10004     case DW_TAG_GNU_template_parameter_pack:
10005     case DW_TAG_GNU_formal_parameter_pack:
10006       return true;
10007     }
10008   return false;
10009 }
10010
10011 /// Test if a DIE represents a type DIE.
10012 ///
10013 /// @param die the DIE to consider.
10014 ///
10015 /// @return true if @p die represents a type, false otherwise.
10016 static bool
10017 die_is_type(const Dwarf_Die* die)
10018 {
10019   if (!die)
10020     return false;
10021   return is_type_tag(dwarf_tag(const_cast<Dwarf_Die*>(die)));
10022 }
10023
10024 /// Test if a DIE represents a declaration.
10025 ///
10026 /// @param die the DIE to consider.
10027 ///
10028 /// @return true if @p die represents a decl, false otherwise.
10029 static bool
10030 die_is_decl(const Dwarf_Die* die)
10031 {
10032   if (!die)
10033     return false;
10034   return is_decl_tag(dwarf_tag(const_cast<Dwarf_Die*>(die)));
10035 }
10036
10037 /// Test if a DIE represents a namespace.
10038 ///
10039 /// @param die the DIE to consider.
10040 ///
10041 /// @return true if @p die represents a namespace, false otherwise.
10042 static bool
10043 die_is_namespace(const Dwarf_Die* die)
10044 {
10045   if (!die)
10046     return false;
10047   return (dwarf_tag(const_cast<Dwarf_Die*>(die)) == DW_TAG_namespace);
10048 }
10049
10050 /// Test if a DIE has tag DW_TAG_unspecified_type.
10051 ///
10052 /// @param die the DIE to consider.
10053 ///
10054 /// @return true if @p die has tag DW_TAG_unspecified_type.
10055 static bool
10056 die_is_unspecified(Dwarf_Die* die)
10057 {
10058   if (!die)
10059     return false;
10060   return (dwarf_tag(die) == DW_TAG_unspecified_type);
10061 }
10062
10063 /// Test if a DIE represents a void type.
10064 ///
10065 /// @param die the DIE to consider.
10066 ///
10067 /// @return true if @p die represents a void type, false otherwise.
10068 static bool
10069 die_is_void_type(Dwarf_Die* die)
10070 {
10071   if (!die || dwarf_tag(die) != DW_TAG_base_type)
10072     return false;
10073
10074   string name = die_name(die);
10075   if (name == "void")
10076     return true;
10077
10078   return false;
10079 }
10080
10081 /// Test if a DIE represents a pointer type.
10082 ///
10083 /// @param die the die to consider.
10084 ///
10085 /// @return true iff @p die represents a pointer type.
10086 static bool
10087 die_is_pointer_type(const Dwarf_Die* die)
10088 {
10089   if (!die)
10090     return false;
10091
10092   int tag = dwarf_tag(const_cast<Dwarf_Die*>(die));
10093   if (tag == DW_TAG_pointer_type)
10094     return true;
10095
10096   return false;
10097 }
10098
10099 /// Test if a DIE is for a pointer, reference or qualified type to
10100 /// anonymous class or struct.
10101 ///
10102 /// @param die the DIE to consider.
10103 ///
10104 /// @return true iff @p is for a pointer, reference or qualified type
10105 /// to anonymous class or struct.
10106 static bool
10107 pointer_or_qual_die_of_anonymous_class_type(const Dwarf_Die* die)
10108 {
10109   if (!die_is_pointer_or_reference_type(die)
10110       && !die_is_qualified_type(die))
10111     return false;
10112
10113   Dwarf_Die underlying_type_die;
10114   if (!die_die_attribute(die, DW_AT_type, underlying_type_die))
10115     return false;
10116
10117   if (!die_is_class_type(&underlying_type_die))
10118     return false;
10119
10120   string name = die_name(&underlying_type_die);
10121
10122   return name.empty();
10123 }
10124
10125 /// Test if a DIE represents a reference type.
10126 ///
10127 /// @param die the die to consider.
10128 ///
10129 /// @return true iff @p die represents a reference type.
10130 static bool
10131 die_is_reference_type(const Dwarf_Die* die)
10132 {
10133   if (!die)
10134     return false;
10135
10136   int tag = dwarf_tag(const_cast<Dwarf_Die*>(die));
10137   if (tag == DW_TAG_reference_type || tag == DW_TAG_rvalue_reference_type)
10138     return true;
10139
10140   return false;
10141 }
10142
10143 /// Test if a DIE represents an array type.
10144 ///
10145 /// @param die the die to consider.
10146 ///
10147 /// @return true iff @p die represents an array type.
10148 static bool
10149 die_is_array_type(const Dwarf_Die* die)
10150 {
10151   if (!die)
10152     return false;
10153
10154   int tag = dwarf_tag(const_cast<Dwarf_Die*>(die));
10155   if (tag == DW_TAG_array_type)
10156     return true;
10157
10158   return false;
10159 }
10160
10161 /// Test if a DIE represents a pointer, reference or array type.
10162 ///
10163 /// @param die the die to consider.
10164 ///
10165 /// @return true iff @p die represents a pointer or reference type.
10166 static bool
10167 die_is_pointer_or_reference_type(const Dwarf_Die* die)
10168 {return (die_is_pointer_type(die)
10169          || die_is_reference_type(die)
10170          || die_is_array_type(die));}
10171
10172 /// Test if a DIE represents a pointer, a reference or a typedef type.
10173 ///
10174 /// @param die the die to consider.
10175 ///
10176 /// @return true iff @p die represents a pointer, a reference or a
10177 /// typedef type.
10178 static bool
10179 die_is_pointer_reference_or_typedef_type(const Dwarf_Die* die)
10180 {return (die_is_pointer_or_reference_type(die)
10181          || dwarf_tag(const_cast<Dwarf_Die*>(die)) == DW_TAG_typedef);}
10182
10183 /// Test if a DIE represents a class type.
10184 ///
10185 /// @param die the die to consider.
10186 ///
10187 /// @return true iff @p die represents a class type.
10188 static bool
10189 die_is_class_type(const Dwarf_Die* die)
10190 {
10191   int tag = dwarf_tag(const_cast<Dwarf_Die*>(die));
10192
10193   if (tag == DW_TAG_class_type || tag == DW_TAG_structure_type)
10194     return true;
10195
10196   return false;
10197 }
10198
10199 /// Test if a DIE is for a qualified type.
10200 ///
10201 /// @param die the DIE to consider.
10202 ///
10203 /// @return true iff @p die is for a qualified type.
10204 static bool
10205 die_is_qualified_type(const Dwarf_Die* die)
10206 {
10207   int tag = dwarf_tag(const_cast<Dwarf_Die*>(die));
10208     if (tag == DW_TAG_const_type
10209         || tag == DW_TAG_volatile_type
10210         || tag == DW_TAG_restrict_type)
10211       return true;
10212
10213     return false;
10214 }
10215
10216 /// Test if a DIE is for a function type.
10217 ///
10218 /// @param die the DIE to consider.
10219 ///
10220 /// @return true iff @p die is for a function type.
10221 static bool
10222 die_is_function_type(const Dwarf_Die *die)
10223 {
10224   int tag = dwarf_tag(const_cast<Dwarf_Die*>(die));
10225   if (tag == DW_TAG_subprogram || tag == DW_TAG_subroutine_type)
10226     return true;
10227
10228   return false;
10229 }
10230
10231 /// Test if a DIE for a function pointer or member function has an
10232 /// DW_AT_object_pointer attribute.
10233 ///
10234 /// @param die the DIE to consider.
10235 ///
10236 /// @param object_pointer out parameter.  It's set to the DIE for the
10237 /// object pointer iff the function returns true.
10238 ///
10239 /// @return true iff the DIE @p die has an object pointer.  In that
10240 /// case, the parameter @p object_pointer is set to the DIE of that
10241 /// object pointer.
10242 static bool
10243 die_has_object_pointer(const Dwarf_Die* die, Dwarf_Die& object_pointer)
10244 {
10245   if (!die)
10246     return false;
10247
10248   if (die_die_attribute(die, DW_AT_object_pointer, object_pointer))
10249     return true;
10250
10251   return false;
10252 }
10253
10254 /// When given the object pointer DIE of a function type or member
10255 /// function DIE, this function returns the "this" pointer that points
10256 /// to the associated class.
10257 ///
10258 /// @param die the DIE of the object pointer of the function or member
10259 /// function to consider.
10260 ///
10261 /// @param this_pointer_die out parameter.  This is set to the DIE of
10262 /// the "this" pointer iff the function returns true.
10263 ///
10264 /// @return true iff the function found the "this" pointer from the
10265 /// object pointer DIE @p die.  In that case, the parameter @p
10266 /// this_pointer_die is set to the DIE of that "this" pointer.
10267 static bool
10268 die_this_pointer_from_object_pointer(Dwarf_Die* die,
10269                                      Dwarf_Die& this_pointer_die)
10270 {
10271   ABG_ASSERT(die);
10272   ABG_ASSERT(dwarf_tag(die) == DW_TAG_formal_parameter);
10273
10274   if (die_die_attribute(die, DW_AT_type, this_pointer_die))
10275     return true;
10276
10277   return false;
10278 }
10279
10280 /// Test if a given "this" pointer that points to a particular class
10281 /// type is for a const class or not.  If it's for a const class, then
10282 /// it means the function type or the member function associated to
10283 /// that "this" pointer is const.
10284 ///
10285 /// @param die the DIE of the "this" pointer to consider.
10286 ///
10287 /// @return true iff @p die points to a const class type.
10288 static bool
10289 die_this_pointer_is_const(Dwarf_Die* die)
10290 {
10291   ABG_ASSERT(die);
10292
10293   if (dwarf_tag(die) == DW_TAG_pointer_type)
10294     {
10295       Dwarf_Die pointed_to_type_die;
10296       if (die_die_attribute(die, DW_AT_type, pointed_to_type_die))
10297         if (dwarf_tag(&pointed_to_type_die) == DW_TAG_const_type)
10298           return true;
10299     }
10300
10301   return false;
10302 }
10303
10304 /// Test if an object pointer (referred-to via a DW_AT_object_pointer
10305 /// attribute) points to a const implicit class and so is for a const
10306 /// method or or a const member function type.
10307 ///
10308 /// @param die the DIE of the object pointer to consider.
10309 ///
10310 /// @return true iff the object pointer represented by @p die is for a
10311 /// a const method or const member function type.
10312 static bool
10313 die_object_pointer_is_for_const_method(Dwarf_Die* die)
10314 {
10315   ABG_ASSERT(die);
10316   ABG_ASSERT(dwarf_tag(die) == DW_TAG_formal_parameter);
10317
10318   Dwarf_Die this_pointer_die;
10319   if (die_this_pointer_from_object_pointer(die, this_pointer_die))
10320     if (die_this_pointer_is_const(&this_pointer_die))
10321       return true;
10322
10323   return false;
10324 }
10325
10326 /// Test if a DIE represents an entity that is at class scope.
10327 ///
10328 /// @param ctxt the read context to use.
10329 ///
10330 /// @param die the DIE to consider.
10331 ///
10332 /// @param where_offset where we are logically at in the DIE stream.
10333 ///
10334 /// @param class_scope_die out parameter.  Set to the DIE of the
10335 /// containing class iff @p die happens to be at class scope; that is,
10336 /// iff the function returns true.
10337 ///
10338 /// @return true iff @p die is at class scope.  In that case, @p
10339 /// class_scope_die is set to the DIE of the class that contains @p
10340 /// die.
10341 static bool
10342 die_is_at_class_scope(const read_context& ctxt,
10343                       const Dwarf_Die* die,
10344                       size_t where_offset,
10345                       Dwarf_Die& class_scope_die)
10346 {
10347   if (!get_scope_die(ctxt, die, where_offset, class_scope_die))
10348     return false;
10349
10350   int tag = dwarf_tag(&class_scope_die);
10351
10352   return (tag == DW_TAG_structure_type
10353           || tag == DW_TAG_class_type
10354           || tag == DW_TAG_union_type);
10355 }
10356
10357 /// Return the leaf object under a pointer, reference or qualified
10358 /// type DIE.
10359 ///
10360 /// @param die the DIE of the type to consider.
10361 ///
10362 /// @param peeled_die out parameter.  Set to the DIE of the leaf
10363 /// object iff the function actually peeled anything.
10364 ///
10365 /// @return true upon successful completion.
10366 static bool
10367 die_peel_qual_ptr(Dwarf_Die *die, Dwarf_Die& peeled_die)
10368 {
10369   if (!die)
10370     return false;
10371
10372   int tag = dwarf_tag(die);
10373
10374   if (tag == DW_TAG_const_type
10375       || tag == DW_TAG_volatile_type
10376       || tag == DW_TAG_restrict_type
10377       || tag == DW_TAG_pointer_type
10378       || tag == DW_TAG_reference_type
10379       || tag == DW_TAG_rvalue_reference_type)
10380     {
10381       if (!die_die_attribute(die, DW_AT_type, peeled_die))
10382         return false;
10383     }
10384   else
10385     return false;
10386
10387   while (tag == DW_TAG_const_type
10388          || tag == DW_TAG_volatile_type
10389          || tag == DW_TAG_restrict_type
10390          || tag == DW_TAG_pointer_type
10391          || tag == DW_TAG_reference_type
10392          || tag == DW_TAG_rvalue_reference_type)
10393     {
10394       if (!die_die_attribute(&peeled_die, DW_AT_type, peeled_die))
10395         break;
10396       tag = dwarf_tag(&peeled_die);
10397     }
10398
10399   return true;
10400 }
10401
10402 /// Return the leaf object under a typedef type DIE.
10403 ///
10404 /// @param die the DIE of the type to consider.
10405 ///
10406 /// @param peeled_die out parameter.  Set to the DIE of the leaf
10407 /// object iff the function actually peeled anything.
10408 ///
10409 /// @return true upon successful completion.
10410 static bool
10411 die_peel_typedef(Dwarf_Die *die, Dwarf_Die& peeled_die)
10412 {
10413   if (!die)
10414     return false;
10415
10416   int tag = dwarf_tag(die);
10417
10418   if (tag == DW_TAG_typedef)
10419     {
10420       if (!die_die_attribute(die, DW_AT_type, peeled_die))
10421         return false;
10422     }
10423   else
10424     return false;
10425
10426   while (tag == DW_TAG_typedef)
10427     {
10428       if (!die_die_attribute(&peeled_die, DW_AT_type, peeled_die))
10429         break;
10430       tag = dwarf_tag(&peeled_die);
10431     }
10432
10433   return true;
10434
10435 }
10436
10437 /// Return the leaf DIE under a pointer, a reference or a typedef DIE.
10438 ///
10439 /// @param die the DIE to consider.
10440 ///
10441 /// @param peeled_die the resulting peeled (or leaf) DIE.  This is set
10442 /// iff the function returned true.
10443 ///
10444 /// @return true iff the function could peel @p die.
10445 static bool
10446 die_peel_pointer_and_typedef(const Dwarf_Die *die, Dwarf_Die& peeled_die)
10447 {
10448   if (!die)
10449     return false;
10450
10451   int tag = dwarf_tag(const_cast<Dwarf_Die*>(die));
10452
10453   if (tag == DW_TAG_pointer_type
10454       || tag == DW_TAG_reference_type
10455       || tag == DW_TAG_rvalue_reference_type
10456       || tag == DW_TAG_typedef)
10457     {
10458       if (!die_die_attribute(die, DW_AT_type, peeled_die))
10459         return false;
10460     }
10461   else
10462     return false;
10463
10464   while (tag == DW_TAG_pointer_type
10465          || tag == DW_TAG_reference_type
10466          || tag == DW_TAG_rvalue_reference_type
10467          || tag == DW_TAG_typedef)
10468     {
10469       if (!die_die_attribute(&peeled_die, DW_AT_type, peeled_die))
10470         break;
10471       tag = dwarf_tag(&peeled_die);
10472     }
10473   return true;
10474 }
10475
10476 /// Test if a DIE for a function type represents a method type.
10477 ///
10478 /// @param ctxt the read context.
10479 ///
10480 /// @param die the DIE to consider.
10481 ///
10482 /// @param where_offset where we logically are in the stream of DIEs.
10483 ///
10484 /// @param object_pointer_die out parameter.  This is set by the
10485 /// function to the DIE that refers to the formal function parameter
10486 /// which holds the implicit "this" pointer of the method.  That die
10487 /// is called the object pointer DIE. This is set iff the function
10488 ///
10489 /// @param class_die out parameter.  This is set by the function to
10490 /// the DIE that represents the class of the method type.  This is set
10491 /// iff the function returns true.
10492 ///
10493 /// @param is_static out parameter.  This is set to true by the
10494 /// function if @p die is a static method.  This is set iff the
10495 /// function returns true.
10496 ///
10497 /// @return true iff @p die is a DIE for a method type.
10498 static bool
10499 die_function_type_is_method_type(const read_context& ctxt,
10500                                  const Dwarf_Die *die,
10501                                  size_t where_offset,
10502                                  Dwarf_Die& object_pointer_die,
10503                                  Dwarf_Die& class_die,
10504                                  bool& is_static)
10505 {
10506   if (!die)
10507     return false;
10508
10509   int tag = dwarf_tag(const_cast<Dwarf_Die*>(die));
10510   ABG_ASSERT(tag == DW_TAG_subroutine_type || tag == DW_TAG_subprogram);
10511
10512   bool has_object_pointer = false;
10513   is_static = false;
10514   if (tag == DW_TAG_subprogram)
10515     {
10516       Dwarf_Die spec_or_origin_die;
10517       if (die_die_attribute(die, DW_AT_specification,
10518                             spec_or_origin_die)
10519           || die_die_attribute(die, DW_AT_abstract_origin,
10520                                spec_or_origin_die))
10521         {
10522           if (die_has_object_pointer(&spec_or_origin_die,
10523                                      object_pointer_die))
10524             has_object_pointer = true;
10525           else
10526             {
10527               if (die_is_at_class_scope(ctxt, &spec_or_origin_die,
10528                                         where_offset, class_die))
10529                 is_static = true;
10530               else
10531                 return false;
10532             }
10533         }
10534       else
10535         {
10536           if (die_has_object_pointer(die, object_pointer_die))
10537             has_object_pointer = true;
10538           else
10539             {
10540               if (die_is_at_class_scope(ctxt, die, where_offset, class_die))
10541                 is_static = true;
10542               else
10543                 return false;
10544             }
10545         }
10546     }
10547   else
10548     {
10549       if (die_has_object_pointer(die, object_pointer_die))
10550         has_object_pointer = true;
10551       else
10552         return false;
10553     }
10554
10555   if (!is_static)
10556     {
10557       ABG_ASSERT(has_object_pointer);
10558       // The object pointer die points to a DW_TAG_formal_parameter which
10559       // is the "this" parameter.  The type of the "this" parameter is a
10560       // pointer.  Let's get that pointer type.
10561       Dwarf_Die this_type_die;
10562       if (!die_die_attribute(&object_pointer_die, DW_AT_type, this_type_die))
10563         return false;
10564
10565       // So the class type is the type pointed to by the type of the "this"
10566       // parameter.
10567       if (!die_peel_qual_ptr(&this_type_die, class_die))
10568         return false;
10569
10570       // And make we return a class type, rather than a typedef to a
10571       // class.
10572       die_peel_typedef(&class_die, class_die);
10573     }
10574
10575   return true;
10576 }
10577
10578 enum virtuality
10579 {
10580   VIRTUALITY_NOT_VIRTUAL,
10581   VIRTUALITY_VIRTUAL,
10582   VIRTUALITY_PURE_VIRTUAL
10583 };
10584
10585 /// Get the virtual-ness of a given DIE, that is, the value of the
10586 /// DW_AT_virtuality attribute.
10587 ///
10588 /// @param die the DIE to read from.
10589 ///
10590 /// @param virt the resulting virtuality attribute.  This is set iff
10591 /// the function returns true.
10592 ///
10593 /// @return true if the virtual-ness could be determined.
10594 static bool
10595 die_virtuality(const Dwarf_Die* die, virtuality& virt)
10596 {
10597   if (!die)
10598     return false;
10599
10600   uint64_t v = 0;
10601   die_unsigned_constant_attribute(die, DW_AT_virtuality, v);
10602
10603   if (v == DW_VIRTUALITY_virtual)
10604     virt = VIRTUALITY_VIRTUAL;
10605   else if (v == DW_VIRTUALITY_pure_virtual)
10606     virt = VIRTUALITY_PURE_VIRTUAL;
10607   else
10608     virt = VIRTUALITY_NOT_VIRTUAL;
10609
10610   return true;
10611 }
10612
10613 /// Test whether the DIE represent either a virtual base or function.
10614 ///
10615 /// @param die the DIE to consider.
10616 ///
10617 /// @return bool if the DIE represents a virtual base or function,
10618 /// false othersise.
10619 static bool
10620 die_is_virtual(const Dwarf_Die* die)
10621 {
10622   virtuality v;
10623   if (!die_virtuality(die, v))
10624     return false;
10625
10626   return v == VIRTUALITY_PURE_VIRTUAL || v == VIRTUALITY_VIRTUAL;
10627 }
10628
10629 /// Test if the DIE represents an entity that was declared inlined.
10630 ///
10631 /// @param die the DIE to test for.
10632 ///
10633 /// @return true if the DIE represents an entity that was declared
10634 /// inlined.
10635 static bool
10636 die_is_declared_inline(Dwarf_Die* die)
10637 {
10638   uint64_t inline_value = 0;
10639   if (!die_unsigned_constant_attribute(die, DW_AT_inline, inline_value))
10640     return false;
10641   return inline_value == DW_INL_declared_inlined;
10642 }
10643
10644 /// This function is a fast routine (optimization) to compare the
10645 /// values of two string attributes of two DIEs.
10646 ///
10647 /// @param l the first DIE to consider.
10648 ///
10649 /// @param r the second DIE to consider.
10650 ///
10651 /// @param attr_name the name of the attribute to compare, on the two
10652 /// DIEs above.
10653 ///
10654 /// @param result out parameter.  This is set to the result of the
10655 /// comparison.  If the value of attribute @p attr_name on DIE @p l
10656 /// equals the value of attribute @p attr_name on DIE @p r, then the
10657 /// the argument of this parameter is set to true.  Otherwise, it's
10658 /// set to false.  Note that the argument of this parameter is set iff
10659 /// the function returned true.
10660 ///
10661 /// @return true iff the comparison could be performed.  There are
10662 /// cases in which the comparison cannot be performed.  For instance,
10663 /// if one of the DIEs does not have the attribute @p attr_name.  In
10664 /// any case, if this function returns true, then the parameter @p
10665 /// result is set to the result of the comparison.
10666 static bool
10667 compare_dies_string_attribute_value(const Dwarf_Die *l, const Dwarf_Die *r,
10668                                     unsigned attr_name,
10669                                     bool &result)
10670 {
10671   Dwarf_Attribute l_attr, r_attr;
10672   if (!dwarf_attr_integrate(const_cast<Dwarf_Die*>(l), attr_name, &l_attr)
10673       || !dwarf_attr_integrate(const_cast<Dwarf_Die*>(r), attr_name, &r_attr))
10674     return false;
10675
10676   ABG_ASSERT(l_attr.form == DW_FORM_strp
10677              || l_attr.form == DW_FORM_string
10678              || l_attr.form == DW_FORM_GNU_strp_alt
10679              || form_is_DW_FORM_strx(l_attr.form));
10680
10681   ABG_ASSERT(r_attr.form == DW_FORM_strp
10682              || r_attr.form == DW_FORM_string
10683              || r_attr.form == DW_FORM_GNU_strp_alt
10684              || form_is_DW_FORM_strx(r_attr.form));
10685
10686   if ((l_attr.form == DW_FORM_strp
10687        && r_attr.form == DW_FORM_strp)
10688       || (l_attr.form == DW_FORM_GNU_strp_alt
10689           && r_attr.form == DW_FORM_GNU_strp_alt)
10690       || (form_is_DW_FORM_strx(l_attr.form)
10691           && form_is_DW_FORM_strx(r_attr.form)))
10692     {
10693       // So these string attributes are actually pointers into a
10694       // string table.  The string table is most likely de-duplicated
10695       // so comparing the *values* of the pointers should be enough.
10696       //
10697       // This is the fast path.
10698       if (l_attr.valp == r_attr.valp)
10699           result = true;
10700       else if (l_attr.valp && r_attr.valp)
10701         result = *l_attr.valp == *r_attr.valp;
10702       else
10703         result = false;
10704       return true;
10705     }
10706
10707   // If we reached this point it means we couldn't use the fast path
10708   // because the string atttributes are strings that are "inline" in
10709   // the debug info section.  Let's just compare them the slow and
10710   // obvious way.
10711   string l_str = die_string_attribute(l, attr_name),
10712     r_str = die_string_attribute(r, attr_name);
10713   result = l_str == r_str;
10714
10715   return true;
10716 }
10717
10718 /// Compare the file path of the compilation units (aka CUs)
10719 /// associated to two DIEs.
10720 ///
10721 /// If the DIEs are for pointers or typedefs, this function also
10722 /// compares the file paths of the CUs of the leaf DIEs (underlying
10723 /// DIEs of the pointer or the typedef).
10724 ///
10725 /// @param l the first type DIE to consider.
10726 ///
10727 /// @param r the second type DIE to consider.
10728 ///
10729 /// @return true iff the file paths of the DIEs of the two types are
10730 /// equal.
10731 static bool
10732 compare_dies_cu_decl_file(const Dwarf_Die* l, const Dwarf_Die *r, bool &result)
10733 {
10734   Dwarf_Die l_cu, r_cu;
10735   if (!dwarf_diecu(const_cast<Dwarf_Die*>(l), &l_cu, 0, 0)
10736       ||!dwarf_diecu(const_cast<Dwarf_Die*>(r), &r_cu, 0, 0))
10737     return false;
10738
10739   bool compared =
10740     compare_dies_string_attribute_value(&l_cu, &r_cu,
10741                                         DW_AT_name,
10742                                         result);
10743   if (compared)
10744     {
10745       Dwarf_Die peeled_l, peeled_r;
10746       if (die_is_pointer_reference_or_typedef_type(l)
10747           && die_is_pointer_reference_or_typedef_type(r)
10748           && die_peel_pointer_and_typedef(l, peeled_l)
10749           && die_peel_pointer_and_typedef(r, peeled_r))
10750         {
10751           if (!dwarf_diecu(&peeled_l, &l_cu, 0, 0)
10752               ||!dwarf_diecu(&peeled_r, &r_cu, 0, 0))
10753             return false;
10754           compared =
10755             compare_dies_string_attribute_value(&l_cu, &r_cu,
10756                                                 DW_AT_name,
10757                                                 result);
10758         }
10759     }
10760
10761   return  compared;
10762 }
10763
10764 // -----------------------------------
10765 // <location expression evaluation>
10766 // -----------------------------------
10767
10768 /// Get the value of a given DIE attribute, knowing that it must be a
10769 /// location expression.
10770 ///
10771 /// @param die the DIE to read the attribute from.
10772 ///
10773 /// @param attr_name the name of the attribute to read the value for.
10774 ///
10775 /// @param expr the pointer to allocate and fill with the resulting
10776 /// array of operators + operands forming a dwarf expression.  This is
10777 /// set iff the function returns true.
10778 ///
10779 /// @param expr_len the length of the resulting dwarf expression.
10780 /// This is set iff the function returns true.
10781 ///
10782 /// @return true if the attribute exists and has a dwarf expression as
10783 /// value.  In that case the expr and expr_len arguments are set to
10784 /// the resulting dwarf exprssion.
10785 static bool
10786 die_location_expr(const Dwarf_Die* die,
10787                   unsigned attr_name,
10788                   Dwarf_Op** expr,
10789                   uint64_t* expr_len)
10790 {
10791   if (!die)
10792     return false;
10793
10794   Dwarf_Attribute attr;
10795   if (!dwarf_attr_integrate(const_cast<Dwarf_Die*>(die), attr_name, &attr))
10796     return false;
10797
10798   size_t len = 0;
10799   bool result = (dwarf_getlocation(&attr, expr, &len) == 0);
10800
10801   if (result)
10802     *expr_len = len;
10803
10804   return result;
10805 }
10806
10807 /// If the current operation in the dwarf expression represents a push
10808 /// of a constant value onto the dwarf expr virtual machine (aka
10809 /// DEVM), perform the operation and update the DEVM.
10810 ///
10811 /// If the result of the operation is a constant, update the DEVM
10812 /// accumulator with its value.  Otherwise, the DEVM accumulator is
10813 /// left with its previous value.
10814 ///
10815 /// @param ops the array of the dwarf expression operations to consider.
10816 ///
10817 /// @param ops_len the lengths of @p ops array above.
10818 ///
10819 /// @param index the index of the operation to interpret, in @p ops.
10820 ///
10821 /// @param next_index the index of the operation to interpret at the
10822 /// next step, after this function completed and returned.  This is
10823 /// set an output parameter that is set iff the function returns true.
10824 ///
10825 /// @param ctxt the DEVM evaluation context.
10826 ///
10827 /// @return true if the current operation actually pushes a constant
10828 /// value onto the DEVM stack, false otherwise.
10829 static bool
10830 op_pushes_constant_value(Dwarf_Op*                      ops,
10831                          uint64_t                       ops_len,
10832                          uint64_t                       index,
10833                          uint64_t&                      next_index,
10834                          dwarf_expr_eval_context&       ctxt)
10835 {
10836   ABG_ASSERT(index < ops_len);
10837
10838   Dwarf_Op& op = ops[index];
10839   int64_t value = 0;
10840
10841   switch (op.atom)
10842     {
10843     case DW_OP_addr:
10844       value = ops[index].number;
10845       break;
10846
10847     case DW_OP_const1u:
10848     case DW_OP_const1s:
10849     case DW_OP_const2u:
10850     case DW_OP_const2s:
10851     case DW_OP_const4u:
10852     case DW_OP_const4s:
10853     case DW_OP_const8u:
10854     case DW_OP_const8s:
10855     case DW_OP_constu:
10856     case DW_OP_consts:
10857       value = ops[index].number;
10858       break;
10859
10860     case DW_OP_lit0:
10861       value = 0;
10862       break;
10863     case DW_OP_lit1:
10864       value = 1;
10865       break;
10866     case DW_OP_lit2:
10867       value = 2;
10868       break;
10869     case DW_OP_lit3:
10870       value = 3;
10871       break;
10872     case DW_OP_lit4:
10873       value = 4;
10874       break;
10875     case DW_OP_lit5:
10876       value = 5;
10877       break;
10878     case DW_OP_lit6:
10879       value = 6;
10880       break;
10881     case DW_OP_lit7:
10882       value = 7;
10883       break;
10884     case DW_OP_lit8:
10885       value = 8;
10886       break;
10887     case DW_OP_lit9:
10888       value = 9;
10889       break;
10890     case DW_OP_lit10:
10891       value = 10;
10892       break;
10893     case DW_OP_lit11:
10894       value = 11;
10895       break;
10896     case DW_OP_lit12:
10897       value = 12;
10898       break;
10899     case DW_OP_lit13:
10900       value = 13;
10901       break;
10902     case DW_OP_lit14:
10903       value = 14;
10904       break;
10905     case DW_OP_lit15:
10906       value = 15;
10907       break;
10908     case DW_OP_lit16:
10909       value = 16;
10910       break;
10911     case DW_OP_lit17:
10912       value = 17;
10913       break;
10914     case DW_OP_lit18:
10915       value = 18;
10916       break;
10917     case DW_OP_lit19:
10918       value = 19;
10919       break;
10920     case DW_OP_lit20:
10921       value = 20;
10922       break;
10923     case DW_OP_lit21:
10924       value = 21;
10925       break;
10926     case DW_OP_lit22:
10927       value = 22;
10928       break;
10929     case DW_OP_lit23:
10930       value = 23;
10931       break;
10932     case DW_OP_lit24:
10933       value = 24;
10934       break;
10935     case DW_OP_lit25:
10936       value = 25;
10937       break;
10938     case DW_OP_lit26:
10939       value = 26;
10940       break;
10941     case DW_OP_lit27:
10942       value = 27;
10943       break;
10944     case DW_OP_lit28:
10945       value = 28;
10946       break;
10947     case DW_OP_lit29:
10948       value = 29;
10949       break;
10950     case DW_OP_lit30:
10951       value = 30;
10952       break;
10953     case DW_OP_lit31:
10954       value = 31;
10955       break;
10956
10957     default:
10958       return false;
10959     }
10960
10961   expr_result r(value);
10962   ctxt.push(r);
10963   ctxt.accum = r;
10964   next_index = index + 1;
10965
10966   return true;
10967 }
10968
10969 /// If the current operation in the dwarf expression represents a push
10970 /// of a non-constant value onto the dwarf expr virtual machine (aka
10971 /// DEVM), perform the operation and update the DEVM.  A non-constant
10972 /// is namely a quantity for which we need inferior (a running program
10973 /// image) state to know the exact value.
10974 ///
10975 /// Upon successful completion, as the result of the operation is a
10976 /// non-constant the DEVM accumulator value is left to its state as of
10977 /// before the invocation of this function.
10978 ///
10979 /// @param ops the array of the dwarf expression operations to consider.
10980 ///
10981 /// @param ops_len the lengths of @p ops array above.
10982 ///
10983 /// @param index the index of the operation to interpret, in @p ops.
10984 ///
10985 /// @param next_index the index of the operation to interpret at the
10986 /// next step, after this function completed and returned.  This is
10987 /// set an output parameter that is set iff the function returns true.
10988 ///
10989 /// @param ctxt the DEVM evaluation context.
10990 ///
10991 /// @return true if the current operation actually pushes a
10992 /// non-constant value onto the DEVM stack, false otherwise.
10993 static bool
10994 op_pushes_non_constant_value(Dwarf_Op* ops,
10995                              uint64_t ops_len,
10996                              uint64_t index,
10997                              uint64_t& next_index,
10998                              dwarf_expr_eval_context& ctxt)
10999 {
11000   ABG_ASSERT(index < ops_len);
11001   Dwarf_Op& op = ops[index];
11002
11003   switch (op.atom)
11004     {
11005     case DW_OP_reg0:
11006     case DW_OP_reg1:
11007     case DW_OP_reg2:
11008     case DW_OP_reg3:
11009     case DW_OP_reg4:
11010     case DW_OP_reg5:
11011     case DW_OP_reg6:
11012     case DW_OP_reg7:
11013     case DW_OP_reg8:
11014     case DW_OP_reg9:
11015     case DW_OP_reg10:
11016     case DW_OP_reg11:
11017     case DW_OP_reg12:
11018     case DW_OP_reg13:
11019     case DW_OP_reg14:
11020     case DW_OP_reg15:
11021     case DW_OP_reg16:
11022     case DW_OP_reg17:
11023     case DW_OP_reg18:
11024     case DW_OP_reg19:
11025     case DW_OP_reg20:
11026     case DW_OP_reg21:
11027     case DW_OP_reg22:
11028     case DW_OP_reg23:
11029     case DW_OP_reg24:
11030     case DW_OP_reg25:
11031     case DW_OP_reg26:
11032     case DW_OP_reg27:
11033     case DW_OP_reg28:
11034     case DW_OP_reg29:
11035     case DW_OP_reg30:
11036     case DW_OP_reg31:
11037       next_index = index + 1;
11038       break;
11039
11040     case DW_OP_breg0:
11041     case DW_OP_breg1:
11042     case DW_OP_breg2:
11043     case DW_OP_breg3:
11044     case DW_OP_breg4:
11045     case DW_OP_breg5:
11046     case DW_OP_breg6:
11047     case DW_OP_breg7:
11048     case DW_OP_breg8:
11049     case DW_OP_breg9:
11050     case DW_OP_breg10:
11051     case DW_OP_breg11:
11052     case DW_OP_breg12:
11053     case DW_OP_breg13:
11054     case DW_OP_breg14:
11055     case DW_OP_breg15:
11056     case DW_OP_breg16:
11057     case DW_OP_breg17:
11058     case DW_OP_breg18:
11059     case DW_OP_breg19:
11060     case DW_OP_breg20:
11061     case DW_OP_breg21:
11062     case DW_OP_breg22:
11063     case DW_OP_breg23:
11064     case DW_OP_breg24:
11065     case DW_OP_breg25:
11066     case DW_OP_breg26:
11067     case DW_OP_breg27:
11068     case DW_OP_breg28:
11069     case DW_OP_breg29:
11070     case DW_OP_breg30:
11071     case DW_OP_breg31:
11072       next_index = index + 1;
11073       break;
11074
11075     case DW_OP_regx:
11076       next_index = index + 2;
11077       break;
11078
11079     case DW_OP_fbreg:
11080       next_index = index + 1;
11081       break;
11082
11083     case DW_OP_bregx:
11084       next_index = index + 1;
11085       break;
11086
11087     default:
11088       return false;
11089     }
11090
11091   expr_result r(false);
11092   ctxt.push(r);
11093
11094   return true;
11095 }
11096
11097 /// If the current operation in the dwarf expression represents a
11098 /// manipulation of the stack of the DWARF Expression Virtual Machine
11099 /// (aka DEVM), this function performs the operation and updates the
11100 /// state of the DEVM.  If the result of the operation represents a
11101 /// constant value, then the accumulator of the DEVM is set to that
11102 /// result's value, Otherwise, the DEVM accumulator is left with its
11103 /// previous value.
11104 ///
11105 /// @param expr the array of the dwarf expression operations to consider.
11106 ///
11107 /// @param expr_len the lengths of @p ops array above.
11108 ///
11109 /// @param index the index of the operation to interpret, in @p ops.
11110 ///
11111 /// @param next_index the index of the operation to interpret at the
11112 /// next step, after this function completed and returned.  This is
11113 /// set an output parameter that is set iff the function returns true.
11114 ///
11115 /// @param ctxt the DEVM evaluation context.
11116 ///
11117 /// @return true if the current operation actually manipulates the
11118 /// DEVM stack, false otherwise.
11119 static bool
11120 op_manipulates_stack(Dwarf_Op* expr,
11121                      uint64_t expr_len,
11122                      uint64_t index,
11123                      uint64_t& next_index,
11124                      dwarf_expr_eval_context& ctxt)
11125 {
11126   Dwarf_Op& op = expr[index];
11127   expr_result v;
11128
11129   switch (op.atom)
11130     {
11131     case DW_OP_dup:
11132       v = ctxt.stack.front();
11133       ctxt.push(v);
11134       break;
11135
11136     case DW_OP_drop:
11137       v = ctxt.stack.front();
11138       ctxt.pop();
11139       break;
11140
11141     case DW_OP_over:
11142       ABG_ASSERT(ctxt.stack.size() > 1);
11143       v = ctxt.stack[1];
11144       ctxt.push(v);
11145       break;
11146
11147     case DW_OP_pick:
11148       ABG_ASSERT(index + 1 < expr_len);
11149       v = op.number;
11150       ctxt.push(v);
11151       break;
11152
11153     case DW_OP_swap:
11154       ABG_ASSERT(ctxt.stack.size() > 1);
11155       v = ctxt.stack[1];
11156       ctxt.stack.erase(ctxt.stack.begin() + 1);
11157       ctxt.push(v);
11158       break;
11159
11160     case DW_OP_rot:
11161       ABG_ASSERT(ctxt.stack.size() > 2);
11162       v = ctxt.stack[2];
11163       ctxt.stack.erase(ctxt.stack.begin() + 2);
11164       ctxt.push(v);
11165       break;
11166
11167     case DW_OP_deref:
11168     case DW_OP_deref_size:
11169       ABG_ASSERT(ctxt.stack.size() > 0);
11170       ctxt.pop();
11171       v.is_const(false);
11172       ctxt.push(v);
11173       break;
11174
11175     case DW_OP_xderef:
11176     case DW_OP_xderef_size:
11177       ABG_ASSERT(ctxt.stack.size() > 1);
11178       ctxt.pop();
11179       ctxt.pop();
11180       v.is_const(false);
11181       ctxt.push(v);
11182       break;
11183
11184     case DW_OP_push_object_address:
11185       v.is_const(false);
11186       ctxt.push(v);
11187       break;
11188
11189     case DW_OP_form_tls_address:
11190     case DW_OP_GNU_push_tls_address:
11191       ABG_ASSERT(ctxt.stack.size() > 0);
11192       v = ctxt.pop();
11193       if (op.atom == DW_OP_form_tls_address)
11194         v.is_const(false);
11195       ctxt.push(v);
11196       break;
11197
11198     case DW_OP_call_frame_cfa:
11199       v.is_const(false);
11200       ctxt.push(v);
11201       break;
11202
11203     default:
11204       return false;
11205     }
11206
11207   if (v.is_const())
11208     ctxt.accum = v;
11209
11210   if (op.atom == DW_OP_form_tls_address
11211       || op.atom == DW_OP_GNU_push_tls_address)
11212     ctxt.set_tls_address(true);
11213   else
11214     ctxt.set_tls_address(false);
11215
11216   next_index = index + 1;
11217
11218   return true;
11219 }
11220
11221 /// If the current operation in the dwarf expression represents a push
11222 /// of an arithmetic or logic operation onto the dwarf expr virtual
11223 /// machine (aka DEVM), perform the operation and update the DEVM.
11224 ///
11225 /// If the result of the operation is a constant, update the DEVM
11226 /// accumulator with its value.  Otherwise, the DEVM accumulator is
11227 /// left with its previous value.
11228 ///
11229 /// @param expr the array of the dwarf expression operations to consider.
11230 ///
11231 /// @param expr_len the lengths of @p expr array above.
11232 ///
11233 /// @param index the index of the operation to interpret, in @p expr.
11234 ///
11235 /// @param next_index the index of the operation to interpret at the
11236 /// next step, after this function completed and returned.  This is
11237 /// set an output parameter that is set iff the function returns true.
11238 ///
11239 /// @param ctxt the DEVM evaluation context.
11240 ///
11241 /// @return true if the current operation actually represent an
11242 /// arithmetic or logic operation.
11243 static bool
11244 op_is_arith_logic(Dwarf_Op* expr,
11245                   uint64_t expr_len,
11246                   uint64_t index,
11247                   uint64_t& next_index,
11248                   dwarf_expr_eval_context& ctxt)
11249 {
11250   ABG_ASSERT(index < expr_len);
11251
11252   Dwarf_Op& op = expr[index];
11253   expr_result val1, val2;
11254
11255   switch (op.atom)
11256     {
11257     case DW_OP_abs:
11258       val1 = ctxt.pop();
11259       val1 = val1.abs();
11260       ctxt.push(val1);
11261       break;
11262
11263     case DW_OP_and:
11264       ABG_ASSERT(ctxt.stack.size() > 1);
11265       val1 = ctxt.pop();
11266       val2 = ctxt.pop();
11267       ctxt.push(val1 & val2);
11268       break;
11269
11270     case DW_OP_div:
11271       val1 = ctxt.pop();
11272       val2 = ctxt.pop();
11273       if (!val1.is_const())
11274         val1 = 1;
11275       ctxt.push(val2 / val1);
11276       break;
11277
11278     case DW_OP_minus:
11279       val1 = ctxt.pop();
11280       val2 = ctxt.pop();
11281       ctxt.push(val2 - val1);
11282       break;
11283
11284     case DW_OP_mod:
11285       val1 = ctxt.pop();
11286       val2 = ctxt.pop();
11287       ctxt.push(val2 % val1);
11288       break;
11289
11290     case DW_OP_mul:
11291       val1 = ctxt.pop();
11292       val2 = ctxt.pop();
11293       ctxt.push(val2 * val1);
11294       break;
11295
11296     case DW_OP_neg:
11297       val1 = ctxt.pop();
11298       ctxt.push(-val1);
11299       break;
11300
11301     case DW_OP_not:
11302       val1 = ctxt.pop();
11303       ctxt.push(~val1);
11304       break;
11305
11306     case DW_OP_or:
11307       val1 = ctxt.pop();
11308       val2 = ctxt.pop();
11309       ctxt.push(val1 | val2);
11310       break;
11311
11312     case DW_OP_plus:
11313       val1 = ctxt.pop();
11314       val2 = ctxt.pop();
11315       ctxt.push(val2 + val1);
11316       break;
11317
11318     case DW_OP_plus_uconst:
11319       val1 = ctxt.pop();
11320       val1 += op.number;
11321       ctxt.push(val1);
11322       break;
11323
11324     case DW_OP_shl:
11325       val1 = ctxt.pop();
11326       val2 = ctxt.pop();
11327       ctxt.push(val2 << val1);
11328       break;
11329
11330     case DW_OP_shr:
11331     case DW_OP_shra:
11332       val1 = ctxt.pop();
11333       val2 = ctxt.pop();
11334       ctxt.push(val2 >> val1);
11335       break;
11336
11337     case DW_OP_xor:
11338       val1 = ctxt.pop();
11339       val2 = ctxt.pop();
11340       ctxt.push(val2 ^ val1);
11341       break;
11342
11343     default:
11344       return false;
11345     }
11346
11347   if (ctxt.stack.front().is_const())
11348     ctxt.accum = ctxt.stack.front();
11349
11350   next_index = index + 1;
11351   return true;
11352 }
11353
11354 /// If the current operation in the dwarf expression represents a push
11355 /// of a control flow operation onto the dwarf expr virtual machine
11356 /// (aka DEVM), perform the operation and update the DEVM.
11357 ///
11358 /// If the result of the operation is a constant, update the DEVM
11359 /// accumulator with its value.  Otherwise, the DEVM accumulator is
11360 /// left with its previous value.
11361 ///
11362 /// @param expr the array of the dwarf expression operations to consider.
11363 ///
11364 /// @param expr_len the lengths of @p expr array above.
11365 ///
11366 /// @param index the index of the operation to interpret, in @p expr.
11367 ///
11368 /// @param next_index the index of the operation to interpret at the
11369 /// next step, after this function completed and returned.  This is
11370 /// set an output parameter that is set iff the function returns true.
11371 ///
11372 /// @param ctxt the DEVM evaluation context.
11373 ///
11374 /// @return true if the current operation actually represents a
11375 /// control flow operation, false otherwise.
11376 static bool
11377 op_is_control_flow(Dwarf_Op* expr,
11378                    uint64_t expr_len,
11379                    uint64_t index,
11380                    uint64_t& next_index,
11381                    dwarf_expr_eval_context& ctxt)
11382 {
11383   ABG_ASSERT(index < expr_len);
11384
11385   Dwarf_Op& op = expr[index];
11386   expr_result val1, val2;
11387
11388   switch (op.atom)
11389     {
11390     case DW_OP_eq:
11391     case DW_OP_ge:
11392     case DW_OP_gt:
11393     case DW_OP_le:
11394     case DW_OP_lt:
11395     case DW_OP_ne:
11396       {
11397         bool value = true;
11398         val1 = ctxt.pop();
11399         val2 = ctxt.pop();
11400         if (op.atom == DW_OP_eq)
11401           value = val2 == val1;
11402         else if (op.atom == DW_OP_ge)
11403           value = val2 >= val1;
11404         else if (op.atom == DW_OP_gt)
11405           value = val2 > val1;
11406         else if (op.atom == DW_OP_le)
11407           value = val2 <= val1;
11408         else if (op.atom == DW_OP_lt)
11409           value = val2 < val1;
11410         else if (op.atom == DW_OP_ne)
11411           value = val2 != val1;
11412
11413         val1 = value ? 1 : 0;
11414         ctxt.push(val1);
11415       }
11416       break;
11417
11418     case DW_OP_skip:
11419       if (op.number > 0)
11420         index += op.number - 1;
11421       break;
11422
11423     case DW_OP_bra:
11424       val1 = ctxt.pop();
11425       if (val1 != 0)
11426         index += val1.const_value() - 1;
11427       break;
11428
11429     case DW_OP_call2:
11430     case DW_OP_call4:
11431     case DW_OP_call_ref:
11432     case DW_OP_nop:
11433       break;
11434
11435     default:
11436       return false;
11437     }
11438
11439   if (ctxt.stack.front().is_const())
11440     ctxt.accum = ctxt.stack.front();
11441
11442   next_index = index + 1;
11443   return true;
11444 }
11445
11446 /// This function quickly evaluates a DWARF expression that is a
11447 /// constant.
11448 ///
11449 /// This is a "fast path" function that quickly evaluates a DWARF
11450 /// expression that is only made of a DW_OP_plus_uconst operator.
11451 ///
11452 /// This is a sub-routine of die_member_offset.
11453 ///
11454 /// @param expr the DWARF expression to evaluate.
11455 ///
11456 /// @param expr_len the length of the expression @p expr.
11457 ///
11458 /// @param value out parameter.  This is set to the result of the
11459 /// evaluation of @p expr, iff this function returns true.
11460 ///
11461 /// @return true iff the evaluation of @p expr went OK.
11462 static bool
11463 eval_quickly(Dwarf_Op*  expr,
11464              uint64_t   expr_len,
11465              int64_t&   value)
11466 {
11467   if (expr_len == 1 && (expr[0].atom == DW_OP_plus_uconst))
11468     {
11469       value = expr[0].number;
11470       return true;
11471     }
11472   return false;
11473 }
11474
11475 /// Evaluate the value of the last sub-expression that is a constant,
11476 /// inside a given DWARF expression.
11477 ///
11478 /// @param expr the DWARF expression to consider.
11479 ///
11480 /// @param expr_len the length of the expression to consider.
11481 ///
11482 /// @param value the resulting value of the last constant
11483 /// sub-expression of the DWARF expression.  This is set iff the
11484 /// function returns true.
11485 ///
11486 /// @param is_tls_address out parameter.  This is set to true iff
11487 /// the resulting value of the evaluation is a TLS (thread local
11488 /// storage) address.
11489 ///
11490 /// @param eval_ctxt the evaluation context to (re)use.  Note that
11491 /// this function initializes this context before using it.
11492 ///
11493 /// @return true if the function could find a constant sub-expression
11494 /// to evaluate, false otherwise.
11495 static bool
11496 eval_last_constant_dwarf_sub_expr(Dwarf_Op*     expr,
11497                                   uint64_t      expr_len,
11498                                   int64_t&      value,
11499                                   bool& is_tls_address,
11500                                   dwarf_expr_eval_context &eval_ctxt)
11501 {
11502   // Reset the evaluation context before evaluating the constant sub
11503   // expression contained in the DWARF expression 'expr'.
11504   eval_ctxt.reset();
11505
11506   uint64_t index = 0, next_index = 0;
11507   do
11508     {
11509       if (op_is_arith_logic(expr, expr_len, index,
11510                             next_index, eval_ctxt)
11511           || op_pushes_constant_value(expr, expr_len, index,
11512                                       next_index, eval_ctxt)
11513           || op_manipulates_stack(expr, expr_len, index,
11514                                   next_index, eval_ctxt)
11515           || op_pushes_non_constant_value(expr, expr_len, index,
11516                                           next_index, eval_ctxt)
11517           || op_is_control_flow(expr, expr_len, index,
11518                                 next_index, eval_ctxt))
11519         ;
11520       else
11521         next_index = index + 1;
11522
11523       ABG_ASSERT(next_index > index);
11524       index = next_index;
11525     } while (index < expr_len);
11526
11527   is_tls_address = eval_ctxt.set_tls_address();
11528   if (eval_ctxt.accum.is_const())
11529     {
11530       value = eval_ctxt.accum;
11531       return true;
11532     }
11533   return false;
11534 }
11535
11536 /// Evaluate the value of the last sub-expression that is a constant,
11537 /// inside a given DWARF expression.
11538 ///
11539 /// @param expr the DWARF expression to consider.
11540 ///
11541 /// @param expr_len the length of the expression to consider.
11542 ///
11543 /// @param value the resulting value of the last constant
11544 /// sub-expression of the DWARF expression.  This is set iff the
11545 /// function returns true.
11546 ///
11547 /// @return true if the function could find a constant sub-expression
11548 /// to evaluate, false otherwise.
11549 static bool
11550 eval_last_constant_dwarf_sub_expr(Dwarf_Op*     expr,
11551                                   uint64_t      expr_len,
11552                                   int64_t&      value,
11553                                   bool& is_tls_address)
11554 {
11555   dwarf_expr_eval_context eval_ctxt;
11556   return eval_last_constant_dwarf_sub_expr(expr, expr_len, value,
11557                                            is_tls_address, eval_ctxt);
11558 }
11559
11560 // -----------------------------------
11561 // </location expression evaluation>
11562 // -----------------------------------
11563
11564 /// Get the offset of a struct/class member as represented by the
11565 /// value of the DW_AT_data_member_location attribute.
11566 ///
11567 /// There is a huge gotcha in here.  The value of the
11568 /// DW_AT_data_member_location is not necessarily a constant that one
11569 /// would just read and be done with it.  Rather, it can be a DWARF
11570 /// expression that one has to interpret.  In general, the offset can
11571 /// be given by the DW_AT_bit_offset attribute.  In that case the
11572 /// offset is a constant.  But it can also be given by the
11573 /// DW_AT_data_member_location attribute.  In that case it's a DWARF
11574 /// location expression.
11575 ///
11576 /// When the it's the DW_AT_data_member_location that is present,
11577 /// there are three cases to possibly take into account:
11578 ///
11579 ///     1/ The offset in the vtable where the offset of a virtual base
11580 ///        can be found, aka vptr offset.  Given the address of a
11581 ///        given object O, the vptr offset for B is given by the
11582 ///        (DWARF) expression:
11583 ///
11584 ///            address(O) + *(*address(0) - VIRTUAL_OFFSET)
11585 ///
11586 ///        where VIRTUAL_OFFSET is a constant value; In this case,
11587 ///        this function returns the constant VIRTUAL_OFFSET, as this
11588 ///        is enough to detect changes in a given virtual base
11589 ///        relative to the other virtual bases.
11590 ///
11591 ///     2/ The offset of a regular data member.  Given the address of
11592 ///        a struct object named O, the memory location for a
11593 ///        particular data member is given by the (DWARF) expression:
11594 ///
11595 ///            address(O) + OFFSET
11596 ///
11597 ///       where OFFSET is a constant.  In this case, this function
11598 ///       returns the OFFSET constant.
11599 ///
11600 ///     3/ The offset of a virtual member function in the virtual
11601 ///     pointer.  The DWARF expression is a constant that designates
11602 ///     the offset of the function in the vtable.  In this case this
11603 ///     function returns that constant.
11604 ///
11605 ///@param ctxt the read context to consider.
11606 ///
11607 ///@param die the DIE to read the information from.
11608 ///
11609 ///@param offset the resulting constant offset, in bits.  This
11610 ///argument is set iff the function returns true.
11611 static bool
11612 die_member_offset(const read_context& ctxt,
11613                   const Dwarf_Die* die,
11614                   int64_t& offset)
11615 {
11616   Dwarf_Op* expr = NULL;
11617   uint64_t expr_len = 0;
11618   uint64_t off = 0;
11619
11620   if (die_unsigned_constant_attribute(die, DW_AT_bit_offset, off))
11621     {
11622       // The DW_AT_bit_offset is present.  If it contains a non-zero
11623       // value, let's read that one.
11624       if (off != 0)
11625         {
11626           offset = off;
11627           return true;
11628         }
11629     }
11630
11631   if (!die_location_expr(die, DW_AT_data_member_location, &expr, &expr_len))
11632     return false;
11633
11634   // Otherwise, the DW_AT_data_member_location attribute is present.
11635   // In that case, let's evaluate it and get its constant
11636   // sub-expression and return that one.
11637
11638   if (!eval_quickly(expr, expr_len, offset))
11639     {
11640       bool is_tls_address = false;
11641       if (!eval_last_constant_dwarf_sub_expr(expr, expr_len,
11642                                              offset, is_tls_address,
11643                                              ctxt.dwarf_expr_eval_ctxt()))
11644         return false;
11645     }
11646
11647   offset *= 8;
11648   return true;
11649 }
11650
11651 /// Read the value of the DW_AT_location attribute from a DIE,
11652 /// evaluate the resulting DWARF expression and, if it's a constant
11653 /// expression, return it.
11654 ///
11655 /// @param die the DIE to consider.
11656 ///
11657 /// @param address the resulting constant address.  This is set iff
11658 /// the function returns true.
11659 ///
11660 /// @return true iff the whole sequence of action described above
11661 /// could be completed normally.
11662 static bool
11663 die_location_address(Dwarf_Die* die,
11664                      Dwarf_Addr&        address,
11665                      bool&              is_tls_address)
11666 {
11667   Dwarf_Op* expr = NULL;
11668   uint64_t expr_len = 0;
11669
11670   is_tls_address = false;
11671   if (!die_location_expr(die, DW_AT_location, &expr, &expr_len))
11672     return false;
11673
11674   int64_t addr = 0;
11675   if (!eval_last_constant_dwarf_sub_expr(expr, expr_len, addr, is_tls_address))
11676     return false;
11677
11678   address = addr;
11679   return true;
11680 }
11681
11682
11683 /// Return the index of a function in its virtual table.  That is,
11684 /// return the value of the DW_AT_vtable_elem_location attribute.
11685 ///
11686 /// @param die the DIE of the function to consider.
11687 ///
11688 /// @param vindex the resulting index.  This is set iff the function
11689 /// returns true.
11690 ///
11691 /// @return true if the DIE has a DW_AT_vtable_elem_location
11692 /// attribute.
11693 static bool
11694 die_virtual_function_index(Dwarf_Die* die,
11695                            int64_t& vindex)
11696 {
11697   if (!die)
11698     return false;
11699
11700   Dwarf_Op* expr = NULL;
11701   uint64_t expr_len = 0;
11702   if (!die_location_expr(die, DW_AT_vtable_elem_location,
11703                          &expr, &expr_len))
11704     return false;
11705
11706   int64_t i = 0;
11707   bool is_tls_addr = false;
11708   if (!eval_last_constant_dwarf_sub_expr(expr, expr_len, i, is_tls_addr))
11709     return false;
11710
11711   vindex = i;
11712   return true;
11713 }
11714
11715 /// Test if a given DIE represents an anonymous type.
11716 ///
11717 /// Anonymous types we are interested in are classes, unions and
11718 /// enumerations.
11719 ///
11720 /// @param die the DIE to consider.
11721 ///
11722 /// @return true iff @p die represents an anonymous type.
11723 bool
11724 is_anonymous_type_die(Dwarf_Die *die)
11725 {
11726   int tag = dwarf_tag(die);
11727
11728   if (tag == DW_TAG_class_type
11729       || tag == DW_TAG_structure_type
11730       || tag == DW_TAG_union_type
11731       || tag == DW_TAG_enumeration_type)
11732     return die_is_anonymous(die);
11733
11734   return false;
11735 }
11736
11737 /// Return the base of the internal name to represent an anonymous
11738 /// type.
11739 ///
11740 /// Typically, anonymous enums would be named
11741 /// __anonymous_enum__<number>, anonymous struct or classes would be
11742 /// named __anonymous_struct__<number> and anonymous unions would be
11743 /// named __anonymous_union__<number>.  The first part of these
11744 /// anonymous names (i.e, __anonymous_{enum,struct,union}__ is called
11745 /// the base name.  This function returns that base name, depending on
11746 /// the kind of type DIE we are looking at.
11747 ///
11748 /// @param die the type DIE to look at.  This function expects a type
11749 /// DIE with an empty DW_AT_name property value (anonymous).
11750 ///
11751 /// @return a string representing the base of the internal anonymous
11752 /// name.
11753 static string
11754 get_internal_anonymous_die_prefix_name(const Dwarf_Die *die)
11755 {
11756   ABG_ASSERT(die_is_type(die));
11757   ABG_ASSERT(die_string_attribute(die, DW_AT_name) == "");
11758
11759   int tag = dwarf_tag(const_cast<Dwarf_Die*>(die));
11760   string type_name;
11761   if (tag == DW_TAG_class_type || tag == DW_TAG_structure_type)
11762     type_name = tools_utils::get_anonymous_struct_internal_name_prefix();
11763   else if (tag == DW_TAG_union_type)
11764     type_name = tools_utils::get_anonymous_union_internal_name_prefix();
11765   else if (tag == DW_TAG_enumeration_type)
11766     type_name = tools_utils::get_anonymous_enum_internal_name_prefix();
11767
11768   return type_name;
11769 }
11770
11771 /// Build a full internal anonymous type name.
11772 ///
11773 /// @param base_name this is the base name as returned by the function
11774 /// @ref get_internal_anonymous_die_prefix_name.
11775 ///
11776 /// @param anonymous_type_index this is the index of the anonymous
11777 /// type in its scope.  That is, if there are more than one anonymous
11778 /// types of a given kind in a scope, this index is what tells them
11779 /// appart, starting from 0.
11780 ///
11781 /// @return the built string, which is a concatenation of @p base_name
11782 /// and @p anonymous_type_index.
11783 static string
11784 build_internal_anonymous_die_name(const string &base_name,
11785                                   size_t anonymous_type_index)
11786 {
11787   string name = base_name;
11788   if (anonymous_type_index && !base_name.empty())
11789     {
11790       std::ostringstream o;
11791       o << base_name << anonymous_type_index;
11792       name = o.str();
11793     }
11794   return name;
11795 }
11796
11797 /// Build a full internal anonymous type name.
11798 ///
11799 /// @param die the DIE representing the anonymous type to consider.
11800 ///
11801 /// @param anonymous_type_index the index of the anonymous type
11802 /// represented by @p DIE, in its scope.  That is, if there are
11803 /// several different anonymous types of the same kind as @p die, this
11804 /// index is what tells them appart.
11805 ///
11806 /// @return the internal name of the anonymous type represented by @p
11807 /// DIE.
11808 static string
11809 get_internal_anonymous_die_name(Dwarf_Die *die,
11810                                 size_t anonymous_type_index)
11811 {
11812   string name = get_internal_anonymous_die_prefix_name(die);
11813   name = build_internal_anonymous_die_name(name, anonymous_type_index);
11814   return name;
11815 }
11816
11817 // ------------------------------------
11818 // <DIE pretty printer>
11819 // ------------------------------------
11820
11821 /// Compute the qualified name of a DIE that represents a type.
11822 ///
11823 /// For instance, if the DIE tag is DW_TAG_subprogram then this
11824 /// function computes the name of the function *type*.
11825 ///
11826 /// @param ctxt the read context.
11827 ///
11828 /// @param die the DIE to consider.
11829 ///
11830 /// @param where_offset where in the are logically are in the DIE
11831 /// stream.
11832 ///
11833 /// @return a copy of the qualified name of the type.
11834 static string
11835 die_qualified_type_name(const read_context& ctxt,
11836                         const Dwarf_Die* die,
11837                         size_t where_offset)
11838 {
11839   if (!die)
11840     return "";
11841
11842   int tag = dwarf_tag (const_cast<Dwarf_Die*>(die));
11843   if (tag == DW_TAG_compile_unit
11844       || tag == DW_TAG_partial_unit
11845       || tag == DW_TAG_type_unit)
11846     return "";
11847
11848   string name = die_name(die);
11849
11850   Dwarf_Die scope_die;
11851   if (!get_scope_die(ctxt, die, where_offset, scope_die))
11852     return "";
11853
11854   string parent_name = die_qualified_name(ctxt, &scope_die, where_offset);
11855   bool colon_colon = die_is_type(die) || die_is_namespace(die);
11856   string separator = colon_colon ? "::" : ".";
11857
11858   string repr;
11859
11860   switch (tag)
11861     {
11862     case DW_TAG_unspecified_type:
11863       break;
11864
11865     case DW_TAG_base_type:
11866       {
11867         abigail::ir::integral_type int_type;
11868         if (parse_integral_type(name, int_type))
11869           repr = int_type;
11870         else
11871           repr = name;
11872       }
11873       break;
11874
11875     case DW_TAG_typedef:
11876     case DW_TAG_enumeration_type:
11877     case DW_TAG_structure_type:
11878     case DW_TAG_class_type:
11879     case DW_TAG_union_type:
11880       {
11881         if (tag == DW_TAG_typedef)
11882           {
11883             // If the underlying type of the typedef is unspecified,
11884             // bail out as we don't support that yet.
11885             Dwarf_Die underlying_type_die;
11886             if (die_die_attribute(die, DW_AT_type, underlying_type_die))
11887               {
11888                 string n = die_qualified_type_name(ctxt, &underlying_type_die,
11889                                                    where_offset);
11890                 if (die_is_unspecified(&underlying_type_die)
11891                     || n.empty())
11892                   break;
11893               }
11894           }
11895
11896         if (name.empty())
11897           // TODO: handle cases where there are more than one
11898           // anonymous type of the same kind in the same scope.  In
11899           // that case, their name must be built with the function
11900           // get_internal_anonymous_die_name or something of the same
11901           // kind.
11902           name = get_internal_anonymous_die_prefix_name(die);
11903
11904         ABG_ASSERT(!name.empty());
11905         repr = parent_name.empty() ? name : parent_name + separator + name;
11906       }
11907       break;
11908
11909     case DW_TAG_const_type:
11910     case DW_TAG_volatile_type:
11911     case DW_TAG_restrict_type:
11912       {
11913         Dwarf_Die underlying_type_die;
11914         bool has_underlying_type_die =
11915           die_die_attribute(die, DW_AT_type, underlying_type_die);
11916
11917         if (has_underlying_type_die && die_is_unspecified(&underlying_type_die))
11918           break;
11919
11920         if (tag == DW_TAG_const_type)
11921           {
11922             if (has_underlying_type_die
11923                 && die_is_reference_type(&underlying_type_die))
11924               // A reference is always const.  So, to lower false
11925               // positive reports in diff computations, we consider a
11926               // const reference just as a reference.  But we need to
11927               // keep the qualified-ness of the type.  So we introduce
11928               // a 'no-op' qualifier here.  Please remember that this
11929               // has to be kept in sync with what is done in
11930               // get_name_of_qualified_type.  So if you change this
11931               // here, you have to change that code there too.
11932               repr = "";
11933             else if (!has_underlying_type_die
11934                      || die_is_void_type(&underlying_type_die))
11935               {
11936                 repr = "void";
11937                 break;
11938               }
11939             else
11940               repr = "const";
11941           }
11942         else if (tag == DW_TAG_volatile_type)
11943           repr = "volatile";
11944         else if (tag == DW_TAG_restrict_type)
11945           repr = "restrict";
11946         else
11947           ABG_ASSERT_NOT_REACHED;
11948
11949         string underlying_type_repr;
11950         if (has_underlying_type_die)
11951           underlying_type_repr =
11952             die_qualified_type_name(ctxt, &underlying_type_die, where_offset);
11953         else
11954           underlying_type_repr = "void";
11955
11956         if (underlying_type_repr.empty())
11957           repr.clear();
11958         else
11959           {
11960             if (has_underlying_type_die
11961                 && die_is_pointer_or_reference_type(&underlying_type_die))
11962               repr = underlying_type_repr + " " + repr;
11963             else
11964               repr += " " + underlying_type_repr;
11965           }
11966       }
11967       break;
11968
11969     case DW_TAG_pointer_type:
11970     case DW_TAG_reference_type:
11971     case DW_TAG_rvalue_reference_type:
11972       {
11973         Dwarf_Die pointed_to_type_die;
11974         if (!die_die_attribute(die, DW_AT_type, pointed_to_type_die))
11975           {
11976             if (tag == DW_TAG_pointer_type)
11977               repr = "void*";
11978             break;
11979           }
11980
11981         if (die_is_unspecified(&pointed_to_type_die))
11982           break;
11983
11984         string pointed_type_repr =
11985           die_qualified_type_name(ctxt, &pointed_to_type_die, where_offset);
11986
11987         repr = pointed_type_repr;
11988         if (repr.empty())
11989           break;
11990
11991         if (tag == DW_TAG_pointer_type)
11992           repr += "*";
11993         else if (tag == DW_TAG_reference_type)
11994           repr += "&";
11995         else if (tag == DW_TAG_rvalue_reference_type)
11996           repr += "&&";
11997         else
11998           ABG_ASSERT_NOT_REACHED;
11999       }
12000       break;
12001
12002     case DW_TAG_subrange_type:
12003       {
12004         // In Ada, this one can be generated on its own, that is, not
12005         // as a sub-type of an array.  So we need to support it on its
12006         // own.  Note that when it's emitted as the sub-type of an
12007         // array like in C and C++, this is handled differently, for
12008         // now.  But we try to make this usable by other languages
12009         // that are not Ada, even if we modelled it after Ada.
12010
12011         // So we build a subrange type for the sole purpose of using
12012         // the ::as_string() method of that type.  So we don't add
12013         // that type to the current type tree being built.
12014         array_type_def::subrange_sptr s =
12015           build_subrange_type(const_cast<read_context&>(ctxt),
12016                               die, where_offset,
12017                               /*associate_die_to_type=*/false);
12018         repr += s->as_string();
12019         break;
12020       }
12021
12022     case DW_TAG_array_type:
12023       {
12024         Dwarf_Die element_type_die;
12025         if (!die_die_attribute(die, DW_AT_type, element_type_die))
12026           break;
12027         string element_type_name =
12028           die_qualified_type_name(ctxt, &element_type_die, where_offset);
12029         if (element_type_name.empty())
12030           break;
12031
12032         array_type_def::subranges_type subranges;
12033         build_subranges_from_array_type_die(const_cast<read_context&>(ctxt),
12034                                             die, subranges, where_offset,
12035                                             /*associate_type_to_die=*/false);
12036
12037         repr = element_type_name;
12038         repr += array_type_def::subrange_type::vector_as_string(subranges);
12039       }
12040       break;
12041
12042     case DW_TAG_subroutine_type:
12043     case DW_TAG_subprogram:
12044       {
12045         string return_type_name;
12046         string class_name;
12047         vector<string> parm_names;
12048         bool is_const = false;
12049         bool is_static = false;
12050
12051         die_return_and_parm_names_from_fn_type_die(ctxt, die, where_offset,
12052                                                    /*pretty_print=*/true,
12053                                                    return_type_name, class_name,
12054                                                    parm_names, is_const,
12055                                                    is_static);
12056         if (return_type_name.empty())
12057           return_type_name = "void";
12058
12059         repr = return_type_name;
12060
12061         if (!class_name.empty())
12062           {
12063             // This is a method, so print the class name.
12064             repr += " (" + class_name + "::*)";
12065           }
12066
12067         // Now parameters.
12068         repr += " (";
12069         for (vector<string>::const_iterator i = parm_names.begin();
12070              i != parm_names.end();
12071              ++i)
12072           {
12073             if (i != parm_names.begin())
12074               repr += ", ";
12075             repr += *i;
12076           }
12077         repr += ")";
12078
12079       }
12080       break;
12081
12082     case DW_TAG_string_type:
12083     case DW_TAG_ptr_to_member_type:
12084     case DW_TAG_set_type:
12085     case DW_TAG_file_type:
12086     case DW_TAG_packed_type:
12087     case DW_TAG_thrown_type:
12088     case DW_TAG_interface_type:
12089     case DW_TAG_shared_type:
12090       break;
12091     }
12092
12093   return repr;
12094 }
12095
12096 /// Compute the qualified name of a decl represented by a given DIE.
12097 ///
12098 /// For instance, for a DIE of tag DW_TAG_subprogram this function
12099 /// computes the signature of the function *declaration*.
12100 ///
12101 /// @param ctxt the read context.
12102 ///
12103 /// @param die the DIE to consider.
12104 ///
12105 /// @param where_offset where we are logically at in the DIE stream.
12106 ///
12107 /// @return a copy of the computed name.
12108 static string
12109 die_qualified_decl_name(const read_context& ctxt,
12110                         const Dwarf_Die* die,
12111                         size_t where_offset)
12112 {
12113   if (!die || !die_is_decl(die))
12114     return "";
12115
12116   string name = die_name(die);
12117
12118   Dwarf_Die scope_die;
12119   if (!get_scope_die(ctxt, die, where_offset, scope_die))
12120     return "";
12121
12122   string scope_name = die_qualified_name(ctxt, &scope_die, where_offset);
12123   string separator = "::";
12124
12125   string repr;
12126
12127   int tag = dwarf_tag(const_cast<Dwarf_Die*>(die));
12128   switch (tag)
12129     {
12130     case DW_TAG_namespace:
12131     case DW_TAG_member:
12132     case DW_TAG_variable:
12133       repr = scope_name.empty() ? name : scope_name + separator + name;
12134       break;
12135     case DW_TAG_subprogram:
12136       repr = die_function_signature(ctxt, die, where_offset);
12137       break;
12138
12139     case DW_TAG_unspecified_parameters:
12140       repr = "...";
12141       break;
12142
12143     case DW_TAG_formal_parameter:
12144     case DW_TAG_imported_declaration:
12145     case DW_TAG_GNU_template_template_param:
12146     case DW_TAG_GNU_template_parameter_pack:
12147     case DW_TAG_GNU_formal_parameter_pack:
12148       break;
12149     }
12150   return repr;
12151 }
12152
12153 /// Compute the qualified name of the artifact represented by a given
12154 /// DIE.
12155 ///
12156 /// If the DIE represents a type, then the function computes the name
12157 /// of the type.  Otherwise, if the DIE represents a decl then the
12158 /// function computes the name of the decl.  Note that a DIE of tag
12159 /// DW_TAG_subprogram is going to be considered as a "type" -- just
12160 /// like if it was a DW_TAG_subroutine_type.
12161 ///
12162 /// @param ctxt the read context.
12163 ///
12164 /// @param die the DIE to consider.
12165 ///
12166 /// @param where_offset where we are logically at in the DIE stream.
12167 ///
12168 /// @return a copy of the computed name.
12169 static string
12170 die_qualified_name(const read_context& ctxt, const Dwarf_Die* die, size_t where)
12171 {
12172   if (die_is_type(die))
12173     return die_qualified_type_name(ctxt, die, where);
12174   else if (die_is_decl(die))
12175     return die_qualified_decl_name(ctxt, die, where);
12176   return "";
12177 }
12178
12179 /// Test if the qualified name of a given type should be empty.
12180 ///
12181 /// The reason why the name of a DIE with a given tag would be empty
12182 /// is that libabigail's internal representation doesn't yet support
12183 /// that tag; or if the DIE's qualified name is built from names of
12184 /// sub-types DIEs whose tags are not yet supported.
12185 ///
12186 /// @param ctxt the reading context.
12187 ///
12188 /// @param die the DIE to consider.
12189 ///
12190 /// @param where where we are logically at, in the DIE stream.
12191 ///
12192 /// @param qualified_name the qualified name of the DIE.  This is set
12193 /// only iff the function returns false.
12194 ///
12195 /// @return true if the qualified name of the DIE is empty.
12196 static bool
12197 die_qualified_type_name_empty(const read_context& ctxt,
12198                               const Dwarf_Die* die,
12199                               size_t where, string &qualified_name)
12200 {
12201   if (!die)
12202     return true;
12203
12204   int tag = dwarf_tag(const_cast<Dwarf_Die*>(die));
12205
12206   string qname;
12207   if (tag == DW_TAG_typedef
12208       || tag == DW_TAG_pointer_type
12209       || tag == DW_TAG_reference_type
12210       || tag == DW_TAG_rvalue_reference_type
12211       || tag == DW_TAG_array_type
12212       || tag == DW_TAG_const_type
12213       || tag == DW_TAG_volatile_type
12214       || tag == DW_TAG_restrict_type)
12215     {
12216       Dwarf_Die underlying_type_die;
12217       if (die_die_attribute(die, DW_AT_type, underlying_type_die))
12218         {
12219           string name =
12220             die_qualified_type_name(ctxt, &underlying_type_die, where);
12221           if (name.empty())
12222             return true;
12223         }
12224     }
12225   else
12226     {
12227       string name = die_qualified_type_name(ctxt, die, where);
12228       if (name.empty())
12229         return true;
12230     }
12231
12232   qname = die_qualified_type_name(ctxt, die, where);
12233   if (qname.empty())
12234     return true;
12235
12236   qualified_name = qname;
12237   return false;
12238 }
12239
12240 /// Given the DIE that represents a function type, compute the names
12241 /// of the following properties the function's type:
12242 ///
12243 ///   - return type
12244 ///   - enclosing class (if the function is a member function)
12245 ///   - function parameter types
12246 ///
12247 /// When the function we are looking at is a member function, it also
12248 /// tells if it's const.
12249 ///
12250 /// @param ctxt the reading context.
12251 ///
12252 /// @param die the DIE of the function or function type we are looking
12253 /// at.
12254 ///
12255 /// @param where_offset where we are logically at in the DIE stream.
12256 ///
12257 /// @param pretty_print if set to yes, the type names are going to be
12258 /// pretty-printed names; otherwise, they are just qualified type
12259 /// names.
12260 ///
12261 /// @param return_type_name out parameter.  This contains the name of
12262 /// the return type of the function.
12263 ///
12264 /// @param class_name out parameter.  If the function is a member
12265 /// function, this contains the name of the enclosing class.
12266 ///
12267 /// @param parm_names out parameter.  This vector is set to the names
12268 /// of the types of the parameters of the function.
12269 ///
12270 /// @param is_const out parameter.  If the function is a member
12271 /// function, this is set to true iff the member function is const.
12272 ///
12273 /// @param is_static out parameter.  If the function is a static
12274 /// member function, then this is set to true.
12275 static void
12276 die_return_and_parm_names_from_fn_type_die(const read_context& ctxt,
12277                                            const Dwarf_Die* die,
12278                                            size_t where_offset,
12279                                            bool pretty_print,
12280                                            string &return_type_name,
12281                                            string &class_name,
12282                                            vector<string>& parm_names,
12283                                            bool& is_const,
12284                                            bool& is_static)
12285 {
12286   Dwarf_Die child;
12287   Dwarf_Die ret_type_die;
12288   if (!die_die_attribute(die, DW_AT_type, ret_type_die))
12289     return_type_name = "void";
12290   else
12291     return_type_name =
12292       pretty_print
12293       ? ctxt.get_die_pretty_representation(&ret_type_die, where_offset)
12294       : ctxt.get_die_qualified_type_name(&ret_type_die, where_offset);
12295
12296   if (return_type_name.empty())
12297     return_type_name = "void";
12298
12299   Dwarf_Die object_pointer_die, class_die;
12300   bool is_method_type =
12301     die_function_type_is_method_type(ctxt, die, where_offset,
12302                                      object_pointer_die,
12303                                      class_die, is_static);
12304
12305   is_const = false;
12306   if (is_method_type)
12307     {
12308       class_name = ctxt.get_die_qualified_type_name(&class_die, where_offset);
12309
12310       Dwarf_Die this_pointer_die;
12311       Dwarf_Die pointed_to_die;
12312       if (!is_static
12313           && die_die_attribute(&object_pointer_die, DW_AT_type,
12314                                this_pointer_die))
12315         if (die_die_attribute(&this_pointer_die, DW_AT_type, pointed_to_die))
12316           if (dwarf_tag(&pointed_to_die) == DW_TAG_const_type)
12317             is_const = true;
12318
12319       string fn_name = die_name(die);
12320       string non_qualified_class_name = die_name(&class_die);
12321       bool is_ctor = fn_name == non_qualified_class_name;
12322       bool is_dtor = !fn_name.empty() && fn_name[0] == '~';
12323
12324       if (is_ctor || is_dtor)
12325         return_type_name.clear();
12326     }
12327
12328   if (dwarf_child(const_cast<Dwarf_Die*>(die), &child) == 0)
12329     do
12330       {
12331         int child_tag = dwarf_tag(&child);
12332         if (child_tag == DW_TAG_formal_parameter)
12333           {
12334             Dwarf_Die parm_type_die;
12335             if (!die_die_attribute(&child, DW_AT_type, parm_type_die))
12336               continue;
12337             string qualified_name =
12338               pretty_print
12339               ? ctxt.get_die_pretty_representation(&parm_type_die, where_offset)
12340               : ctxt.get_die_qualified_type_name(&parm_type_die, where_offset);
12341
12342             if (qualified_name.empty())
12343               continue;
12344             parm_names.push_back(qualified_name);
12345           }
12346         else if (child_tag == DW_TAG_unspecified_parameters)
12347           {
12348             // This is a variadic function parameter.
12349             parm_names.push_back("variadic parameter type");
12350             // After a DW_TAG_unspecified_parameters tag, we shouldn't
12351             // keep reading for parameters.  The
12352             // unspecified_parameters TAG should be the last parameter
12353             // that we record. For instance, if there are multiple
12354             // DW_TAG_unspecified_parameters DIEs then we should care
12355             // only for the first one.
12356             break;
12357           }
12358       }
12359     while (dwarf_siblingof(&child, &child) == 0);
12360
12361   if (class_name.empty())
12362     {
12363       Dwarf_Die parent_die;
12364       if (get_parent_die(ctxt, die, parent_die, where_offset))
12365         {
12366           if (die_is_class_type(&parent_die))
12367             class_name =
12368               ctxt.get_die_qualified_type_name(&parent_die, where_offset);
12369         }
12370     }
12371 }
12372
12373 /// This computes the signature of the a function declaration
12374 /// represented by a DIE.
12375 ///
12376 /// @param ctxt the reading context.
12377 ///
12378 /// @param fn_die the DIE of the function to consider.
12379 ///
12380 /// @param where_offset where we are logically at in the stream of
12381 /// DIEs.
12382 ///
12383 /// @return a copy of the computed function signature string.
12384 static string
12385 die_function_signature(const read_context& ctxt,
12386                        const Dwarf_Die *fn_die,
12387                        size_t where_offset)
12388 {
12389
12390   translation_unit::language lang;
12391   bool has_lang = false;
12392   if ((has_lang = ctxt.get_die_language(fn_die, lang)))
12393     {
12394       // In a binary originating from the C language, it's OK to use
12395       // the linkage name of the function as a key for the map which
12396       // is meant to reduce the number of DIE comparisons involved
12397       // during DIE canonicalization computation.
12398       if (is_c_language(lang))
12399         {
12400           string fn_name = die_linkage_name(fn_die);
12401           if (fn_name.empty())
12402             fn_name = die_name(fn_die);
12403           return fn_name;
12404         }
12405     }
12406
12407   // TODO: When we can structurally compare DIEs originating from C++
12408   // as well, we can use the linkage name of functions in C++ too, to
12409   // reduce the number of comparisons involved during DIE
12410   // canonicalization.
12411
12412   string return_type_name;
12413   Dwarf_Die ret_type_die;
12414   if (die_die_attribute(fn_die, DW_AT_type, ret_type_die))
12415     return_type_name = ctxt.get_die_qualified_type_name(&ret_type_die,
12416                                                         where_offset);
12417
12418   if (return_type_name.empty())
12419     return_type_name = "void";
12420
12421   Dwarf_Die scope_die;
12422   string scope_name;
12423   if (get_scope_die(ctxt, fn_die, where_offset, scope_die))
12424     scope_name = ctxt.get_die_qualified_name(&scope_die, where_offset);
12425   string fn_name = die_name(fn_die);
12426   if (!scope_name.empty())
12427     fn_name  = scope_name + "::" + fn_name;
12428
12429   string class_name;
12430   vector<string> parm_names;
12431   bool is_const = false;
12432   bool is_static = false;
12433
12434   die_return_and_parm_names_from_fn_type_die(ctxt, fn_die, where_offset,
12435                                              /*pretty_print=*/false,
12436                                              return_type_name, class_name,
12437                                              parm_names, is_const, is_static);
12438
12439   bool is_virtual = die_is_virtual(fn_die);
12440
12441   string repr = class_name.empty() ? "function" : "method";
12442   if (is_virtual)
12443     repr += " virtual";
12444
12445   if (!return_type_name.empty())
12446     repr += " " + return_type_name;
12447
12448   repr += " " + fn_name;
12449
12450   // Now parameters.
12451   repr += "(";
12452   bool some_parm_emitted = false;
12453   for (vector<string>::const_iterator i = parm_names.begin();
12454        i != parm_names.end();
12455        ++i)
12456     {
12457       if (i != parm_names.begin())
12458         {
12459           if (some_parm_emitted)
12460             repr += ", ";
12461         }
12462       else
12463         if (!is_static && !class_name.empty())
12464           // We are printing a non-static method name, skip the implicit "this"
12465           // parameter type.
12466           continue;
12467       repr += *i;
12468       some_parm_emitted = true;
12469     }
12470   repr += ")";
12471
12472   if (is_const)
12473     {
12474       ABG_ASSERT(!class_name.empty());
12475       repr += " const";
12476     }
12477
12478   return repr;
12479 }
12480
12481 /// Return a pretty string representation of a type, for internal purposes.
12482 ///
12483 /// By internal purpose, we mean things like key-ing types for lookup
12484 /// purposes and so on.
12485 ///
12486 /// Note that this function is also used to pretty print functions.
12487 /// For functions, it prints the *type* of the function.
12488 ///
12489 /// @param ctxt the context to use.
12490 ///
12491 /// @param the DIE of the type to pretty print.
12492 ///
12493 /// @param where_offset where we logically are placed when calling
12494 /// this.  It's useful to handle inclusion of DW_TAG_compile_unit
12495 /// entries.
12496 ///
12497 /// @return the resulting pretty representation.
12498 static string
12499 die_pretty_print_type(read_context& ctxt,
12500                       const Dwarf_Die* die,
12501                       size_t where_offset)
12502 {
12503   if (!die
12504       || (!die_is_type(die)
12505           && dwarf_tag(const_cast<Dwarf_Die*>(die)) != DW_TAG_subprogram))
12506     return "";
12507
12508   string repr;
12509
12510   int tag = dwarf_tag(const_cast<Dwarf_Die*>(die));
12511   switch (tag)
12512     {
12513     case DW_TAG_string_type:
12514       // For now, we won't try to go get the actual representation of
12515       // the string because this would make things more complicated;
12516       // for that we'd need to interpret some location expressions to
12517       // get the length of the string.  And for dynamically allocated
12518       // strings, the result of the location expression evaluation
12519       // might not even be a constant.  So at the moment I consider
12520       // this to be a lot of hassle for no great return.  Until proven
12521       // otherwise, of course.
12522       repr = "string type";
12523
12524     case DW_TAG_unspecified_type:
12525     case DW_TAG_ptr_to_member_type:
12526       break;
12527
12528     case DW_TAG_namespace:
12529       repr = "namespace " + ctxt.get_die_qualified_type_name(die, where_offset);
12530       break;
12531
12532     case DW_TAG_base_type:
12533       repr = ctxt.get_die_qualified_type_name(die, where_offset);
12534       break;
12535
12536     case DW_TAG_typedef:
12537       {
12538         string qualified_name;
12539         if (!die_qualified_type_name_empty(ctxt, die,
12540                                            where_offset,
12541                                            qualified_name))
12542           repr = "typedef " + qualified_name;
12543       }
12544       break;
12545
12546     case DW_TAG_const_type:
12547     case DW_TAG_volatile_type:
12548     case DW_TAG_restrict_type:
12549     case DW_TAG_pointer_type:
12550     case DW_TAG_reference_type:
12551     case DW_TAG_rvalue_reference_type:
12552       repr = ctxt.get_die_qualified_type_name(die, where_offset);
12553       break;
12554
12555     case DW_TAG_enumeration_type:
12556       {
12557         string qualified_name =
12558           ctxt.get_die_qualified_type_name(die, where_offset);
12559         repr = "enum " + qualified_name;
12560       }
12561       break;
12562
12563     case DW_TAG_structure_type:
12564     case DW_TAG_class_type:
12565       {
12566         string qualified_name =
12567           ctxt.get_die_qualified_type_name(die, where_offset);
12568         repr = "class " + qualified_name;
12569       }
12570       break;
12571
12572     case DW_TAG_union_type:
12573       {
12574         string qualified_name =
12575           ctxt.get_die_qualified_type_name(die, where_offset);
12576         repr = "union " + qualified_name;
12577       }
12578       break;
12579
12580     case DW_TAG_array_type:
12581       {
12582         Dwarf_Die element_type_die;
12583         if (!die_die_attribute(die, DW_AT_type, element_type_die))
12584           break;
12585         string element_type_name =
12586           ctxt.get_die_qualified_type_name(&element_type_die, where_offset);
12587         if (element_type_name.empty())
12588           break;
12589
12590         array_type_def::subranges_type subranges;
12591         build_subranges_from_array_type_die(ctxt, die, subranges, where_offset,
12592                                             /*associate_type_to_die=*/false);
12593
12594         repr = element_type_name;
12595         repr += array_type_def::subrange_type::vector_as_string(subranges);
12596       }
12597       break;
12598
12599     case DW_TAG_subrange_type:
12600       {
12601         // So this can be generated by Ada, on its own; that is, not
12602         // as a subtype of an array.  In that case we need to handle
12603         // it properly.
12604
12605         // For now, we consider that the pretty printed name of the
12606         // subrange type is its name.  We might need something more
12607         // advance, should the needs of the users get more
12608         // complicated.
12609         repr += die_qualified_type_name(ctxt, die, where_offset);
12610       }
12611       break;
12612
12613     case DW_TAG_subroutine_type:
12614     case DW_TAG_subprogram:
12615       {
12616         string return_type_name;
12617         string class_name;
12618         vector<string> parm_names;
12619         bool is_const = false;
12620         bool is_static = false;
12621
12622         die_return_and_parm_names_from_fn_type_die(ctxt, die, where_offset,
12623                                                    /*pretty_print=*/true,
12624                                                    return_type_name, class_name,
12625                                                    parm_names, is_const,
12626                                                    is_static);
12627         if (class_name.empty())
12628           repr = "function type";
12629         else
12630           repr = "method type";
12631         repr += " " + ctxt.get_die_qualified_type_name(die, where_offset);
12632       }
12633       break;
12634
12635     case DW_TAG_set_type:
12636     case DW_TAG_file_type:
12637     case DW_TAG_packed_type:
12638     case DW_TAG_thrown_type:
12639     case DW_TAG_interface_type:
12640     case DW_TAG_shared_type:
12641       ABG_ASSERT_NOT_REACHED;
12642     }
12643
12644   return repr;
12645 }
12646
12647 /// Return a pretty string representation of a declaration, for
12648 /// internal purposes.
12649 ///
12650 /// By internal purpose, we mean things like key-ing declarations for
12651 /// lookup purposes and so on.
12652 ///
12653 /// Note that this function is also used to pretty print functions.
12654 /// For functions, it prints the signature of the function.
12655 ///
12656 /// @param ctxt the context to use.
12657 ///
12658 /// @param the DIE of the declaration to pretty print.
12659 ///
12660 /// @param where_offset where we logically are placed when calling
12661 /// this.  It's useful to handle inclusion of DW_TAG_compile_unit
12662 /// entries.
12663 ///
12664 /// @return the resulting pretty representation.
12665 static string
12666 die_pretty_print_decl(read_context& ctxt,
12667                       const Dwarf_Die* die,
12668                       size_t where_offset)
12669 {
12670   if (!die || !die_is_decl(die))
12671     return "";
12672
12673   string repr;
12674
12675   int tag = dwarf_tag(const_cast<Dwarf_Die*>(die));
12676   switch (tag)
12677     {
12678     case DW_TAG_namespace:
12679       repr = "namespace " + die_qualified_name(ctxt, die, where_offset);
12680       break;
12681
12682     case DW_TAG_member:
12683     case DW_TAG_variable:
12684       {
12685         string type_repr = "void";
12686         Dwarf_Die type_die;
12687         if (die_die_attribute(die, DW_AT_type, type_die))
12688           type_repr = die_qualified_type_name(ctxt, &type_die, where_offset);
12689         repr = die_qualified_name(ctxt, die, where_offset);
12690         if (!repr.empty())
12691           repr = type_repr + " " + repr;
12692       }
12693       break;
12694
12695     case DW_TAG_subprogram:
12696       repr = die_function_signature(ctxt, die, where_offset);
12697       break;
12698
12699     default:
12700       break;
12701     }
12702   return repr;
12703 }
12704
12705 /// Compute the pretty printed representation of an artifact
12706 /// represented by a DIE.
12707 ///
12708 /// If the DIE is a type, compute the its pretty representation as a
12709 /// type; otherwise, if it's a declaration, compute its pretty
12710 /// representation as a declaration.  Note for For instance, that a
12711 /// DW_TAG_subprogram DIE is going to be represented as a function
12712 /// *type*.
12713 ///
12714 /// @param ctxt the reading context.
12715 ///
12716 /// @param die the DIE to consider.
12717 ///
12718 /// @param where_offset we in the DIE stream we are logically at.
12719 ///
12720 /// @return a copy of the pretty printed artifact.
12721 static string
12722 die_pretty_print(read_context& ctxt, const Dwarf_Die* die, size_t where_offset)
12723 {
12724   if (die_is_type(die))
12725     return die_pretty_print_type(ctxt, die, where_offset);
12726   else if (die_is_decl(die))
12727     return die_pretty_print_decl(ctxt, die, where_offset);
12728   return "";
12729 }
12730
12731 // -----------------------------------
12732 // </die pretty printer>
12733 // -----------------------------------
12734
12735
12736 // ----------------------------------
12737 // <die comparison engine>
12738 // ---------------------------------
12739
12740 /// Compares two decls DIEs
12741 ///
12742 /// This works only for DIEs emitted by the C language.
12743 ///
12744 /// This implementation doesn't yet support namespaces.
12745 ///
12746 /// This is a subroutine of compare_dies.
12747 ///
12748 /// @return true iff @p l equals @p r.
12749 static bool
12750 compare_as_decl_dies(const Dwarf_Die *l, const Dwarf_Die *r)
12751 {
12752   ABG_ASSERT(l && r);
12753
12754   int l_tag = dwarf_tag(const_cast<Dwarf_Die*>(l));
12755   int r_tag = dwarf_tag(const_cast<Dwarf_Die*>(r));
12756   if (l_tag != r_tag)
12757     return false;
12758
12759   bool result = false;
12760
12761   if (l_tag == DW_TAG_subprogram || l_tag == DW_TAG_variable)
12762     {
12763       // Fast path for functions and global variables.
12764       if (compare_dies_string_attribute_value(l, r, DW_AT_linkage_name,
12765                                               result)
12766           || compare_dies_string_attribute_value(l, r, DW_AT_MIPS_linkage_name,
12767                                                  result))
12768         {
12769           if (!result)
12770             return false;
12771         }
12772
12773       if (compare_dies_string_attribute_value(l, r, DW_AT_name,
12774                                               result))
12775         {
12776           if (!result)
12777             return false;
12778         }
12779       return true;
12780     }
12781
12782   // Fast path for types.
12783   if (compare_dies_string_attribute_value(l, r, DW_AT_name,
12784                                           result))
12785     return result;
12786   return true;
12787 }
12788
12789 /// Compares two type DIEs
12790 ///
12791 /// This is a subroutine of compare_dies.
12792 ///
12793 /// @param l the left operand of the comparison operator.
12794 ///
12795 /// @param r the right operand of the comparison operator.
12796 ///
12797 /// @return true iff @p l equals @p r.
12798 static bool
12799 compare_as_type_dies(const Dwarf_Die *l, const Dwarf_Die *r)
12800 {
12801   ABG_ASSERT(l && r);
12802   ABG_ASSERT(die_is_type(l));
12803   ABG_ASSERT(die_is_type(r));
12804
12805   if (dwarf_tag(const_cast<Dwarf_Die*>(l)) == DW_TAG_string_type
12806       && dwarf_tag(const_cast<Dwarf_Die*>(r)) == DW_TAG_string_type
12807       && (dwarf_dieoffset(const_cast<Dwarf_Die*>(l))
12808           != dwarf_dieoffset(const_cast<Dwarf_Die*>(r))))
12809     // For now, we cannot compare DW_TAG_string_type because of its
12810     // string_length attribute that is a location descriptor that is
12811     // not necessarily a constant.  So it's super hard to evaluate it
12812     // in a libabigail context.  So for now, we just say that all
12813     // DW_TAG_string_type DIEs are different, by default.
12814     return false;
12815
12816   uint64_t l_size = 0, r_size = 0;
12817   die_size_in_bits(l, l_size);
12818   die_size_in_bits(r, r_size);
12819
12820   return l_size == r_size;
12821 }
12822
12823 /// Test if two DIEs representing function declarations have the same
12824 /// linkage name, and thus are considered equal if they are C or C++,
12825 /// because the two DIEs represent functions in the same binary.
12826 ///
12827 /// If the DIEs don't have a linkage name, the function compares their
12828 /// name.  But in that case, the caller of the function must know that
12829 /// in C++ for instance, that doesn't imply that the two functions are
12830 /// equal.
12831 ///
12832 /// @param ctxt the @ref read_context to consider.
12833 ///
12834 /// @param l the first function DIE to consider.
12835 ///
12836 /// @param r the second function DIE to consider.
12837 ///
12838 /// @return true iff the function represented by @p l have the same
12839 /// linkage name as the function represented by @p r.
12840 static bool
12841 fn_die_equal_by_linkage_name(const read_context &ctxt,
12842                              const Dwarf_Die *l,
12843                              const Dwarf_Die *r)
12844 {
12845   if (!!l != !!r)
12846     return false;
12847
12848   if (!l)
12849     return false;
12850
12851   int tag = dwarf_tag(const_cast<Dwarf_Die*>(l));
12852   ABG_ASSERT(tag == DW_TAG_subprogram);
12853   tag = dwarf_tag(const_cast<Dwarf_Die*>(r));
12854   ABG_ASSERT(tag == DW_TAG_subprogram);
12855
12856   string lname = die_name(l), rname = die_name(r);
12857   string llinkage_name = die_linkage_name(l),
12858     rlinkage_name = die_linkage_name(r);
12859
12860   if (ctxt.die_is_in_c_or_cplusplus(l)
12861       && ctxt.die_is_in_c_or_cplusplus(r))
12862     {
12863       if (!llinkage_name.empty() && !rlinkage_name.empty())
12864         return llinkage_name == rlinkage_name;
12865       else if (!!llinkage_name.empty() != !!rlinkage_name.empty())
12866         return false;
12867       else
12868         return lname == rname;
12869     }
12870
12871   return (!llinkage_name.empty()
12872           && !rlinkage_name.empty()
12873           && llinkage_name == rlinkage_name);
12874 }
12875
12876 /// Compare two DIEs emitted by a C compiler.
12877 ///
12878 /// @param ctxt the read context used to load the DWARF information.
12879 ///
12880 /// @param l the left-hand-side argument of this comparison operator.
12881 ///
12882 /// @param r the righ-hand-side argument of this comparison operator.
12883 ///
12884 /// @param aggregates_being_compared this holds the names of the set
12885 /// of aggregates being compared.  It's used by the comparison
12886 /// function to avoid recursing infinitely when faced with types
12887 /// referencing themselves through pointers or references.  By
12888 /// default, just pass an empty instance of @ref istring_set_type to
12889 /// it.
12890 ///
12891 /// @param update_canonical_dies_on_the_fly if true, when two
12892 /// sub-types compare equal (during the comparison of @p l and @p r)
12893 /// update their canonical type.  That way, two types of the same name
12894 /// are structurally compared to each other only once.  So the
12895 /// non-linear structural comparison of two types of the same name
12896 /// only happen once.
12897 ///
12898 /// @return true iff @p l equals @p r.
12899 static bool
12900 compare_dies(const read_context& ctxt,
12901              const Dwarf_Die *l, const Dwarf_Die *r,
12902              istring_set_type& aggregates_being_compared,
12903              bool update_canonical_dies_on_the_fly)
12904 {
12905   ABG_ASSERT(l);
12906   ABG_ASSERT(r);
12907
12908   int l_tag = dwarf_tag(const_cast<Dwarf_Die*>(l)),
12909     r_tag = dwarf_tag(const_cast<Dwarf_Die*>(r));
12910
12911   if (l_tag != r_tag)
12912     return false;
12913
12914   Dwarf_Off l_offset = dwarf_dieoffset(const_cast<Dwarf_Die*>(l)),
12915     r_offset = dwarf_dieoffset(const_cast<Dwarf_Die*>(r));
12916   Dwarf_Off l_canonical_die_offset = 0, r_canonical_die_offset = 0;
12917   die_source l_die_source, r_die_source;
12918   ABG_ASSERT(ctxt.get_die_source(l, l_die_source));
12919   ABG_ASSERT(ctxt.get_die_source(r, r_die_source));
12920
12921   // If 'l' and 'r' already have canonical DIEs, then just compare the
12922   // offsets of their canonical DIEs.
12923   bool l_has_canonical_die_offset =
12924     (l_canonical_die_offset =
12925      ctxt.get_canonical_die_offset(l_offset, l_die_source,
12926                                    /*die_as_type=*/true));
12927
12928   bool r_has_canonical_die_offset =
12929     (r_canonical_die_offset =
12930      ctxt.get_canonical_die_offset(r_offset, r_die_source,
12931                                    /*die_as_type=*/true));
12932
12933   if (l_has_canonical_die_offset && r_has_canonical_die_offset)
12934     return l_canonical_die_offset == r_canonical_die_offset;
12935
12936   bool result = true;
12937
12938   switch (l_tag)
12939     {
12940     case DW_TAG_base_type:
12941     case DW_TAG_string_type:
12942       if (!compare_as_type_dies(l, r)
12943           || !compare_as_decl_dies(l, r))
12944         result = false;
12945       break;
12946
12947     case DW_TAG_typedef:
12948     case DW_TAG_pointer_type:
12949     case DW_TAG_reference_type:
12950     case DW_TAG_rvalue_reference_type:
12951     case DW_TAG_const_type:
12952     case DW_TAG_volatile_type:
12953     case DW_TAG_restrict_type:
12954       {
12955         if (!compare_as_type_dies(l, r))
12956           {
12957             result = false;
12958             break;
12959           }
12960
12961         bool from_the_same_tu = false;
12962         if (!pointer_or_qual_die_of_anonymous_class_type(l)
12963             && compare_dies_cu_decl_file(l, r, from_the_same_tu)
12964             && from_the_same_tu)
12965           {
12966             // These two typedefs, pointer, reference, or qualified
12967             // types have the same name and are defined in the same TU.
12968             // They thus ought to be the same.
12969             //
12970             // Note that pointers, reference or qualified types to
12971             // anonymous types are not taking into account here because
12972             // those always need to be structurally compared.
12973             result = true;
12974             break;
12975           }
12976       }
12977
12978       {
12979         // No fancy optimization in this case.  We need to
12980         // structurally compare the two DIEs.
12981         Dwarf_Die lu_type_die, ru_type_die;
12982         bool lu_is_void, ru_is_void;
12983
12984         lu_is_void = !die_die_attribute(l, DW_AT_type, lu_type_die);
12985         ru_is_void = !die_die_attribute(r, DW_AT_type, ru_type_die);
12986
12987         if (lu_is_void && ru_is_void)
12988           result = true;
12989         else if (lu_is_void != ru_is_void)
12990           result = false;
12991         else
12992           result = compare_dies(ctxt, &lu_type_die, &ru_type_die,
12993                                 aggregates_being_compared,
12994                                 update_canonical_dies_on_the_fly);
12995       }
12996       break;
12997
12998     case DW_TAG_enumeration_type:
12999       if (!compare_as_type_dies(l, r)
13000           || !compare_as_decl_dies(l, r))
13001         result = false;
13002       else
13003         {
13004           // Walk the enumerators.
13005           Dwarf_Die l_enumtor, r_enumtor;
13006           bool found_l_enumtor, found_r_enumtor;
13007
13008           for (found_l_enumtor = dwarf_child(const_cast<Dwarf_Die*>(l),
13009                                              &l_enumtor) == 0,
13010                  found_r_enumtor = dwarf_child(const_cast<Dwarf_Die*>(r),
13011                                                &r_enumtor) == 0;
13012                found_l_enumtor && found_r_enumtor;
13013                found_l_enumtor = dwarf_siblingof(&l_enumtor, &l_enumtor) == 0,
13014                  found_r_enumtor = dwarf_siblingof(&r_enumtor, &r_enumtor) == 0)
13015             {
13016               int l_tag = dwarf_tag(&l_enumtor), r_tag = dwarf_tag(&r_enumtor);
13017               if ( l_tag != r_tag)
13018                 {
13019                   result = false;
13020                   break;
13021                 }
13022
13023               if (l_tag != DW_TAG_enumerator)
13024                 continue;
13025
13026               uint64_t l_val = 0, r_val = 0;
13027               die_unsigned_constant_attribute(&l_enumtor,
13028                                               DW_AT_const_value,
13029                                               l_val);
13030               die_unsigned_constant_attribute(&r_enumtor,
13031                                               DW_AT_const_value,
13032                                               r_val);
13033               if (l_val != r_val)
13034                 {
13035                   result = false;
13036                   break;
13037                 }
13038             }
13039           if (found_l_enumtor != found_r_enumtor )
13040             result = false;
13041
13042         }
13043       break;
13044
13045     case DW_TAG_structure_type:
13046     case DW_TAG_union_type:
13047       {
13048         interned_string ln = ctxt.get_die_pretty_type_representation(l, 0);
13049         interned_string rn = ctxt.get_die_pretty_type_representation(r, 0);
13050
13051         if ((aggregates_being_compared.find(ln)
13052              != aggregates_being_compared.end())
13053             || (aggregates_being_compared.find(rn)
13054                 != aggregates_being_compared.end()))
13055           result = true;
13056         else if (!compare_as_decl_dies(l, r))
13057           result = false;
13058         else if (!compare_as_type_dies(l, r))
13059           result = false;
13060         else
13061           {
13062             aggregates_being_compared.insert(ln);
13063             aggregates_being_compared.insert(rn);
13064
13065             Dwarf_Die l_member, r_member;
13066             bool found_l_member, found_r_member;
13067             for (found_l_member = dwarf_child(const_cast<Dwarf_Die*>(l),
13068                                               &l_member) == 0,
13069                    found_r_member = dwarf_child(const_cast<Dwarf_Die*>(r),
13070                                                 &r_member) == 0;
13071                  found_l_member && found_r_member;
13072                  found_l_member = dwarf_siblingof(&l_member, &l_member) == 0,
13073                    found_r_member = dwarf_siblingof(&r_member, &r_member) == 0)
13074               {
13075                 int l_tag = dwarf_tag(&l_member), r_tag = dwarf_tag(&r_member);
13076                 if (l_tag != r_tag)
13077                   {
13078                     result = false;
13079                     break;
13080                   }
13081
13082                 if (l_tag != DW_TAG_member && l_tag != DW_TAG_variable)
13083                   continue;
13084
13085                 if (!compare_dies(ctxt, &l_member, &r_member,
13086                                   aggregates_being_compared,
13087                                   update_canonical_dies_on_the_fly))
13088                   {
13089                     result = false;
13090                     break;
13091                   }
13092               }
13093             if (found_l_member != found_r_member)
13094               result = false;
13095
13096             aggregates_being_compared.erase(ln);
13097             aggregates_being_compared.erase(rn);
13098           }
13099       }
13100       break;
13101
13102     case DW_TAG_array_type:
13103       {
13104         Dwarf_Die l_child, r_child;
13105         bool found_l_child, found_r_child;
13106         for (found_l_child = dwarf_child(const_cast<Dwarf_Die*>(l),
13107                                          &l_child) == 0,
13108                found_r_child = dwarf_child(const_cast<Dwarf_Die*>(r),
13109                                            &r_child) == 0;
13110              found_l_child && found_r_child;
13111              found_l_child = dwarf_siblingof(&l_child, &l_child) == 0,
13112                found_r_child = dwarf_siblingof(&r_child, &r_child) == 0)
13113           {
13114             int l_child_tag = dwarf_tag(&l_child),
13115               r_child_tag = dwarf_tag(&r_child);
13116             if (l_child_tag == DW_TAG_subrange_type
13117                 || r_child_tag == DW_TAG_subrange_type)
13118               if (!compare_dies(ctxt, &l_child, &r_child,
13119                                 aggregates_being_compared,
13120                                 update_canonical_dies_on_the_fly))
13121                 {
13122                   result = false;
13123                   break;
13124                 }
13125           }
13126         if (found_l_child != found_r_child)
13127           result = false;
13128       }
13129       break;
13130
13131     case DW_TAG_subrange_type:
13132       {
13133         uint64_t l_lower_bound = 0, r_lower_bound = 0,
13134           l_upper_bound = 0, r_upper_bound = 0;
13135         die_unsigned_constant_attribute(l, DW_AT_lower_bound, l_lower_bound);
13136         die_unsigned_constant_attribute(r, DW_AT_lower_bound, r_lower_bound);
13137         if (!die_unsigned_constant_attribute(l, DW_AT_upper_bound,
13138                                              l_upper_bound))
13139           {
13140             uint64_t l_count = 0;
13141             if (die_unsigned_constant_attribute(l, DW_AT_count, l_count))
13142               {
13143                 l_upper_bound = l_lower_bound + l_count;
13144                 if (l_upper_bound)
13145                   --l_upper_bound;
13146               }
13147           }
13148         if (!die_unsigned_constant_attribute(r, DW_AT_upper_bound,
13149                                              r_upper_bound))
13150           {
13151             uint64_t r_count = 0;
13152             if (die_unsigned_constant_attribute(l, DW_AT_count, r_count))
13153               {
13154                 r_upper_bound = r_lower_bound + r_count;
13155                 if (r_upper_bound)
13156                   --r_upper_bound;
13157               }
13158           }
13159
13160         if ((l_lower_bound != r_lower_bound)
13161             || (l_upper_bound != r_upper_bound))
13162           result = false;
13163       }
13164       break;
13165
13166     case DW_TAG_subroutine_type:
13167     case DW_TAG_subprogram:
13168       {
13169         interned_string ln = ctxt.get_die_pretty_type_representation(l, 0);
13170         interned_string rn = ctxt.get_die_pretty_type_representation(r, 0);
13171
13172         if ((aggregates_being_compared.find(ln)
13173              != aggregates_being_compared.end())
13174             || (aggregates_being_compared.find(rn)
13175                 != aggregates_being_compared.end()))
13176           result = true;
13177       else if (l_tag == DW_TAG_subroutine_type)
13178         {
13179           // The string reprs of l and r are already equal.  Now let's
13180           // just check if they both come from the same TU.
13181           bool from_the_same_tu = false;
13182           if (compare_dies_cu_decl_file(l, r, from_the_same_tu)
13183               && from_the_same_tu)
13184             result = true;
13185         }
13186       else
13187         {
13188           if (!fn_die_equal_by_linkage_name(ctxt, l, r))
13189             {
13190               result = false;
13191               break;
13192             }
13193
13194           if (!ctxt.die_is_in_c(l) && !ctxt.die_is_in_c(r))
13195             {
13196               // In C, we cannot have two different functions with the
13197               // same linkage name in a given binary.  But here we are
13198               // looking at DIEs that don't originate from C.  So we
13199               // need to compare return types and parameter types.
13200               Dwarf_Die l_return_type, r_return_type;
13201               bool l_return_type_is_void = !die_die_attribute(l, DW_AT_type,
13202                                                               l_return_type);
13203               bool r_return_type_is_void = !die_die_attribute(r, DW_AT_type,
13204                                                               r_return_type);
13205               if (l_return_type_is_void != r_return_type_is_void
13206                   || (!l_return_type_is_void
13207                       && !compare_dies(ctxt,
13208                                        &l_return_type, &r_return_type,
13209                                        aggregates_being_compared,
13210                                        update_canonical_dies_on_the_fly)))
13211                 result = false;
13212               else
13213                 {
13214                   Dwarf_Die l_child, r_child;
13215                   bool found_l_child, found_r_child;
13216                   for (found_l_child = dwarf_child(const_cast<Dwarf_Die*>(l),
13217                                                    &l_child) == 0,
13218                          found_r_child = dwarf_child(const_cast<Dwarf_Die*>(r),
13219                                                      &r_child) == 0;
13220                        found_l_child && found_r_child;
13221                        found_l_child = dwarf_siblingof(&l_child,
13222                                                        &l_child) == 0,
13223                          found_r_child = dwarf_siblingof(&r_child,
13224                                                          &r_child)==0)
13225                     {
13226                       int l_child_tag = dwarf_tag(&l_child);
13227                       int r_child_tag = dwarf_tag(&r_child);
13228                       if (l_child_tag != r_child_tag
13229                           || (l_child_tag == DW_TAG_formal_parameter
13230                               && !compare_dies(ctxt, &l_child, &r_child,
13231                                                aggregates_being_compared,
13232                                                update_canonical_dies_on_the_fly)))
13233                         {
13234                           result = false;
13235                           break;
13236                         }
13237                     }
13238                   if (found_l_child != found_r_child)
13239                     result = false;
13240                 }
13241             }
13242
13243           aggregates_being_compared.erase(ln);
13244           aggregates_being_compared.erase(rn);
13245         }
13246       }
13247       break;
13248
13249     case DW_TAG_formal_parameter:
13250       {
13251         Dwarf_Die l_type, r_type;
13252         bool l_type_is_void = !die_die_attribute(l, DW_AT_type, l_type);
13253         bool r_type_is_void = !die_die_attribute(r, DW_AT_type, r_type);
13254         if ((l_type_is_void != r_type_is_void)
13255             || !compare_dies(ctxt, &l_type, &r_type,
13256                              aggregates_being_compared,
13257                              update_canonical_dies_on_the_fly))
13258           result = false;
13259       }
13260       break;
13261
13262     case DW_TAG_variable:
13263     case DW_TAG_member:
13264       if (compare_as_decl_dies(l, r))
13265         {
13266           // Compare the offsets of the data members
13267           if (l_tag == DW_TAG_member)
13268             {
13269               int64_t l_offset_in_bits = 0, r_offset_in_bits = 0;
13270               die_member_offset(ctxt, l, l_offset_in_bits);
13271               die_member_offset(ctxt, r, r_offset_in_bits);
13272               if (l_offset_in_bits != r_offset_in_bits)
13273                 result = false;
13274             }
13275           if (result)
13276             {
13277               // Compare the types of the data members or variables.
13278               Dwarf_Die l_type, r_type;
13279               ABG_ASSERT(die_die_attribute(l, DW_AT_type, l_type));
13280               ABG_ASSERT(die_die_attribute(r, DW_AT_type, r_type));
13281               if (aggregates_being_compared.size () < 5)
13282                 {
13283                   if (!compare_dies(ctxt, &l_type, &r_type,
13284                                     aggregates_being_compared,
13285                                     update_canonical_dies_on_the_fly))
13286                     result = false;
13287                 }
13288               else
13289                 {
13290                   if (!compare_as_type_dies(&l_type, &r_type)
13291                       ||!compare_as_decl_dies(&l_type, &r_type))
13292                     return false;
13293                 }
13294             }
13295         }
13296       else
13297         result = false;
13298       break;
13299
13300     case DW_TAG_class_type:
13301     case DW_TAG_enumerator:
13302     case DW_TAG_packed_type:
13303     case DW_TAG_set_type:
13304     case DW_TAG_file_type:
13305     case DW_TAG_ptr_to_member_type:
13306     case DW_TAG_thrown_type:
13307     case DW_TAG_interface_type:
13308     case DW_TAG_unspecified_type:
13309     case DW_TAG_shared_type:
13310     case DW_TAG_compile_unit:
13311     case DW_TAG_namespace:
13312     case DW_TAG_module:
13313     case DW_TAG_constant:
13314     case DW_TAG_partial_unit:
13315     case DW_TAG_imported_unit:
13316     case DW_TAG_dwarf_procedure:
13317     case DW_TAG_imported_declaration:
13318     case DW_TAG_entry_point:
13319     case DW_TAG_label:
13320     case DW_TAG_lexical_block:
13321     case DW_TAG_unspecified_parameters:
13322     case DW_TAG_variant:
13323     case DW_TAG_common_block:
13324     case DW_TAG_common_inclusion:
13325     case DW_TAG_inheritance:
13326     case DW_TAG_inlined_subroutine:
13327     case DW_TAG_with_stmt:
13328     case DW_TAG_access_declaration:
13329     case DW_TAG_catch_block:
13330     case DW_TAG_friend:
13331     case DW_TAG_namelist:
13332     case DW_TAG_namelist_item:
13333     case DW_TAG_template_type_parameter:
13334     case DW_TAG_template_value_parameter:
13335     case DW_TAG_try_block:
13336     case DW_TAG_variant_part:
13337     case DW_TAG_imported_module:
13338     case DW_TAG_condition:
13339     case DW_TAG_type_unit:
13340     case DW_TAG_template_alias:
13341     case DW_TAG_lo_user:
13342     case DW_TAG_MIPS_loop:
13343     case DW_TAG_format_label:
13344     case DW_TAG_function_template:
13345     case DW_TAG_class_template:
13346     case DW_TAG_GNU_BINCL:
13347     case DW_TAG_GNU_EINCL:
13348     case DW_TAG_GNU_template_template_param:
13349     case DW_TAG_GNU_template_parameter_pack:
13350     case DW_TAG_GNU_formal_parameter_pack:
13351     case DW_TAG_GNU_call_site:
13352     case DW_TAG_GNU_call_site_parameter:
13353     case DW_TAG_hi_user:
13354       ABG_ASSERT_NOT_REACHED;
13355     }
13356
13357   if (result == true
13358       && update_canonical_dies_on_the_fly
13359       && is_canonicalizeable_type_tag(l_tag))
13360     {
13361       // If 'l' has no canonical DIE and if 'r' has one, then propagage
13362       // the canonical DIE of 'r' to 'l'.
13363       //
13364       // In case 'r' has no canonical DIE, then compute it, and then
13365       // propagate that canonical DIE to 'r'.
13366       die_source l_source = NO_DEBUG_INFO_DIE_SOURCE,
13367         r_source = NO_DEBUG_INFO_DIE_SOURCE;
13368       ABG_ASSERT(ctxt.get_die_source(l, l_source));
13369       ABG_ASSERT(ctxt.get_die_source(r, r_source));
13370       if (!l_has_canonical_die_offset
13371           // A DIE can be equivalent only to another DIE of the same
13372           // source.
13373           && l_source == r_source)
13374         {
13375           if (!r_has_canonical_die_offset)
13376             ctxt.compute_canonical_die_offset(r, r_canonical_die_offset,
13377                                               /*die_as_type=*/true);
13378           ABG_ASSERT(r_canonical_die_offset);
13379           ctxt.set_canonical_die_offset(l, r_canonical_die_offset,
13380                                         /*die_as_type=*/true);
13381         }
13382     }
13383   return result;
13384 }
13385
13386 /// Compare two DIEs emitted by a C compiler.
13387 ///
13388 /// @param ctxt the read context used to load the DWARF information.
13389 ///
13390 /// @param l the left-hand-side argument of this comparison operator.
13391 ///
13392 /// @param r the righ-hand-side argument of this comparison operator.
13393 ///
13394 /// @param update_canonical_dies_on_the_fly if yes, then this function
13395 /// updates the canonical DIEs of sub-type DIEs of 'l' and 'r', while
13396 /// comparing l and r.  This helps in making so that sub-type DIEs of
13397 /// 'l' and 'r' are compared structurally only once.  This is how we
13398 /// turn this exponential comparison problem into a problem that is a
13399 /// closer to a linear one.
13400 ///
13401 /// @return true iff @p l equals @p r.
13402 static bool
13403 compare_dies(const read_context& ctxt,
13404              const Dwarf_Die *l,
13405              const Dwarf_Die *r,
13406              bool update_canonical_dies_on_the_fly)
13407 {
13408   istring_set_type aggregates_being_compared;
13409   return compare_dies(ctxt, l, r, aggregates_being_compared,
13410                       update_canonical_dies_on_the_fly);
13411 }
13412
13413 // ----------------------------------
13414 // </die comparison engine>
13415 // ---------------------------------
13416
13417 /// Get the point where a DW_AT_import DIE is used to import a given
13418 /// (unit) DIE, between two DIEs.
13419 ///
13420 /// @param ctxt the dwarf reading context to consider.
13421 ///
13422 /// @param partial_unit_offset the imported unit for which we want to
13423 /// know the insertion point.  This is usually a partial unit (with
13424 /// tag DW_TAG_partial_unit) but it does not necessarily have to be
13425 /// so.
13426 ///
13427 /// @param first_die_offset the offset of the DIE from which this
13428 /// function starts looking for the import point of
13429 /// @partial_unit_offset.  Note that this offset is excluded from the
13430 /// set of potential solutions.
13431 ///
13432 /// @param first_die_cu_offset the offset of the (compilation) unit
13433 /// that @p first_die_cu_offset belongs to.
13434 ///
13435 /// @param source where the DIE of first_die_cu_offset unit comes
13436 /// from.
13437 ///
13438 /// @param last_die_offset the offset of the last DIE of the up to
13439 /// which this function looks for the import point of @p
13440 /// partial_unit_offset.  Note that this offset is excluded from the
13441 /// set of potential solutions.
13442 ///
13443 /// @param imported_point_offset.  The resulting
13444 /// imported_point_offset.  Note that if the imported DIE @p
13445 /// partial_unit_offset is not found between @p first_die_offset and
13446 /// @p last_die_offset, this parameter is left untouched by this
13447 /// function.
13448 ///
13449 /// @return true iff an imported unit is found between @p
13450 /// first_die_offset and @p last_die_offset.
13451 static bool
13452 find_import_unit_point_between_dies(const read_context& ctxt,
13453                                     size_t              partial_unit_offset,
13454                                     Dwarf_Off           first_die_offset,
13455                                     Dwarf_Off           first_die_cu_offset,
13456                                     die_source          source,
13457                                     size_t              last_die_offset,
13458                                     size_t&             imported_point_offset)
13459 {
13460   const tu_die_imported_unit_points_map_type& tu_die_imported_unit_points_map =
13461     ctxt.tu_die_imported_unit_points_map(source);
13462
13463   tu_die_imported_unit_points_map_type::const_iterator iter =
13464     tu_die_imported_unit_points_map.find(first_die_cu_offset);
13465
13466   ABG_ASSERT(iter != tu_die_imported_unit_points_map.end());
13467
13468   const imported_unit_points_type& imported_unit_points = iter->second;
13469   if (imported_unit_points.empty())
13470     return false;
13471
13472   imported_unit_points_type::const_iterator b = imported_unit_points.begin();
13473   imported_unit_points_type::const_iterator e = imported_unit_points.end();
13474
13475   find_lower_bound_in_imported_unit_points(imported_unit_points,
13476                                            first_die_offset,
13477                                            b);
13478
13479   if (last_die_offset != static_cast<size_t>(-1))
13480     find_lower_bound_in_imported_unit_points(imported_unit_points,
13481                                              last_die_offset,
13482                                              e);
13483
13484   if (e != imported_unit_points.end())
13485     {
13486       for (imported_unit_points_type::const_iterator i = e; i >= b; --i)
13487         if (i->imported_unit_die_off == partial_unit_offset)
13488           {
13489             imported_point_offset = i->offset_of_import ;
13490             return true;
13491           }
13492
13493       for (imported_unit_points_type::const_iterator i = e; i >= b; --i)
13494         {
13495           if (find_import_unit_point_between_dies(ctxt,
13496                                                   partial_unit_offset,
13497                                                   i->imported_unit_child_off,
13498                                                   i->imported_unit_cu_off,
13499                                                   i->imported_unit_die_source,
13500                                                   /*(Dwarf_Off)*/-1,
13501                                                   imported_point_offset))
13502             return true;
13503         }
13504     }
13505   else
13506     {
13507       for (imported_unit_points_type::const_iterator i = b; i != e; ++i)
13508         if (i->imported_unit_die_off == partial_unit_offset)
13509           {
13510             imported_point_offset = i->offset_of_import ;
13511             return true;
13512           }
13513
13514       for (imported_unit_points_type::const_iterator i = b; i != e; ++i)
13515         {
13516           if (find_import_unit_point_between_dies(ctxt,
13517                                                   partial_unit_offset,
13518                                                   i->imported_unit_child_off,
13519                                                   i->imported_unit_cu_off,
13520                                                   i->imported_unit_die_source,
13521                                                   /*(Dwarf_Off)*/-1,
13522                                                   imported_point_offset))
13523             return true;
13524         }
13525     }
13526
13527   return false;
13528 }
13529
13530 /// In the current translation unit, get the last point where a
13531 /// DW_AT_import DIE is used to import a given (unit) DIE, before a
13532 /// given DIE is found.  That given DIE is called the limit DIE.
13533 ///
13534 /// Said otherwise, this function returns the last import point of a
13535 /// unit, before a limit.
13536 ///
13537 /// @param ctxt the dwarf reading context to consider.
13538 ///
13539 /// @param partial_unit_offset the imported unit for which we want to
13540 /// know the insertion point of.  This is usually a partial unit (with
13541 /// tag DW_TAG_partial_unit) but it does not necessarily have to be
13542 /// so.
13543 ///
13544 /// @param where_offset the offset of the limit DIE.
13545 ///
13546 /// @param imported_point_offset.  The resulting imported_point_offset.
13547 /// Note that if the imported DIE @p partial_unit_offset is not found
13548 /// before @p die_offset, this is set to the last @p
13549 /// partial_unit_offset found under @p parent_die.
13550 ///
13551 /// @return true iff an imported unit is found before @p die_offset.
13552 /// Note that if an imported unit is found after @p die_offset then @p
13553 /// imported_point_offset is set and the function return false.
13554 static bool
13555 find_import_unit_point_before_die(const read_context&   ctxt,
13556                                   size_t                partial_unit_offset,
13557                                   size_t                where_offset,
13558                                   size_t&               imported_point_offset)
13559 {
13560   size_t import_point_offset = 0;
13561   Dwarf_Die first_die_of_tu;
13562
13563   if (dwarf_child(const_cast<Dwarf_Die*>(ctxt.cur_tu_die()),
13564                   &first_die_of_tu) != 0)
13565     return false;
13566
13567   Dwarf_Die cu_die_memory;
13568   Dwarf_Die *cu_die;
13569
13570   cu_die = dwarf_diecu(const_cast<Dwarf_Die*>(&first_die_of_tu),
13571                        &cu_die_memory, 0, 0);
13572
13573   if (find_import_unit_point_between_dies(ctxt, partial_unit_offset,
13574                                           dwarf_dieoffset(&first_die_of_tu),
13575                                           dwarf_dieoffset(cu_die),
13576                                           /*source=*/PRIMARY_DEBUG_INFO_DIE_SOURCE,
13577                                           where_offset,
13578                                           import_point_offset))
13579     {
13580       imported_point_offset = import_point_offset;
13581       return true;
13582     }
13583
13584   if (import_point_offset)
13585     {
13586       imported_point_offset = import_point_offset;
13587       return true;
13588     }
13589
13590   return false;
13591 }
13592
13593 /// Return the parent DIE for a given DIE.
13594 ///
13595 /// Note that the function build_die_parent_map() must have been
13596 /// called before this one can work.  This function either succeeds or
13597 /// aborts the current process.
13598 ///
13599 /// @param ctxt the read context to consider.
13600 ///
13601 /// @param die the DIE for which we want the parent.
13602 ///
13603 /// @param parent_die the output parameter set to the parent die of
13604 /// @p die.  Its memory must be allocated and handled by the caller.
13605 ///
13606 /// @param where_offset the offset of the DIE where we are "logically"
13607 /// positionned at, in the DIE tree.  This is useful when @p die is
13608 /// e.g, DW_TAG_partial_unit that can be included in several places in
13609 /// the DIE tree.
13610 ///
13611 /// @return true if the function could get a parent DIE, false
13612 /// otherwise.
13613 static bool
13614 get_parent_die(const read_context&      ctxt,
13615                const Dwarf_Die* die,
13616                Dwarf_Die&               parent_die,
13617                size_t                   where_offset)
13618 {
13619   ABG_ASSERT(ctxt.dwarf());
13620
13621   die_source source = NO_DEBUG_INFO_DIE_SOURCE;
13622   ABG_ASSERT(ctxt.get_die_source(die, source));
13623
13624   const offset_offset_map_type& m = ctxt.die_parent_map(source);
13625   offset_offset_map_type::const_iterator i =
13626     m.find(dwarf_dieoffset(const_cast<Dwarf_Die*>(die)));
13627
13628   if (i == m.end())
13629     return false;
13630
13631   switch (source)
13632     {
13633     case PRIMARY_DEBUG_INFO_DIE_SOURCE:
13634       ABG_ASSERT(dwarf_offdie(ctxt.dwarf(), i->second, &parent_die));
13635       break;
13636     case ALT_DEBUG_INFO_DIE_SOURCE:
13637       ABG_ASSERT(dwarf_offdie(ctxt.alt_dwarf(), i->second, &parent_die));
13638       break;
13639     case TYPE_UNIT_DIE_SOURCE:
13640       ABG_ASSERT(dwarf_offdie_types(ctxt.dwarf(), i->second, &parent_die));
13641       break;
13642     case NO_DEBUG_INFO_DIE_SOURCE:
13643     case NUMBER_OF_DIE_SOURCES:
13644       ABG_ASSERT_NOT_REACHED;
13645     }
13646
13647   if (dwarf_tag(&parent_die) == DW_TAG_partial_unit)
13648     {
13649       if (where_offset == 0)
13650         {
13651           parent_die = *ctxt.cur_tu_die();
13652           return true;
13653         }
13654       size_t import_point_offset = 0;
13655       bool found =
13656         find_import_unit_point_before_die(ctxt,
13657                                           dwarf_dieoffset(&parent_die),
13658                                           where_offset,
13659                                           import_point_offset);
13660       if (!found)
13661         // It looks like parent_die (which comes from the alternate
13662         // debug info file) hasn't been imported into this TU.  So,
13663         // Let's assume its logical parent is the DIE of the current
13664         // TU.
13665         parent_die = *ctxt.cur_tu_die();
13666       else
13667         {
13668           ABG_ASSERT(import_point_offset);
13669           Dwarf_Die import_point_die;
13670           ABG_ASSERT(dwarf_offdie(ctxt.dwarf(),
13671                               import_point_offset,
13672                               &import_point_die));
13673           return get_parent_die(ctxt, &import_point_die,
13674                                 parent_die, where_offset);
13675         }
13676     }
13677
13678   return true;
13679 }
13680
13681 /// Get the DIE representing the scope of a given DIE.
13682 ///
13683 /// Please note that when the DIE we are looking at has a
13684 /// DW_AT_specification or DW_AT_abstract_origin attribute, the scope
13685 /// DIE is the parent DIE of the DIE referred to by that attribute.
13686 /// This is the only case where a scope DIE is different from the
13687 /// parent DIE of a given DIE.
13688 ///
13689 /// Also note that if the current translation unit is from C, then
13690 /// this returns the global scope.
13691 ///
13692 /// @param ctxt the reading context to use.
13693 ///
13694 /// @param die the DIE to consider.
13695 ///
13696 /// @param where_offset where we are logically at in the DIE stream.
13697 ///
13698 /// @param scope_die out parameter.  This is set to the resulting
13699 /// scope DIE iff the function returns true.
13700 static bool
13701 get_scope_die(const read_context&       ctxt,
13702               const Dwarf_Die*          die,
13703               size_t                    where_offset,
13704               Dwarf_Die&                scope_die)
13705 {
13706   if (is_c_language(ctxt.cur_transl_unit()->get_language()))
13707     {
13708       ABG_ASSERT(dwarf_tag(const_cast<Dwarf_Die*>(die)) != DW_TAG_member);
13709       return dwarf_diecu(const_cast<Dwarf_Die*>(die), &scope_die, 0, 0);
13710     }
13711
13712   Dwarf_Die logical_parent_die;
13713   if (die_die_attribute(die, DW_AT_specification,
13714                         logical_parent_die, false)
13715       || die_die_attribute(die, DW_AT_abstract_origin,
13716                            logical_parent_die, false))
13717     return get_scope_die(ctxt, &logical_parent_die, where_offset, scope_die);
13718
13719   if (!get_parent_die(ctxt, die, scope_die, where_offset))
13720     return false;
13721
13722   if (dwarf_tag(&scope_die) == DW_TAG_subprogram
13723       || dwarf_tag(&scope_die) == DW_TAG_subroutine_type
13724       || dwarf_tag(&scope_die) == DW_TAG_array_type)
13725     return get_scope_die(ctxt, &scope_die, where_offset, scope_die);
13726
13727   return true;
13728 }
13729
13730 /// Return the abigail IR node representing the scope of a given DIE.
13731 ///
13732 /// Note that it is the logical scope that is returned.  That is, if
13733 /// the DIE has a DW_AT_specification or DW_AT_abstract_origin
13734 /// attribute, it's the scope of the referred-to DIE (via these
13735 /// attributes) that is returned.
13736 ///
13737 /// Also note that if the current translation unit is from C, then
13738 /// this returns the global scope.
13739 ///
13740 /// @param ctxt the dwarf reading context to use.
13741 ///
13742 /// @param die the DIE to get the scope for.
13743 ///
13744 /// @param called_from_public_decl is true if this function has been
13745 /// initially called within the context of a public decl.
13746 ///
13747 /// @param where_offset the offset of the DIE where we are "logically"
13748 /// positionned at, in the DIE tree.  This is useful when @p die is
13749 /// e.g, DW_TAG_partial_unit that can be included in several places in
13750 /// the DIE tree.
13751 static scope_decl_sptr
13752 get_scope_for_die(read_context& ctxt,
13753                   Dwarf_Die*    die,
13754                   bool          called_for_public_decl,
13755                   size_t        where_offset)
13756 {
13757   die_source source_of_die;
13758   ABG_ASSERT(ctxt.get_die_source(die, source_of_die));
13759
13760   if (is_c_language(ctxt.cur_transl_unit()->get_language()))
13761     {
13762       ABG_ASSERT(dwarf_tag(die) != DW_TAG_member);
13763       return ctxt.global_scope();
13764     }
13765
13766   Dwarf_Die cloned_die;
13767   if (die_die_attribute(die, DW_AT_specification, cloned_die, false)
13768       || die_die_attribute(die, DW_AT_abstract_origin, cloned_die, false))
13769     return get_scope_for_die(ctxt, &cloned_die,
13770                              called_for_public_decl,
13771                              where_offset);
13772
13773   Dwarf_Die parent_die;
13774
13775   if (!get_parent_die(ctxt, die, parent_die, where_offset))
13776     return ctxt.nil_scope();
13777
13778   if (dwarf_tag(&parent_die) == DW_TAG_compile_unit
13779       || dwarf_tag(&parent_die) == DW_TAG_partial_unit
13780       || dwarf_tag(&parent_die) == DW_TAG_type_unit)
13781     {
13782       if (dwarf_tag(&parent_die) == DW_TAG_partial_unit
13783           || dwarf_tag(&parent_die) == DW_TAG_type_unit)
13784         {
13785           ABG_ASSERT(source_of_die == ALT_DEBUG_INFO_DIE_SOURCE
13786                  || source_of_die == TYPE_UNIT_DIE_SOURCE);
13787           return ctxt.cur_transl_unit()->get_global_scope();
13788         }
13789
13790       // For top level DIEs like DW_TAG_compile_unit, we just want to
13791       // return the global scope for the corresponding translation
13792       // unit.  This must have been set by
13793       // build_translation_unit_and_add_to_ir if we already started to
13794       // build the translation unit of parent_die.  Otherwise, just
13795       // return the global scope of the current translation unit.
13796       die_tu_map_type::const_iterator i =
13797         ctxt.die_tu_map().find(dwarf_dieoffset(&parent_die));
13798       if (i != ctxt.die_tu_map().end())
13799         return i->second->get_global_scope();
13800       return ctxt.cur_transl_unit()->get_global_scope();
13801     }
13802
13803   scope_decl_sptr s;
13804   type_or_decl_base_sptr d;
13805   if (dwarf_tag(&parent_die) == DW_TAG_subprogram
13806       || dwarf_tag(&parent_die) == DW_TAG_array_type)
13807     // this is an entity defined in a scope that is a function.
13808     // Normally, I would say that this should be dropped.  But I have
13809     // seen a case where a typedef DIE needed by a function parameter
13810     // was defined right before the parameter, under the scope of the
13811     // function.  Yeah, weird.  So if I drop the typedef DIE, I'd drop
13812     // the function parm too.  So for that case, let's say that the
13813     // scope is the scope of the function itself.  Note that this is
13814     // an error of the DWARF emitter.  We should never see this DIE in
13815     // this context.
13816     {
13817       scope_decl_sptr s = get_scope_for_die(ctxt, &parent_die,
13818                                             called_for_public_decl,
13819                                             where_offset);
13820       if (is_anonymous_type_die(die))
13821         // For anonymous type that have nothing to do in a function or
13822         // array type context, let's put it in the containing
13823         // namespace.  That is, do not let it be in a containing class
13824         // or union where it has nothing to do.
13825         while (is_class_or_union_type(s))
13826           {
13827             if (!get_parent_die(ctxt, &parent_die, parent_die, where_offset))
13828               return ctxt.nil_scope();
13829             s = get_scope_for_die(ctxt, &parent_die,
13830                                   called_for_public_decl,
13831                                   where_offset);
13832           }
13833       return s;
13834     }
13835   else
13836     d = build_ir_node_from_die(ctxt, &parent_die,
13837                                called_for_public_decl,
13838                                where_offset);
13839   s =  dynamic_pointer_cast<scope_decl>(d);
13840   if (!s)
13841     // this is an entity defined in someting that is not a scope.
13842     // Let's drop it.
13843     return ctxt.nil_scope();
13844
13845   class_decl_sptr cl = dynamic_pointer_cast<class_decl>(d);
13846   if (cl && cl->get_is_declaration_only())
13847     {
13848       scope_decl_sptr scop (cl->get_definition_of_declaration());
13849       if (scop)
13850         s = scop;
13851       else
13852         s = cl;
13853     }
13854   return s;
13855 }
13856
13857 /// Convert a DWARF constant representing the value of the
13858 /// DW_AT_language property into the translation_unit::language
13859 /// enumerator.
13860 ///
13861 /// @param l the DWARF constant to convert.
13862 ///
13863 /// @return the resulting translation_unit::language enumerator.
13864 static translation_unit::language
13865 dwarf_language_to_tu_language(size_t l)
13866 {
13867   switch (l)
13868     {
13869     case DW_LANG_C89:
13870       return translation_unit::LANG_C89;
13871     case DW_LANG_C:
13872       return translation_unit::LANG_C;
13873     case DW_LANG_Ada83:
13874       return translation_unit::LANG_Ada83;
13875     case DW_LANG_C_plus_plus:
13876       return translation_unit::LANG_C_plus_plus;
13877     case DW_LANG_Cobol74:
13878       return translation_unit::LANG_Cobol74;
13879     case DW_LANG_Cobol85:
13880       return translation_unit::LANG_Cobol85;
13881     case DW_LANG_Fortran77:
13882       return translation_unit::LANG_Fortran77;
13883     case DW_LANG_Fortran90:
13884       return translation_unit::LANG_Fortran90;
13885     case DW_LANG_Pascal83:
13886       return translation_unit::LANG_Pascal83;
13887     case DW_LANG_Modula2:
13888       return translation_unit::LANG_Modula2;
13889     case DW_LANG_Java:
13890       return translation_unit::LANG_Java;
13891     case DW_LANG_C99:
13892       return translation_unit::LANG_C99;
13893     case DW_LANG_Ada95:
13894       return translation_unit::LANG_Ada95;
13895     case DW_LANG_Fortran95:
13896       return translation_unit::LANG_Fortran95;
13897     case DW_LANG_PL1:
13898       return translation_unit::LANG_PL1;
13899     case DW_LANG_ObjC:
13900       return translation_unit::LANG_ObjC;
13901     case DW_LANG_ObjC_plus_plus:
13902       return translation_unit::LANG_ObjC_plus_plus;
13903
13904 #ifdef HAVE_DW_LANG_Rust_enumerator
13905     case DW_LANG_Rust:
13906       return translation_unit::LANG_Rust;
13907 #endif
13908
13909 #ifdef HAVE_DW_LANG_UPC_enumerator
13910     case DW_LANG_UPC:
13911       return translation_unit::LANG_UPC;
13912 #endif
13913
13914 #ifdef HAVE_DW_LANG_D_enumerator
13915     case DW_LANG_D:
13916       return translation_unit::LANG_D;
13917 #endif
13918
13919 #ifdef HAVE_DW_LANG_Python_enumerator
13920     case DW_LANG_Python:
13921       return translation_unit::LANG_Python;
13922 #endif
13923
13924 #ifdef HAVE_DW_LANG_Go_enumerator
13925     case DW_LANG_Go:
13926       return translation_unit::LANG_Go;
13927 #endif
13928
13929 #ifdef HAVE_DW_LANG_C11_enumerator
13930     case DW_LANG_C11:
13931       return translation_unit::LANG_C11;
13932 #endif
13933
13934 #ifdef HAVE_DW_LANG_C_plus_plus_03_enumerator
13935       case DW_LANG_C_plus_plus_03:
13936         return translation_unit::LANG_C_plus_plus_03;
13937 #endif
13938
13939 #ifdef HAVE_DW_LANG_C_plus_plus_11_enumerator
13940     case DW_LANG_C_plus_plus_11:
13941       return translation_unit::LANG_C_plus_plus_11;
13942 #endif
13943
13944 #ifdef HAVE_DW_LANG_C_plus_plus_14_enumerator
13945     case DW_LANG_C_plus_plus_14:
13946       return translation_unit::LANG_C_plus_plus_14;
13947 #endif
13948
13949 #ifdef HAVE_DW_LANG_Mips_Assembler_enumerator
13950     case DW_LANG_Mips_Assembler:
13951       return translation_unit::LANG_Mips_Assembler;
13952 #endif
13953
13954     default:
13955       return translation_unit::LANG_UNKNOWN;
13956     }
13957 }
13958
13959 /// Get the default array lower bound value as defined by the DWARF
13960 /// specification, version 4, depending on the language of the
13961 /// translation unit.
13962 ///
13963 /// @param l the language of the translation unit.
13964 ///
13965 /// @return the default array lower bound value.
13966 static uint64_t
13967 get_default_array_lower_bound(translation_unit::language l)
13968 {
13969   int value = 0;
13970   switch (l)
13971     {
13972     case translation_unit::LANG_UNKNOWN:
13973       value = 0;
13974       break;
13975     case translation_unit::LANG_Cobol74:
13976     case translation_unit::LANG_Cobol85:
13977       value = 1;
13978       break;
13979     case translation_unit::LANG_C89:
13980     case translation_unit::LANG_C99:
13981     case translation_unit::LANG_C11:
13982     case translation_unit::LANG_C:
13983     case translation_unit::LANG_C_plus_plus_03:
13984     case translation_unit::LANG_C_plus_plus_11:
13985     case translation_unit::LANG_C_plus_plus_14:
13986     case translation_unit::LANG_C_plus_plus:
13987     case translation_unit::LANG_ObjC:
13988     case translation_unit::LANG_ObjC_plus_plus:
13989     case translation_unit::LANG_Rust:
13990       value = 0;
13991       break;
13992     case translation_unit::LANG_Fortran77:
13993     case translation_unit::LANG_Fortran90:
13994     case translation_unit::LANG_Fortran95:
13995     case translation_unit::LANG_Ada83:
13996     case translation_unit::LANG_Ada95:
13997     case translation_unit::LANG_Pascal83:
13998     case translation_unit::LANG_Modula2:
13999       value = 1;
14000       break;
14001     case translation_unit::LANG_Java:
14002       value = 0;
14003       break;
14004     case translation_unit::LANG_PL1:
14005       value = 1;
14006       break;
14007     case translation_unit::LANG_UPC:
14008     case translation_unit::LANG_D:
14009     case translation_unit::LANG_Python:
14010     case translation_unit::LANG_Go:
14011     case translation_unit::LANG_Mips_Assembler:
14012       value = 0;
14013       break;
14014     }
14015
14016   return value;
14017 }
14018
14019 /// For a given offset, find the lower bound of a sorted vector of
14020 /// imported unit point offset.
14021 ///
14022 /// The lower bound is the smallest point (the point with the smallest
14023 /// offset) which is the greater than a given offset.
14024 ///
14025 /// @param imported_unit_points_type the sorted vector  of imported
14026 /// unit points.
14027 ///
14028 /// @param val the offset to consider when looking for the lower
14029 /// bound.
14030 ///
14031 /// @param r an iterator to the lower bound found.  This parameter is
14032 /// set iff the function returns true.
14033 ///
14034 /// @return true iff the lower bound has been found.
14035 static bool
14036 find_lower_bound_in_imported_unit_points(const imported_unit_points_type& p,
14037                                          Dwarf_Off val,
14038                                          imported_unit_points_type::const_iterator& r)
14039 {
14040   imported_unit_point v(val);
14041   imported_unit_points_type::const_iterator result =
14042     std::lower_bound(p.begin(), p.end(), v);
14043
14044   bool is_ok = result != p.end();
14045
14046   if (is_ok)
14047     r = result;
14048
14049   return is_ok;
14050 }
14051
14052 /// Given a DW_TAG_compile_unit, build and return the corresponding
14053 /// abigail::translation_unit ir node.  Note that this function
14054 /// recursively reads the children dies of the current DIE and
14055 /// populates the resulting translation unit.
14056 ///
14057 /// @param ctxt the read_context to use.
14058 ///
14059 /// @param die the DW_TAG_compile_unit DIE to consider.
14060 ///
14061 /// @param address_size the size of the addresses expressed in this
14062 /// translation unit in general.
14063 ///
14064 /// @return a pointer to the resulting translation_unit.
14065 static translation_unit_sptr
14066 build_translation_unit_and_add_to_ir(read_context&      ctxt,
14067                                      Dwarf_Die* die,
14068                                      char               address_size)
14069 {
14070   translation_unit_sptr result;
14071
14072   if (!die)
14073     return result;
14074   ABG_ASSERT(dwarf_tag(die) == DW_TAG_compile_unit);
14075
14076   // Clear the part of the context that is dependent on the translation
14077   // unit we are reading.
14078   ctxt.clear_per_translation_unit_data();
14079
14080   ctxt.cur_tu_die(die);
14081
14082   string path = die_string_attribute(die, DW_AT_name);
14083   string compilation_dir = die_string_attribute(die, DW_AT_comp_dir);
14084
14085   // See if the same translation unit exits already in the current
14086   // corpus.  Sometimes, the same translation unit can be present
14087   // several times in the same debug info.  The content of the
14088   // different instances of the translation unit are different.  So to
14089   // represent that, we are going to re-use the same translation
14090   // unit.  That is, it's going to be the union of all the translation
14091   // units of the same path.
14092   {
14093     string abs_path = compilation_dir + "/" + path;
14094     result = ctxt.current_corpus()->find_translation_unit(abs_path);
14095   }
14096
14097   if (!result)
14098     {
14099       result.reset(new translation_unit(ctxt.env(),
14100                                         path,
14101                                         address_size));
14102       result->set_compilation_dir_path(compilation_dir);
14103       ctxt.current_corpus()->add(result);
14104       uint64_t l = 0;
14105       die_unsigned_constant_attribute(die, DW_AT_language, l);
14106       result->set_language(dwarf_language_to_tu_language(l));
14107     }
14108
14109   ctxt.cur_transl_unit(result);
14110   ctxt.die_tu_map()[dwarf_dieoffset(die)] = result;
14111
14112   Dwarf_Die child;
14113   if (dwarf_child(die, &child) != 0)
14114     return result;
14115
14116   result->set_is_constructed(false);
14117
14118   do
14119     build_ir_node_from_die(ctxt, &child,
14120                            die_is_public_decl(&child),
14121                            dwarf_dieoffset(&child));
14122   while (dwarf_siblingof(&child, &child) == 0);
14123
14124   if (!ctxt.var_decls_to_re_add_to_tree().empty())
14125     for (list<var_decl_sptr>::const_iterator v =
14126            ctxt.var_decls_to_re_add_to_tree().begin();
14127          v != ctxt.var_decls_to_re_add_to_tree().end();
14128          ++v)
14129       {
14130         if (is_member_decl(*v))
14131           continue;
14132
14133         ABG_ASSERT((*v)->get_scope());
14134         string demangled_name =
14135           demangle_cplus_mangled_name((*v)->get_linkage_name());
14136         if (!demangled_name.empty())
14137           {
14138             std::list<string> fqn_comps;
14139             fqn_to_components(demangled_name, fqn_comps);
14140             string mem_name = fqn_comps.back();
14141             fqn_comps.pop_back();
14142             class_decl_sptr class_type;
14143             string ty_name;
14144             if (!fqn_comps.empty())
14145               {
14146                 ty_name = components_to_type_name(fqn_comps);
14147                 class_type =
14148                   lookup_class_type(ty_name, *ctxt.cur_transl_unit());
14149               }
14150             if (class_type)
14151               {
14152                 // So we are seeing a member variable for which there
14153                 // is a global variable definition DIE not having a
14154                 // reference attribute pointing back to the member
14155                 // variable declaration DIE.  Thus remove the global
14156                 // variable definition from its current non-class
14157                 // scope ...
14158                 decl_base_sptr d;
14159                 if ((d = lookup_var_decl_in_scope(mem_name, class_type)))
14160                   // This is the data member with the same name in cl.
14161                   // We just need to flag it as static.
14162                   ;
14163                 else
14164                   {
14165                     // In this case there is no data member with the
14166                     // same name in cl already.  Let's add it there then
14167                     // ...
14168                     remove_decl_from_scope(*v);
14169                     d = add_decl_to_scope(*v, class_type);
14170                   }
14171
14172                 ABG_ASSERT(dynamic_pointer_cast<var_decl>(d));
14173                 // Let's flag the data member as static.
14174                 set_member_is_static(d, true);
14175               }
14176           }
14177       }
14178   ctxt.var_decls_to_re_add_to_tree().clear();
14179
14180   result->set_is_constructed(true);
14181
14182   return result;
14183 }
14184
14185 /// Build a abigail::namespace_decl out of a DW_TAG_namespace or
14186 /// DW_TAG_module (for fortran) DIE.
14187 ///
14188 /// Note that this function connects the DW_TAG_namespace to the IR
14189 /// being currently created, reads the children of the DIE and
14190 /// connects them to the IR as well.
14191 ///
14192 /// @param ctxt the read context to use.
14193 ///
14194 /// @param die the DIE to read from.  Must be either DW_TAG_namespace
14195 /// or DW_TAG_module.
14196 ///
14197 /// @param where_offset the offset of the DIE where we are "logically"
14198 /// positionned at, in the DIE tree.  This is useful when @p die is
14199 /// e.g, DW_TAG_partial_unit that can be included in several places in
14200 /// the DIE tree.
14201 ///
14202 /// @return the resulting @ref abigail::namespace_decl or NULL if it
14203 /// couldn't be created.
14204 static namespace_decl_sptr
14205 build_namespace_decl_and_add_to_ir(read_context&        ctxt,
14206                                    Dwarf_Die*           die,
14207                                    size_t               where_offset)
14208 {
14209   namespace_decl_sptr result;
14210
14211   if (!die)
14212     return result;
14213
14214   die_source source;
14215   ABG_ASSERT(ctxt.get_die_source(die, source));
14216
14217   unsigned tag = dwarf_tag(die);
14218   if (tag != DW_TAG_namespace && tag != DW_TAG_module)
14219     return result;
14220
14221   scope_decl_sptr scope = get_scope_for_die(ctxt, die,
14222                                             /*called_for_public_decl=*/false,
14223                                             where_offset);
14224
14225   string name, linkage_name;
14226   location loc;
14227   die_loc_and_name(ctxt, die, loc, name, linkage_name);
14228
14229   result.reset(new namespace_decl(ctxt.env(), name, loc));
14230   add_decl_to_scope(result, scope.get());
14231   ctxt.associate_die_to_decl(die, result, where_offset);
14232
14233   Dwarf_Die child;
14234   if (dwarf_child(die, &child) != 0)
14235     return result;
14236
14237   ctxt.scope_stack().push(result.get());
14238   do
14239     build_ir_node_from_die(ctxt, &child,
14240                            /*called_from_public_decl=*/false,
14241                            where_offset);
14242   while (dwarf_siblingof(&child, &child) == 0);
14243   ctxt.scope_stack().pop();
14244
14245   return result;
14246 }
14247
14248 /// Build a @ref type_decl out of a DW_TAG_base_type DIE.
14249 ///
14250 /// @param ctxt the read context to use.
14251 ///
14252 /// @param die the DW_TAG_base_type to consider.
14253 ///
14254 /// @param where_offset where we are logically at in the DIE stream.
14255 ///
14256 /// @return the resulting decl_base_sptr.
14257 static type_decl_sptr
14258 build_type_decl(read_context& ctxt, Dwarf_Die* die, size_t where_offset)
14259 {
14260   type_decl_sptr result;
14261
14262   if (!die)
14263     return result;
14264   ABG_ASSERT(dwarf_tag(die) == DW_TAG_base_type);
14265
14266   uint64_t byte_size = 0, bit_size = 0;
14267   if (!die_unsigned_constant_attribute(die, DW_AT_byte_size, byte_size))
14268     if (!die_unsigned_constant_attribute(die, DW_AT_bit_size, bit_size))
14269       return result;
14270
14271   if (bit_size == 0 && byte_size != 0)
14272     // Update the bit size.
14273     bit_size = byte_size * 8;
14274
14275   string type_name, linkage_name;
14276   location loc;
14277   die_loc_and_name(ctxt, die, loc, type_name, linkage_name);
14278
14279   if (byte_size == 0)
14280     {
14281       // The size of the type is zero, that must mean that we are
14282       // looking at the definition of the void type.
14283       if (type_name == "void")
14284         result = is_type_decl(build_ir_node_for_void_type(ctxt));
14285       else
14286         // A type of size zero that is not void? Hmmh, I am not sure
14287         // what that means.  Return nil for now.
14288         return result;
14289     }
14290
14291   if (corpus_sptr corp = ctxt.should_reuse_type_from_corpus_group())
14292     {
14293       string normalized_type_name = type_name;
14294       integral_type int_type;
14295       if (parse_integral_type(type_name, int_type))
14296         normalized_type_name = int_type.to_string();
14297       result = lookup_basic_type(normalized_type_name, *corp);
14298     }
14299
14300   if (!result)
14301     if (corpus_sptr corp = ctxt.current_corpus())
14302       result = lookup_basic_type(type_name, *corp);
14303   if (!result)
14304     result.reset(new type_decl(ctxt.env(), type_name, bit_size,
14305                                /*alignment=*/0, loc, linkage_name));
14306   ctxt.associate_die_to_type(die, result, where_offset);
14307   return result;
14308 }
14309
14310 /// Build an enum_type_decl from a DW_TAG_enumeration_type DIE.
14311 ///
14312 /// @param ctxt the read context to use.
14313 ///
14314 /// @param die the DIE to read from.
14315 ///
14316 /// @param scope the scope of the final enum.  Note that this function
14317 /// does *NOT* add the built type to this scope.  The scope is just so
14318 /// that the function knows how to name anonymous enums.
14319 ///
14320 /// @return the built enum_type_decl or NULL if it could not be built.
14321 static enum_type_decl_sptr
14322 build_enum_type(read_context&   ctxt,
14323                 Dwarf_Die*      die,
14324                 scope_decl*     scope,
14325                 size_t          where_offset)
14326 {
14327   enum_type_decl_sptr result;
14328   if (!die)
14329     return result;
14330
14331   unsigned tag = dwarf_tag(die);
14332   if (tag != DW_TAG_enumeration_type)
14333     return result;
14334
14335   string name, linkage_name;
14336   location loc;
14337   die_loc_and_name(ctxt, die, loc, name, linkage_name);
14338
14339   bool enum_is_anonymous = false;
14340   // If the enum is anonymous, let's give it a name.
14341   if (name.empty())
14342     {
14343       name = get_internal_anonymous_die_prefix_name(die);
14344       ABG_ASSERT(!name.empty());
14345       // But we remember that the type is anonymous.
14346       enum_is_anonymous = true;
14347
14348       if (size_t s = scope->get_num_anonymous_member_enums())
14349         name = build_internal_anonymous_die_name(name, s);
14350     }
14351
14352   bool use_odr = ctxt.odr_is_relevant(die);
14353   // If the type has location, then associate it to its
14354   // representation.  This way, all occurences of types with the same
14355   // representation (name) and location can be later detected as being
14356   // for the same type.
14357
14358   if (!enum_is_anonymous)
14359     {
14360       if (use_odr)
14361         {
14362           if (enum_type_decl_sptr pre_existing_enum =
14363               is_enum_type(ctxt.lookup_artifact_from_die(die)))
14364             result = pre_existing_enum;
14365         }
14366       else if (corpus_sptr corp = ctxt.should_reuse_type_from_corpus_group())
14367         {
14368           if (loc)
14369             result = lookup_enum_type_per_location(loc.expand(), *corp);
14370         }
14371       else if (loc)
14372         {
14373           if (enum_type_decl_sptr pre_existing_enum =
14374               is_enum_type(ctxt.lookup_artifact_from_die(die)))
14375             if (pre_existing_enum->get_location() == loc)
14376               result = pre_existing_enum;
14377         }
14378
14379       if (result)
14380         {
14381           ctxt.associate_die_to_type(die, result, where_offset);
14382           return result;
14383         }
14384     }
14385   // TODO: for anonymous enums, maybe have a map of loc -> enums so that
14386   // we can look them up?
14387
14388   uint64_t size = 0;
14389   if (die_unsigned_constant_attribute(die, DW_AT_byte_size, size))
14390     size *= 8;
14391
14392   // for now we consider that underlying types of enums are all anonymous
14393   bool enum_underlying_type_is_anonymous= true;
14394   string underlying_type_name;
14395   if (enum_underlying_type_is_anonymous)
14396     {
14397       underlying_type_name = "unnamed-enum";
14398       enum_underlying_type_is_anonymous = true;
14399     }
14400   else
14401     underlying_type_name = string("enum-") + name;
14402   underlying_type_name += "-underlying-type";
14403
14404   enum_type_decl::enumerators enms;
14405   Dwarf_Die child;
14406   if (dwarf_child(die, &child) == 0)
14407     {
14408       do
14409         {
14410           if (dwarf_tag(&child) != DW_TAG_enumerator)
14411             continue;
14412
14413           string n, m;
14414           location l;
14415           die_loc_and_name(ctxt, &child, l, n, m);
14416           uint64_t val = 0;
14417           die_unsigned_constant_attribute(&child, DW_AT_const_value, val);
14418           enms.push_back(enum_type_decl::enumerator(ctxt.env(), n, val));
14419         }
14420       while (dwarf_siblingof(&child, &child) == 0);
14421     }
14422
14423   // DWARF up to version 4 (at least) doesn't seem to carry the
14424   // underlying type, so let's create an artificial one here, which
14425   // sole purpose is to be passed to the constructor of the
14426   // enum_type_decl type.
14427   type_decl_sptr t(new type_decl(ctxt.env(), underlying_type_name,
14428                                  size, size, location()));
14429   t->set_is_anonymous(enum_underlying_type_is_anonymous);
14430   translation_unit_sptr tu = ctxt.cur_transl_unit();
14431   decl_base_sptr d =
14432     add_decl_to_scope(t, tu->get_global_scope().get());
14433   canonicalize(t);
14434
14435   t = dynamic_pointer_cast<type_decl>(d);
14436   ABG_ASSERT(t);
14437   result.reset(new enum_type_decl(name, loc, t, enms, linkage_name));
14438   result->set_is_anonymous(enum_is_anonymous);
14439   ctxt.associate_die_to_type(die, result, where_offset);
14440   return result;
14441 }
14442
14443 /// Once a function_decl has been built and added to a class as a
14444 /// member function, this function updates the information of the
14445 /// function_decl concerning the properties of its relationship with
14446 /// the member class.  That is, it updates properties like
14447 /// virtualness, access, constness, cdtorness, etc ...
14448 ///
14449 /// @param die the DIE of the function_decl that has been just built.
14450 ///
14451 /// @param f the function_decl that has just been built from @p die.
14452 ///
14453 /// @param klass the @ref class_or_union that @p f belongs to.
14454 ///
14455 /// @param ctxt the context used to read the ELF/DWARF information.
14456 static void
14457 finish_member_function_reading(Dwarf_Die*                 die,
14458                                const function_decl_sptr&  f,
14459                                const class_or_union_sptr& klass,
14460                                read_context&              ctxt)
14461 {
14462   ABG_ASSERT(klass);
14463
14464   method_decl_sptr m = is_method_decl(f);
14465   ABG_ASSERT(m);
14466
14467   method_type_sptr method_t = is_method_type(m->get_type());
14468   ABG_ASSERT(method_t);
14469
14470   bool is_ctor = (f->get_name() == klass->get_name());
14471   bool is_dtor = (!f->get_name().empty()
14472                   && static_cast<string>(f->get_name())[0] == '~');
14473   bool is_virtual = die_is_virtual(die);
14474   int64_t vindex = -1;
14475   if (is_virtual)
14476     die_virtual_function_index(die, vindex);
14477   access_specifier access = private_access;
14478   if (class_decl_sptr c = is_class_type(klass))
14479     if (c->is_struct())
14480       access = public_access;
14481   die_access_specifier(die, access);
14482
14483   bool is_static = false;
14484   {
14485     // Let's see if the first parameter is a pointer to an instance of
14486     // the same class type as the current class and has a
14487     // DW_AT_artificial attribute flag set.  We are not looking at
14488     // DW_AT_object_pointer (for DWARF 3) because it wasn't being
14489     // emitted in GCC 4_4, which was already DWARF 3.
14490     function_decl::parameter_sptr first_parm;
14491     if (!f->get_parameters().empty())
14492       first_parm = f->get_parameters()[0];
14493
14494     bool is_artificial =
14495       first_parm && first_parm->get_artificial();;
14496     pointer_type_def_sptr this_ptr_type;
14497     type_base_sptr other_klass;
14498
14499     if (is_artificial)
14500       this_ptr_type = is_pointer_type(first_parm->get_type());
14501     if (this_ptr_type)
14502       other_klass = this_ptr_type->get_pointed_to_type();
14503     // Sometimes, other_klass can be qualified; e.g, volatile.  In
14504     // that case, let's get the unqualified version of other_klass.
14505     if (qualified_type_def_sptr q = is_qualified_type(other_klass))
14506       other_klass = q->get_underlying_type();
14507
14508     if (other_klass
14509         && get_type_name(other_klass) == klass->get_qualified_name())
14510       ;
14511     else
14512       is_static = true;
14513   }
14514   set_member_access_specifier(m, access);
14515   if (vindex != -1)
14516     set_member_function_vtable_offset(m, vindex);
14517   set_member_function_is_virtual(m, is_virtual);
14518   set_member_is_static(m, is_static);
14519   set_member_function_is_ctor(m, is_ctor);
14520   set_member_function_is_dtor(m, is_dtor);
14521   set_member_function_is_const(m, method_t->get_is_const());
14522
14523   ABG_ASSERT(is_member_function(m));
14524
14525   if (is_virtual && !f->get_linkage_name().empty() && !f->get_symbol())
14526     {
14527       // This is a virtual member function which has a linkage name
14528       // but has no underlying symbol set.
14529       //
14530       // The underlying elf symbol to set to this function can show up
14531       // later in the DWARF input or it can be that, because of some
14532       // compiler optimization, the relation between this function and
14533       // its underlying elf symbol is simply not emitted in the DWARF.
14534       //
14535       // Let's thus schedule this function for a later fixup pass
14536       // (performed by
14537       // read_context::fixup_functions_with_no_symbols()) that will
14538       // set its underlying symbol.
14539       //
14540       // Note that if the underying symbol is encountered later in the
14541       // DWARF input, then the part of build_function_decl() that
14542       // updates the function to set its underlying symbol will
14543       // de-schedule this function wrt fixup pass.
14544       Dwarf_Off die_offset = dwarf_dieoffset(die);
14545       die_function_decl_map_type &fns_with_no_symbol =
14546         ctxt.die_function_decl_with_no_symbol_map();
14547       die_function_decl_map_type::const_iterator i =
14548         fns_with_no_symbol.find(die_offset);
14549       if (i == fns_with_no_symbol.end())
14550         fns_with_no_symbol[die_offset] = f;
14551     }
14552
14553 }
14554
14555 /// If a function DIE has attributes which have not yet been read and
14556 /// added to the internal representation that represents that function
14557 /// then read those extra attributes and update the internal
14558 /// representation.
14559 ///
14560 /// @param ctxt the read context to use.
14561 ///
14562 /// @param die the function DIE to consider.
14563 ///
14564 /// @param where_offset where we logical are, currently, in the stream
14565 /// of DIEs.  If you don't know what this is, you can just set it to zero.
14566 ///
14567 /// @param existing_fn the representation of the function to update.
14568 ///
14569 /// @return the updated function  representation.
14570 static function_decl_sptr
14571 maybe_finish_function_decl_reading(read_context&                ctxt,
14572                                    Dwarf_Die*                   die,
14573                                    size_t                       where_offset,
14574                                    const function_decl_sptr&    existing_fn)
14575 {
14576   function_decl_sptr result = build_function_decl(ctxt, die,
14577                                                   where_offset,
14578                                                   existing_fn);
14579
14580   return result;
14581 }
14582
14583 /// Lookup a class or a typedef with a given qualified name in the
14584 /// corpus that a given scope belongs to.
14585 ///
14586 /// @param scope the scope to consider.
14587 ///
14588 /// @param type_name the qualified name of the type to look for.
14589 ///
14590 /// @return the typedef or class type found.
14591 static type_base_sptr
14592 lookup_class_or_typedef_from_corpus(scope_decl* scope, const string& type_name)
14593 {
14594   string qname = build_qualified_name(scope, type_name);
14595   corpus* corp = scope->get_corpus();
14596   type_base_sptr result = lookup_class_or_typedef_type(qname, *corp);
14597   return result;
14598 }
14599
14600 /// Lookup a class of typedef type from the current corpus being
14601 /// constructed.
14602 ///
14603 /// The type being looked for has the same name as a given DIE.
14604 ///
14605 /// @param ctxt the reading context to use.
14606 ///
14607 /// @param die the DIE which has the same name as the type we are
14608 /// looking for.
14609 ///
14610 /// @param called_for_public_decl whether this function is being
14611 /// called from a a publicly defined declaration.
14612 ///
14613 /// @param where_offset where we are logically at in the DIE stream.
14614 ///
14615 /// @return the type found.
14616 static type_base_sptr
14617 lookup_class_or_typedef_from_corpus(read_context& ctxt,
14618                                     Dwarf_Die* die,
14619                                     bool called_for_public_decl,
14620                                     size_t where_offset)
14621 {
14622   if (!die)
14623     return class_decl_sptr();
14624
14625   string class_name = die_string_attribute(die, DW_AT_name);
14626   if (class_name.empty())
14627     return class_decl_sptr();
14628
14629   scope_decl_sptr scope = get_scope_for_die(ctxt, die,
14630                                             called_for_public_decl,
14631                                             where_offset);
14632   if (scope)
14633     return lookup_class_or_typedef_from_corpus(scope.get(), class_name);
14634
14635   return type_base_sptr();
14636 }
14637
14638 /// Lookup a class, typedef or enum type with a given qualified name
14639 /// in the corpus that a given scope belongs to.
14640 ///
14641 /// @param scope the scope to consider.
14642 ///
14643 /// @param type_name the qualified name of the type to look for.
14644 ///
14645 /// @return the typedef, enum or class type found.
14646 static type_base_sptr
14647 lookup_class_typedef_or_enum_type_from_corpus(scope_decl* scope,
14648                                               const string& type_name)
14649 {
14650   string qname = build_qualified_name(scope, type_name);
14651   corpus* corp = scope->get_corpus();
14652   type_base_sptr result = lookup_class_typedef_or_enum_type(qname, *corp);
14653   return result;
14654 }
14655
14656 /// Lookup a class, typedef or enum type in a given scope, in the
14657 /// corpus that scope belongs to.
14658 ///
14659 /// @param die the DIE of the class, typedef or enum to lookup.
14660 ///
14661 /// @param anonymous_member_type_idx if @p DIE represents an anonymous
14662 /// type, this is the index of that anonymous type in its scope, in
14663 /// case there are several anonymous types of the same kind in that
14664 /// scope.
14665 ///
14666 /// @param scope the scope in which to look the type for.
14667 ///
14668 /// @return the typedef, enum or class type found.
14669 static type_base_sptr
14670 lookup_class_typedef_or_enum_type_from_corpus(Dwarf_Die* die,
14671                                               size_t anonymous_member_type_idx,
14672                                               scope_decl* scope)
14673 {
14674   if (!die)
14675     return class_decl_sptr();
14676
14677   string type_name = die_string_attribute(die, DW_AT_name);
14678   if (is_anonymous_type_die(die))
14679     type_name =
14680       get_internal_anonymous_die_name(die, anonymous_member_type_idx);
14681
14682   if (type_name.empty())
14683     return class_decl_sptr();
14684
14685   return lookup_class_typedef_or_enum_type_from_corpus(scope, type_name);
14686 }
14687
14688 /// Test if a DIE represents a function that is a member of a given
14689 /// class type.
14690 ///
14691 /// @param ctxt the reading context.
14692 ///
14693 /// @param function_die the DIE of the function to consider.
14694 ///
14695 /// @param class_type the class type to consider.
14696 ///
14697 /// @param where_offset where we are logically at in the DIE stream.
14698 ///
14699 /// @return the method declaration corresponding to the member
14700 /// function of @p class_type, iff @p function_die is for a member
14701 /// function of @p class_type.
14702 static method_decl_sptr
14703 is_function_for_die_a_member_of_class(read_context& ctxt,
14704                                       Dwarf_Die* function_die,
14705                                       const class_or_union_sptr& class_type)
14706 {
14707   type_or_decl_base_sptr artifact = ctxt.lookup_artifact_from_die(function_die);
14708
14709   if (!artifact)
14710     return method_decl_sptr();
14711
14712   method_decl_sptr method = is_method_decl(artifact);
14713   method_type_sptr method_type;
14714
14715   if (method)
14716     method_type = method->get_type();
14717   else
14718     method_type = is_method_type(artifact);
14719   ABG_ASSERT(method_type);
14720
14721   class_or_union_sptr method_class = method_type->get_class_type();
14722   ABG_ASSERT(method_class);
14723
14724   string method_class_name = method_class->get_qualified_name(),
14725     class_type_name = class_type->get_qualified_name();
14726
14727   if (method_class_name == class_type_name)
14728     {
14729       //ABG_ASSERT(class_type.get() == method_class.get());
14730       return method;
14731     }
14732
14733   return method_decl_sptr();
14734 }
14735
14736 /// If a given function DIE represents an existing member function of
14737 /// a given class, then update that member function with new
14738 /// properties present in the DIE.  Otherwise, if the DIE represents a
14739 /// new member function that is not already present in the class then
14740 /// add that new member function to the class.
14741 ///
14742 /// @param ctxt the reading context.
14743 ///
14744 /// @param function_die the DIE of the potential member function to
14745 /// consider.
14746 ///
14747 /// @param class_type the class type to consider.
14748 ///
14749 /// @param called_from_public_decl is true iff this function was
14750 /// called from a publicly defined and exported declaration.
14751 ///
14752 /// @param where_offset where we are logically at in the DIE stream.
14753 ///
14754 /// @return the method decl representing the member function.
14755 static method_decl_sptr
14756 add_or_update_member_function(read_context& ctxt,
14757                               Dwarf_Die* function_die,
14758                               const class_or_union_sptr& class_type,
14759                               bool called_from_public_decl,
14760                               size_t where_offset)
14761 {
14762   method_decl_sptr method =
14763     is_function_for_die_a_member_of_class(ctxt, function_die, class_type);
14764
14765   if (!method)
14766     method = is_method_decl(build_ir_node_from_die(ctxt, function_die,
14767                                                    class_type.get(),
14768                                                    called_from_public_decl,
14769                                                    where_offset));
14770   if (!method)
14771     return method_decl_sptr();
14772
14773   finish_member_function_reading(function_die,
14774                                  is_function_decl(method),
14775                                  class_type, ctxt);
14776   return method;
14777 }
14778
14779 /// Build a an IR node for class type from a DW_TAG_structure_type or
14780 /// DW_TAG_class_type DIE and add that node to the ABI corpus being
14781 /// currently built.
14782 ///
14783 /// If the represents class type that already exists, then update the
14784 /// existing class type with the new properties found in the DIE.
14785 ///
14786 /// It meanst that this function can also update an existing
14787 /// class_decl node with data members, member functions and other
14788 /// properties coming from the DIE.
14789 ///
14790 /// @param ctxt the read context to consider.
14791 ///
14792 /// @param die the DIE to read information from.  Must be either a
14793 /// DW_TAG_structure_type or a DW_TAG_class_type.
14794 ///
14795 /// @param scope a pointer to the scope_decl* under which this class
14796 /// is to be added to.
14797 ///
14798 /// @param is_struct whether the class was declared as a struct.
14799 ///
14800 /// @param klass if non-null, this is a klass to append the members
14801 /// to.  Otherwise, this function just builds the class from scratch.
14802 ///
14803 /// @param called_from_public_decl set to true if this class is being
14804 /// called from a "Public declaration like vars or public symbols".
14805 ///
14806 /// @param where_offset the offset of the DIE where we are "logically"
14807 /// positionned at, in the DIE tree.  This is useful when @p die is
14808 /// e.g, DW_TAG_partial_unit that can be included in several places in
14809 /// the DIE tree.
14810 ///
14811 /// @return the resulting class_type.
14812 static class_decl_sptr
14813 add_or_update_class_type(read_context&   ctxt,
14814                          Dwarf_Die*      die,
14815                          scope_decl*     scope,
14816                          bool            is_struct,
14817                          class_decl_sptr klass,
14818                          bool            called_from_public_decl,
14819                          size_t  where_offset)
14820 {
14821   class_decl_sptr result;
14822   if (!die)
14823     return result;
14824
14825   die_source source;
14826   ABG_ASSERT(ctxt.get_die_source(die, source));
14827
14828   unsigned tag = dwarf_tag(die);
14829
14830   if (tag != DW_TAG_class_type && tag != DW_TAG_structure_type)
14831     return result;
14832
14833   {
14834     die_class_or_union_map_type::const_iterator i =
14835       ctxt.die_wip_classes_map(source).find(dwarf_dieoffset(die));
14836     if (i != ctxt.die_wip_classes_map(source).end())
14837       {
14838         class_decl_sptr class_type = is_class_type(i->second);
14839         ABG_ASSERT(class_type);
14840         return class_type;
14841       }
14842   }
14843
14844   if (!ctxt.die_is_in_cplus_plus(die))
14845     // In c++, a given class might be put together "piecewise".  That
14846     // is, in a translation unit, some data members of that class
14847     // might be defined; then in another later, some member types
14848     // might be defined.  So we can't just re-use a class "verbatim"
14849     // just because we've seen previously.  So in c++, re-using the
14850     // class is a much clever process.  In the other languages however
14851     // (like in C) we can re-use a class definition verbatim.
14852     if (class_decl_sptr class_type =
14853         is_class_type(ctxt.lookup_type_from_die(die)))
14854       if (!class_type->get_is_declaration_only())
14855         return class_type;
14856
14857   string name, linkage_name;
14858   location loc;
14859   die_loc_and_name(ctxt, die, loc, name, linkage_name);
14860   bool is_declaration_only = die_is_declaration_only(die);
14861
14862   bool is_anonymous = false;
14863   if (name.empty())
14864     {
14865       // So we are looking at an anonymous struct.  Let's
14866       // give it a name.
14867       name = get_internal_anonymous_die_prefix_name(die);
14868       ABG_ASSERT(!name.empty());
14869       // But we remember that the type is anonymous.
14870       is_anonymous = true;
14871
14872       if (size_t s = scope->get_num_anonymous_member_classes())
14873         name = build_internal_anonymous_die_name(name, s);
14874     }
14875
14876   if (!is_anonymous)
14877     {
14878       if (corpus_sptr corp = ctxt.should_reuse_type_from_corpus_group())
14879         {
14880           if (loc)
14881             // TODO: if there is only one class defined in the corpus
14882             // for this location, then re-use it.  But if there are
14883             // more than one, then do not re-use it, for now.
14884             result = lookup_class_type_per_location(loc.expand(), *corp);
14885           else
14886             // TODO: if there is just one class for that name defined,
14887             // then re-use it.  Otherwise, don't.
14888             result = lookup_class_type(name, *corp);
14889           if (result
14890               // If we are seeing a declaration of a definition we
14891               // already had, or if we are seing a type with the same
14892               // declaration-only-ness that we had before, then keep
14893               // the one we already had.
14894               && (result->get_is_declaration_only() == is_declaration_only
14895                   || (!result->get_is_declaration_only()
14896                       && is_declaration_only)))
14897             {
14898               ctxt.associate_die_to_type(die, result, where_offset);
14899               return result;
14900             }
14901           else
14902             // We might be seeing the definition of a declaration we
14903             // already had.  In that case, keep the definition and
14904             // drop the declaration.
14905             result.reset();
14906         }
14907     }
14908
14909   // If we've already seen the same class as 'die', then let's re-use
14910   // that one, unless it's an anonymous class.  We can't really safely
14911   // re-use anonymous classes as they have no name, by construction.
14912   // What we can do, rather, is to reuse the typedef that name them,
14913   // when they do have a naming typedef.
14914   if (!is_anonymous)
14915     if (class_decl_sptr pre_existing_class =
14916         is_class_type(ctxt.lookup_type_artifact_from_die(die)))
14917       klass = pre_existing_class;
14918
14919   uint64_t size = 0;
14920   die_size_in_bits(die, size);
14921
14922   Dwarf_Die child;
14923   bool has_child = (dwarf_child(die, &child) == 0);
14924
14925   decl_base_sptr res;
14926   if (klass)
14927     {
14928       res = result = klass;
14929       if (loc)
14930         result->set_location(loc);
14931     }
14932   else
14933     {
14934       result.reset(new class_decl(ctxt.env(), name, size,
14935                                   /*alignment=*/0, is_struct, loc,
14936                                   decl_base::VISIBILITY_DEFAULT));
14937       result->set_is_anonymous(is_anonymous);
14938
14939       if (is_declaration_only)
14940         result->set_is_declaration_only(true);
14941
14942       res = add_decl_to_scope(result, scope);
14943       result = dynamic_pointer_cast<class_decl>(res);
14944       ABG_ASSERT(result);
14945     }
14946
14947   if (size)
14948     result->set_size_in_bits(size);
14949
14950   ctxt.associate_die_to_type(die, result, where_offset);
14951
14952   ctxt.maybe_schedule_declaration_only_class_for_resolution(result);
14953
14954   if (!has_child)
14955     // TODO: set the access specifier for the declaration-only class
14956     // here.
14957     return result;
14958
14959   ctxt.die_wip_classes_map(source)[dwarf_dieoffset(die)] = result;
14960
14961   scope_decl_sptr scop =
14962     dynamic_pointer_cast<scope_decl>(res);
14963   ABG_ASSERT(scop);
14964   ctxt.scope_stack().push(scop.get());
14965
14966   if (has_child)
14967     {
14968       int anonymous_member_class_index = -1;
14969       int anonymous_member_union_index = -1;
14970       int anonymous_member_enum_index = -1;
14971
14972       do
14973         {
14974           tag = dwarf_tag(&child);
14975
14976           // Handle base classes.
14977           if (tag == DW_TAG_inheritance)
14978             {
14979               result->set_is_declaration_only(false);
14980
14981               Dwarf_Die type_die;
14982               if (!die_die_attribute(&child, DW_AT_type, type_die))
14983                 continue;
14984
14985               type_base_sptr base_type;
14986               if (!(base_type =
14987                     lookup_class_or_typedef_from_corpus(ctxt, &type_die,
14988                                                         called_from_public_decl,
14989                                                         where_offset)))
14990                 {
14991                   base_type =
14992                     is_type(build_ir_node_from_die(ctxt, &type_die,
14993                                                    called_from_public_decl,
14994                                                    where_offset));
14995                 }
14996               // Sometimes base_type can be a typedef.  Let's make
14997               // sure that typedef is compatible with a class type.
14998               class_decl_sptr b = is_compatible_with_class_type(base_type);
14999               if (!b)
15000                 continue;
15001
15002               access_specifier access =
15003                 is_struct
15004                 ? public_access
15005                 : private_access;
15006
15007               die_access_specifier(&child, access);
15008
15009               bool is_virt= die_is_virtual(&child);
15010               int64_t offset = 0;
15011               bool is_offset_present =
15012                 die_member_offset(ctxt, &child, offset);
15013
15014               class_decl::base_spec_sptr base(new class_decl::base_spec
15015                                               (b, access,
15016                                                is_offset_present ? offset : -1,
15017                                                is_virt));
15018               if (b->get_is_declaration_only())
15019                 ABG_ASSERT(ctxt.is_decl_only_class_scheduled_for_resolution(b));
15020               if (result->find_base_class(b->get_qualified_name()))
15021                 continue;
15022               result->add_base_specifier(base);
15023             }
15024           // Handle data members.
15025           else if (tag == DW_TAG_member
15026                    || tag == DW_TAG_variable)
15027             {
15028               Dwarf_Die type_die;
15029               if (!die_die_attribute(&child, DW_AT_type, type_die))
15030                 continue;
15031
15032               string n, m;
15033               location loc;
15034               die_loc_and_name(ctxt, &child, loc, n, m);
15035               /// For now, we skip the hidden vtable pointer.
15036               /// Currently, we're looking for a member starting with
15037               /// "_vptr[^0-9a-zA-Z_]", which is what Clang and GCC
15038               /// use as a name for the hidden vtable pointer.
15039               if (n.substr(0, 5) == "_vptr"
15040                   && !std::isalnum(n.at(5))
15041                   && n.at(5) != '_')
15042                 continue;
15043
15044               // If the variable is already a member of this class,
15045               // move on.
15046               if (lookup_var_decl_in_scope(n, result))
15047                 continue;
15048
15049               int64_t offset_in_bits = 0;
15050               bool is_laid_out = die_member_offset(ctxt, &child,
15051                                                    offset_in_bits);
15052               // For now, is_static == !is_laid_out.  When we have
15053               // templates, we'll try to be more specific.  For now,
15054               // this approximation should do OK.
15055               bool is_static = !is_laid_out;
15056
15057               if (is_static && variable_is_suppressed(ctxt,
15058                                                       result.get(),
15059                                                       &child))
15060                 continue;
15061
15062               decl_base_sptr ty = is_decl(
15063                                           build_ir_node_from_die(ctxt, &type_die,
15064                                                                  called_from_public_decl,
15065                                                                  where_offset));
15066               type_base_sptr t = is_type(ty);
15067               if (!t)
15068                 continue;
15069
15070               // The call to build_ir_node_from_die above could have
15071               // triggered the adding of a data member named 'n' into
15072               // result.  So let's check again if the variable is
15073               // already a member of this class.
15074               if (lookup_var_decl_in_scope(n, result))
15075                 continue;
15076
15077               if (!is_static)
15078                 // We have a non-static data member.  So this class
15079                 // cannot be a declaration-only class anymore, even if
15080                 // some DWARF emitters might consider it otherwise.
15081                 result->set_is_declaration_only(false);
15082               access_specifier access =
15083                 is_struct
15084                 ? public_access
15085                 : private_access;
15086
15087               die_access_specifier(&child, access);
15088
15089               var_decl_sptr dm(new var_decl(n, t, loc, m));
15090               result->add_data_member(dm, access, is_laid_out,
15091                                       is_static, offset_in_bits);
15092               ABG_ASSERT(has_scope(dm));
15093               ctxt.associate_die_to_decl(&child, dm, where_offset,
15094                                          /*associate_by_repr=*/false);
15095             }
15096           // Handle member functions;
15097           else if (tag == DW_TAG_subprogram)
15098             {
15099               decl_base_sptr r =
15100                 add_or_update_member_function(ctxt, &child, result,
15101                                               called_from_public_decl,
15102                                               where_offset);
15103               if (function_decl_sptr f = is_function_decl(r))
15104                 ctxt.associate_die_to_decl(&child, f, where_offset,
15105                                            /*associate_by_repr=*/true);
15106             }
15107           // Handle member types
15108           else if (die_is_type(&child))
15109             {
15110               // Track the anonymous type index in the current
15111               // scope. Look for what this means by reading the
15112               // comment of the function
15113               // build_internal_anonymous_die_name.
15114               int anonymous_member_type_index = 0;
15115               if (is_anonymous_type_die(&child))
15116                 {
15117                   // Update the anonymous type index.
15118                   if (die_is_class_type(&child))
15119                     anonymous_member_type_index =
15120                       ++anonymous_member_class_index;
15121                   else if (dwarf_tag(&child) == DW_TAG_union_type)
15122                     anonymous_member_type_index =
15123                       ++anonymous_member_union_index;
15124                   else if (dwarf_tag(&child) == DW_TAG_enumeration_type)
15125                     anonymous_member_type_index =
15126                       ++anonymous_member_enum_index;
15127                 }
15128               // if the type is not already a member of this class,
15129               // then add it to the class.
15130               if (!lookup_class_typedef_or_enum_type_from_corpus
15131                   (&child, anonymous_member_type_index, result.get()))
15132                 build_ir_node_from_die(ctxt, &child, result.get(),
15133                                        called_from_public_decl,
15134                                        where_offset);
15135             }
15136         } while (dwarf_siblingof(&child, &child) == 0);
15137     }
15138
15139   ctxt.scope_stack().pop();
15140
15141   {
15142     die_class_or_union_map_type::const_iterator i =
15143       ctxt.die_wip_classes_map(source).find(dwarf_dieoffset(die));
15144     if (i != ctxt.die_wip_classes_map(source).end())
15145       {
15146         if (is_member_type(i->second))
15147           set_member_access_specifier(res,
15148                                       get_member_access_specifier(i->second));
15149         ctxt.die_wip_classes_map(source).erase(i);
15150       }
15151   }
15152
15153   ctxt.maybe_schedule_declaration_only_class_for_resolution(result);
15154   return result;
15155 }
15156
15157 /// Build an @ref union_decl from a DW_TAG_union_type DIE.
15158 ///
15159 /// @param ctxt the read context to use.
15160 ///
15161 /// @param die the DIE to read from.
15162 ///
15163 /// @param scope the scope the resulting @ref union_decl belongs to.
15164 ///
15165 /// @param union_type if this parameter is non-nil, then this function
15166 /// updates the @ref union_decl that it points to, rather than
15167 /// creating a new @ref union_decl.
15168 ///
15169 /// @param called_from_public_decl is true if this function has been
15170 /// initially called within the context of a public decl.
15171 ///
15172 /// @param where_offset the offset of the DIE where we are "logically"
15173 /// positionned at, in the DIE tree.  This is useful when @p die is
15174 /// e.g, DW_TAG_partial_unit that can be included in several places in
15175 /// the DIE tree.
15176 static union_decl_sptr
15177 add_or_update_union_type(read_context&  ctxt,
15178                          Dwarf_Die*     die,
15179                          scope_decl*    scope,
15180                          union_decl_sptr union_type,
15181                          bool           called_from_public_decl,
15182                          size_t where_offset)
15183 {
15184   union_decl_sptr result;
15185   if (!die)
15186     return result;
15187
15188   unsigned tag = dwarf_tag(die);
15189
15190   if (tag != DW_TAG_union_type)
15191     return result;
15192
15193   die_source source;
15194   ABG_ASSERT(ctxt.get_die_source(die, source));
15195   {
15196     die_class_or_union_map_type::const_iterator i =
15197       ctxt.die_wip_classes_map(source).find(dwarf_dieoffset(die));
15198     if (i != ctxt.die_wip_classes_map(source).end())
15199       {
15200         union_decl_sptr u = is_union_type(i->second);
15201         ABG_ASSERT(u);
15202         return u;
15203       }
15204   }
15205
15206   string name, linkage_name;
15207   location loc;
15208   die_loc_and_name(ctxt, die, loc, name, linkage_name);
15209   bool is_declaration_only = die_is_declaration_only(die);
15210
15211   bool is_anonymous = false;
15212   if (name.empty())
15213     {
15214       // So we are looking at an anonymous union.  Let's give it a
15215       // name.
15216       name = get_internal_anonymous_die_prefix_name(die);
15217       ABG_ASSERT(!name.empty());
15218       // But we remember that the type is anonymous.
15219       is_anonymous = true;
15220
15221       if (size_t s = scope->get_num_anonymous_member_unions())
15222         name = build_internal_anonymous_die_name(name, s);
15223     }
15224
15225   // If the type has location, then associate it to its
15226   // representation.  This way, all occurences of types with the same
15227   // representation (name) and location can be later detected as being
15228   // for the same type.
15229
15230   if (!is_anonymous)
15231     {
15232       if (corpus_sptr corp = ctxt.should_reuse_type_from_corpus_group())
15233         {
15234           if (loc)
15235             result = lookup_union_type_per_location(loc.expand(), *corp);
15236           else
15237             result = lookup_union_type(name, *corp);
15238
15239           if (result)
15240             {
15241               ctxt.associate_die_to_type(die, result, where_offset);
15242               return result;
15243             }
15244         }
15245     }
15246
15247   // if we've already seen a union with the same union as 'die' then
15248   // let's re-use that one. We can't really safely re-use anonymous
15249   // classes as they have no name, by construction.  What we can do,
15250   // rather, is to reuse the typedef that name them, when they do have
15251   // a naming typedef.
15252   if (!is_anonymous)
15253     if (union_decl_sptr pre_existing_union =
15254         is_union_type(ctxt.lookup_artifact_from_die(die)))
15255       union_type = pre_existing_union;
15256
15257   uint64_t size = 0;
15258   die_size_in_bits(die, size);
15259
15260   if (union_type)
15261     {
15262       result = union_type;
15263       result->set_location(loc);
15264     }
15265   else
15266     {
15267       result.reset(new union_decl(ctxt.env(), name, size,
15268                                   loc, decl_base::VISIBILITY_DEFAULT));
15269       result->set_is_anonymous(is_anonymous);
15270       if (is_declaration_only)
15271         result->set_is_declaration_only(true);
15272       result = is_union_type(add_decl_to_scope(result, scope));
15273       ABG_ASSERT(result);
15274     }
15275
15276   if (size)
15277     {
15278       result->set_size_in_bits(size);
15279       result->set_is_declaration_only(false);
15280     }
15281
15282   ctxt.associate_die_to_type(die, result, where_offset);
15283
15284   // TODO: maybe schedule declaration-only union for result like we do
15285   // for classes:
15286   // ctxt.maybe_schedule_declaration_only_class_for_resolution(result);
15287
15288   Dwarf_Die child;
15289   bool has_child = (dwarf_child(die, &child) == 0);
15290   if (!has_child)
15291     return result;
15292
15293   ctxt.die_wip_classes_map(source)[dwarf_dieoffset(die)] = result;
15294
15295   scope_decl_sptr scop =
15296     dynamic_pointer_cast<scope_decl>(result);
15297   ABG_ASSERT(scop);
15298   ctxt.scope_stack().push(scop.get());
15299
15300   if (has_child)
15301     {
15302       do
15303         {
15304           tag = dwarf_tag(&child);
15305           // Handle data members.
15306           if (tag == DW_TAG_member || tag == DW_TAG_variable)
15307             {
15308               Dwarf_Die type_die;
15309               if (!die_die_attribute(&child, DW_AT_type, type_die))
15310                 continue;
15311
15312               string n, m;
15313               location loc;
15314               die_loc_and_name(ctxt, &child, loc, n, m);
15315
15316               if (lookup_var_decl_in_scope(n, result))
15317                 continue;
15318
15319               ssize_t offset_in_bits = 0;
15320               decl_base_sptr ty =
15321                 is_decl(build_ir_node_from_die(ctxt, &type_die,
15322                                                called_from_public_decl,
15323                                                where_offset));
15324               type_base_sptr t = is_type(ty);
15325               if (!t)
15326                 continue;
15327
15328               // We have a non-static data member.  So this class
15329               // cannot be a declaration-only class anymore, even if
15330               // some DWARF emitters might consider it otherwise.
15331               result->set_is_declaration_only(false);
15332               access_specifier access = private_access;
15333
15334               die_access_specifier(&child, access);
15335
15336               var_decl_sptr dm(new var_decl(n, t, loc, m));
15337               result->add_data_member(dm, access, /*is_laid_out=*/true,
15338                                       /*is_static=*/false,
15339                                       offset_in_bits);
15340               ABG_ASSERT(has_scope(dm));
15341               ctxt.associate_die_to_decl(&child, dm, where_offset,
15342                                          /*associate_by_repr=*/false);
15343             }
15344           // Handle member functions;
15345           else if (tag == DW_TAG_subprogram)
15346             {
15347               decl_base_sptr r =
15348                 is_decl(build_ir_node_from_die(ctxt, &child,
15349                                                result.get(),
15350                                                called_from_public_decl,
15351                                                where_offset));
15352               if (!r)
15353                 continue;
15354
15355               function_decl_sptr f = dynamic_pointer_cast<function_decl>(r);
15356               ABG_ASSERT(f);
15357
15358               finish_member_function_reading(&child, f, result, ctxt);
15359
15360               ctxt.associate_die_to_decl(&child, f, where_offset,
15361                                          /*associate_by_repr=*/false);
15362             }
15363           // Handle member types
15364           else if (die_is_type(&child))
15365             decl_base_sptr td =
15366               is_decl(build_ir_node_from_die(ctxt, &child, result.get(),
15367                                              called_from_public_decl,
15368                                              where_offset));
15369         } while (dwarf_siblingof(&child, &child) == 0);
15370     }
15371
15372   ctxt.scope_stack().pop();
15373
15374   {
15375     die_class_or_union_map_type::const_iterator i =
15376       ctxt.die_wip_classes_map(source).find(dwarf_dieoffset(die));
15377     if (i != ctxt.die_wip_classes_map(source).end())
15378       {
15379         if (is_member_type(i->second))
15380           set_member_access_specifier(result,
15381                                       get_member_access_specifier(i->second));
15382         ctxt.die_wip_classes_map(source).erase(i);
15383       }
15384   }
15385
15386   return result;
15387 }
15388
15389 /// build a qualified type from a DW_TAG_const_type,
15390 /// DW_TAG_volatile_type or DW_TAG_restrict_type DIE.
15391 ///
15392 /// @param ctxt the read context to consider.
15393 ///
15394 /// @param die the input DIE to read from.
15395 ///
15396 /// @param called_from_public_decl true if this function was called
15397 /// from a context where either a public function or a public variable
15398 /// is being built.
15399 ///
15400 /// @param where_offset the offset of the DIE where we are "logically"
15401 /// positionned at, in the DIE tree.  This is useful when @p die is
15402 /// e.g, DW_TAG_partial_unit that can be included in several places in
15403 /// the DIE tree.
15404 ///
15405 /// @return the resulting qualified_type_def.
15406 static type_base_sptr
15407 build_qualified_type(read_context&      ctxt,
15408                      Dwarf_Die* die,
15409                      bool               called_from_public_decl,
15410                      size_t             where_offset)
15411 {
15412   type_base_sptr result;
15413   if (!die)
15414     return result;
15415
15416   die_source source;
15417   ABG_ASSERT(ctxt.get_die_source(die, source));
15418
15419   unsigned tag = dwarf_tag(die);
15420
15421   if (tag != DW_TAG_const_type
15422       && tag != DW_TAG_volatile_type
15423       && tag != DW_TAG_restrict_type)
15424     return result;
15425
15426   Dwarf_Die underlying_type_die;
15427   decl_base_sptr utype_decl;
15428   if (!die_die_attribute(die, DW_AT_type, underlying_type_die))
15429     // So, if no DW_AT_type is present, then this means (if we are
15430     // looking at a debug info emitted by GCC) that we are looking
15431     // at a qualified void type.
15432     utype_decl = build_ir_node_for_void_type(ctxt);
15433
15434   if (!utype_decl)
15435     utype_decl = is_decl(build_ir_node_from_die(ctxt, &underlying_type_die,
15436                                                 called_from_public_decl,
15437                                                 where_offset));
15438   if (!utype_decl)
15439     return result;
15440
15441   // The call to build_ir_node_from_die() could have triggered the
15442   // creation of the type for this DIE.  In that case, just return it.
15443   if (type_base_sptr t = ctxt.lookup_type_from_die(die))
15444     {
15445       result = t;
15446       ctxt.associate_die_to_type(die, result, where_offset);
15447       return result;
15448     }
15449
15450   type_base_sptr utype = is_type(utype_decl);
15451   ABG_ASSERT(utype);
15452
15453   qualified_type_def::CV qual = qualified_type_def::CV_NONE;
15454   if (tag == DW_TAG_const_type)
15455     qual |= qualified_type_def::CV_CONST;
15456   else if (tag == DW_TAG_volatile_type)
15457     qual |= qualified_type_def::CV_VOLATILE;
15458   else if (tag == DW_TAG_restrict_type)
15459     qual |= qualified_type_def::CV_RESTRICT;
15460   else
15461     ABG_ASSERT_NOT_REACHED;
15462
15463   if (!result)
15464     result.reset(new qualified_type_def(utype, qual, location()));
15465
15466   ctxt.associate_die_to_type(die, result, where_offset);
15467
15468   return result;
15469 }
15470
15471 /// Strip qualification from a qualified type, when it makes sense.
15472 ///
15473 /// DWARF constructs "const reference".  This is redundant because a
15474 /// reference is always const.  The issue is these redundant types then
15475 /// leak into the IR and make for bad diagnostics.
15476 ///
15477 /// This function thus strips the const qualifier from the type in
15478 /// that case.  It might contain code to strip other cases like this
15479 /// in the future.
15480 ///
15481 /// @param t the type to strip const qualification from.
15482 ///
15483 /// @param ctxt the @ref read_context to use.
15484 ///
15485 /// @return the stripped type or just return @p t.
15486 static decl_base_sptr
15487 maybe_strip_qualification(const qualified_type_def_sptr t,
15488                           read_context &ctxt)
15489 {
15490   if (!t)
15491     return t;
15492
15493   decl_base_sptr result = t;
15494   type_base_sptr u = t->get_underlying_type();
15495   environment* env = t->get_environment();
15496
15497   if (t->get_cv_quals() & qualified_type_def::CV_CONST
15498       && (is_reference_type(u)))
15499     {
15500       // Let's strip only the const qualifier.  To do that, the "const"
15501       // qualified is turned into a no-op "none" qualified.
15502       result.reset(new qualified_type_def
15503                    (u, t->get_cv_quals() & ~qualified_type_def::CV_CONST,
15504                     t->get_location()));
15505     }
15506   else if (t->get_cv_quals() & qualified_type_def::CV_CONST
15507            && env->is_void_type(u))
15508     {
15509       // So this type is a "const void".  Let's strip the "const"
15510       // qualifier out and make this just be "void", so that a "const
15511       // void" type and a "void" type compare equal after going through
15512       // this function.
15513       result = is_decl(u);
15514     }
15515   else if (is_array_of_qualified_element(u))
15516     {
15517       // In C and C++, a cv qualifiers of a qualified array apply to
15518       // the array element type.  So the qualifiers of the array can
15519       // be dropped and applied to the element type.
15520       //
15521       // Here, the element type is qualified already.  So apply the
15522       // qualifiers of the array itself to the already qualified
15523       // element type and drop the array qualifiers.
15524       array_type_def_sptr array = is_array_type(u);
15525       qualified_type_def_sptr element_type =
15526         is_qualified_type(array->get_element_type());
15527       qualified_type_def::CV quals = element_type->get_cv_quals();
15528       quals |= t->get_cv_quals();
15529       element_type->set_cv_quals(quals);
15530       result = is_decl(u);
15531       if (u->get_canonical_type()
15532           || element_type->get_canonical_type())
15533         // We shouldn't be editing types that were already
15534         // canonicalized.  For those, canonicalization should be
15535         // delayed until after all editing is done.
15536         ABG_ASSERT_NOT_REACHED;
15537     }
15538   else if (is_array_type(u) && !is_array_of_qualified_element(is_array_type(u)))
15539     {
15540       // In C and C++, a cv qualifiers of a qualified array apply to
15541       // the array element type.  So the qualifiers of the array can
15542       // be dropped and applied to the element type.
15543       //
15544       // Here, the element type is not qualified.  So apply the
15545       // qualifiers of the array itself to the element type and drop
15546       // the array qualifiers.
15547       array_type_def_sptr array = is_array_type(u);
15548       type_base_sptr element_type = array->get_element_type();
15549       qualified_type_def_sptr qual_type
15550         (new qualified_type_def(element_type,
15551                                 t->get_cv_quals(),
15552                                 t->get_location()));
15553       add_decl_to_scope(qual_type, is_decl(element_type)->get_scope());
15554       array->set_element_type(qual_type);
15555       ctxt.schedule_type_for_late_canonicalization(is_type(qual_type));
15556       result = is_decl(u);
15557       if (u->get_canonical_type())
15558         // We shouldn't be editing types that were already
15559         // canonicalized.  For those, canonicalization should be
15560         // delayed until after all editing is done.
15561         ABG_ASSERT_NOT_REACHED;
15562     }
15563
15564   return result;
15565 }
15566
15567 /// Build a pointer type from a DW_TAG_pointer_type DIE.
15568 ///
15569 /// @param ctxt the read context to consider.
15570 ///
15571 /// @param die the DIE to read information from.
15572 ///
15573 /// @param called_from_public_decl true if this function was called
15574 /// from a context where either a public function or a public variable
15575 /// is being built.
15576 ///
15577 /// @param where_offset the offset of the DIE where we are "logically"
15578 /// positionned at, in the DIE tree.  This is useful when @p die is
15579 /// e.g, DW_TAG_partial_unit that can be included in several places in
15580 /// the DIE tree.
15581 ///
15582 /// @return the resulting pointer to pointer_type_def.
15583 static pointer_type_def_sptr
15584 build_pointer_type_def(read_context&    ctxt,
15585                        Dwarf_Die*       die,
15586                        bool             called_from_public_decl,
15587                        size_t           where_offset)
15588 {
15589   pointer_type_def_sptr result;
15590
15591   if (!die)
15592     return result;
15593
15594   die_source source;
15595   ABG_ASSERT(ctxt.get_die_source(die, source));
15596
15597   unsigned tag = dwarf_tag(die);
15598   if (tag != DW_TAG_pointer_type)
15599     return result;
15600
15601   type_or_decl_base_sptr utype_decl;
15602   Dwarf_Die underlying_type_die;
15603   bool has_underlying_type_die = false;
15604   if (!die_die_attribute(die, DW_AT_type, underlying_type_die))
15605     // If the DW_AT_type attribute is missing, that means we are
15606     // looking at a pointer to "void".
15607     utype_decl = build_ir_node_for_void_type(ctxt);
15608   else
15609     has_underlying_type_die = true;
15610
15611   if (!utype_decl && has_underlying_type_die)
15612     utype_decl = build_ir_node_from_die(ctxt, &underlying_type_die,
15613                                         called_from_public_decl,
15614                                         where_offset);
15615   if (!utype_decl)
15616     return result;
15617
15618   // The call to build_ir_node_from_die() could have triggered the
15619   // creation of the type for this DIE.  In that case, just return it.
15620   if (type_base_sptr t = ctxt.lookup_type_from_die(die))
15621     {
15622       result = is_pointer_type(t);
15623       ABG_ASSERT(result);
15624       return result;
15625     }
15626
15627   type_base_sptr utype = is_type(utype_decl);
15628   ABG_ASSERT(utype);
15629
15630   // if the DIE for the pointer type doesn't have a byte_size
15631   // attribute then we assume the size of the pointer is the address
15632   // size of the current translation unit.
15633   uint64_t size = ctxt.cur_transl_unit()->get_address_size();
15634   if (die_unsigned_constant_attribute(die, DW_AT_byte_size, size))
15635     // The size as expressed by DW_AT_byte_size is in byte, so let's
15636     // convert it to bits.
15637     size *= 8;
15638
15639   // And the size of the pointer must be the same as the address size
15640   // of the current translation unit.
15641   ABG_ASSERT((size_t) ctxt.cur_transl_unit()->get_address_size() == size);
15642
15643   result.reset(new pointer_type_def(utype, size, /*alignment=*/0, location()));
15644   ABG_ASSERT(result->get_pointed_to_type());
15645
15646   ctxt.associate_die_to_type(die, result, where_offset);
15647   return result;
15648 }
15649
15650 /// Build a reference type from either a DW_TAG_reference_type or
15651 /// DW_TAG_rvalue_reference_type DIE.
15652 ///
15653 /// @param ctxt the read context to consider.
15654 ///
15655 /// @param die the DIE to read from.
15656 ///
15657 /// @param called_from_public_decl true if this function was called
15658 /// from a context where either a public function or a public variable
15659 /// is being built.
15660 ///
15661 /// @param where_offset the offset of the DIE where we are "logically"
15662 /// positionned at, in the DIE tree.  This is useful when @p die is
15663 /// e.g, DW_TAG_partial_unit that can be included in several places in
15664 /// the DIE tree.
15665 ///
15666 /// @return a pointer to the resulting reference_type_def.
15667 static reference_type_def_sptr
15668 build_reference_type(read_context&      ctxt,
15669                      Dwarf_Die* die,
15670                      bool               called_from_public_decl,
15671                      size_t             where_offset)
15672 {
15673   reference_type_def_sptr result;
15674
15675   if (!die)
15676     return result;
15677
15678   die_source source;
15679   ABG_ASSERT(ctxt.get_die_source(die, source));
15680
15681   unsigned tag = dwarf_tag(die);
15682   if (tag != DW_TAG_reference_type
15683       && tag != DW_TAG_rvalue_reference_type)
15684     return result;
15685
15686   Dwarf_Die underlying_type_die;
15687   if (!die_die_attribute(die, DW_AT_type, underlying_type_die))
15688     return result;
15689
15690   type_or_decl_base_sptr utype_decl =
15691     build_ir_node_from_die(ctxt, &underlying_type_die,
15692                            called_from_public_decl,
15693                            where_offset);
15694   if (!utype_decl)
15695     return result;
15696
15697   // The call to build_ir_node_from_die() could have triggered the
15698   // creation of the type for this DIE.  In that case, just return it.
15699   if (type_base_sptr t = ctxt.lookup_type_from_die(die))
15700     {
15701       result = is_reference_type(t);
15702       ABG_ASSERT(result);
15703       return result;
15704     }
15705
15706   type_base_sptr utype = is_type(utype_decl);
15707   ABG_ASSERT(utype);
15708
15709   // if the DIE for the reference type doesn't have a byte_size
15710   // attribute then we assume the size of the reference is the address
15711   // size of the current translation unit.
15712   uint64_t size = ctxt.cur_transl_unit()->get_address_size();
15713   if (die_unsigned_constant_attribute(die, DW_AT_byte_size, size))
15714     size *= 8;
15715
15716   // And the size of the pointer must be the same as the address size
15717   // of the current translation unit.
15718   ABG_ASSERT((size_t) ctxt.cur_transl_unit()->get_address_size() == size);
15719
15720   bool is_lvalue = (tag == DW_TAG_reference_type) ? true : false;
15721
15722   result.reset(new reference_type_def(utype, is_lvalue, size,
15723                                       /*alignment=*/0,
15724                                       location()));
15725   if (corpus_sptr corp = ctxt.current_corpus())
15726     if (reference_type_def_sptr t = lookup_reference_type(*result, *corp))
15727       result = t;
15728   ctxt.associate_die_to_type(die, result, where_offset);
15729   return result;
15730 }
15731
15732 /// Build a subroutine type from a DW_TAG_subroutine_type DIE.
15733 ///
15734 /// @param ctxt the read context to consider.
15735 ///
15736 /// @param die the DIE to read from.
15737 ///
15738 /// @param is_method points to a class or union declaration iff we're
15739 /// building the type for a method.  This is the enclosing class or
15740 /// union of the method.
15741 ///
15742 /// @param where_offset the offset of the DIE where we are "logically"
15743 /// positioned at, in the DIE tree.  This is useful when @p die is
15744 /// e.g, DW_TAG_partial_unit that can be included in several places in
15745 /// the DIE tree.
15746 ///
15747 /// @return a pointer to the resulting function_type_sptr.
15748 static function_type_sptr
15749 build_function_type(read_context&       ctxt,
15750                     Dwarf_Die*          die,
15751                     class_or_union_sptr is_method,
15752                     size_t              where_offset)
15753 {
15754   function_type_sptr result;
15755
15756   if (!die)
15757     return result;
15758
15759   ABG_ASSERT(dwarf_tag(die) == DW_TAG_subroutine_type
15760              || dwarf_tag(die) == DW_TAG_subprogram);
15761
15762   die_source source;
15763   ABG_ASSERT(ctxt.get_die_source(die, source));
15764
15765   decl_base_sptr type_decl;
15766
15767   translation_unit_sptr tu = ctxt.cur_transl_unit();
15768   ABG_ASSERT(tu);
15769
15770   /// If, inside the current translation unit, we've already seen a
15771   /// function type with the same text representation, then reuse that
15772   /// one instead.
15773   if (type_base_sptr t = ctxt.lookup_fn_type_from_die_repr_per_tu(die))
15774     {
15775       result = is_function_type(t);
15776       ABG_ASSERT(result);
15777       ctxt.associate_die_to_type(die, result, where_offset);
15778       return result;
15779     }
15780
15781   bool odr_is_relevant = ctxt.odr_is_relevant(die);
15782   if (odr_is_relevant)
15783     {
15784       // So we can rely on the One Definition Rule to say that if
15785       // several different function types have the same name (or
15786       // rather, representation) across the entire binary, then they
15787       // ought to designate the same function type.  So let's ensure
15788       // that if we've already seen a function type with the same
15789       // representation as the function type 'die', then it's the same
15790       // type as the one denoted by 'die'.
15791       if (function_type_sptr fn_type =
15792           is_function_type(ctxt.lookup_type_artifact_from_die(die)))
15793         {
15794           ctxt.associate_die_to_type(die, fn_type, where_offset);
15795           return fn_type;
15796         }
15797     }
15798
15799   // Let's look at the DIE to detect if it's the DIE for a method
15800   // (type).  If it is, we can deduce the name of its enclosing class
15801   // and if it's a static or const.
15802   bool is_const = false;
15803   bool is_static = false;
15804   Dwarf_Die object_pointer_die;
15805   Dwarf_Die class_type_die;
15806   bool has_this_parm_die =
15807     die_function_type_is_method_type(ctxt, die, where_offset,
15808                                      object_pointer_die,
15809                                      class_type_die,
15810                                      is_static);
15811   if (has_this_parm_die)
15812     {
15813       // The function (type) has a "this" parameter DIE. It means it's
15814       // a member function DIE.
15815       if (!is_static)
15816         if (die_object_pointer_is_for_const_method(&object_pointer_die))
15817           is_const = true;
15818
15819       if (!is_method)
15820         {
15821           // We were initially called as if the function represented
15822           // by DIE was *NOT* a member function.  But now we know it's
15823           // a member function.  Let's take that into account.
15824           class_or_union_sptr klass_type =
15825             is_class_or_union_type(build_ir_node_from_die(ctxt, &class_type_die,
15826                                                           /*called_from_pub_decl=*/true,
15827                                                           where_offset));
15828           ABG_ASSERT(klass_type);
15829           is_method = klass_type;
15830         }
15831     }
15832
15833   // Let's create the type early and record it as being for the DIE
15834   // 'die'.  This way, when building the sub-type triggers the
15835   // creation of a type matching the same 'die', then we'll reuse this
15836   // one.
15837
15838   result.reset(is_method
15839                ? new method_type(is_method, is_const,
15840                                  tu->get_address_size(),
15841                                  /*alignment=*/0)
15842                : new function_type(ctxt.env(), tu->get_address_size(),
15843                                    /*alignment=*/0));
15844   ctxt.associate_die_to_type(die, result, where_offset);
15845   ctxt.die_wip_function_types_map(source)[dwarf_dieoffset(die)] = result;
15846   ctxt.associate_die_repr_to_fn_type_per_tu(die, result);
15847
15848   type_base_sptr return_type;
15849   Dwarf_Die ret_type_die;
15850   if (die_die_attribute(die, DW_AT_type, ret_type_die))
15851     return_type =
15852       is_type(build_ir_node_from_die(ctxt, &ret_type_die,
15853                                      /*called_from_public_decl=*/true,
15854                                      where_offset));
15855   if (!return_type)
15856     return_type = is_type(build_ir_node_for_void_type(ctxt));
15857   result->set_return_type(return_type);
15858
15859   Dwarf_Die child;
15860   function_decl::parameters function_parms;
15861
15862   if (dwarf_child(die, &child) == 0)
15863     do
15864       {
15865         int child_tag = dwarf_tag(&child);
15866         if (child_tag == DW_TAG_formal_parameter)
15867           {
15868             // This is a "normal" function parameter.
15869             string name, linkage_name;
15870             location loc;
15871             die_loc_and_name(ctxt, &child, loc, name, linkage_name);
15872             if (!tools_utils::string_is_ascii_identifier(name))
15873               // Sometimes, bogus compiler emit names that are
15874               // non-ascii garbage.  Let's just ditch that for now.
15875               name.clear();
15876             bool is_artificial = die_is_artificial(&child);
15877             type_base_sptr parm_type;
15878             Dwarf_Die parm_type_die;
15879             if (die_die_attribute(&child, DW_AT_type, parm_type_die))
15880               parm_type =
15881                 is_type(build_ir_node_from_die(ctxt, &parm_type_die,
15882                                                /*called_from_public_decl=*/true,
15883                                                where_offset));
15884             if (!parm_type)
15885               continue;
15886             function_decl::parameter_sptr p
15887               (new function_decl::parameter(parm_type, name, loc,
15888                                             /*variadic_marker=*/false,
15889                                             is_artificial));
15890             function_parms.push_back(p);
15891           }
15892         else if (child_tag == DW_TAG_unspecified_parameters)
15893           {
15894             // This is a variadic function parameter.
15895             bool is_artificial = die_is_artificial(&child);
15896             ir::environment* env = ctxt.env();
15897             ABG_ASSERT(env);
15898             type_base_sptr parm_type = env->get_variadic_parameter_type();
15899             function_decl::parameter_sptr p
15900               (new function_decl::parameter(parm_type,
15901                                             /*name=*/"",
15902                                             location(),
15903                                             /*variadic_marker=*/true,
15904                                             is_artificial));
15905             function_parms.push_back(p);
15906             // After a DW_TAG_unspecified_parameters tag, we shouldn't
15907             // keep reading for parameters.  The
15908             // unspecified_parameters TAG should be the last parameter
15909             // that we record. For instance, if there are multiple
15910             // DW_TAG_unspecified_parameters DIEs then we should care
15911             // only for the first one.
15912             break;
15913           }
15914       }
15915     while (dwarf_siblingof(&child, &child) == 0);
15916
15917   result->set_parameters(function_parms);
15918
15919   tu->bind_function_type_life_time(result);
15920
15921   {
15922     die_function_type_map_type::const_iterator i =
15923       ctxt.die_wip_function_types_map(source).
15924       find(dwarf_dieoffset(die));
15925     if (i != ctxt.die_wip_function_types_map(source).end())
15926       ctxt.die_wip_function_types_map(source).erase(i);
15927   }
15928
15929   maybe_canonicalize_type(result, ctxt);
15930   return result;
15931 }
15932
15933 /// Build a subrange type from a DW_TAG_subrange_type.
15934 ///
15935 /// @param ctxt the read context to consider.
15936 ///
15937 /// @param die the DIE to read from.
15938 ///
15939 /// @param where_offset the offset of the DIE where we are "logically"
15940 /// positionned at in the DIE tree.  This is useful when @p die is
15941 /// e,g, DW_TAG_partial_unit that can be included in several places in
15942 /// the DIE tree.
15943 ///
15944 /// @param associate_die_to_type if this is true then the resulting
15945 /// type is associated to the @p die, so that next time when the
15946 /// system looks up the type associated to it, the current resulting
15947 /// type is returned.  If false, then no association is done and the
15948 /// resulting type can be destroyed right after.  This can be useful
15949 /// when the sole purpose of building the @ref
15950 /// array_type_def::subrange_type is to use some of its method like,
15951 /// e.g, its name pretty printing methods.
15952 ///
15953 /// @return the newly built instance of @ref
15954 /// array_type_def::subrange_type, or nil if no type could be built.
15955 static array_type_def::subrange_sptr
15956 build_subrange_type(read_context&       ctxt,
15957                     const Dwarf_Die*            die,
15958                     size_t              where_offset,
15959                     bool                associate_type_to_die)
15960 {
15961   array_type_def::subrange_sptr result;
15962
15963   if (!die)
15964     return result;
15965
15966   die_source source;
15967   ABG_ASSERT(ctxt.get_die_source(die, source));
15968
15969   unsigned tag = dwarf_tag(const_cast<Dwarf_Die*>(die));
15970   if (tag != DW_TAG_subrange_type)
15971     return result;
15972
15973   string name = die_name(die);
15974
15975   translation_unit::language language = ctxt.cur_transl_unit()->get_language();
15976   array_type_def::subrange_type::bound_value lower_bound =
15977     get_default_array_lower_bound(language);
15978   array_type_def::subrange_type::bound_value upper_bound;
15979   uint64_t count = 0;
15980   bool is_infinite = false;
15981
15982   // The DWARF 4 specifications says, in [5.11 Subrange
15983   // Type Entries]:
15984   //
15985   //     The subrange entry may have the attributes
15986   //     DW_AT_lower_bound and DW_AT_upper_bound to
15987   //     specify, respectively, the lower and upper bound
15988   //     values of the subrange.
15989   //
15990   // So let's look for DW_AT_lower_bound first.
15991   die_constant_attribute(die, DW_AT_lower_bound, lower_bound);
15992
15993   // Then, DW_AT_upper_bound.
15994   if (!die_constant_attribute(die, DW_AT_upper_bound, upper_bound))
15995     {
15996       // The DWARF 4 spec says, in [5.11 Subrange Type
15997       // Entries]:
15998       //
15999       //   The DW_AT_upper_bound attribute may be replaced
16000       //   by a DW_AT_count attribute, whose value
16001       //   describes the number of elements in the
16002       //   subrange rather than the value of the last
16003       //   element."
16004       //
16005       // So, as DW_AT_upper_bound is not present in this
16006       // case, let's see if there is a DW_AT_count.
16007       die_unsigned_constant_attribute(die, DW_AT_count, count);
16008
16009       // We can deduce the upper_bound from the
16010       // lower_bound and the number of elements of the
16011       // array:
16012       if (int64_t u = lower_bound.get_signed_value() + count)
16013         upper_bound = u - 1;
16014
16015       if (upper_bound.get_unsigned_value() == 0 && count == 0)
16016         // No upper_bound nor count was present on the DIE, this means
16017         // the array is considered to have an infinite (or rather not
16018         // known) size.
16019         is_infinite = true;
16020     }
16021
16022   if (UINT64_MAX == upper_bound.get_unsigned_value())
16023     {
16024       // If the upper_bound size is the max of the integer value, then
16025       // it most certainly means infinite size.
16026       is_infinite = true;
16027       upper_bound.set_unsigned(0);
16028     }
16029
16030   result.reset
16031     (new array_type_def::subrange_type(ctxt.env(),
16032                                        name,
16033                                        lower_bound,
16034                                        upper_bound,
16035                                        location()));
16036   result->is_infinite(is_infinite);
16037
16038   // load the underlying type.
16039   Dwarf_Die underlying_type_die;
16040   type_base_sptr underlying_type;
16041   if (die_die_attribute(die, DW_AT_type, underlying_type_die))
16042     underlying_type =
16043       is_type(build_ir_node_from_die(ctxt,
16044                                      &underlying_type_die,
16045                                      /*called_from_public_decl=*/true,
16046                                      where_offset));
16047
16048   if (underlying_type)
16049     result->set_underlying_type(underlying_type);
16050
16051   if (associate_type_to_die)
16052     ctxt.associate_die_to_type(die, result, where_offset);
16053
16054   return result;
16055 }
16056
16057 /// Build the sub-ranges of an array type.
16058 ///
16059 /// This is a sub-routine of build_array_type().
16060 ///
16061 /// @param ctxt the context to read from.
16062 ///
16063 /// @param die the DIE of tag DW_TAG_array_type which contains
16064 /// children DIEs that represent the sub-ranges.
16065 ///
16066 /// @param subranges out parameter.  This is set to the sub-ranges
16067 /// that are built from @p die.
16068 ///
16069 /// @param where_offset the offset of the DIE where we are "logically"
16070 /// positioned at, in the DIE tree.  This is useful when @p die is
16071 /// e.g, DW_TAG_partial_unit that can be included in several places in
16072 /// the DIE tree.
16073 static void
16074 build_subranges_from_array_type_die(read_context&                       ctxt,
16075                                     const Dwarf_Die*                    die,
16076                                     array_type_def::subranges_type&     subranges,
16077                                     size_t                              where_offset,
16078                                     bool                                associate_type_to_die)
16079 {
16080   Dwarf_Die child;
16081
16082   if (dwarf_child(const_cast<Dwarf_Die*>(die), &child) == 0)
16083     {
16084       do
16085         {
16086           int child_tag = dwarf_tag(&child);
16087           if (child_tag == DW_TAG_subrange_type)
16088             {
16089               array_type_def::subrange_sptr s;
16090               if (associate_type_to_die)
16091                 {
16092                   // We are being called to create the type, add it to
16093                   // the current type graph and associate it to the
16094                   // DIE it's been created from.
16095                   type_or_decl_base_sptr t =
16096                     build_ir_node_from_die(ctxt, &child,
16097                                            /*called_from_public_decl=*/true,
16098                                            where_offset);
16099                   s = is_subrange_type(t);
16100                 }
16101               else
16102                 // We are being called to create the type but *NOT*
16103                 // add it to the current tyupe tree, *NOR* associate
16104                 // it to the DIE it's been created from.
16105                 s = build_subrange_type(ctxt, &child,
16106                                         where_offset,
16107                                         /*associate_type_to_die=*/false);
16108               if (s)
16109                 subranges.push_back(s);
16110             }
16111         }
16112       while (dwarf_siblingof(&child, &child) == 0);
16113     }
16114 }
16115
16116 /// Build an array type from a DW_TAG_array_type DIE.
16117 ///
16118 /// @param ctxt the read context to consider.
16119 ///
16120 /// @param die the DIE to read from.
16121 ///
16122 /// @param called_from_public_decl true if this function was called
16123 /// from a context where either a public function or a public variable
16124 /// is being built.
16125 ///
16126 /// @param where_offset the offset of the DIE where we are "logically"
16127 /// positioned at, in the DIE tree.  This is useful when @p die is
16128 /// e.g, DW_TAG_partial_unit that can be included in several places in
16129 /// the DIE tree.
16130 ///
16131 /// @return a pointer to the resulting array_type_def.
16132 static array_type_def_sptr
16133 build_array_type(read_context&  ctxt,
16134                  Dwarf_Die*     die,
16135                  bool           called_from_public_decl,
16136                  size_t where_offset)
16137 {
16138   array_type_def_sptr result;
16139
16140   if (!die)
16141     return result;
16142
16143   die_source source;
16144   ABG_ASSERT(ctxt.get_die_source(die, source));
16145
16146   unsigned tag = dwarf_tag(die);
16147   if (tag != DW_TAG_array_type)
16148     return result;
16149
16150   decl_base_sptr type_decl;
16151   Dwarf_Die type_die;
16152
16153   if (die_die_attribute(die, DW_AT_type, type_die))
16154     type_decl = is_decl(build_ir_node_from_die(ctxt, &type_die,
16155                                                called_from_public_decl,
16156                                                where_offset));
16157   if (!type_decl)
16158     return result;
16159
16160   // The call to build_ir_node_from_die() could have triggered the
16161   // creation of the type for this DIE.  In that case, just return it.
16162   if (type_base_sptr t = ctxt.lookup_type_from_die(die))
16163     {
16164       result = is_array_type(t);
16165       ABG_ASSERT(result);
16166       return result;
16167     }
16168
16169   type_base_sptr type = is_type(type_decl);
16170   ABG_ASSERT(type);
16171
16172   array_type_def::subranges_type subranges;
16173
16174   build_subranges_from_array_type_die(ctxt, die, subranges, where_offset);
16175
16176   result.reset(new array_type_def(type, subranges, location()));
16177
16178   return result;
16179 }
16180
16181 /// Create a typedef_decl from a DW_TAG_typedef DIE.
16182 ///
16183 /// @param ctxt the read context to consider.
16184 ///
16185 /// @param die the DIE to read from.
16186 ///
16187 /// @param called_from_public_decl true if this function was called
16188 /// from a context where either a public function or a public variable
16189 /// is being built.
16190 ///
16191 /// @param where_offset the offset of the DIE where we are "logically"
16192 /// positionned at, in the DIE tree.  This is useful when @p die is
16193 /// e.g, DW_TAG_partial_unit that can be included in several places in
16194 /// the DIE tree.
16195 ///
16196 /// @return the newly created typedef_decl.
16197 static typedef_decl_sptr
16198 build_typedef_type(read_context&        ctxt,
16199                    Dwarf_Die*           die,
16200                    bool         called_from_public_decl,
16201                    size_t               where_offset)
16202 {
16203   typedef_decl_sptr result;
16204
16205   if (!die)
16206     return result;
16207
16208   die_source source;
16209   ABG_ASSERT(ctxt.get_die_source(die, source));
16210
16211   unsigned tag = dwarf_tag(die);
16212   if (tag != DW_TAG_typedef)
16213     return result;
16214
16215   string name, linkage_name;
16216   location loc;
16217   die_loc_and_name(ctxt, die, loc, name, linkage_name);
16218
16219   if (corpus_sptr corp = ctxt.should_reuse_type_from_corpus_group())
16220     if (loc)
16221       result = lookup_typedef_type_per_location(loc.expand(), *corp);
16222
16223   if (!ctxt.odr_is_relevant(die))
16224     if (typedef_decl_sptr t = is_typedef(ctxt.lookup_artifact_from_die(die)))
16225       result = t;
16226
16227   if (!result)
16228     {
16229       type_base_sptr utype;
16230       Dwarf_Die underlying_type_die;
16231       if (!die_die_attribute(die, DW_AT_type, underlying_type_die))
16232         // A typedef DIE with no underlying type means a typedef to
16233         // void type.
16234         utype = ctxt.env()->get_void_type();
16235
16236       if (!utype)
16237         utype =
16238           is_type(build_ir_node_from_die(ctxt,
16239                                          &underlying_type_die,
16240                                          called_from_public_decl,
16241                                          where_offset));
16242       if (!utype)
16243         return result;
16244
16245       // The call to build_ir_node_from_die() could have triggered the
16246       // creation of the type for this DIE.  In that case, just return
16247       // it.
16248       if (type_base_sptr t = ctxt.lookup_type_from_die(die))
16249         {
16250           result = is_typedef(t);
16251           ABG_ASSERT(result);
16252           return result;
16253         }
16254
16255       ABG_ASSERT(utype);
16256       result.reset(new typedef_decl(name, utype, loc, linkage_name));
16257
16258       if (class_decl_sptr klass = is_class_type(utype))
16259         if (is_anonymous_type(klass))
16260           klass->set_naming_typedef(result);
16261     }
16262
16263   ctxt.associate_die_to_type(die, result, where_offset);
16264
16265   return result;
16266 }
16267
16268 /// Build a @ref var_decl out of a DW_TAG_variable DIE if the variable
16269 /// denoted by the DIE is not suppressed by a suppression
16270 /// specification associated to the current read context.
16271 ///
16272 /// Note that if a member variable declaration with the same name as
16273 /// the name of the DIE we are looking at exists, this function returns
16274 /// that existing variable declaration.
16275 ///
16276 /// @param ctxt the read context to use.
16277 ///
16278 /// @param die the DIE representing the variable we are looking at.
16279 ///
16280 /// @param where_offset the offset of the DIE where we are "logically"
16281 /// positionned at, in the DIE tree.  This is useful when @p die is
16282 /// e.g, DW_TAG_partial_unit that can be included in several places in
16283 /// the DIE tree.
16284 ///
16285 /// @param result if this is set to an existing var_decl, this means
16286 /// that the function will append the new properties it sees on @p die
16287 /// to that exising var_decl.  Otherwise, if this parameter is NULL, a
16288 /// new var_decl is going to be allocated and returned.
16289 ///
16290 /// @param is_required_decl_spec this is true iff the variable to
16291 /// build is referred to as being the specification of another
16292 /// variable.
16293 ///
16294 /// @return a pointer to the newly created var_decl.  If the var_decl
16295 /// could not be built, this function returns NULL.
16296 static var_decl_sptr
16297 build_or_get_var_decl_if_not_suppressed(read_context&   ctxt,
16298                                         scope_decl      *scope,
16299                                         Dwarf_Die       *die,
16300                                         size_t  where_offset,
16301                                         var_decl_sptr   result,
16302                                         bool is_required_decl_spec)
16303 {
16304   var_decl_sptr var;
16305   if (variable_is_suppressed(ctxt, scope, die, is_required_decl_spec))
16306     return var;
16307
16308   if (class_decl* class_type = is_class_type(scope))
16309     {
16310       string var_name = die_name(die);
16311       if (!var_name.empty())
16312         if ((var = class_type->find_data_member(var_name)))
16313           return var;
16314     }
16315   var = build_var_decl(ctxt, die, where_offset, result);
16316   return var;
16317 }
16318
16319 /// Create a variable symbol with a given name.
16320 ///
16321 /// @param sym_name the name of the variable symbol.
16322 ///
16323 /// @param env the environment to create the default symbol in.
16324 ///
16325 /// @return the newly created symbol.
16326 static elf_symbol_sptr
16327 create_default_var_sym(const string& sym_name, const environment *env)
16328 {
16329   elf_symbol::version ver;
16330   elf_symbol::visibility vis = elf_symbol::DEFAULT_VISIBILITY;
16331   elf_symbol_sptr result =
16332     elf_symbol::create(env,
16333                        /*symbol index=*/ 0,
16334                        /*symbol size=*/ 0,
16335                        sym_name,
16336                        /*symbol type=*/ elf_symbol::OBJECT_TYPE,
16337                        /*symbol binding=*/ elf_symbol::GLOBAL_BINDING,
16338                        /*symbol is defined=*/ true,
16339                        /*symbol is common=*/ false,
16340                        /*symbol version=*/ ver,
16341                        /*symbol_visibility=*/vis,
16342                        /*is_linux_string_cst=*/false);
16343   return result;
16344 }
16345
16346 /// Build a @ref var_decl out of a DW_TAG_variable DIE.
16347 ///
16348 /// @param ctxt the read context to use.
16349 ///
16350 /// @param die the DIE representing the variable we are looking at.
16351 ///
16352 /// @param where_offset the offset of the DIE where we are "logically"
16353 /// positionned at, in the DIE tree.  This is useful when @p die is
16354 /// e.g, DW_TAG_partial_unit that can be included in several places in
16355 /// the DIE tree.
16356 ///
16357 /// @param result if this is set to an existing var_decl, this means
16358 /// that the function will append the new properties it sees on @p die
16359 /// to that exising var_decl.  Otherwise, if this parameter is NULL, a
16360 /// new var_decl is going to be allocated and returned.
16361 ///
16362 /// @return a pointer to the newly created var_decl.  If the var_decl
16363 /// could not be built, this function returns NULL.
16364 static var_decl_sptr
16365 build_var_decl(read_context&    ctxt,
16366                Dwarf_Die        *die,
16367                size_t           where_offset,
16368                var_decl_sptr    result)
16369 {
16370   if (!die)
16371     return result;
16372
16373   int tag = dwarf_tag(die);
16374   ABG_ASSERT(tag == DW_TAG_variable || tag == DW_TAG_member);
16375
16376   if (!die_is_public_decl(die))
16377     return result;
16378
16379   die_source source;
16380   ABG_ASSERT(ctxt.get_die_source(die, source));
16381
16382   type_base_sptr type;
16383   Dwarf_Die type_die;
16384   if (die_die_attribute(die, DW_AT_type, type_die))
16385     {
16386       decl_base_sptr ty =
16387         is_decl(build_ir_node_from_die(ctxt, &type_die,
16388                                        /*called_from_public_decl=*/true,
16389                                        where_offset));
16390       if (!ty)
16391         return result;
16392       type = is_type(ty);
16393       ABG_ASSERT(type);
16394     }
16395
16396   if (!type)
16397     return result;
16398
16399   string name, linkage_name;
16400   location loc;
16401   die_loc_and_name(ctxt, die, loc, name, linkage_name);
16402
16403   if (!result)
16404     result.reset(new var_decl(name, type, loc, linkage_name));
16405   else
16406     {
16407       // We were called to append properties that might have been
16408       // missing from the first version of the variable.  And usually
16409       // that missing property is the mangled name.
16410       if (!linkage_name.empty())
16411         result->set_linkage_name(linkage_name);
16412     }
16413
16414   // Check if a variable symbol with this name is exported by the elf
16415   // binary.  If it is, then set the symbol of the variable, if it's
16416   // not set already.
16417   if (!result->get_symbol())
16418     {
16419       elf_symbol_sptr var_sym;
16420       if (get_ignore_symbol_table(ctxt))
16421         {
16422           string var_name =
16423             result->get_linkage_name().empty()
16424             ? result->get_name()
16425             : result->get_linkage_name();
16426
16427           var_sym = create_default_var_sym(var_name, ctxt.env());
16428           ABG_ASSERT(var_sym);
16429           add_symbol_to_map(var_sym, ctxt.var_syms());
16430         }
16431       else
16432         {
16433           Dwarf_Addr var_addr;
16434           if (ctxt.get_variable_address(die, var_addr))
16435             var_sym = var_sym = ctxt.variable_symbol_is_exported(var_addr);
16436         }
16437
16438       if (var_sym)
16439         {
16440           result->set_symbol(var_sym);
16441           // If the linkage name is not set or is wrong, set it to
16442           // the name of the underlying symbol.
16443           string linkage_name = result->get_linkage_name();
16444           if (linkage_name.empty()
16445               || !var_sym->get_alias_from_name(linkage_name))
16446             result->set_linkage_name(var_sym->get_name());
16447           result->set_is_in_public_symbol_table(true);
16448         }
16449     }
16450
16451   return result;
16452 }
16453
16454 /// Test if a given function denoted by its DIE and its scope is
16455 /// suppressed by any of the suppression specifications associated to
16456 /// a given context of ELF/DWARF reading.
16457 ///
16458 /// Note that a non-member function which symbol is not exported is
16459 /// also suppressed.
16460 ///
16461 /// @param ctxt the ELF/DWARF reading content of interest.
16462 ///
16463 /// @param scope of the scope of the function.
16464 ///
16465 /// @param function_die the DIE representing the function.
16466 ///
16467 /// @return true iff @p function_die is suppressed by at least one
16468 /// suppression specification attached to the @p ctxt.
16469 static bool
16470 function_is_suppressed(const read_context& ctxt,
16471                        const scope_decl* scope,
16472                        Dwarf_Die *function_die)
16473 {
16474   if (function_die == 0
16475       || dwarf_tag(function_die) != DW_TAG_subprogram)
16476     return false;
16477
16478   string fname = die_string_attribute(function_die, DW_AT_name);
16479   string flinkage_name = die_linkage_name(function_die);
16480   string qualified_name = build_qualified_name(scope, fname);
16481
16482   // A non-member function which symbol is not exported is suppressed.
16483   if (!is_class_type(scope) && !die_is_declaration_only(function_die))
16484     {
16485       Dwarf_Addr fn_addr;
16486       elf_symbol_sptr fn_sym;
16487       if (!ctxt.get_function_address(function_die, fn_addr))
16488         return true;
16489       if (!get_ignore_symbol_table(ctxt))
16490         {
16491           // We were not instructed to ignore (avoid loading) the
16492           // symbol table, so we can rely on its presence to see if
16493           // the address corresponds to the address of an exported
16494           // function symbol.
16495           if (!ctxt.function_symbol_is_exported(fn_addr))
16496             return true;
16497         }
16498     }
16499
16500   return suppr::function_is_suppressed(ctxt, qualified_name,
16501                                        flinkage_name,
16502                                        /*require_drop_property=*/true);
16503 }
16504
16505 /// Build a @ref function_decl out of a DW_TAG_subprogram DIE if the
16506 /// function denoted by the DIE is not suppressed by a suppression
16507 /// specification associated to the current read context.
16508 ///
16509 /// Note that if a member function declaration with the same signature
16510 /// (pretty representation) as one of the DIE we are looking at
16511 /// exists, this function returns that existing function declaration.
16512 ///
16513 /// @param ctxt the read context to use.
16514 ///
16515 /// @param scope the scope of the function we are looking at.
16516 ///
16517 /// @param fn_die the DIE representing the function we are looking at.
16518 ///
16519 /// @param where_offset the offset of the DIE where we are "logically"
16520 /// positionned at, in the DIE tree.  This is useful when @p die is
16521 /// e.g, DW_TAG_partial_unit that can be included in several places in
16522 /// the DIE tree.
16523 ///
16524 /// @param result if this is set to an existing function_decl, this
16525 /// means that the function will append the new properties it sees on
16526 /// @p fn_die to that exising function_decl.  Otherwise, if this
16527 /// parameter is NULL, a new function_decl is going to be allocated
16528 /// and returned.
16529 ///
16530 /// @return a pointer to the newly created var_decl.  If the var_decl
16531 /// could not be built, this function returns NULL.
16532 static function_decl_sptr
16533 build_or_get_fn_decl_if_not_suppressed(read_context&      ctxt,
16534                                        scope_decl         *scope,
16535                                        Dwarf_Die          *fn_die,
16536                                        size_t             where_offset,
16537                                        function_decl_sptr result)
16538 {
16539   function_decl_sptr fn;
16540   if (function_is_suppressed(ctxt, scope, fn_die))
16541     return fn;
16542
16543   if (!result)
16544     if ((fn = is_function_decl(ctxt.lookup_artifact_from_die(fn_die))))
16545       {
16546         fn = maybe_finish_function_decl_reading(ctxt, fn_die, where_offset, fn);
16547         ctxt.associate_die_to_decl(fn_die, fn, /*do_associate_by_repr=*/true);
16548         ctxt.associate_die_to_type(fn_die, fn->get_type(), where_offset);
16549         return fn;
16550       }
16551
16552   fn = build_function_decl(ctxt, fn_die, where_offset, result);
16553
16554   return fn;
16555 }
16556
16557 /// Test if a given variable denoted by its DIE and its scope is
16558 /// suppressed by any of the suppression specifications associated to
16559 /// a given context of ELF/DWARF reading.
16560 ///
16561 /// @param ctxt the ELF/DWARF reading content of interest.
16562 ///
16563 /// @param scope of the scope of the variable.
16564 ///
16565 /// @param variable_die the DIE representing the variable.
16566 ///
16567 /// @param is_required_decl_spec if true, means that the @p
16568 /// variable_die being considered is for a variable decl that is a
16569 /// specification for a concrete variable being built.
16570 ///
16571 /// @return true iff @p variable_die is suppressed by at least one
16572 /// suppression specification attached to the @p ctxt.
16573 static bool
16574 variable_is_suppressed(const read_context& ctxt,
16575                        const scope_decl* scope,
16576                        Dwarf_Die *variable_die,
16577                        bool is_required_decl_spec)
16578 {
16579   if (variable_die == 0
16580       || (dwarf_tag(variable_die) != DW_TAG_variable
16581           && dwarf_tag(variable_die) != DW_TAG_member))
16582     return false;
16583
16584   string name = die_string_attribute(variable_die, DW_AT_name);
16585   string linkage_name = die_linkage_name(variable_die);
16586   string qualified_name = build_qualified_name(scope, name);
16587
16588   // If a non member variable that is a declaration (has no exported
16589   // symbol), is not the specification of another concrete variable,
16590   // then it's suppressed.  This is a size optimization; it removes
16591   // useless declaration-only variables from the IR.
16592   //
16593   // Otherwise, if a non-member variable is the specification of
16594   // another concrete variable, then this function looks at
16595   // suppression specification specifications to know if its
16596   // suppressed.
16597   if (!is_class_type(scope) && !is_required_decl_spec)
16598     {
16599       Dwarf_Addr var_addr = 0;
16600       elf_symbol_sptr var_sym;
16601       if (!ctxt.get_variable_address(variable_die, var_addr))
16602         return true;
16603       if (!get_ignore_symbol_table(ctxt))
16604         {
16605           // We were not instructed to ignore (avoid loading) the
16606           // symbol table, so we can rely on its presence to see if
16607           // the address corresponds to the address of an exported
16608           // variable symbol.
16609           if (!ctxt.variable_symbol_is_exported(var_addr))
16610             return true;
16611         }
16612     }
16613
16614   return suppr::variable_is_suppressed(ctxt, qualified_name,
16615                                        linkage_name,
16616                                        /*require_drop_property=*/true);
16617 }
16618
16619 /// Test if a type (designated by a given DIE) in a given scope is
16620 /// suppressed by the suppression specifications that are associated
16621 /// to a given read context.
16622 ///
16623 /// @param ctxt the read context to consider.
16624 ///
16625 /// @param scope of the scope of the type DIE to consider.
16626 ///
16627 /// @param type_die the DIE that designates the type to consider.
16628 ///
16629 /// @param type_is_private out parameter.  If this function returns
16630 /// true (the type @p type_die is suppressed) and if the type was
16631 /// suppressed because it's private then this parameter is set to
16632 /// true.
16633 ///
16634 /// @return true iff the type designated by the DIE @p type_die, in
16635 /// the scope @p scope is suppressed by at the suppression
16636 /// specifications associated to the current read context.
16637 static bool
16638 type_is_suppressed(const read_context& ctxt,
16639                    const scope_decl* scope,
16640                    Dwarf_Die *type_die,
16641                    bool &type_is_private)
16642 {
16643   if (type_die == 0
16644       || (dwarf_tag(type_die) != DW_TAG_enumeration_type
16645           && dwarf_tag(type_die) != DW_TAG_class_type
16646           && dwarf_tag(type_die) != DW_TAG_structure_type
16647           && dwarf_tag(type_die) != DW_TAG_union_type))
16648     return false;
16649
16650   string type_name, linkage_name;
16651   location type_location;
16652   die_loc_and_name(ctxt, type_die, type_location, type_name, linkage_name);
16653   string qualified_name = build_qualified_name(scope, type_name);
16654
16655   return suppr::type_is_suppressed(ctxt, qualified_name,
16656                                    type_location,
16657                                    type_is_private,
16658                                    /*require_drop_property=*/true);
16659 }
16660
16661 /// Test if a type (designated by a given DIE) in a given scope is
16662 /// suppressed by the suppression specifications that are associated
16663 /// to a given read context.
16664 ///
16665 /// @param ctxt the read context to consider.
16666 ///
16667 /// @param scope of the scope of the type DIE to consider.
16668 ///
16669 /// @param type_die the DIE that designates the type to consider.
16670 ///
16671 /// @return true iff the type designated by the DIE @p type_die, in
16672 /// the scope @p scope is suppressed by at the suppression
16673 /// specifications associated to the current read context.
16674 static bool
16675 type_is_suppressed(const read_context& ctxt,
16676                    const scope_decl* scope,
16677                    Dwarf_Die *type_die)
16678 {
16679   bool type_is_private = false;
16680   return type_is_suppressed(ctxt, scope, type_die, type_is_private);
16681 }
16682
16683 /// Get the opaque version of a type that was suppressed because it's
16684 /// a private type.
16685 ///
16686 /// The opaque version version of the type is just a declared-only
16687 /// version of the type (class or union type) denoted by @p type_die.
16688 ///
16689 /// @param ctxt the read context in use.
16690 ///
16691 /// @param scope the scope of the type die we are looking at.
16692 ///
16693 /// @param type_die the type DIE we are looking at.
16694 ///
16695 /// @param where_offset the offset of the DIE where we are "logically"
16696 /// positionned at, in the DIE tree.  This is useful when @p die is
16697 /// e.g, DW_TAG_partial_unit that can be included in several places in
16698 /// the DIE tree.
16699 ///
16700 /// @return the opaque version of the type denoted by @p type_die or
16701 /// nil if no opaque version was found.
16702 static class_or_union_sptr
16703 get_opaque_version_of_type(read_context &ctxt,
16704                            scope_decl           *scope,
16705                            Dwarf_Die            *type_die,
16706                            size_t               where_offset)
16707 {
16708   class_or_union_sptr result;
16709
16710   if (type_die == 0)
16711     return result;
16712
16713   unsigned tag = dwarf_tag(type_die);
16714   if (tag != DW_TAG_class_type
16715       && tag != DW_TAG_structure_type
16716       && tag != DW_TAG_union_type)
16717     return result;
16718
16719   string type_name, linkage_name;
16720   location type_location;
16721   die_loc_and_name(ctxt, type_die, type_location, type_name, linkage_name);
16722   if (!type_location)
16723     return result;
16724
16725   string qualified_name = build_qualified_name(scope, type_name);
16726
16727   // TODO: also handle declaration-only unions.  To do that, we mostly
16728   // need to adapt add_or_update_union_type to make it schedule
16729   // declaration-only unions for resolution too.
16730   string_classes_map::const_iterator i =
16731     ctxt.declaration_only_classes().find(qualified_name);
16732   if (i != ctxt.declaration_only_classes().end())
16733     result = i->second.back();
16734
16735   if (!result)
16736     {
16737       if (tag == DW_TAG_class_type || tag == DW_TAG_structure_type)
16738         {
16739           // So we didn't find any pre-existing forward-declared-only
16740           // class for the class definition that we could return as an
16741           // opaque type.  So let's build one.
16742           //
16743           // TODO: we need to be able to do this for unions too!
16744           class_decl_sptr klass(new class_decl(ctxt.env(), type_name,
16745                                                /*alignment=*/0, /*size=*/0,
16746                                                tag == DW_TAG_structure_type,
16747                                                type_location,
16748                                                decl_base::VISIBILITY_DEFAULT));
16749           klass->set_is_declaration_only(true);
16750           add_decl_to_scope(klass, scope);
16751           ctxt.associate_die_to_type(type_die, klass, where_offset);
16752           ctxt.maybe_schedule_declaration_only_class_for_resolution(klass);
16753           result = klass;
16754         }
16755     }
16756
16757   return result;
16758 }
16759
16760 /// Create a function symbol with a given name.
16761 ///
16762 /// @param sym_name the name of the symbol to create.
16763 ///
16764 /// @param env the environment to create the symbol in.
16765 ///
16766 /// @return the newly created symbol.
16767 elf_symbol_sptr
16768 create_default_fn_sym(const string& sym_name, const environment *env)
16769 {
16770   elf_symbol::version ver;
16771   elf_symbol_sptr result =
16772     elf_symbol::create(env,
16773                        /*symbol index=*/ 0,
16774                        /*symbol size=*/ 0,
16775                        sym_name,
16776                        /*symbol type=*/ elf_symbol::FUNC_TYPE,
16777                        /*symbol binding=*/ elf_symbol::GLOBAL_BINDING,
16778                        /*symbol is defined=*/ true,
16779                        /*symbol is common=*/ false,
16780                        /*symbol version=*/ ver,
16781                        /*symbol visibility=*/elf_symbol::DEFAULT_VISIBILITY,
16782                        /*symbol is linux string cst=*/false);
16783   return result;
16784 }
16785
16786 /// Build a @ref function_decl our of a DW_TAG_subprogram DIE.
16787 ///
16788 /// @param ctxt the read context to use
16789 ///
16790 /// @param die the DW_TAG_subprogram DIE to read from.
16791 ///
16792 /// @param where_offset the offset of the DIE where we are "logically"
16793 /// positionned at, in the DIE tree.  This is useful when @p die is
16794 /// e.g, DW_TAG_partial_unit that can be included in several places in
16795 /// the DIE tree.
16796 ///
16797 /// @param called_for_public_decl this is set to true if the function
16798 /// was called for a public (function) decl.
16799 static function_decl_sptr
16800 build_function_decl(read_context&       ctxt,
16801                     Dwarf_Die*          die,
16802                     size_t              where_offset,
16803                     function_decl_sptr  fn)
16804 {
16805   function_decl_sptr result = fn;
16806   if (!die)
16807     return result;
16808   ABG_ASSERT(dwarf_tag(die) == DW_TAG_subprogram);
16809
16810   die_source source;
16811   ABG_ASSERT(ctxt.get_die_source(die, source));
16812
16813   if (!die_is_public_decl(die))
16814     return result;
16815
16816   translation_unit_sptr tu = ctxt.cur_transl_unit();
16817   ABG_ASSERT(tu);
16818
16819   string fname, flinkage_name;
16820   location floc;
16821   die_loc_and_name(ctxt, die, floc, fname, flinkage_name);
16822
16823   size_t is_inline = die_is_declared_inline(die);
16824   class_or_union_sptr is_method =
16825     is_class_or_union_type(get_scope_for_die(ctxt, die, true, where_offset));
16826
16827   if (result)
16828     {
16829       // Add the properties that might have been missing from the
16830       // first declaration of the function.  For now, it usually is
16831       // the mangled name that goes missing in the first declarations.
16832       //
16833       // Also note that if 'fn' has just been cloned, the current
16834       // linkage name (of the current DIE) might be different from the
16835       // linkage name of 'fn'.  In that case, update the linkage name
16836       // of 'fn' too.
16837       if (!flinkage_name.empty()
16838           && result->get_linkage_name() != flinkage_name)
16839         result->set_linkage_name(flinkage_name);
16840       if (floc)
16841         if (!result->get_location())
16842           result->set_location(floc);
16843     }
16844   else
16845     {
16846       function_type_sptr fn_type(build_function_type(ctxt, die, is_method,
16847                                                      where_offset));
16848       if (!fn_type)
16849         return result;
16850
16851       result.reset(is_method
16852                    ? new method_decl(fname, fn_type,
16853                                      is_inline, floc,
16854                                      flinkage_name)
16855                    : new function_decl(fname, fn_type,
16856                                        is_inline, floc,
16857                                        flinkage_name));
16858     }
16859
16860   // Set the symbol of the function.  If the linkage name is not set
16861   // or is wrong, set it to the name of the underlying symbol.
16862   if (!result->get_symbol())
16863     {
16864       elf_symbol_sptr fn_sym;
16865       if (get_ignore_symbol_table(ctxt))
16866         {
16867           string fn_name =
16868             result->get_linkage_name().empty()
16869             ? result->get_name()
16870             : result->get_linkage_name();
16871
16872           fn_sym = create_default_fn_sym(fn_name, ctxt.env());
16873           ABG_ASSERT(fn_sym);
16874           add_symbol_to_map(fn_sym, ctxt.fun_syms());
16875         }
16876       else
16877         {
16878           Dwarf_Addr fn_addr;
16879           if (ctxt.get_function_address(die, fn_addr))
16880             fn_sym = ctxt.function_symbol_is_exported(fn_addr);
16881         }
16882
16883       if (fn_sym)
16884         {
16885           result->set_symbol(fn_sym);
16886           string linkage_name = result->get_linkage_name();
16887           if (linkage_name.empty()
16888               || !fn_sym->get_alias_from_name(linkage_name))
16889             result->set_linkage_name(fn_sym->get_name());
16890           result->set_is_in_public_symbol_table(true);
16891         }
16892     }
16893
16894   ctxt.associate_die_to_type(die, result->get_type(), where_offset);
16895
16896   size_t die_offset = dwarf_dieoffset(die);
16897
16898   if (fn
16899       && is_member_function(fn)
16900       && get_member_function_is_virtual(fn)
16901       && !result->get_linkage_name().empty())
16902     // This function is a virtual member function which has its
16903     // linkage name *and* and has its underlying symbol correctly set.
16904     // It thus doesn't need any fixup related to elf symbol.  So
16905     // remove it from the set of virtual member functions with linkage
16906     // names and no elf symbol that need to be fixed up.
16907     ctxt.die_function_decl_with_no_symbol_map().erase(die_offset);
16908   return result;
16909 }
16910
16911 /// Add a set of addresses (representing function symbols) to a
16912 /// function symbol name -> symbol map.
16913 ///
16914 /// For a given symbol address, the function retrieves the name of the
16915 /// symbol as well as the symbol itself and inserts an entry {symbol
16916 /// name, symbol} into a map of symbol name -> symbol map.
16917 ///
16918 /// @param syms the set of symbol addresses to consider.
16919 ///
16920 /// @param map the map to populate.
16921 ///
16922 /// @param ctxt the context in which we are loading a given ELF file.
16923 static void
16924 add_fn_symbols_to_map(address_set_type& syms,
16925                       string_elf_symbols_map_type& map,
16926                       read_context& ctxt)
16927 {
16928   for (address_set_type::iterator i = syms.begin(); i != syms.end(); ++i)
16929     {
16930       elf_symbol_sptr sym = ctxt.lookup_elf_fn_symbol_from_address(*i);
16931       ABG_ASSERT(sym);
16932       string_elf_symbols_map_type::iterator it =
16933         ctxt.fun_syms().find(sym->get_name());
16934       ABG_ASSERT(it != ctxt.fun_syms().end());
16935       map.insert(*it);
16936     }
16937 }
16938
16939 /// Add a symbol to a symbol map.
16940 ///
16941 /// @param sym the symbol to add.
16942 ///
16943 /// @param map the symbol map to add the symbol into.
16944 static void
16945 add_symbol_to_map(const elf_symbol_sptr& sym,
16946                   string_elf_symbols_map_type& map)
16947 {
16948   if (!sym)
16949     return;
16950
16951   string_elf_symbols_map_type::iterator it = map.find(sym->get_name());
16952   if (it == map.end())
16953     {
16954       elf_symbols syms;
16955       syms.push_back(sym);
16956       map[sym->get_name()] = syms;
16957     }
16958   else
16959     it->second.push_back(sym);
16960 }
16961
16962 /// Add a set of addresses (representing variable symbols) to a
16963 /// variable symbol name -> symbol map.
16964 ///
16965 /// For a given symbol address, the variable retrieves the name of the
16966 /// symbol as well as the symbol itself and inserts an entry {symbol
16967 /// name, symbol} into a map of symbol name -> symbol map.
16968 ///
16969 /// @param syms the set of symbol addresses to consider.
16970 ///
16971 /// @param map the map to populate.
16972 ///
16973 /// @param ctxt the context in which we are loading a given ELF file.
16974 static void
16975 add_var_symbols_to_map(address_set_type& syms,
16976                        string_elf_symbols_map_type& map,
16977                        read_context& ctxt)
16978 {
16979   for (address_set_type::iterator i = syms.begin(); i != syms.end(); ++i)
16980     {
16981       elf_symbol_sptr sym = ctxt.lookup_elf_var_symbol_from_address(*i);
16982       ABG_ASSERT(sym);
16983       string_elf_symbols_map_type::iterator it =
16984         ctxt.var_syms().find(sym->get_name());
16985       ABG_ASSERT(it != ctxt.var_syms().end());
16986       map.insert(*it);
16987     }
16988 }
16989
16990 /// Read all @ref abigail::translation_unit possible from the debug info
16991 /// accessible through a DWARF Front End Library handle, and stuff
16992 /// them into a libabigail ABI Corpus.
16993 ///
16994 /// @param ctxt the read context.
16995 ///
16996 /// @return a pointer to the resulting corpus, or NULL if the corpus
16997 /// could not be constructed.
16998 static corpus_sptr
16999 read_debug_info_into_corpus(read_context& ctxt)
17000 {
17001   ctxt.clear_per_corpus_data();
17002
17003   if (!ctxt.current_corpus())
17004     {
17005       corpus_sptr corp (new corpus(ctxt.env(), ctxt.elf_path()));
17006       ctxt.current_corpus(corp);
17007       if (!ctxt.env())
17008         ctxt.env(corp->get_environment());
17009     }
17010
17011   // First set some mundane properties of the corpus gathered from
17012   // ELF.
17013   ctxt.current_corpus()->set_path(ctxt.elf_path());
17014   if (ctxt.is_linux_kernel_binary())
17015     ctxt.current_corpus()->set_origin(corpus::LINUX_KERNEL_BINARY_ORIGIN);
17016   else
17017     ctxt.current_corpus()->set_origin(corpus::DWARF_ORIGIN);
17018   ctxt.current_corpus()->set_soname(ctxt.dt_soname());
17019   ctxt.current_corpus()->set_needed(ctxt.dt_needed());
17020   ctxt.current_corpus()->set_architecture_name(ctxt.elf_architecture());
17021   if (corpus_group_sptr group = ctxt.current_corpus_group())
17022     group->add_corpus(ctxt.current_corpus());
17023
17024   // Set symbols information to the corpus.
17025   if (!get_ignore_symbol_table(ctxt))
17026     {
17027       if (ctxt.load_in_linux_kernel_mode() && ctxt.is_linux_kernel_binary())
17028         {
17029           string_elf_symbols_map_sptr exported_fn_symbols_map
17030             (new string_elf_symbols_map_type);
17031           add_fn_symbols_to_map(*ctxt.linux_exported_fn_syms(),
17032                                 *exported_fn_symbols_map,
17033                                 ctxt);
17034           add_fn_symbols_to_map(*ctxt.linux_exported_gpl_fn_syms(),
17035                                 *exported_fn_symbols_map,
17036                                 ctxt);
17037           ctxt.current_corpus()->set_fun_symbol_map(exported_fn_symbols_map);
17038
17039           string_elf_symbols_map_sptr exported_var_symbols_map
17040             (new string_elf_symbols_map_type);
17041           add_var_symbols_to_map(*ctxt.linux_exported_var_syms(),
17042                                  *exported_var_symbols_map,
17043                                  ctxt);
17044           add_var_symbols_to_map(*ctxt.linux_exported_gpl_var_syms(),
17045                                  *exported_var_symbols_map,
17046                                  ctxt);
17047           ctxt.current_corpus()->set_var_symbol_map(exported_var_symbols_map);
17048         }
17049       else
17050         {
17051           ctxt.current_corpus()->set_fun_symbol_map(ctxt.fun_syms_sptr());
17052           ctxt.current_corpus()->set_var_symbol_map(ctxt.var_syms_sptr());
17053         }
17054
17055       ctxt.current_corpus()->set_undefined_fun_symbol_map
17056         (ctxt.undefined_fun_syms_sptr());
17057       ctxt.current_corpus()->set_undefined_var_symbol_map
17058         (ctxt.undefined_var_syms_sptr());
17059     }
17060   else
17061     {
17062       ctxt.current_corpus()->set_fun_symbol_map(ctxt.fun_syms_sptr());
17063       ctxt.current_corpus()->set_var_symbol_map(ctxt.var_syms_sptr());
17064     }
17065
17066   // Get out now if no debug info is found.
17067   if (!ctxt.dwarf())
17068     return ctxt.current_corpus();
17069
17070   uint8_t address_size = 0;
17071   size_t header_size = 0;
17072
17073   // Set the set of exported declaration that are defined.
17074   ctxt.exported_decls_builder
17075     (ctxt.current_corpus()->get_exported_decls_builder().get());
17076
17077   // Walk all the DIEs of the debug info to build a DIE -> parent map
17078   // useful for get_die_parent() to work.
17079   {
17080     tools_utils::timer t;
17081     if (ctxt.do_log())
17082       {
17083         cerr << "building die -> parent maps ...";
17084         t.start();
17085       }
17086
17087     ctxt.build_die_parent_maps();
17088
17089     if (ctxt.do_log())
17090       {
17091         t.stop();
17092         cerr << " DONE@" << ctxt.current_corpus()->get_path()
17093              << ":"
17094              << t
17095              << "\n";
17096       }
17097   }
17098
17099   ctxt.env()->canonicalization_is_done(false);
17100
17101   {
17102     tools_utils::timer t;
17103     if (ctxt.do_log())
17104       {
17105         cerr << "building the libabigail internal representation ...";
17106         t.start();
17107       }
17108     // And now walk all the DIEs again to build the libabigail IR.
17109     Dwarf_Half dwarf_version = 0;
17110     for (Dwarf_Off offset = 0, next_offset = 0;
17111          (dwarf_next_unit(ctxt.dwarf(), offset, &next_offset, &header_size,
17112                           &dwarf_version, NULL, &address_size, NULL,
17113                           NULL, NULL) == 0);
17114          offset = next_offset)
17115       {
17116         Dwarf_Off die_offset = offset + header_size;
17117         Dwarf_Die unit;
17118         if (!dwarf_offdie(ctxt.dwarf(), die_offset, &unit)
17119             || dwarf_tag(&unit) != DW_TAG_compile_unit)
17120           continue;
17121
17122         ctxt.dwarf_version(dwarf_version);
17123
17124         address_size *= 8;
17125
17126         // Build a translation_unit IR node from cu; note that cu must
17127         // be a DW_TAG_compile_unit die.
17128         translation_unit_sptr ir_node =
17129           build_translation_unit_and_add_to_ir(ctxt, &unit, address_size);
17130         ABG_ASSERT(ir_node);
17131       }
17132     if (ctxt.do_log())
17133       {
17134         t.stop();
17135         cerr << " DONE@" << ctxt.current_corpus()->get_path()
17136              << ":"
17137              << t
17138              << "\n";
17139       }
17140   }
17141
17142   {
17143     tools_utils::timer t;
17144     if (ctxt.do_log())
17145       {
17146         cerr << "resolving declaration only classes ...";
17147         t.start();
17148       }
17149     ctxt.resolve_declaration_only_classes();
17150     if (ctxt.do_log())
17151       {
17152         t.stop();
17153         cerr << " DONE@" << ctxt.current_corpus()->get_path()
17154              << ":"
17155              << t
17156              <<"\n";
17157       }
17158   }
17159
17160   {
17161     tools_utils::timer t;
17162     if (ctxt.do_log())
17163       {
17164         cerr << "fixing up functions with linkage name but "
17165              << "no advertised underlying symbols ....";
17166         t.start();
17167       }
17168     ctxt.fixup_functions_with_no_symbols();
17169     if (ctxt.do_log())
17170       {
17171         t.stop();
17172         cerr << " DONE@" << ctxt.current_corpus()->get_path()
17173              <<":"
17174              << t
17175              <<"\n";
17176       }
17177   }
17178
17179   /// Now, look at the types that needs to be canonicalized after the
17180   /// translation has been constructed (which is just now) and
17181   /// canonicalize them.
17182   ///
17183   /// These types need to be constructed at the end of the translation
17184   /// unit reading phase because some types are modified by some DIEs
17185   /// even after the principal DIE describing the type has been read;
17186   /// this happens for clones of virtual destructors (for instance) or
17187   /// even for some static data members.  We need to do that for types
17188   /// are in the alternate debug info section and for types that in
17189   /// the main debug info section.
17190   {
17191     tools_utils::timer t;
17192     if (ctxt.do_log())
17193       {
17194         cerr << "perform late type canonicalizing ...\n";
17195         t.start();
17196       }
17197
17198     ctxt.perform_late_type_canonicalizing();
17199     if (ctxt.do_log())
17200       {
17201         t.stop();
17202         cerr << "late type canonicalizing DONE@"
17203              << ctxt.current_corpus()->get_path()
17204              << ":"
17205              << t
17206              << "\n";
17207       }
17208   }
17209
17210   ctxt.env()->canonicalization_is_done(true);
17211
17212   {
17213     tools_utils::timer t;
17214     if (ctxt.do_log())
17215       {
17216         cerr << "sort functions and variables ...";
17217         t.start();
17218       }
17219     ctxt.current_corpus()->sort_functions();
17220     ctxt.current_corpus()->sort_variables();
17221     if (ctxt.do_log())
17222       {
17223         t.stop();
17224         cerr << " DONE@" << ctxt.current_corpus()->get_path()
17225              << ":"
17226              << t
17227              <<" \n";
17228       }
17229   }
17230
17231   return ctxt.current_corpus();
17232 }
17233
17234 /// Canonicalize a type if it's suitable for early canonicalizing, or,
17235 /// if it's not, schedule it for late canonicalization, after the
17236 /// debug info of the current translation unit has been fully read.
17237 ///
17238 /// A (composite) type is deemed suitable for early canonicalizing iff
17239 /// all of its sub-types are canonicalized themselve.  Non composite
17240 /// types are always deemed suitable for early canonicalization.
17241 ///
17242 /// Note that this function doesn't work on *ANONYMOUS* classes,
17243 /// structs, unions or enums because it first does some
17244 /// canonicalization of the DWARF DIE @p die.  That canonicalization
17245 /// is done by looking up @p die by name; and because these are
17246 /// anonymous types, they don't have names! and so that
17247 /// canonicalization fails.  So the type artifact associated to @p
17248 /// die often ends being *NOT* canonicalized.  This later leads to
17249 /// extreme slowness of operation, especially when comparisons are
17250 /// later performed on these anonymous types.
17251 ///
17252 /// So when you have classes, structs, unions, or enums that can be
17253 /// anonymous, please use this overload instead:
17254 ///
17255 ///     void
17256 ///     maybe_canonicalize_type(const Dwarf_Die*        die,
17257 ///                             const type_base_sptr&   t,
17258 ///                             read_context&           ctxt);
17259 ///
17260 /// It knows how to deal with anonymous types.
17261 ///
17262 /// @p looks up the type artifact
17263 /// associated to @p die.  During that lookup, ; but then those types don't have
17264 /// names because they are anonymous.
17265 ///
17266 /// @param die the type DIE to consider for canonicalization.  Note
17267 /// that this DIE must have been associated with its type using the
17268 /// function read_context::associate_die_to_type() prior to calling
17269 /// this function.
17270 ///
17271 /// @param ctxt the @ref read_context to use.
17272 static void
17273 maybe_canonicalize_type(const Dwarf_Die *die, read_context& ctxt)
17274 {
17275   die_source source;
17276   ABG_ASSERT(ctxt.get_die_source(die, source));
17277
17278   size_t die_offset = dwarf_dieoffset(const_cast<Dwarf_Die*>(die));
17279   type_base_sptr t = ctxt.lookup_type_from_die(die);
17280
17281   if (!t)
17282     return;
17283
17284   type_base_sptr peeled_type =
17285     peel_typedef_pointer_or_reference_type(t, /*peel_qual_types=*/false);
17286   if (is_class_type(peeled_type)
17287       || is_union_type(peeled_type)
17288       || is_function_type(peeled_type)
17289       || is_array_type(peeled_type)
17290       || is_qualified_type(peeled_type))
17291     // We delay canonicalization of classes/unions or typedef,
17292     // pointers, references and array to classes/unions.  This is
17293     // because the (underlying) class might not be finished yet and we
17294     // might not be able to able detect it here (thinking about
17295     // classes that are work-in-progress, or classes that might be
17296     // later amended by some DWARF construct).  So we err on the safe
17297     // side.  We also delay canonicalization for array and qualified
17298     // types because they can be edited (in particular by
17299     // maybe_strip_qualification) after they are initially built.
17300     ctxt.schedule_type_for_late_canonicalization(die);
17301   else if ((is_function_type(t)
17302             && ctxt.is_wip_function_type_die_offset(die_offset, source))
17303            || type_has_non_canonicalized_subtype(t))
17304     ctxt.schedule_type_for_late_canonicalization(die);
17305   else
17306     canonicalize(t);
17307 }
17308
17309 /// Canonicalize a type if it's suitable for early canonicalizing, or,
17310 /// if it's not, schedule it for late canonicalization, after the
17311 /// debug info of the current translation unit has been fully read.
17312 ///
17313 /// A (composite) type is deemed suitable for early canonicalizing iff
17314 /// all of its sub-types are canonicalized themselve.  Non composite
17315 /// types are always deemed suitable for early canonicalization.
17316 ///
17317 /// Note that this function nows how to deal with anonymous classes,
17318 /// structs and enums, unlike the overload below:
17319 ///
17320 ///     void maybe_canonicalize_type(const Dwarf_Die *die, read_context& ctxt)
17321 ///
17322 /// The problem, though is that this function is much slower that that
17323 /// overload above because of how the types that are meant for later
17324 /// canonicalization are stored.  So the idea is that this function
17325 /// should be used only for the smallest possible subset of types that
17326 /// are anonymous and thus cannot be handled by the overload above.
17327 ///
17328 /// @param t the type DIE to consider for canonicalization.
17329 ///
17330 /// @param ctxt the @ref read_context to use.
17331 static void
17332 maybe_canonicalize_type(const type_base_sptr& t,
17333                         read_context&   ctxt)
17334 {
17335   if (!t)
17336     return;
17337
17338   type_base_sptr peeled_type =
17339     peel_typedef_pointer_or_reference_type(t, /*peel_qual_types=*/false);
17340   if (is_class_type(peeled_type)
17341       || is_union_type(peeled_type)
17342       || is_function_type(peeled_type)
17343       || is_array_type(peeled_type)
17344       || is_qualified_type(peeled_type))
17345     // We delay canonicalization of classes/unions or typedef,
17346     // pointers, references and array to classes/unions.  This is
17347     // because the (underlying) class might not be finished yet and we
17348     // might not be able to able detect it here (thinking about
17349     // classes that are work-in-progress, or classes that might be
17350     // later amended by some DWARF construct).  So we err on the safe
17351     // side.  We also delay canonicalization for array and qualified
17352     // types because they can be edited (in particular by
17353     // maybe_strip_qualification) after they are initially built.
17354     ctxt.schedule_type_for_late_canonicalization(t);
17355   else if (type_has_non_canonicalized_subtype(t))
17356     ctxt.schedule_type_for_late_canonicalization(t);
17357   else
17358     canonicalize(t);
17359 }
17360
17361 /// Canonicalize a type if it's suitable for early canonicalizing, or,
17362 /// if it's not, schedule it for late canonicalization, after the
17363 /// debug info of the current translation unit has been fully read.
17364 ///
17365 /// A (composite) type is deemed suitable for early canonicalizing iff
17366 /// all of its sub-types are canonicalized themselve.  Non composite
17367 /// types are always deemed suitable for early canonicalization.
17368 ///
17369 /// Note that this function knows how to properly use either one of
17370 /// the following two overloads:
17371 ///
17372 ///     1/
17373 ///     void maybe_canonicalize_type(const Dwarf_Die*   die,
17374 ///                                  const type_base_sptr&      t,
17375 ///                                  read_context&              ctxt);
17376 ///
17377 ///     2/
17378 ///     void maybe_canonicalize_type(const Dwarf_Die *die, read_context& ctxt);
17379 ///
17380 /// So this function uses 1/ for most types and uses uses 2/ function
17381 /// types.  Using 2/ is slower and bigger than using 1/, but then 1/
17382 /// deals poorly with anonymous types because of how poorly DIEs
17383 /// canonicalization works on anonymous types.  That's why this
17384 /// function uses 2/ only for the types that really need it.
17385 ///
17386 /// @param die the DIE of the type denoted by @p t.
17387 ///
17388 /// @param t the type to consider.  Its DIE is @p die.
17389 ///
17390 /// @param ctxt the read context in use.
17391 static void
17392 maybe_canonicalize_type(const Dwarf_Die *die,
17393                         const type_base_sptr&   t,
17394                         read_context&           ctxt)
17395 {
17396   if (const function_type_sptr ft = is_function_type(t))
17397     {
17398       maybe_canonicalize_type(ft, ctxt);
17399       return;
17400     }
17401
17402   maybe_canonicalize_type(die, ctxt);
17403 }
17404
17405 /// If a given decl is a member type declaration, set its access
17406 /// specifier from the DIE that represents it.
17407 ///
17408 /// @param member_type_declaration the member type declaration to
17409 /// consider.
17410 static void
17411 maybe_set_member_type_access_specifier(decl_base_sptr member_type_declaration,
17412                                        Dwarf_Die* die)
17413 {
17414   if (is_type(member_type_declaration)
17415       && is_member_decl(member_type_declaration))
17416     {
17417       class_or_union* scope =
17418         is_class_or_union_type(member_type_declaration->get_scope());
17419       ABG_ASSERT(scope);
17420
17421       access_specifier access = private_access;
17422       if (class_decl* cl = is_class_type(scope))
17423         if (cl->is_struct())
17424           access = public_access;
17425
17426       die_access_specifier(die, access);
17427       set_member_access_specifier(member_type_declaration, access);
17428     }
17429 }
17430
17431 /// Build an IR node from a given DIE and add the node to the current
17432 /// IR being build and held in the read_context.  Doing that is called
17433 /// "emitting an IR node for the DIE".
17434 ///
17435 /// @param ctxt the read context.
17436 ///
17437 /// @param die the DIE to consider.
17438 ///
17439 /// @param scope the scope under which the resulting IR node has to be
17440 /// added.
17441 ///
17442 /// @param called_from_public_decl set to yes if this function is
17443 /// called from the functions used to build a public decl (functions
17444 /// and variables).  In that case, this function accepts building IR
17445 /// nodes representing types.  Otherwise, this function only creates
17446 /// IR nodes representing public decls (functions and variables).
17447 /// This is done to avoid emitting IR nodes for types that are not
17448 /// referenced by public functions or variables.
17449 ///
17450 /// @param where_offset the offset of the DIE where we are "logically"
17451 /// positionned at, in the DIE tree.  This is useful when @p die is
17452 /// e.g, DW_TAG_partial_unit that can be included in several places in
17453 /// the DIE tree.
17454 ///
17455 /// @param is_required_decl_spec if true, it means the ir node to
17456 /// build is for a decl that is a specification for another decl that
17457 /// is concrete.  If you don't know what this is, set it to false.
17458 ///
17459 /// @return the resulting IR node.
17460 static type_or_decl_base_sptr
17461 build_ir_node_from_die(read_context&    ctxt,
17462                        Dwarf_Die*       die,
17463                        scope_decl*      scope,
17464                        bool             called_from_public_decl,
17465                        size_t           where_offset,
17466                        bool             is_required_decl_spec)
17467 {
17468   type_or_decl_base_sptr result;
17469
17470   if (!die || !scope)
17471     return result;
17472
17473   int tag = dwarf_tag(die);
17474
17475   if (!called_from_public_decl)
17476     {
17477       if (ctxt.load_all_types() && die_is_type(die))
17478         /* We were instructed to load debug info for all types,
17479            included those that are not reachable from a public
17480            declaration.  So load the debug info for this type.  */;
17481       else if (tag != DW_TAG_subprogram
17482                && tag != DW_TAG_variable
17483                && tag != DW_TAG_member
17484                && tag != DW_TAG_namespace)
17485         return result;
17486     }
17487
17488   die_source source_of_die;
17489   ABG_ASSERT(ctxt.get_die_source(die, source_of_die));
17490
17491   if ((result = ctxt.lookup_decl_from_die_offset(dwarf_dieoffset(die),
17492                                                  source_of_die)))
17493     return result;
17494
17495   switch (tag)
17496     {
17497       // Type DIEs we support.
17498     case DW_TAG_base_type:
17499       if (type_decl_sptr t = build_type_decl(ctxt, die, where_offset))
17500         {
17501           result =
17502             add_decl_to_scope(t, ctxt.cur_transl_unit()->get_global_scope());
17503           canonicalize(t);
17504         }
17505       break;
17506
17507     case DW_TAG_typedef:
17508       {
17509         typedef_decl_sptr t = build_typedef_type(ctxt, die,
17510                                                  called_from_public_decl,
17511                                                  where_offset);
17512         result = add_decl_to_scope(t, scope);
17513         if (result)
17514           {
17515             maybe_set_member_type_access_specifier(is_decl(result), die);
17516             maybe_canonicalize_type(die, ctxt);
17517           }
17518       }
17519       break;
17520
17521     case DW_TAG_pointer_type:
17522       {
17523         pointer_type_def_sptr p =
17524           build_pointer_type_def(ctxt, die,
17525                                  called_from_public_decl,
17526                                  where_offset);
17527         if (p)
17528           {
17529             result =
17530               add_decl_to_scope(p, ctxt.cur_transl_unit()->get_global_scope());
17531             ABG_ASSERT(result->get_translation_unit());
17532             maybe_canonicalize_type(die, ctxt);
17533           }
17534       }
17535       break;
17536
17537     case DW_TAG_reference_type:
17538     case DW_TAG_rvalue_reference_type:
17539       {
17540         reference_type_def_sptr r =
17541           build_reference_type(ctxt, die,
17542                                called_from_public_decl,
17543                                where_offset);
17544         if (r)
17545           {
17546             result =
17547               add_decl_to_scope(r, ctxt.cur_transl_unit()->get_global_scope());
17548
17549             ctxt.associate_die_to_type(die, r, where_offset);
17550             maybe_canonicalize_type(die, ctxt);
17551           }
17552       }
17553       break;
17554
17555     case DW_TAG_const_type:
17556     case DW_TAG_volatile_type:
17557     case DW_TAG_restrict_type:
17558       {
17559         type_base_sptr q =
17560           build_qualified_type(ctxt, die,
17561                                called_from_public_decl,
17562                                where_offset);
17563         if (q)
17564           {
17565             // Strip some potentially redundant type qualifiers from
17566             // the qualified type we just built.
17567             decl_base_sptr d = maybe_strip_qualification(is_qualified_type(q),
17568                                                          ctxt);
17569             if (!d)
17570               d = get_type_declaration(q);
17571             ABG_ASSERT(d);
17572             type_base_sptr ty = is_type(d);
17573             // Associate the die to type ty again because 'ty'might be
17574             // different from 'q', because 'ty' is 'q' possibly
17575             // stripped from some redundant type qualifier.
17576             ctxt.associate_die_to_type(die, ty, where_offset);
17577             result =
17578               add_decl_to_scope(d, ctxt.cur_transl_unit()->get_global_scope());
17579             maybe_canonicalize_type(die, ctxt);
17580           }
17581       }
17582       break;
17583
17584     case DW_TAG_enumeration_type:
17585       {
17586         if (!type_is_suppressed(ctxt, scope, die))
17587           {
17588             enum_type_decl_sptr e = build_enum_type(ctxt, die, scope,
17589                                                     where_offset);
17590             result = add_decl_to_scope(e, scope);
17591             if (result)
17592               {
17593                 maybe_set_member_type_access_specifier(is_decl(result), die);
17594                 maybe_canonicalize_type(die, ctxt);
17595               }
17596           }
17597       }
17598       break;
17599
17600     case DW_TAG_class_type:
17601     case DW_TAG_structure_type:
17602       {
17603         bool type_is_private = false;
17604         bool type_suppressed=
17605           type_is_suppressed(ctxt, scope, die, type_is_private);
17606
17607         if (type_suppressed && type_is_private)
17608           // The type is suppressed because it's private.  If other
17609           // non-suppressed and declaration-only instances of this
17610           // type exist in the current corpus, then it means those
17611           // non-suppressed instances are opaque versions of the
17612           // suppressed private type.  Lets return one of these opaque
17613           // types then.
17614           result = get_opaque_version_of_type(ctxt, scope, die, where_offset);
17615         else if (!type_suppressed)
17616           {
17617             Dwarf_Die spec_die;
17618             scope_decl_sptr scop;
17619             class_decl_sptr klass;
17620             if (die_die_attribute(die, DW_AT_specification, spec_die))
17621               {
17622                 scope_decl_sptr skope =
17623                   get_scope_for_die(ctxt, &spec_die,
17624                                     called_from_public_decl,
17625                                     where_offset);
17626                 ABG_ASSERT(skope);
17627                 decl_base_sptr cl =
17628                   is_decl(build_ir_node_from_die(ctxt, &spec_die,
17629                                                  skope.get(),
17630                                                  called_from_public_decl,
17631                                                  where_offset));
17632                 ABG_ASSERT(cl);
17633                 klass = dynamic_pointer_cast<class_decl>(cl);
17634                 ABG_ASSERT(klass);
17635
17636                 klass =
17637                   add_or_update_class_type(ctxt, die,
17638                                            skope.get(),
17639                                            tag == DW_TAG_structure_type,
17640                                            klass,
17641                                            called_from_public_decl,
17642                                            where_offset);
17643               }
17644             else
17645               klass =
17646                 add_or_update_class_type(ctxt, die, scope,
17647                                          tag == DW_TAG_structure_type,
17648                                          class_decl_sptr(),
17649                                          called_from_public_decl,
17650                                          where_offset);
17651             result = klass;
17652             if (klass)
17653               {
17654                 maybe_set_member_type_access_specifier(klass, die);
17655                 maybe_canonicalize_type(die, klass, ctxt);
17656               }
17657           }
17658       }
17659       break;
17660     case DW_TAG_union_type:
17661       if (!type_is_suppressed(ctxt, scope, die))
17662         {
17663           union_decl_sptr union_type =
17664             add_or_update_union_type(ctxt, die, scope,
17665                                      union_decl_sptr(),
17666                                      called_from_public_decl,
17667                                      where_offset);
17668           if (union_type)
17669             {
17670               maybe_set_member_type_access_specifier(union_type, die);
17671               maybe_canonicalize_type(die, union_type, ctxt);
17672             }
17673           result = union_type;
17674         }
17675       break;
17676     case DW_TAG_string_type:
17677       break;
17678     case DW_TAG_subroutine_type:
17679       {
17680         function_type_sptr f = build_function_type(ctxt, die,
17681                                                    class_decl_sptr(),
17682                                                    where_offset);
17683         if (f)
17684           {
17685             result = f;
17686             maybe_canonicalize_type(die, ctxt);
17687           }
17688       }
17689       break;
17690     case DW_TAG_array_type:
17691       {
17692         array_type_def_sptr a = build_array_type(ctxt,
17693                                                  die,
17694                                                  called_from_public_decl,
17695                                                  where_offset);
17696         if (a)
17697           {
17698             result =
17699               add_decl_to_scope(a, ctxt.cur_transl_unit()->get_global_scope());
17700             ctxt.associate_die_to_type(die, a, where_offset);
17701             maybe_canonicalize_type(die, ctxt);
17702           }
17703         break;
17704       }
17705     case DW_TAG_subrange_type:
17706       {
17707         // If we got here, this means the subrange type is a "free
17708         // form" defined in the global namespace of the current
17709         // translation unit, like what is found in Ada.
17710         array_type_def::subrange_sptr s =
17711           build_subrange_type(ctxt, die, where_offset);
17712         if (s)
17713           {
17714             result =
17715               add_decl_to_scope(s, ctxt.cur_transl_unit()->get_global_scope());
17716             ctxt.associate_die_to_type(die, s, where_offset);
17717             maybe_canonicalize_type(die, ctxt);
17718           }
17719       }
17720       break;
17721     case DW_TAG_packed_type:
17722       break;
17723     case DW_TAG_set_type:
17724       break;
17725     case DW_TAG_file_type:
17726       break;
17727     case DW_TAG_ptr_to_member_type:
17728       break;
17729     case DW_TAG_thrown_type:
17730       break;
17731     case DW_TAG_interface_type:
17732       break;
17733     case DW_TAG_unspecified_type:
17734       break;
17735     case DW_TAG_shared_type:
17736       break;
17737
17738     case DW_TAG_compile_unit:
17739       // We shouldn't reach this point b/c this should be handled by
17740       // build_translation_unit.
17741       ABG_ASSERT_NOT_REACHED;
17742
17743     case DW_TAG_namespace:
17744     case DW_TAG_module:
17745       result = build_namespace_decl_and_add_to_ir(ctxt, die, where_offset);
17746       break;
17747
17748     case DW_TAG_variable:
17749     case DW_TAG_member:
17750       {
17751         Dwarf_Die spec_die;
17752         bool var_is_cloned = false;
17753
17754         if (tag == DW_TAG_member)
17755           ABG_ASSERT(!is_c_language(ctxt.cur_transl_unit()->get_language()));
17756
17757         if (die_die_attribute(die, DW_AT_specification, spec_die,false)
17758             || (var_is_cloned = die_die_attribute(die, DW_AT_abstract_origin,
17759                                                   spec_die, false)))
17760           {
17761             scope_decl_sptr spec_scope = get_scope_for_die(ctxt, &spec_die,
17762                                                            called_from_public_decl,
17763                                                            where_offset);
17764             if (spec_scope)
17765               {
17766                 decl_base_sptr d =
17767                   is_decl(build_ir_node_from_die(ctxt, &spec_die,
17768                                                  spec_scope.get(),
17769                                                  called_from_public_decl,
17770                                                  where_offset,
17771                                                  /*is_required_decl_spec=*/true));
17772                 if (d)
17773                   {
17774                     var_decl_sptr m =
17775                       dynamic_pointer_cast<var_decl>(d);
17776                     if (var_is_cloned)
17777                       m = m->clone();
17778                     m = build_var_decl(ctxt, die, where_offset, m);
17779                     if (is_data_member(m))
17780                       {
17781                         set_member_is_static(m, true);
17782                         ctxt.associate_die_to_decl(die, m, where_offset,
17783                                                    /*associate_by_repr=*/false);
17784                       }
17785                     else
17786                       {
17787                         ABG_ASSERT(has_scope(m));
17788                         ctxt.var_decls_to_re_add_to_tree().push_back(m);
17789                       }
17790                     ABG_ASSERT(m->get_scope());
17791                     ctxt.maybe_add_var_to_exported_decls(m.get());
17792                     return m;
17793                   }
17794               }
17795           }
17796         else if (var_decl_sptr v =
17797                  build_or_get_var_decl_if_not_suppressed(ctxt, scope, die,
17798                                                          where_offset,
17799                                                          /*result=*/var_decl_sptr(),
17800                                                          is_required_decl_spec))
17801           {
17802             result = add_decl_to_scope(v, scope);
17803             ABG_ASSERT(is_decl(result)->get_scope());
17804             v = dynamic_pointer_cast<var_decl>(result);
17805             ABG_ASSERT(v);
17806             ABG_ASSERT(v->get_scope());
17807             ctxt.var_decls_to_re_add_to_tree().push_back(v);
17808             ctxt.maybe_add_var_to_exported_decls(v.get());
17809           }
17810       }
17811       break;
17812
17813     case DW_TAG_subprogram:
17814       {
17815         Dwarf_Die spec_die;
17816         Dwarf_Die abstract_origin_die;
17817         Dwarf_Die *interface_die = 0, *origin_die = 0;
17818         scope_decl_sptr interface_scope;
17819         if (die_is_artificial(die))
17820           break;
17821
17822         function_decl_sptr fn;
17823         bool has_spec = die_die_attribute(die, DW_AT_specification,
17824                                           spec_die, true);
17825         bool has_abstract_origin =
17826           die_die_attribute(die, DW_AT_abstract_origin,
17827                             abstract_origin_die, true);
17828         if (has_spec || has_abstract_origin)
17829           {
17830             interface_die =
17831               has_spec
17832               ? &spec_die
17833               : &abstract_origin_die;
17834             origin_die =
17835               has_abstract_origin
17836               ? &abstract_origin_die
17837               : &spec_die;
17838
17839             string linkage_name = die_linkage_name(die);
17840             string spec_linkage_name = die_linkage_name(interface_die);
17841
17842             interface_scope = get_scope_for_die(ctxt, interface_die,
17843                                                 called_from_public_decl,
17844                                                 where_offset);
17845             if (interface_scope)
17846               {
17847                 decl_base_sptr d =
17848                   is_decl(build_ir_node_from_die(ctxt,
17849                                                  origin_die,
17850                                                  interface_scope.get(),
17851                                                  called_from_public_decl,
17852                                                  where_offset));
17853                 if (d)
17854                   {
17855                     fn = dynamic_pointer_cast<function_decl>(d);
17856                     if (has_abstract_origin
17857                         && (linkage_name != spec_linkage_name))
17858                       // The current DIE has 'd' as abstract orign,
17859                       // and has a linkage name that is different
17860                       // from from the linkage name of 'd'.  That
17861                       // means, the current DIE represents a clone
17862                       // of 'd'.
17863                       fn = fn->clone();
17864                   }
17865               }
17866           }
17867         ctxt.scope_stack().push(scope);
17868
17869         scope_decl* logical_scope =
17870           interface_scope
17871           ? interface_scope.get()
17872           : scope;
17873
17874         result = build_or_get_fn_decl_if_not_suppressed(ctxt, logical_scope,
17875                                                         die, where_offset, fn);
17876
17877         if (result && !fn)
17878           result = add_decl_to_scope(is_decl(result), logical_scope);
17879
17880         fn = is_function_decl(result);
17881         if (fn && is_member_function(fn))
17882           {
17883             class_decl_sptr klass(static_cast<class_decl*>(logical_scope),
17884                                   sptr_utils::noop_deleter());
17885             ABG_ASSERT(klass);
17886             finish_member_function_reading(die, fn, klass, ctxt);
17887           }
17888
17889         if (fn)
17890           {
17891             ctxt.maybe_add_fn_to_exported_decls(fn.get());
17892             ctxt.associate_die_to_decl(die, fn, where_offset,
17893                                        /*associate_by_repr=*/false);
17894             maybe_canonicalize_type(die, ctxt);
17895           }
17896
17897         ctxt.scope_stack().pop();
17898       }
17899       break;
17900
17901     case DW_TAG_formal_parameter:
17902       // We should not read this case as it should have been dealt
17903       // with by build_function_decl above.
17904       ABG_ASSERT_NOT_REACHED;
17905
17906     case DW_TAG_constant:
17907       break;
17908     case DW_TAG_enumerator:
17909       break;
17910
17911     case DW_TAG_partial_unit:
17912     case DW_TAG_imported_unit:
17913       // For now, the DIEs under these are read lazily when they are
17914       // referenced by a public decl DIE that is under a
17915       // DW_TAG_compile_unit, so we shouldn't get here.
17916       ABG_ASSERT_NOT_REACHED;
17917
17918       // Other declaration we don't really intend to support yet.
17919     case DW_TAG_dwarf_procedure:
17920     case DW_TAG_imported_declaration:
17921     case DW_TAG_entry_point:
17922     case DW_TAG_label:
17923     case DW_TAG_lexical_block:
17924     case DW_TAG_unspecified_parameters:
17925     case DW_TAG_variant:
17926     case DW_TAG_common_block:
17927     case DW_TAG_common_inclusion:
17928     case DW_TAG_inheritance:
17929     case DW_TAG_inlined_subroutine:
17930     case DW_TAG_with_stmt:
17931     case DW_TAG_access_declaration:
17932     case DW_TAG_catch_block:
17933     case DW_TAG_friend:
17934     case DW_TAG_namelist:
17935     case DW_TAG_namelist_item:
17936     case DW_TAG_template_type_parameter:
17937     case DW_TAG_template_value_parameter:
17938     case DW_TAG_try_block:
17939     case DW_TAG_variant_part:
17940     case DW_TAG_imported_module:
17941     case DW_TAG_condition:
17942     case DW_TAG_type_unit:
17943     case DW_TAG_template_alias:
17944     case DW_TAG_lo_user:
17945     case DW_TAG_MIPS_loop:
17946     case DW_TAG_format_label:
17947     case DW_TAG_function_template:
17948     case DW_TAG_class_template:
17949     case DW_TAG_GNU_BINCL:
17950     case DW_TAG_GNU_EINCL:
17951     case DW_TAG_GNU_template_template_param:
17952     case DW_TAG_GNU_template_parameter_pack:
17953     case DW_TAG_GNU_formal_parameter_pack:
17954     case DW_TAG_GNU_call_site:
17955     case DW_TAG_GNU_call_site_parameter:
17956     case DW_TAG_hi_user:
17957     default:
17958       break;
17959     }
17960
17961   if (result && tag != DW_TAG_subroutine_type)
17962     ctxt.associate_die_to_decl(die, is_decl(result), where_offset,
17963                                /*associate_by_repr=*/false);
17964
17965   return result;
17966 }
17967
17968 ///  Build the IR node for a void type.
17969 ///
17970 ///  @param ctxt the read context to use.
17971 ///
17972 ///  @return the void type node.
17973 static decl_base_sptr
17974 build_ir_node_for_void_type(read_context& ctxt)
17975 {
17976   ir::environment* env = ctxt.env();
17977   ABG_ASSERT(env);
17978   type_base_sptr t = env->get_void_type();
17979   decl_base_sptr type_declaration = get_type_declaration(t);
17980   if (!has_scope(type_declaration))
17981     add_decl_to_scope(type_declaration,
17982                       ctxt.cur_transl_unit()->get_global_scope());
17983   canonicalize(t);
17984   return type_declaration;
17985 }
17986
17987 /// Build an IR node from a given DIE and add the node to the current
17988 /// IR being build and held in the read_context.  Doing that is called
17989 /// "emitting an IR node for the DIE".
17990 ///
17991 /// @param ctxt the read context.
17992 ///
17993 /// @param die the DIE to consider.
17994 ///
17995 /// @param called_from_public_decl set to yes if this function is
17996 /// called from the functions used to build a public decl (functions
17997 /// and variables).  In that case, this function accepts building IR
17998 /// nodes representing types.  Otherwise, this function only creates
17999 /// IR nodes representing public decls (functions and variables).
18000 /// This is done to avoid emitting IR nodes for types that are not
18001 /// referenced by public functions or variables.
18002 ///
18003 /// @param where_offset the offset of the DIE where we are "logically"
18004 /// positionned at, in the DIE tree.  This is useful when @p die is
18005 /// e.g, DW_TAG_partial_unit that can be included in several places in
18006 /// the DIE tree.
18007 ///
18008 /// @return the resulting IR node.
18009 static type_or_decl_base_sptr
18010 build_ir_node_from_die(read_context&    ctxt,
18011                        Dwarf_Die*       die,
18012                        bool             called_from_public_decl,
18013                        size_t           where_offset)
18014 {
18015   if (!die)
18016     return decl_base_sptr();
18017
18018   if (is_c_language(ctxt.cur_transl_unit()->get_language()))
18019     {
18020       const scope_decl_sptr& scop = ctxt.global_scope();
18021       return build_ir_node_from_die(ctxt, die, scop.get(),
18022                                     called_from_public_decl,
18023                                     where_offset);
18024     }
18025
18026   scope_decl_sptr scope = get_scope_for_die(ctxt, die,
18027                                             called_from_public_decl,
18028                                             where_offset);
18029   return build_ir_node_from_die(ctxt, die, scope.get(),
18030                                 called_from_public_decl,
18031                                 where_offset);
18032 }
18033
18034 status
18035 operator|(status l, status r)
18036 {
18037   return static_cast<status>(static_cast<unsigned>(l)
18038                              | static_cast<unsigned>(r));
18039 }
18040
18041 status
18042 operator&(status l, status r)
18043 {
18044   return static_cast<status>(static_cast<unsigned>(l)
18045                              & static_cast<unsigned>(r));
18046 }
18047
18048 status&
18049 operator|=(status& l, status r)
18050 {
18051   l = l | r;
18052   return l;
18053 }
18054
18055 status&
18056 operator&=(status& l, status r)
18057 {
18058   l = l & r;
18059   return l;
18060 }
18061
18062 /// Emit a diagnostic status with english sentences to describe the
18063 /// problems encoded in a given abigail::dwarf_reader::status, if
18064 /// there is an error.
18065 ///
18066 /// @param status the status to diagnose
18067 ///
18068 /// @return a string containing sentences that describe the possible
18069 /// errors encoded in @p s.  If there is no error to encode, then the
18070 /// empty string is returned.
18071 string
18072 status_to_diagnostic_string(status s)
18073 {
18074   string str;
18075
18076   if (s & STATUS_DEBUG_INFO_NOT_FOUND)
18077     str += "could not find debug info\n";
18078
18079   if (s & STATUS_ALT_DEBUG_INFO_NOT_FOUND)
18080     str += "could not find alternate debug info\n";
18081
18082   if (s & STATUS_NO_SYMBOLS_FOUND)
18083     str += "could not load ELF symbols\n";
18084
18085   return str;
18086 }
18087
18088 /// Create a dwarf_reader::read_context.
18089 ///
18090 /// @param elf_path the path to the elf file the context is to be used for.
18091 ///
18092 /// @param debug_info_root_paths a pointer to the path to the root
18093 /// directory under which the debug info is to be found for @p
18094 /// elf_path.  Leave this to NULL if the debug info is not in a split
18095 /// file.
18096 ///
18097 /// @param environment the environment used by the current context.
18098 /// This environment contains resources needed by the reader and by
18099 /// the types and declarations that are to be created later.  Note
18100 /// that ABI artifacts that are to be compared all need to be created
18101 /// within the same environment.
18102 ///
18103 /// Please also note that the life time of this environment object
18104 /// must be greater than the life time of the resulting @ref
18105 /// read_context the context uses resources that are allocated in the
18106 /// environment.
18107 ///
18108 /// @param load_all_types if set to false only the types that are
18109 /// reachable from publicly exported declarations (of functions and
18110 /// variables) are read.  If set to true then all types found in the
18111 /// debug information are loaded.
18112 ///
18113 /// @param linux_kernel_mode if set to true, then consider the special
18114 /// linux kernel symbol tables when determining if a symbol is
18115 /// exported or not.
18116 ///
18117 /// @return a smart pointer to the resulting dwarf_reader::read_context.
18118 read_context_sptr
18119 create_read_context(const std::string&          elf_path,
18120                     const vector<char**>&       debug_info_root_paths,
18121                     ir::environment*            environment,
18122                     bool                        load_all_types,
18123                     bool                        linux_kernel_mode)
18124 {
18125   // Create a DWARF Front End Library handle to be used by functions
18126   // of that library.
18127   read_context_sptr result(new read_context(elf_path, debug_info_root_paths,
18128                                             environment, load_all_types,
18129                                             linux_kernel_mode));
18130   return result;
18131 }
18132
18133 /// Getter for the path to the binary this @ref read_context is for.
18134 ///
18135 /// @return the path to the binary the @ref read_context is for.
18136 const string&
18137 read_context_get_path(const read_context& ctxt)
18138 {return ctxt.elf_path();}
18139
18140 /// Re-initialize a read_context so that it can re-used to read
18141 /// another binary.
18142 ///
18143 /// @param ctxt the context to re-initialize.
18144 ///
18145 /// @param elf_path the path to the elf file the context is to be used
18146 /// for.
18147 ///
18148 /// @param debug_info_root_path a pointer to the path to the root
18149 /// directory under which the debug info is to be found for @p
18150 /// elf_path.  Leave this to NULL if the debug info is not in a split
18151 /// file.
18152 ///
18153 /// @param environment the environment used by the current context.
18154 /// This environment contains resources needed by the reader and by
18155 /// the types and declarations that are to be created later.  Note
18156 /// that ABI artifacts that are to be compared all need to be created
18157 /// within the same environment.
18158 ///
18159 /// Please also note that the life time of this environment object
18160 /// must be greater than the life time of the resulting @ref
18161 /// read_context the context uses resources that are allocated in the
18162 /// environment.
18163 ///
18164 /// @param load_all_types if set to false only the types that are
18165 /// reachable from publicly exported declarations (of functions and
18166 /// variables) are read.  If set to true then all types found in the
18167 /// debug information are loaded.
18168 ///
18169 /// @param linux_kernel_mode if set to true, then consider the special
18170 /// linux kernel symbol tables when determining if a symbol is
18171 /// exported or not.
18172 ///
18173 /// @return a smart pointer to the resulting dwarf_reader::read_context.
18174 void
18175 reset_read_context(read_context_sptr    &ctxt,
18176                    const std::string&    elf_path,
18177                    const vector<char**>& debug_info_root_path,
18178                    ir::environment*      environment,
18179                    bool          read_all_types,
18180                    bool          linux_kernel_mode)
18181 {
18182   if (ctxt)
18183     ctxt->initialize(elf_path, debug_info_root_path, environment,
18184                      read_all_types, linux_kernel_mode);
18185 }
18186
18187 /// Add suppressions specifications to the set of suppressions to be
18188 /// used during the construction of the ABI internal representation
18189 /// (the ABI corpus) from ELF and DWARF.
18190 ///
18191 /// During the construction of the ABI corpus, ABI artifacts that
18192 /// match the a given suppression specification are dropped on the
18193 /// floor; that is, they are discarded and won't be part of the final
18194 /// ABI corpus.  This is a way to reduce the amount of data held by
18195 /// the final ABI corpus.
18196 ///
18197 /// Note that the suppression specifications provided to this function
18198 /// are only considered during the construction of the ABI corpus.
18199 /// For instance, they are not taken into account during e.g
18200 /// comparisons of two ABI corpora that might happen later.  If you
18201 /// want to apply suppression specificatins to the comparison (or
18202 /// reporting) of ABI corpora please refer to the documentation of the
18203 /// @ref diff_context type to learn how to set suppressions that are
18204 /// to be used in that context.
18205 ///
18206 /// @param ctxt the context that is going to be used by functions that
18207 /// read ELF and DWARF information to construct and ABI corpus.
18208 ///
18209 /// @param supprs the suppression specifications to be applied during
18210 /// the construction of the ABI corpus.
18211 void
18212 add_read_context_suppressions(read_context& ctxt,
18213                               const suppr::suppressions_type& supprs)
18214 {
18215   for (suppr::suppressions_type::const_iterator i = supprs.begin();
18216        i != supprs.end();
18217        ++i)
18218     if ((*i)->get_drops_artifact_from_ir())
18219       ctxt.get_suppressions().push_back(*i);
18220 }
18221
18222 /// Set the @ref corpus_group being created to the current read context.
18223 ///
18224 /// @param ctxt the read_context to consider.
18225 ///
18226 /// @param group the @ref corpus_group to set.
18227 void
18228 set_read_context_corpus_group(read_context& ctxt,
18229                               corpus_group_sptr& group)
18230 {
18231   ctxt.cur_corpus_group_ = group;
18232 }
18233
18234 /// Read all @ref abigail::translation_unit possible from the debug info
18235 /// accessible from an elf file, stuff them into a libabigail ABI
18236 /// Corpus and return it.
18237 ///
18238 /// @param ctxt the context to use for reading the elf file.
18239 ///
18240 /// @param resulting_corp a pointer to the resulting abigail::corpus.
18241 ///
18242 /// @return the resulting status.
18243 corpus_sptr
18244 read_corpus_from_elf(read_context& ctxt, status& status)
18245 {
18246   status = STATUS_UNKNOWN;
18247
18248   // Load debug info from the elf path.
18249   if (!ctxt.load_debug_info())
18250     status |= STATUS_DEBUG_INFO_NOT_FOUND;
18251
18252   {
18253     string alt_di_path;
18254     if (refers_to_alt_debug_info(ctxt, alt_di_path) && !ctxt.alt_dwarf())
18255       status |= STATUS_ALT_DEBUG_INFO_NOT_FOUND;
18256   }
18257
18258   if (!get_ignore_symbol_table(ctxt))
18259     {
18260       ctxt.load_elf_properties();
18261       // Read the symbols for publicly defined decls
18262       if (!ctxt.load_symbol_maps())
18263         status |= STATUS_NO_SYMBOLS_FOUND;
18264     }
18265
18266   if (// If no elf symbol was found ...
18267       status & STATUS_NO_SYMBOLS_FOUND
18268       // ... or if debug info was found but not the required alternate
18269       // debug info ...
18270       || ((status & STATUS_ALT_DEBUG_INFO_NOT_FOUND)
18271           && !(status & STATUS_DEBUG_INFO_NOT_FOUND)))
18272     // ... then we cannot handle the binary.
18273     return corpus_sptr();
18274
18275   // Read the variable and function descriptions from the debug info
18276   // we have, through the dwfl handle.
18277   corpus_sptr corp = read_debug_info_into_corpus(ctxt);
18278
18279   status |= STATUS_OK;
18280
18281   return corp;
18282 }
18283
18284 /// Read a corpus and add it to a given @ref corpus_group.
18285 ///
18286 /// @param ctxt the reading context to consider.
18287 ///
18288 /// @param group the @ref corpus_group to add the new corpus to.
18289 ///
18290 /// @param status output parameter. The status of the read.  It is set
18291 /// by this function upon its completion.
18292 corpus_sptr
18293 read_and_add_corpus_to_group_from_elf(read_context& ctxt,
18294                                       corpus_group& group,
18295                                       status& status)
18296 {
18297   corpus_sptr result;
18298   corpus_sptr corp = read_corpus_from_elf(ctxt, status);
18299   if (status & STATUS_OK)
18300     {
18301       if (!corp->get_group())
18302         group.add_corpus(corp);
18303       result = corp;
18304     }
18305
18306   return result;
18307 }
18308
18309 /// Read all @ref abigail::translation_unit possible from the debug info
18310 /// accessible from an elf file, stuff them into a libabigail ABI
18311 /// Corpus and return it.
18312 ///
18313 /// @param elf_path the path to the elf file.
18314 ///
18315 /// @param debug_info_root_paths a vector of pointers to root paths
18316 /// under which to look for the debug info of the elf files that are
18317 /// later handled by the Dwfl.  This for cases where the debug info is
18318 /// split into a different file from the binary we want to inspect.
18319 /// On Red Hat compatible systems, this root path is usually
18320 /// /usr/lib/debug by default.  If this argument is set to NULL, then
18321 /// "./debug" and /usr/lib/debug will be searched for sub-directories
18322 /// containing the debug info file.
18323 ///
18324 /// @param environment the environment used by the current context.
18325 /// This environment contains resources needed by the reader and by
18326 /// the types and declarations that are to be created later.  Note
18327 /// that ABI artifacts that are to be compared all need to be created
18328 /// within the same environment.  Also, the lifetime of the
18329 /// environment must be greater than the lifetime of the resulting
18330 /// corpus because the corpus uses resources that are allocated in the
18331 /// environment.
18332 ///
18333 /// @param load_all_types if set to false only the types that are
18334 /// reachable from publicly exported declarations (of functions and
18335 /// variables) are read.  If set to true then all types found in the
18336 /// debug information are loaded.
18337 ///
18338 /// @param resulting_corp a pointer to the resulting abigail::corpus.
18339 ///
18340 /// @return the resulting status.
18341 corpus_sptr
18342 read_corpus_from_elf(const std::string& elf_path,
18343                      const vector<char**>& debug_info_root_paths,
18344                      ir::environment*   environment,
18345                      bool               load_all_types,
18346                      status&            status)
18347 {
18348   read_context_sptr c = create_read_context(elf_path,
18349                                             debug_info_root_paths,
18350                                             environment,
18351                                             load_all_types);
18352   read_context& ctxt = *c;
18353   return read_corpus_from_elf(ctxt, status);
18354 }
18355
18356 /// Look into the symbol tables of a given elf file and see if we find
18357 /// a given symbol.
18358 ///
18359 /// @param env the environment we are operating from.
18360 ///
18361 /// @param elf_path the path to the elf file to consider.
18362 ///
18363 /// @param symbol_name the name of the symbol to look for.
18364 ///
18365 /// @param demangle if true, try to demangle the symbol name found in
18366 /// the symbol table.
18367 ///
18368 /// @param syms the vector of symbols found with the name @p symbol_name.
18369 ///
18370 /// @return true iff the symbol was found among the publicly exported
18371 /// symbols of the ELF file.
18372 bool
18373 lookup_symbol_from_elf(const environment*               env,
18374                        const string&                    elf_path,
18375                        const string&                    symbol_name,
18376                        bool                             demangle,
18377                        vector<elf_symbol_sptr>& syms)
18378
18379 {
18380   if (elf_version(EV_CURRENT) == EV_NONE)
18381     return false;
18382
18383   int fd = open(elf_path.c_str(), O_RDONLY);
18384   if (fd < 0)
18385     return false;
18386
18387   struct stat s;
18388   if (fstat(fd, &s))
18389     return false;
18390
18391   Elf* elf = elf_begin(fd, ELF_C_READ, 0);
18392   if (elf == 0)
18393     return false;
18394
18395   bool value = lookup_symbol_from_elf(env, elf, symbol_name,
18396                                       demangle, syms);
18397   elf_end(elf);
18398   close(fd);
18399
18400   return value;
18401 }
18402
18403 /// Look into the symbol tables of an elf file to see if a public
18404 /// function of a given name is found.
18405 ///
18406 /// @param env the environment we are operating from.
18407 ///
18408 /// @param elf_path the path to the elf file to consider.
18409 ///
18410 /// @param symbol_name the name of the function to look for.
18411 ///
18412 /// @param syms the vector of public function symbols found with the
18413 /// name @p symname.
18414 ///
18415 /// @return true iff a function with symbol name @p symbol_name is
18416 /// found.
18417 bool
18418 lookup_public_function_symbol_from_elf(const environment*               env,
18419                                        const string&                    path,
18420                                        const string&                    symname,
18421                                        vector<elf_symbol_sptr>& syms)
18422 {
18423   if (elf_version(EV_CURRENT) == EV_NONE)
18424     return false;
18425
18426   int fd = open(path.c_str(), O_RDONLY);
18427   if (fd < 0)
18428     return false;
18429
18430   struct stat s;
18431   if (fstat(fd, &s))
18432     return false;
18433
18434   Elf* elf = elf_begin(fd, ELF_C_READ, 0);
18435   if (elf == 0)
18436     return false;
18437
18438   bool value = lookup_public_function_symbol_from_elf(env, elf, symname, syms);
18439   elf_end(elf);
18440   close(fd);
18441
18442   return value;
18443 }
18444
18445 /// Check if the underlying elf file refers to an alternate debug info
18446 /// file associated to it.
18447 ///
18448 /// Note that "alternate debug info sections" is a GNU extension as
18449 /// of DWARF4 and is described at
18450 /// http://www.dwarfstd.org/ShowIssue.php?issue=120604.1.
18451 ///
18452 /// @param ctxt the context used to read the elf file.
18453 ///
18454 /// @param alt_di the path to the alternate debug info file.  This is
18455 /// set iff the function returns true.
18456 ///
18457 /// @return true if the ELF file refers to an alternate debug info
18458 /// file.
18459 bool
18460 refers_to_alt_debug_info(const read_context&    ctxt,
18461                          string&                alt_di_path)
18462 {
18463   if (!ctxt.alt_debug_info_path().empty())
18464     {
18465       alt_di_path = ctxt.alt_debug_info_path();
18466       return true;
18467     }
18468   return false;
18469 }
18470
18471 /// Check if the underlying elf file has an alternate debug info file
18472 /// associated to it.
18473 ///
18474 /// Note that "alternate debug info sections" is a GNU extension as
18475 /// of DWARF4 and is described at
18476 /// http://www.dwarfstd.org/ShowIssue.php?issue=120604.1.
18477 ///
18478 /// @param ctxt the read_context to use to handle the underlying elf file.
18479 ///
18480 /// @param has_alt_di out parameter.  This is set to true upon
18481 /// succesful completion of the function iff an alternate debug info
18482 /// file was found, false otherwise.  Note thas this parameter is set
18483 /// only if the function returns STATUS_OK.
18484 ///
18485 /// @param alt_debug_info_path if the function returned STATUS_OK and
18486 /// if @p has been set to true, then this parameter contains the path
18487 /// to the alternate debug info file found.
18488 ///
18489 /// return STATUS_OK upon successful completion, false otherwise.
18490 status
18491 has_alt_debug_info(read_context&        ctxt,
18492                    bool&                has_alt_di,
18493                    string&              alt_debug_info_path)
18494 {
18495   // Load debug info from the elf path.
18496   if (!ctxt.load_debug_info())
18497     return STATUS_DEBUG_INFO_NOT_FOUND;
18498
18499   if (ctxt.alt_dwarf())
18500     {
18501       has_alt_di = true;
18502       alt_debug_info_path = ctxt.alt_debug_info_path();
18503     }
18504   else
18505     has_alt_di = false;
18506
18507   return STATUS_OK;
18508 }
18509
18510 /// Check if a given elf file has an alternate debug info file
18511 /// associated to it.
18512 ///
18513 /// Note that "alternate debug info sections" is a GNU extension as
18514 /// of DWARF4 and is described at
18515 /// http://www.dwarfstd.org/ShowIssue.php?issue=120604.1.
18516 ///
18517 /// @param elf_path the path to the elf file to consider.
18518 ///
18519 /// @param a pointer to the root directory under which the split debug info
18520 /// file associated to elf_path is to be found.  This has to be NULL
18521 /// if the debug info file is not in a split file.
18522 ///
18523 /// @param has_alt_di out parameter.  This is set to true upon
18524 /// succesful completion of the function iff an alternate debug info
18525 /// file was found, false otherwise.  Note thas this parameter is set
18526 /// only if the function returns STATUS_OK.
18527 ///
18528 /// @param alt_debug_info_path if the function returned STATUS_OK and
18529 /// if @p has been set to true, then this parameter contains the path
18530 /// to the alternate debug info file found.
18531 ///
18532 /// return STATUS_OK upon successful completion, false otherwise.
18533 status
18534 has_alt_debug_info(const string&        elf_path,
18535                    char**               debug_info_root_path,
18536                    bool&                has_alt_di,
18537                    string&              alt_debug_info_path)
18538 {
18539   vector<char**> di_roots;
18540   di_roots.push_back(debug_info_root_path);
18541   read_context_sptr c = create_read_context(elf_path, di_roots, 0);
18542   read_context& ctxt = *c;
18543
18544   // Load debug info from the elf path.
18545   if (!ctxt.load_debug_info())
18546     return STATUS_DEBUG_INFO_NOT_FOUND;
18547
18548   if (ctxt.alt_dwarf())
18549     {
18550       has_alt_di = true;
18551       alt_debug_info_path = ctxt.alt_debug_info_path();
18552     }
18553   else
18554     has_alt_di = false;
18555
18556   return STATUS_OK;
18557 }
18558
18559 /// Fetch the SONAME ELF property from an ELF binary file.
18560 ///
18561 /// @param path The path to the elf file to consider.
18562 ///
18563 /// @param soname out parameter. Set to the SONAME property of the
18564 /// binary file, if it present in the ELF file.
18565 ///
18566 /// return false if an error occured while looking for the SONAME
18567 /// property in the binary, true otherwise.
18568 bool
18569 get_soname_of_elf_file(const string& path, string &soname)
18570 {
18571
18572   int fd = open(path.c_str(), O_RDONLY);
18573   if (fd == -1)
18574     return false;
18575
18576   elf_version (EV_CURRENT);
18577   Elf* elf = elf_begin (fd, ELF_C_READ_MMAP, NULL);
18578
18579   GElf_Ehdr ehdr_mem;
18580   GElf_Ehdr* ehdr = gelf_getehdr (elf, &ehdr_mem);
18581   if (ehdr == NULL)
18582     return false;
18583
18584   for (int i = 0; i < ehdr->e_phnum; ++i)
18585     {
18586       GElf_Phdr phdr_mem;
18587       GElf_Phdr* phdr = gelf_getphdr (elf, i, &phdr_mem);
18588
18589       if (phdr != NULL && phdr->p_type == PT_DYNAMIC)
18590         {
18591           Elf_Scn* scn = gelf_offscn (elf, phdr->p_offset);
18592           GElf_Shdr shdr_mem;
18593           GElf_Shdr* shdr = gelf_getshdr (scn, &shdr_mem);
18594           int maxcnt = (shdr != NULL
18595                         ? shdr->sh_size / shdr->sh_entsize : INT_MAX);
18596           ABG_ASSERT (shdr == NULL || shdr->sh_type == SHT_DYNAMIC);
18597           Elf_Data* data = elf_getdata (scn, NULL);
18598           if (data == NULL)
18599             break;
18600
18601           for (int cnt = 0; cnt < maxcnt; ++cnt)
18602             {
18603               GElf_Dyn dynmem;
18604               GElf_Dyn* dyn = gelf_getdyn (data, cnt, &dynmem);
18605               if (dyn == NULL)
18606                 continue;
18607
18608               if (dyn->d_tag == DT_NULL)
18609                 break;
18610
18611               if (dyn->d_tag != DT_SONAME)
18612                 continue;
18613
18614               soname = elf_strptr (elf, shdr->sh_link, dyn->d_un.d_val);
18615               break;
18616             }
18617           break;
18618         }
18619     }
18620
18621   elf_end(elf);
18622   close(fd);
18623
18624   return true;
18625 }
18626
18627 /// Get the type of a given elf type.
18628 ///
18629 /// @param path the absolute path to the ELF file to analyzed.
18630 ///
18631 /// @param type the kind of the ELF file designated by @p path.
18632 ///
18633 /// @param out parameter.  Is set to the type of ELF file of @p path.
18634 /// This parameter is set iff the function returns true.
18635 ///
18636 /// @return true iff the file could be opened and analyzed.
18637 bool
18638 get_type_of_elf_file(const string& path, elf_type& type)
18639 {
18640   int fd = open(path.c_str(), O_RDONLY);
18641   if (fd == -1)
18642     return false;
18643
18644   elf_version (EV_CURRENT);
18645   Elf *elf = elf_begin (fd, ELF_C_READ_MMAP, NULL);
18646   type = elf_file_type(elf);
18647   elf_end(elf);
18648   close(fd);
18649
18650   return true;
18651 }
18652
18653 }// end namespace dwarf_reader
18654
18655 }// end namespace abigail