ELFSectionHeaderTable.hxx revision c40d8a8b26547ab9c51792d9d9b3aca13fb5cdf9
1#ifndef ELF_SECTION_HEADER_TABLE_HXX
2#define ELF_SECTION_HEADER_TABLE_HXX
3
4#include "ELFHeader.h"
5#include "ELFObject.h"
6#include "ELFSectionHeader.h"
7
8#include "utils/rsl_assert.h"
9
10template <unsigned Bitwidth>
11ELFSectionHeaderTable<Bitwidth>::~ELFSectionHeaderTable() {
12  for (size_t i = 0; i < table.size(); ++i) {
13    delete table[i];
14  }
15}
16
17template <unsigned Bitwidth>
18template <typename Archiver>
19inline ELFSectionHeaderTable<Bitwidth> *
20ELFSectionHeaderTable<Bitwidth>::read(Archiver &AR, ELFObjectTy *owner) {
21  if (!AR) {
22    // Archiver is in bad state before calling read function.
23    // Return NULL and do nothing.
24    return 0;
25  }
26
27  // Allocate a new section header table and assign the owner.
28  llvm::OwningPtr<ELFSectionHeaderTable> tab(new ELFSectionHeaderTable());
29
30  // Get ELF header
31  ELFHeaderTy const *header = owner->getHeader();
32
33  rsl_assert(header->getSectionHeaderEntrySize() ==
34         TypeTraits<ELFSectionHeaderTy>::size);
35
36  // Seek to the address of section header
37  AR.seek(header->getSectionHeaderTableOffset(), true);
38
39  for (size_t i = 0; i < header->getSectionHeaderNum(); ++i) {
40    llvm::OwningPtr<ELFSectionHeaderTy> sh(
41      ELFSectionHeaderTy::read(AR, owner, i));
42
43    if (!sh) {
44      // Something wrong while reading the section header.
45      return 0;
46    }
47
48    tab->table.push_back(sh.take());
49  }
50
51  return tab.take();
52}
53
54template <unsigned Bitwidth>
55inline void ELFSectionHeaderTable<Bitwidth>::print() const {
56  using namespace llvm;
57
58  out() << '\n' << fillformat('=', 79) << '\n';
59  out().changeColor(raw_ostream::WHITE, true);
60  out() << "ELF Section Header Table" << '\n';
61  out().resetColor();
62
63  for (size_t i = 0; i < table.size(); ++i) {
64    (*this)[i]->print();
65  }
66
67  out() << fillformat('=', 79) << '\n';
68}
69
70template <unsigned Bitwidth>
71inline ELFSectionHeader<Bitwidth> const *
72ELFSectionHeaderTable<Bitwidth>::getByName(const std::string &str) const {
73  // TODO: Use map
74  for (size_t i = 0; i < table.size(); ++i) {
75    if (str == std::string(table[i]->getName())) {
76      return table[i];
77    }
78  }
79  // Return SHN_UNDEF section header;
80  return table[0];
81}
82
83template <unsigned Bitwidth>
84inline ELFSectionHeader<Bitwidth> *
85ELFSectionHeaderTable<Bitwidth>::getByName(const std::string &str) {
86  ELFSectionHeaderTableTy const *const_this = this;
87  ELFSectionHeaderTy const *shptr = const_this->getByName(str);
88  // Const cast for the same API's const and non-const versions.
89  return const_cast<ELFSectionHeaderTy *>(shptr);
90}
91
92#endif // ELF_SECTION_HEADER_TABLE_HXX
93