libabigail
abg-symtab-reader.cc
Go to the documentation of this file.
1 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
2 // -*- Mode: C++ -*-
3 //
4 // Copyright (C) 2013-2023 Red Hat, Inc.
5 // Copyright (C) 2020-2023 Google, Inc.
6 //
7 // Author: Matthias Maennich
8 
9 /// @file
10 ///
11 /// This contains the definition of the symtab reader
12 
13 #include <algorithm>
14 #include <iostream>
15 #include <unordered_map>
16 #include <unordered_set>
17 
18 #include "abg-elf-helpers.h"
19 #include "abg-fwd.h"
20 #include "abg-internal.h"
21 #include "abg-tools-utils.h"
22 
23 // Though this is an internal header, we need to export the symbols to be able
24 // to test this code. TODO: find a way to export symbols just for unit tests.
25 ABG_BEGIN_EXPORT_DECLARATIONS
26 #include "abg-symtab-reader.h"
27 ABG_END_EXPORT_DECLARATIONS
28 
29 namespace abigail
30 {
31 
32 namespace symtab_reader
33 {
34 
35 /// symtab_filter implementations
36 
37 /// Determine whether a symbol is matching the filter criteria of this filter
38 /// object. In terms of a filter functionality, you would _not_ filter out
39 /// this symbol if it passes this (i.e. returns true).
40 ///
41 /// @param symbol The Elf symbol under test.
42 ///
43 /// @return whether the symbol matches all relevant / required criteria
44 bool
45 symtab_filter::matches(const elf_symbol& symbol) const
46 {
47  if (functions_ && *functions_ != symbol.is_function())
48  return false;
49  if (variables_ && *variables_ != symbol.is_variable())
50  return false;
51  if (public_symbols_ && *public_symbols_ != symbol.is_public())
52  return false;
53  if (undefined_symbols_ && *undefined_symbols_ == symbol.is_defined())
54  return false;
55  if (kernel_symbols_ && *kernel_symbols_ != symbol.is_in_ksymtab())
56  return false;
57 
58  return true;
59 }
60 
61 /// symtab implementations
62 
63 /// Obtain a suitable default filter for iterating this symtab object.
64 ///
65 /// The symtab_filter obtained is populated with some sensible default
66 /// settings, such as public_symbols(true) and kernel_symbols(true) if the
67 /// binary has been identified as Linux Kernel binary.
68 ///
69 /// @return a symtab_filter with sensible populated defaults
72 {
73  symtab_filter filter;
74  filter.set_public_symbols();
75  if (is_kernel_binary_)
76  filter.set_kernel_symbols();
77  return filter;
78 }
79 
80 /// Get a vector of symbols that are associated with a certain name
81 ///
82 /// @param name the name the symbols need to match
83 ///
84 /// @return a vector of symbols, empty if no matching symbols have been found
85 const elf_symbols&
86 symtab::lookup_symbol(const std::string& name) const
87 {
88  static const elf_symbols empty_result;
89  const auto it = name_symbol_map_.find(name);
90  if (it != name_symbol_map_.end())
91  return it->second;
92  return empty_result;
93 }
94 
95 /// Lookup a symbol by its address
96 ///
97 /// @param symbol_addr the starting address of the symbol
98 ///
99 /// @return a symbol if found, else an empty sptr
100 const elf_symbol_sptr&
101 symtab::lookup_symbol(GElf_Addr symbol_addr) const
102 {
103  static const elf_symbol_sptr empty_result;
104  const auto addr_it = addr_symbol_map_.find(symbol_addr);
105  if (addr_it != addr_symbol_map_.end())
106  return addr_it->second;
107  else
108  {
109  // check for a potential entry address mapping instead,
110  // relevant for ppc ELFv1 binaries
111  const auto entry_it = entry_addr_symbol_map_.find(symbol_addr);
112  if (entry_it != entry_addr_symbol_map_.end())
113  return entry_it->second;
114  }
115  return empty_result;
116 }
117 
118 /// Lookup an undefined function symbol with a given name.
119 ///
120 /// @param sym_name the name of the function symbol to lookup.
121 ///
122 /// @return the undefined function symbol found or nil if none was
123 /// found.
124 const elf_symbol_sptr
125 symtab::lookup_undefined_function_symbol(const std::string& sym_name)
126 {
128  f.set_variables(false);
129  f.set_public_symbols(false);
130  f.set_functions(true);
131  f.set_undefined_symbols(true);
132 
133  elf_symbol_sptr result;
134  for (auto sym : filtered_symtab(*this, f))
135  if (sym_name == sym->get_name())
136  {
137  result = sym;
138  break;
139  }
140 
141  return result;
142 }
143 
144 /// Lookup an undefined variable symbol with a given name.
145 ///
146 /// @param sym_name the name of the variable symbol to lookup.
147 ///
148 /// @return the undefined variable symbol found or nil if none was
149 /// found.
150 const elf_symbol_sptr
151 symtab::lookup_undefined_variable_symbol(const std::string& sym_name)
152 {
154  f.set_functions(false);
155  f.set_public_symbols(false);
156  f.set_undefined_symbols(true);
157  f.set_variables(true);
158 
159  elf_symbol_sptr result;
160  for (auto sym : filtered_symtab(*this, f))
161  if (sym_name == sym->get_name())
162  {
163  result = sym;
164  break;
165  }
166  return result;
167 }
168 
169 /// Test if a given function symbol has been exported.
170 ///
171 /// Note that this doesn't test if the symbol is defined or not, but
172 /// assumes the symbol is defined.
173 ///
174 /// @param name the name of the symbol we are looking for.
175 ///
176 /// @return the elf symbol if found, or nil otherwise.
179 {
180  const elf_symbols& syms = lookup_symbol(name);
181  for (auto s : syms)
182  if (s->is_function() && s->is_public())
183  return s;
184 
185  return elf_symbol_sptr();
186 }
187 
188 /// Test if a given function symbol has been exported.
189 ///
190 /// Note that this doesn't test if the symbol is defined or not, but
191 /// assumes the symbol is defined.
192 ///
193 /// @param symbol_address the address of the symbol we are looking
194 /// for. Note that this address must be a relative offset from the
195 /// beginning of the .text section, just like the kind of addresses
196 /// that are present in the .symtab section.
197 ///
198 /// @return the elf symbol if found, or nil otherwise.
200 symtab::function_symbol_is_exported(const GElf_Addr symbol_address)
201 {
202  elf_symbol_sptr symbol = lookup_symbol(symbol_address);
203  if (!symbol)
204  return symbol;
205 
206  if (!symbol->is_function() || !symbol->is_public())
207  return elf_symbol_sptr();
208 
209  return symbol;
210 }
211 
212 /// Test if a given variable symbol has been exported.
213 ///
214 /// Note that this assumes the symbol is exported but doesn't test for
215 /// it.
216 ///
217 /// @param name the name of the symbol we are looking
218 /// for.
219 ///
220 /// @return the elf symbol if found, or nil otherwise.
223 {
224  const elf_symbols& syms = lookup_symbol(name);
225  for (auto s : syms)
226  if (s->is_variable() && s->is_public())
227  return s;
228 
229  return elf_symbol_sptr();
230 }
231 
232 /// Test if a given variable symbol has been exported.
233 ///
234 /// Note that this assumes the symbol is exported but doesn't test for
235 /// it.
236 ///
237 /// @param symbol_address the address of the symbol we are looking
238 /// for. Note that this address must be a relative offset from the
239 /// beginning of the .text section, just like the kind of addresses
240 /// that are present in the .symtab section.
241 ///
242 /// @return the elf symbol if found, or nil otherwise.
244 symtab::variable_symbol_is_exported(const GElf_Addr symbol_address)
245 {
246  elf_symbol_sptr symbol = lookup_symbol(symbol_address);
247  if (!symbol)
248  return symbol;
249 
250  if (!symbol->is_variable() || !symbol->is_public())
251  return elf_symbol_sptr();
252 
253  return symbol;
254 }
255 
256 /// Test if a name is a the name of an undefined function symbol.
257 ///
258 /// @param sym_name the symbol name to consider.
259 ///
260 /// @return the undefined symbol if found, nil otherwise.
263 {
264  collect_undefined_fns_and_vars_linkage_names();
265  if (undefined_function_linkage_names_.count(sym_name))
266  {
268  ABG_ASSERT(sym);
269  ABG_ASSERT(sym->is_function());
270  ABG_ASSERT(!sym->is_defined());
271  return sym;
272  }
273  return elf_symbol_sptr();
274 }
275 
276 /// Test if a name is a the name of an undefined variable symbol.
277 ///
278 /// @param sym_name the symbol name to consider.
279 ///
280 // @return the undefined symbol if found, nil otherwise.
283 {
284  collect_undefined_fns_and_vars_linkage_names();
285  if (undefined_variable_linkage_names_.count(sym_name))
286  {
288  ABG_ASSERT(sym);
289  ABG_ASSERT(sym->is_variable());
290  ABG_ASSERT(!sym->is_defined());
291  return sym;
292  }
293  return elf_symbol_sptr();
294 }
295 
296 /// A symbol sorting functor.
297 static struct
298 {
299  bool
300  operator()(const elf_symbol_sptr& left, const elf_symbol_sptr& right)
301  {return left->get_id_string() < right->get_id_string();}
302 } symbol_sort;
303 
304 /// Construct a symtab object and instantiate it from an ELF
305 /// handle. Also pass in the ir::environment we are living in. If
306 /// specified, the symbol_predicate will be respected when creating
307 /// the full vector of symbols.
308 ///
309 /// @param elf_handle the elf handle to load the symbol table from
310 ///
311 /// @param env the environment we are operating in
312 ///
313 /// @param is_suppressed a predicate function to determine if a symbol should
314 /// be suppressed
315 ///
316 /// @return a smart pointer handle to symtab, set to nullptr if the load was
317 /// not completed
318 symtab_ptr
319 symtab::load(Elf* elf_handle,
320  const ir::environment& env,
321  symbol_predicate is_suppressed)
322 {
323  ABG_ASSERT(elf_handle);
324 
325  symtab_ptr result(new symtab);
326  if (!result->load_(elf_handle, env, is_suppressed))
327  return {};
328 
329  return result;
330 }
331 
332 /// Construct a symtab object from existing name->symbol lookup maps.
333 /// They were possibly read from a different representation (XML maybe).
334 ///
335 /// @param function_symbol_map a map from ELF function name to elf_symbol
336 ///
337 /// @param variable_symbol_map a map from ELF variable name to elf_symbol
338 ///
339 /// @return a smart pointer handle to symtab, set to nullptr if the load was
340 /// not completed
341 symtab_ptr
343  string_elf_symbols_map_sptr variables_symbol_map)
344 {
345  symtab_ptr result(new symtab);
346  if (!result->load_(function_symbol_map, variables_symbol_map))
347  return {};
348 
349  return result;
350 }
351 
352 /// Default constructor of the @ref symtab type.
353 symtab::symtab()
354  : is_kernel_binary_(false), has_ksymtab_entries_(false),
355  cached_undefined_symbol_names_(false)
356 {}
357 
358 /// Load the symtab representation from an Elf binary presented to us by an
359 /// Elf* handle.
360 ///
361 /// This method iterates over the entries of .symtab and collects all
362 /// interesting symbols (functions and variables).
363 ///
364 /// In case of a Linux Kernel binary, it also collects information about the
365 /// symbols exported via EXPORT_SYMBOL in the Kernel that would then end up
366 /// having a corresponding __ksymtab entry.
367 ///
368 /// Symbols that are suppressed will be omitted from the symbols_ vector, but
369 /// still be discoverable through the name->symbol and addr->symbol lookup
370 /// maps.
371 ///
372 /// @param elf_handle the elf handle to load the symbol table from
373 ///
374 /// @param env the environment we are operating in
375 ///
376 /// @param is_suppressed a predicate function to determine if a symbol should
377 /// be suppressed
378 ///
379 /// @return true if the load succeeded
380 bool
381 symtab::load_(Elf* elf_handle,
382  const ir::environment& env,
383  symbol_predicate is_suppressed)
384 {
385  GElf_Ehdr ehdr_mem;
386  GElf_Ehdr* header = gelf_getehdr(elf_handle, &ehdr_mem);
387  if (!header)
388  {
389  std::cerr << "Could not get ELF header: Skipping symtab load.\n";
390  return false;
391  }
392 
393  Elf_Scn* symtab_section = elf_helpers::find_symbol_table_section(elf_handle);
394  if (!symtab_section)
395  {
396  std::cerr << "No symbol table found: Skipping symtab load.\n";
397  return false;
398  }
399 
400  GElf_Shdr symtab_sheader;
401  gelf_getshdr(symtab_section, &symtab_sheader);
402 
403  // check for bogus section header
404  if (symtab_sheader.sh_entsize == 0)
405  {
406  std::cerr << "Invalid symtab header found: Skipping symtab load.\n";
407  return false;
408  }
409 
410  const size_t number_syms =
411  symtab_sheader.sh_size / symtab_sheader.sh_entsize;
412 
413  Elf_Data* symtab = elf_getdata(symtab_section, 0);
414  if (!symtab)
415  {
416  std::cerr << "Could not load elf symtab: Skipping symtab load.\n";
417  return false;
418  }
419 
420  // The __kstrtab_strings sections is basically an ELF strtab but does not
421  // support elf_strptr lookups. A single call to elf_getdata gives a handle to
422  // washed section data.
423  //
424  // The value of a __kstrtabns_FOO (or other similar) symbol is an address
425  // within the __kstrtab_strings section. To look up the string value, we need
426  // to translate from vmlinux load address to section offset by subtracting the
427  // base address of the section. This adjustment is not needed for loadable
428  // modules which are relocatable and so identifiable by ELF type ET_REL.
429  Elf_Scn* strings_section = elf_helpers::find_ksymtab_strings_section(elf_handle);
430  size_t strings_offset = 0;
431  const char* strings_data = nullptr;
432  size_t strings_size = 0;
433  if (strings_section)
434  {
435  GElf_Shdr strings_sheader;
436  gelf_getshdr(strings_section, &strings_sheader);
437  strings_offset = header->e_type == ET_REL ? 0 : strings_sheader.sh_addr;
438  Elf_Data* data = elf_getdata(strings_section, nullptr);
439  ABG_ASSERT(data->d_off == 0);
440  strings_data = reinterpret_cast<const char *>(data->d_buf);
441  strings_size = data->d_size;
442  }
443 
444  const bool is_kernel = elf_helpers::is_linux_kernel(elf_handle);
445  std::unordered_set<std::string> exported_kernel_symbols;
446  std::unordered_map<std::string, uint32_t> crc_values;
447  std::unordered_map<std::string, std::string> namespaces;
448 
449  for (size_t i = 0; i < number_syms; ++i)
450  {
451  GElf_Sym *sym, sym_mem;
452  sym = gelf_getsym(symtab, i, &sym_mem);
453  if (!sym)
454  {
455  std::cerr << "Could not load symbol with index " << i
456  << ": Skipping symtab load.\n";
457  return false;
458  }
459 
460  const char* const name_str =
461  elf_strptr(elf_handle, symtab_sheader.sh_link, sym->st_name);
462 
463  // no name, no game
464  if (!name_str)
465  continue;
466 
467  const std::string name = name_str;
468  if (name.empty())
469  continue;
470 
471  // Handle ksymtab entries. Every symbol entry that starts with __ksymtab_
472  // indicates that the symbol in question is exported through ksymtab. We
473  // do not know whether this is ksymtab_gpl or ksymtab, but that is good
474  // enough for now.
475  //
476  // We could follow up with this entry:
477  //
478  // symbol_value -> ksymtab_entry in either ksymtab_gpl or ksymtab
479  // -> addr/name/namespace (in case of PREL32: offset)
480  //
481  // That way we could also detect ksymtab<>ksymtab_gpl changes or changes
482  // of the symbol namespace.
483  //
484  // As of now this lookup is fragile, as occasionally ksymtabs are empty
485  // (seen so far for kernel modules and LTO builds). Hence we stick to the
486  // fairly safe assumption that ksymtab exported entries are having an
487  // appearence as __ksymtab_<symbol> in the symtab.
488  if (is_kernel && name.rfind("__ksymtab_", 0) == 0)
489  {
490  ABG_ASSERT(exported_kernel_symbols.insert(name.substr(10)).second);
491  continue;
492  }
493  if (is_kernel && name.rfind("__crc_", 0) == 0)
494  {
495  uint32_t crc_value;
496  ABG_ASSERT(elf_helpers::get_crc_for_symbol(elf_handle,
497  sym, crc_value));
498  ABG_ASSERT(crc_values.emplace(name.substr(6), crc_value).second);
499  continue;
500  }
501  if (strings_section && is_kernel && name.rfind("__kstrtabns_", 0) == 0)
502  {
503  // This symbol lives in the __ksymtab_strings section but st_value may
504  // be a vmlinux load address so we need to subtract the offset before
505  // looking it up in that section.
506  const size_t value = sym->st_value;
507  const size_t offset = value - strings_offset;
508  // check offset
509  ABG_ASSERT(offset < strings_size);
510  // find the terminating NULL
511  const char* first = strings_data + offset;
512  const char* last = strings_data + strings_size;
513  const char* limit = std::find(first, last, 0);
514  // check NULL found
515  ABG_ASSERT(limit < last);
516  // interpret the empty namespace name as no namespace name
517  if (first < limit)
518  ABG_ASSERT(namespaces.emplace(
519  name.substr(12), std::string(first, limit - first)).second);
520  continue;
521  }
522 
523  // filter out uninteresting entries and only keep functions/variables for
524  // now. The rest might be interesting in the future though.
525  const int sym_type = GELF_ST_TYPE(sym->st_info);
526  if (!(sym_type == STT_FUNC
527  || sym_type == STT_GNU_IFUNC
528  // If the symbol is for an OBJECT, the index of the
529  // section it refers to cannot be absolute.
530  // Otherwise that OBJECT is not a variable.
531  || (sym_type == STT_OBJECT && sym->st_shndx != SHN_ABS)
532  // Undefined global variable symbols have symbol type
533  // STT_NOTYPE. No idea why.
534  || (sym_type == STT_NOTYPE && sym->st_shndx == SHN_UNDEF)
535  || sym_type == STT_TLS))
536  continue;
537 
538  const bool sym_is_defined = sym->st_shndx != SHN_UNDEF;
539  // this occurs in relocatable files.
540  const bool sym_is_common = sym->st_shndx == SHN_COMMON;
541 
542  elf_symbol::version ver;
543  elf_helpers::get_version_for_symbol(elf_handle, i, sym_is_defined, ver);
544 
545  const elf_symbol_sptr& symbol_sptr =
547  (env, i, sym->st_size, name,
548  elf_helpers::stt_to_elf_symbol_type(GELF_ST_TYPE(sym->st_info)),
549  elf_helpers::stb_to_elf_symbol_binding(GELF_ST_BIND(sym->st_info)),
550  sym_is_defined, sym_is_common, ver,
551  elf_helpers::stv_to_elf_symbol_visibility
552  (GELF_ST_VISIBILITY(sym->st_other)));
553 
554  // We do not take suppressed symbols into our symbol vector to avoid
555  // accidental leakage. But we ensure supressed symbols are otherwise set
556  // up for lookup.
557  if (!(is_suppressed && is_suppressed(symbol_sptr)))
558  // add to the symbol vector
559  symbols_.push_back(symbol_sptr);
560  else
561  symbol_sptr->set_is_suppressed(true);
562 
563  // add to the name->symbol lookup
564  name_symbol_map_[name].push_back(symbol_sptr);
565 
566  // add to the addr->symbol lookup
567  if (symbol_sptr->is_common_symbol())
568  {
569  const auto it = name_symbol_map_.find(name);
570  ABG_ASSERT(it != name_symbol_map_.end());
571  const elf_symbols& common_sym_instances = it->second;
572  ABG_ASSERT(!common_sym_instances.empty());
573  if (common_sym_instances.size() > 1)
574  {
575  elf_symbol_sptr main_common_sym = common_sym_instances[0];
576  ABG_ASSERT(main_common_sym->get_name() == name);
577  ABG_ASSERT(main_common_sym->is_common_symbol());
578  ABG_ASSERT(symbol_sptr.get() != main_common_sym.get());
579  main_common_sym->add_common_instance(symbol_sptr);
580  }
581  }
582  else if (symbol_sptr->is_defined())
583  setup_symbol_lookup_tables(elf_handle, sym, symbol_sptr);
584  }
585 
586  add_alternative_address_lookups(elf_handle);
587 
588  is_kernel_binary_ = elf_helpers::is_linux_kernel(elf_handle);
589 
590  // Now apply the ksymtab_exported attribute to the symbols we collected.
591  for (const auto& symbol : exported_kernel_symbols)
592  {
593  const auto r = name_symbol_map_.find(symbol);
594  if (r == name_symbol_map_.end())
595  continue;
596 
597  for (const auto& elf_symbol : r->second)
598  if (elf_symbol->is_public())
599  elf_symbol->set_is_in_ksymtab(true);
600  has_ksymtab_entries_ = true;
601  }
602 
603  // Now add the CRC values
604  for (const auto& crc_entry : crc_values)
605  {
606  const auto r = name_symbol_map_.find(crc_entry.first);
607  if (r == name_symbol_map_.end())
608  continue;
609 
610  for (const auto& symbol : r->second)
611  symbol->set_crc(crc_entry.second);
612  }
613 
614  // Now add the namespaces
615  for (const auto& namespace_entry : namespaces)
616  {
617  const auto r = name_symbol_map_.find(namespace_entry.first);
618  if (r == name_symbol_map_.end())
619  continue;
620 
621  for (const auto& symbol : r->second)
622  symbol->set_namespace(namespace_entry.second);
623  }
624 
625  // sort the symbols for deterministic output
626  std::sort(symbols_.begin(), symbols_.end(), symbol_sort);
627 
628  return true;
629 }
630 
631 /// Load the symtab representation from a function/variable lookup map pair.
632 ///
633 /// This method assumes the lookup maps are correct and sets up the data
634 /// vector as well as the name->symbol lookup map. The addr->symbol lookup
635 /// map cannot be set up in this case.
636 ///
637 /// @param function_symbol_map a map from ELF function name to elf_symbol
638 ///
639 /// @param variable_symbol_map a map from ELF variable name to elf_symbol
640 ///
641 /// @return true if the load succeeded
642 bool
643 symtab::load_(string_elf_symbols_map_sptr function_symbol_map,
644  string_elf_symbols_map_sptr variables_symbol_map)
645 
646 {
647  if (function_symbol_map)
648  for (const auto& symbol_map_entry : *function_symbol_map)
649  {
650  for (const auto& symbol : symbol_map_entry.second)
651  {
652  if (!symbol->is_suppressed())
653  symbols_.push_back(symbol);
654  }
655  ABG_ASSERT(name_symbol_map_.insert(symbol_map_entry).second);
656  }
657 
658  if (variables_symbol_map)
659  for (const auto& symbol_map_entry : *variables_symbol_map)
660  {
661  for (const auto& symbol : symbol_map_entry.second)
662  {
663  if (!symbol->is_suppressed())
664  symbols_.push_back(symbol);
665  }
666  ABG_ASSERT(name_symbol_map_.insert(symbol_map_entry).second);
667  }
668 
669  // sort the symbols for deterministic output
670  std::sort(symbols_.begin(), symbols_.end(), symbol_sort);
671 
672  return true;
673 }
674 
675 /// Notify the symtab about the name of the main symbol at a given address.
676 ///
677 /// From just alone the symtab we can't guess the main symbol of a bunch of
678 /// aliased symbols that all point to the same address. During processing of
679 /// additional information (such as DWARF), this information becomes apparent
680 /// and we can adjust the addr->symbol lookup map as well as the alias
681 /// reference of the symbol objects.
682 ///
683 /// @param addr the addr that we are updating the main symbol for
684 /// @param name the name of the main symbol
685 void
686 symtab::update_main_symbol(GElf_Addr addr, const std::string& name)
687 {
688  // get one symbol (i.e. the current main symbol)
689  elf_symbol_sptr symbol = lookup_symbol(addr);
690 
691  // The caller might not know whether the addr is associated to an ELF symbol
692  // that we care about. E.g. the addr could be associated to an ELF symbol,
693  // but not one in .dynsym when looking at a DSO. Hence, early exit if the
694  // lookup failed.
695  if (!symbol)
696  return;
697 
698  // determine the new main symbol by attempting an update
699  elf_symbol_sptr new_main = symbol->update_main_symbol(name);
700 
701  // also update the default symbol we return when looked up by address
702  if (new_main)
703  addr_symbol_map_[addr] = new_main;
704 }
705 
706 /// Various adjustments and bookkeeping may be needed to provide a correct
707 /// interpretation (one that matches DWARF addresses) of raw symbol values.
708 ///
709 /// This is a sub-routine for symtab::load_and
710 /// symtab::add_alternative_address_lookups and must be called only
711 /// once (per symbol) during the execution of the former.
712 ///
713 /// @param elf_handle the ELF handle
714 ///
715 /// @param elf_symbol the ELF symbol
716 ///
717 /// @param symbol_sptr the libabigail symbol
718 ///
719 /// @return a possibly-adjusted symbol value
720 GElf_Addr
721 symtab::setup_symbol_lookup_tables(Elf* elf_handle,
722  GElf_Sym* elf_symbol,
723  const elf_symbol_sptr& symbol_sptr)
724 {
725  const bool is_arm32 = elf_helpers::architecture_is_arm32(elf_handle);
726  const bool is_arm64 = elf_helpers::architecture_is_arm64(elf_handle);
727  const bool is_ppc64 = elf_helpers::architecture_is_ppc64(elf_handle);
728  const bool is_ppc32 = elf_helpers::architecture_is_ppc32(elf_handle);
729 
730  GElf_Addr symbol_value =
731  elf_helpers::maybe_adjust_et_rel_sym_addr_to_abs_addr(elf_handle,
732  elf_symbol);
733 
734  if (is_arm32 && symbol_sptr->is_function())
735  // Clear bit zero of ARM32 addresses as per "ELF for the Arm
736  // Architecture" section 5.5.3.
737  // https://static.docs.arm.com/ihi0044/g/aaelf32.pdf
738  symbol_value &= ~1;
739 
740  if (is_arm64)
741  // Copy bit 55 over bits 56 to 63 which may be tag information.
742  symbol_value = symbol_value & (1ULL<<55)
743  ? symbol_value | (0xffULL<<56)
744  : symbol_value &~ (0xffULL<<56);
745 
746  if (symbol_sptr->is_defined())
747  {
748  const auto result =
749  addr_symbol_map_.emplace(symbol_value, symbol_sptr);
750  if (!result.second)
751  // A symbol with the same address already exists. This
752  // means this symbol is an alias of the main symbol with
753  // that address. So let's register this new alias as such.
754  result.first->second->get_main_symbol()->add_alias(symbol_sptr);
755  }
756 
757  // Please note that update_function_entry_address_symbol_map depends
758  // on the symbol aliases been setup. This is why, the
759  // elf_symbol::add_alias call is done above BEFORE this point.
760  if ((is_ppc64 || is_ppc32) && symbol_sptr->is_function())
761  update_function_entry_address_symbol_map(elf_handle, elf_symbol,
762  symbol_sptr);
763 
764  return symbol_value;
765 }
766 
767 /// Update the function entry symbol map to later allow lookups of this symbol
768 /// by entry address as well. This is relevant for ppc64 ELFv1 binaries.
769 ///
770 /// For ppc64 ELFv1 binaries, we need to build a function entry point address
771 /// -> function symbol map. This is in addition to the function pointer ->
772 /// symbol map. This is because on ppc64 ELFv1, a function pointer is
773 /// different from a function entry point address.
774 ///
775 /// On ppc64 ELFv1, the DWARF DIE of a function references the address of the
776 /// entry point of the function symbol; whereas the value of the function
777 /// symbol is the function pointer. As these addresses are different, if I we
778 /// want to get to the symbol of a function from its entry point address (as
779 /// referenced by DWARF function DIEs) we must have the two maps I mentionned
780 /// right above.
781 ///
782 /// In other words, we need a map that associates a function entry point
783 /// address with the symbol of that function, to be able to get the function
784 /// symbol that corresponds to a given function DIE, on ppc64.
785 ///
786 /// The value of the function pointer (the value of the symbol) usually refers
787 /// to the offset of a table in the .opd section. But sometimes, for a symbol
788 /// named "foo", the corresponding symbol named ".foo" (note the dot before
789 /// foo) which value is the entry point address of the function; that entry
790 /// point address refers to a region in the .text section.
791 ///
792 /// So we are only interested in values of the symbol that are in the .opd
793 /// section.
794 ///
795 /// @param elf_handle the ELF handle to operate on
796 ///
797 /// @param native_symbol the native Elf symbol to update the entry for
798 ///
799 /// @param symbol_sptr the internal symbol to associte the entry address with
800 void
801 symtab::update_function_entry_address_symbol_map(
802  Elf* elf_handle, GElf_Sym* native_symbol, const elf_symbol_sptr& symbol_sptr)
803 {
804  const GElf_Addr fn_desc_addr = native_symbol->st_value;
805  const GElf_Addr fn_entry_point_addr =
806  elf_helpers::lookup_ppc64_elf_fn_entry_point_address(elf_handle,
807  fn_desc_addr);
808 
809  const std::pair<addr_symbol_map_type::const_iterator, bool>& result =
810  entry_addr_symbol_map_.emplace(fn_entry_point_addr, symbol_sptr);
811 
812  const addr_symbol_map_type::const_iterator it = result.first;
813  const bool was_inserted = result.second;
814  if (!was_inserted
815  && elf_helpers::address_is_in_opd_section(elf_handle, fn_desc_addr))
816  {
817  // Either
818  //
819  // 'symbol' must have been registered as an alias for
820  // it->second->get_main_symbol()
821  //
822  // Or
823  //
824  // if the name of 'symbol' is foo, then the name of it2->second is
825  // ".foo". That is, foo is the name of the symbol when it refers to the
826  // function descriptor in the .opd section and ".foo" is an internal name
827  // for the address of the entry point of foo.
828  //
829  // In the latter case, we just want to keep a reference to "foo" as .foo
830  // is an internal name.
831 
832  const bool two_symbols_alias =
833  it->second->get_main_symbol()->does_alias(*symbol_sptr);
834  const bool symbol_is_foo_and_prev_symbol_is_dot_foo =
835  (it->second->get_name() == std::string(".") + symbol_sptr->get_name());
836 
837  ABG_ASSERT(two_symbols_alias
838  || symbol_is_foo_and_prev_symbol_is_dot_foo);
839 
840  if (symbol_is_foo_and_prev_symbol_is_dot_foo)
841  // Let's just keep a reference of the symbol that the user sees in the
842  // source code (the one named foo). The symbol which name is prefixed
843  // with a "dot" is an artificial one.
844  entry_addr_symbol_map_[fn_entry_point_addr] = symbol_sptr;
845  }
846 }
847 
848 /// Fill up the lookup maps with alternative keys
849 ///
850 /// Due to special features like Control-Flow-Integrity (CFI), the symbol
851 /// lookup could be done indirectly. E.g. enabling CFI causes clang to
852 /// associate the DWARF information with the actual CFI protected function
853 /// (suffix .cfi) instead of with the entry symbol in the symtab.
854 ///
855 /// This function adds additional lookup keys to compensate for that.
856 ///
857 /// So far, this only implements CFI support, by adding addr->symbol pairs
858 /// where
859 /// addr : symbol value of the <foo>.cfi value
860 /// symbol : symbol_sptr looked up via "<foo>"
861 ///
862 /// @param elf_handle the ELF handle to operate on
863 void
864 symtab::add_alternative_address_lookups(Elf* elf_handle)
865 {
866  Elf_Scn* symtab_section = elf_helpers::find_symtab_section(elf_handle);
867  if (!symtab_section)
868  return;
869  GElf_Shdr symtab_sheader;
870  gelf_getshdr(symtab_section, &symtab_sheader);
871 
872  const size_t number_syms =
873  symtab_sheader.sh_size / symtab_sheader.sh_entsize;
874 
875  Elf_Data* symtab = elf_getdata(symtab_section, 0);
876 
877  for (size_t i = 0; i < number_syms; ++i)
878  {
879  GElf_Sym *sym, sym_mem;
880  sym = gelf_getsym(symtab, i, &sym_mem);
881  if (!sym)
882  {
883  std::cerr << "Could not load symbol with index " << i
884  << ": Skipping alternative symbol load.\n";
885  continue;
886  }
887 
888  const char* const name_str =
889  elf_strptr(elf_handle, symtab_sheader.sh_link, sym->st_name);
890 
891  // no name, no game
892  if (!name_str)
893  continue;
894 
895  const std::string name = name_str;
896  if (name.empty())
897  continue;
898 
899  // Add alternative lookup addresses for CFI symbols
900  static const std::string cfi = ".cfi";
901  if (name.size() > cfi.size()
902  && name.compare(name.size() - cfi.size(), cfi.size(), cfi) == 0)
903  // ... name.ends_with(".cfi")
904  {
905  const auto candidate_name = name.substr(0, name.size() - cfi.size());
906 
907  auto symbols = lookup_symbol(candidate_name);
908  // lookup_symbol returns a vector of symbols. For this case we handle
909  // only the case that there has been exactly one match. Otherwise we
910  // can't reasonably handle it and need to bail out.
911  ABG_ASSERT(symbols.size() <= 1);
912  if (symbols.size() == 1)
913  {
914  const auto& symbol_sptr = symbols[0];
915  setup_symbol_lookup_tables(elf_handle, sym, symbol_sptr);
916  }
917  }
918  }
919 }
920 
921 /// Collect the names of the variable and function symbols that are
922 /// undefined. Cache those names into sets to speed up their lookup.
923 ///
924 /// Once the names are cached into sets, subsequent invocations of
925 /// this function are essentially a no-op.
926 void
927 symtab::collect_undefined_fns_and_vars_linkage_names()
928 {
929  if (!cached_undefined_symbol_names_)
930  {
931  {
932  symtab_filter f = make_filter();
933  f.set_variables(false);
934  f.set_functions(true);
935  f.set_public_symbols(false);
936  f.set_undefined_symbols(true);
937  for (auto sym : filtered_symtab(*this, f))
938  undefined_function_linkage_names_.insert(sym->get_name());
939  }
940 
941  {
942  symtab_filter f = make_filter();
943  f.set_variables(true);
944  f.set_functions(false);
945  f.set_public_symbols(false);
946  f.set_undefined_symbols(true);
947  for (auto sym : filtered_symtab(*this, f))
948  undefined_variable_linkage_names_.insert(sym->get_name());
949  }
950  }
951  cached_undefined_symbol_names_ = true;
952 }
953 } // end namespace symtab_reader
954 } // end namespace abigail
This contains a set of ELF utilities used by the dwarf reader.
#define ABG_ASSERT(cond)
This is a wrapper around the 'assert' glibc call. It allows for its argument to have side effects,...
Definition: abg-fwd.h:1714
This contains the declarations for the symtab reader.
Abstraction of an elf symbol.
Definition: abg-ir.h:923
bool is_variable() const
Test if the current instance of elf_symbol is a variable symbol or not.
Definition: abg-ir.cc:2211
bool is_function() const
Test if the current instance of elf_symbol is a function symbol or not.
Definition: abg-ir.cc:2202
static elf_symbol_sptr create(const environment &e, size_t i, size_t s, const string &n, type t, binding b, bool d, bool c, const version &ve, visibility vi, bool is_in_ksymtab=false, const abg_compat::optional< uint32_t > &crc={}, const abg_compat::optional< std::string > &ns={}, bool is_suppressed=false)
Factory of instances of elf_symbol.
Definition: abg-ir.cc:1994
bool is_public() const
Test if the current instance of elf_symbol is public or not.
Definition: abg-ir.cc:2186
bool is_in_ksymtab() const
Getter of the 'is-in-ksymtab' property.
Definition: abg-ir.cc:2225
bool is_defined() const
Test if the current instance of elf_symbol is defined or not.
Definition: abg-ir.cc:2164
This is an abstraction of the set of resources necessary to manage several aspects of the internal re...
Definition: abg-ir.h:140
Helper class to allow range-for loops on symtabs for C++11 and later code. It serves as a proxy for t...
The symtab filter is the object passed to the symtab object in order to iterate over the symbols in t...
void set_public_symbols(bool new_value=true)
Enable or disable public symbol filtering.
bool matches(const elf_symbol &symbol) const
symtab_filter implementations
void set_functions(bool new_value=true)
Enable or disable function filtering.
void set_kernel_symbols(bool new_value=true)
Enable or disable kernel symbol filtering.
void set_variables(bool new_value=true)
Enable or disable variable filtering.
void set_undefined_symbols(bool new_value=true)
Enable or disable undefined symbol filtering.
symtab is the actual data container of the symtab_reader implementation.
const elf_symbol_sptr lookup_undefined_variable_symbol(const std::string &name)
Lookup an undefined variable symbol with a given name.
const elf_symbols & lookup_symbol(const std::string &name) const
Get a vector of symbols that are associated with a certain name.
symtab_filter make_filter() const
symtab implementations
static symtab_ptr load(Elf *elf_handle, const ir::environment &env, symbol_predicate is_suppressed=NULL)
Construct a symtab object and instantiate it from an ELF handle. Also pass in the ir::environment we ...
elf_symbol_sptr function_symbol_is_undefined(const string &)
Test if a name is a the name of an undefined function symbol.
elf_symbol_sptr variable_symbol_is_undefined(const string &)
Test if a name is a the name of an undefined variable symbol.
elf_symbol_sptr function_symbol_is_exported(const string &)
Test if a given function symbol has been exported.
elf_symbol_sptr variable_symbol_is_exported(const string &)
Test if a given variable symbol has been exported.
const elf_symbol_sptr lookup_undefined_function_symbol(const std::string &name)
Lookup an undefined function symbol with a given name.
void update_main_symbol(GElf_Addr addr, const std::string &name)
Notify the symtab about the name of the main symbol at a given address.
shared_ptr< elf_symbol > elf_symbol_sptr
A convenience typedef for a shared pointer to elf_symbol.
Definition: abg-ir.h:886
std::vector< elf_symbol_sptr > elf_symbols
Convenience typedef for a vector of elf_symbol.
Definition: abg-ir.h:904
shared_ptr< string_elf_symbols_map_type > string_elf_symbols_map_sptr
Convenience typedef for a shared pointer to string_elf_symbols_map_type.
Definition: abg-ir.h:913
Toplevel namespace for libabigail.