1 //===- ELFTypes.h - Endian specific types for ELF ---------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #ifndef LLVM_OBJECT_ELFTYPES_H
10 #define LLVM_OBJECT_ELFTYPES_H
11 
12 #include "llvm/ADT/ArrayRef.h"
13 #include "llvm/ADT/StringRef.h"
14 #include "llvm/BinaryFormat/ELF.h"
15 #include "llvm/Object/Error.h"
16 #include "llvm/Support/Endian.h"
17 #include "llvm/Support/Error.h"
18 #include <cassert>
19 #include <cstdint>
20 #include <cstring>
21 #include <type_traits>
22 
23 namespace llvm {
24 namespace object {
25 
26 using support::endianness;
27 
28 template <class ELFT> struct Elf_Ehdr_Impl;
29 template <class ELFT> struct Elf_Shdr_Impl;
30 template <class ELFT> struct Elf_Sym_Impl;
31 template <class ELFT> struct Elf_Dyn_Impl;
32 template <class ELFT> struct Elf_Phdr_Impl;
33 template <class ELFT, bool isRela> struct Elf_Rel_Impl;
34 template <class ELFT> struct Elf_Verdef_Impl;
35 template <class ELFT> struct Elf_Verdaux_Impl;
36 template <class ELFT> struct Elf_Verneed_Impl;
37 template <class ELFT> struct Elf_Vernaux_Impl;
38 template <class ELFT> struct Elf_Versym_Impl;
39 template <class ELFT> struct Elf_Hash_Impl;
40 template <class ELFT> struct Elf_GnuHash_Impl;
41 template <class ELFT> struct Elf_Chdr_Impl;
42 template <class ELFT> struct Elf_Nhdr_Impl;
43 template <class ELFT> class Elf_Note_Impl;
44 template <class ELFT> class Elf_Note_Iterator_Impl;
45 template <class ELFT> struct Elf_CGProfile_Impl;
46 
47 template <endianness E, bool Is64> struct ELFType {
48 private:
49   template <typename Ty>
50   using packed = support::detail::packed_endian_specific_integral<Ty, E, 1>;
51 
52 public:
53   static const endianness TargetEndianness = E;
54   static const bool Is64Bits = Is64;
55 
56   using uint = std::conditional_t<Is64, uint64_t, uint32_t>;
57   using Ehdr = Elf_Ehdr_Impl<ELFType<E, Is64>>;
58   using Shdr = Elf_Shdr_Impl<ELFType<E, Is64>>;
59   using Sym = Elf_Sym_Impl<ELFType<E, Is64>>;
60   using Dyn = Elf_Dyn_Impl<ELFType<E, Is64>>;
61   using Phdr = Elf_Phdr_Impl<ELFType<E, Is64>>;
62   using Rel = Elf_Rel_Impl<ELFType<E, Is64>, false>;
63   using Rela = Elf_Rel_Impl<ELFType<E, Is64>, true>;
64   using Relr = packed<uint>;
65   using Verdef = Elf_Verdef_Impl<ELFType<E, Is64>>;
66   using Verdaux = Elf_Verdaux_Impl<ELFType<E, Is64>>;
67   using Verneed = Elf_Verneed_Impl<ELFType<E, Is64>>;
68   using Vernaux = Elf_Vernaux_Impl<ELFType<E, Is64>>;
69   using Versym = Elf_Versym_Impl<ELFType<E, Is64>>;
70   using Hash = Elf_Hash_Impl<ELFType<E, Is64>>;
71   using GnuHash = Elf_GnuHash_Impl<ELFType<E, Is64>>;
72   using Chdr = Elf_Chdr_Impl<ELFType<E, Is64>>;
73   using Nhdr = Elf_Nhdr_Impl<ELFType<E, Is64>>;
74   using Note = Elf_Note_Impl<ELFType<E, Is64>>;
75   using NoteIterator = Elf_Note_Iterator_Impl<ELFType<E, Is64>>;
76   using CGProfile = Elf_CGProfile_Impl<ELFType<E, Is64>>;
77   using DynRange = ArrayRef<Dyn>;
78   using ShdrRange = ArrayRef<Shdr>;
79   using SymRange = ArrayRef<Sym>;
80   using RelRange = ArrayRef<Rel>;
81   using RelaRange = ArrayRef<Rela>;
82   using RelrRange = ArrayRef<Relr>;
83   using PhdrRange = ArrayRef<Phdr>;
84 
85   using Half = packed<uint16_t>;
86   using Word = packed<uint32_t>;
87   using Sword = packed<int32_t>;
88   using Xword = packed<uint64_t>;
89   using Sxword = packed<int64_t>;
90   using Addr = packed<uint>;
91   using Off = packed<uint>;
92 };
93 
94 using ELF32LE = ELFType<support::little, false>;
95 using ELF32BE = ELFType<support::big, false>;
96 using ELF64LE = ELFType<support::little, true>;
97 using ELF64BE = ELFType<support::big, true>;
98 
99 // Use an alignment of 2 for the typedefs since that is the worst case for
100 // ELF files in archives.
101 
102 // I really don't like doing this, but the alternative is copypasta.
103 #define LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)                                       \
104   using Elf_Addr = typename ELFT::Addr;                                        \
105   using Elf_Off = typename ELFT::Off;                                          \
106   using Elf_Half = typename ELFT::Half;                                        \
107   using Elf_Word = typename ELFT::Word;                                        \
108   using Elf_Sword = typename ELFT::Sword;                                      \
109   using Elf_Xword = typename ELFT::Xword;                                      \
110   using Elf_Sxword = typename ELFT::Sxword;
111 
112 #define LLVM_ELF_COMMA ,
113 #define LLVM_ELF_IMPORT_TYPES(E, W)                                            \
114   LLVM_ELF_IMPORT_TYPES_ELFT(ELFType<E LLVM_ELF_COMMA W>)
115 
116 // Section header.
117 template <class ELFT> struct Elf_Shdr_Base;
118 
119 template <endianness TargetEndianness>
120 struct Elf_Shdr_Base<ELFType<TargetEndianness, false>> {
121   LLVM_ELF_IMPORT_TYPES(TargetEndianness, false)
122   Elf_Word sh_name;      // Section name (index into string table)
123   Elf_Word sh_type;      // Section type (SHT_*)
124   Elf_Word sh_flags;     // Section flags (SHF_*)
125   Elf_Addr sh_addr;      // Address where section is to be loaded
126   Elf_Off sh_offset;     // File offset of section data, in bytes
127   Elf_Word sh_size;      // Size of section, in bytes
128   Elf_Word sh_link;      // Section type-specific header table index link
129   Elf_Word sh_info;      // Section type-specific extra information
130   Elf_Word sh_addralign; // Section address alignment
131   Elf_Word sh_entsize;   // Size of records contained within the section
132 };
133 
134 template <endianness TargetEndianness>
135 struct Elf_Shdr_Base<ELFType<TargetEndianness, true>> {
136   LLVM_ELF_IMPORT_TYPES(TargetEndianness, true)
137   Elf_Word sh_name;       // Section name (index into string table)
138   Elf_Word sh_type;       // Section type (SHT_*)
139   Elf_Xword sh_flags;     // Section flags (SHF_*)
140   Elf_Addr sh_addr;       // Address where section is to be loaded
141   Elf_Off sh_offset;      // File offset of section data, in bytes
142   Elf_Xword sh_size;      // Size of section, in bytes
143   Elf_Word sh_link;       // Section type-specific header table index link
144   Elf_Word sh_info;       // Section type-specific extra information
145   Elf_Xword sh_addralign; // Section address alignment
146   Elf_Xword sh_entsize;   // Size of records contained within the section
147 };
148 
149 template <class ELFT>
150 struct Elf_Shdr_Impl : Elf_Shdr_Base<ELFT> {
151   using Elf_Shdr_Base<ELFT>::sh_entsize;
152   using Elf_Shdr_Base<ELFT>::sh_size;
153 
154   /// Get the number of entities this section contains if it has any.
155   unsigned getEntityCount() const {
156     if (sh_entsize == 0)
157       return 0;
158     return sh_size / sh_entsize;
159   }
160 };
161 
162 template <class ELFT> struct Elf_Sym_Base;
163 
164 template <endianness TargetEndianness>
165 struct Elf_Sym_Base<ELFType<TargetEndianness, false>> {
166   LLVM_ELF_IMPORT_TYPES(TargetEndianness, false)
167   Elf_Word st_name;       // Symbol name (index into string table)
168   Elf_Addr st_value;      // Value or address associated with the symbol
169   Elf_Word st_size;       // Size of the symbol
170   unsigned char st_info;  // Symbol's type and binding attributes
171   unsigned char st_other; // Must be zero; reserved
172   Elf_Half st_shndx;      // Which section (header table index) it's defined in
173 };
174 
175 template <endianness TargetEndianness>
176 struct Elf_Sym_Base<ELFType<TargetEndianness, true>> {
177   LLVM_ELF_IMPORT_TYPES(TargetEndianness, true)
178   Elf_Word st_name;       // Symbol name (index into string table)
179   unsigned char st_info;  // Symbol's type and binding attributes
180   unsigned char st_other; // Must be zero; reserved
181   Elf_Half st_shndx;      // Which section (header table index) it's defined in
182   Elf_Addr st_value;      // Value or address associated with the symbol
183   Elf_Xword st_size;      // Size of the symbol
184 };
185 
186 template <class ELFT>
187 struct Elf_Sym_Impl : Elf_Sym_Base<ELFT> {
188   using Elf_Sym_Base<ELFT>::st_info;
189   using Elf_Sym_Base<ELFT>::st_shndx;
190   using Elf_Sym_Base<ELFT>::st_other;
191   using Elf_Sym_Base<ELFT>::st_value;
192 
193   // These accessors and mutators correspond to the ELF32_ST_BIND,
194   // ELF32_ST_TYPE, and ELF32_ST_INFO macros defined in the ELF specification:
195   unsigned char getBinding() const { return st_info >> 4; }
196   unsigned char getType() const { return st_info & 0x0f; }
197   uint64_t getValue() const { return st_value; }
198   void setBinding(unsigned char b) { setBindingAndType(b, getType()); }
199   void setType(unsigned char t) { setBindingAndType(getBinding(), t); }
200 
201   void setBindingAndType(unsigned char b, unsigned char t) {
202     st_info = (b << 4) + (t & 0x0f);
203   }
204 
205   /// Access to the STV_xxx flag stored in the first two bits of st_other.
206   /// STV_DEFAULT: 0
207   /// STV_INTERNAL: 1
208   /// STV_HIDDEN: 2
209   /// STV_PROTECTED: 3
210   unsigned char getVisibility() const { return st_other & 0x3; }
211   void setVisibility(unsigned char v) {
212     assert(v < 4 && "Invalid value for visibility");
213     st_other = (st_other & ~0x3) | v;
214   }
215 
216   bool isAbsolute() const { return st_shndx == ELF::SHN_ABS; }
217 
218   bool isCommon() const {
219     return getType() == ELF::STT_COMMON || st_shndx == ELF::SHN_COMMON;
220   }
221 
222   bool isDefined() const { return !isUndefined(); }
223 
224   bool isProcessorSpecific() const {
225     return st_shndx >= ELF::SHN_LOPROC && st_shndx <= ELF::SHN_HIPROC;
226   }
227 
228   bool isOSSpecific() const {
229     return st_shndx >= ELF::SHN_LOOS && st_shndx <= ELF::SHN_HIOS;
230   }
231 
232   bool isReserved() const {
233     // ELF::SHN_HIRESERVE is 0xffff so st_shndx <= ELF::SHN_HIRESERVE is always
234     // true and some compilers warn about it.
235     return st_shndx >= ELF::SHN_LORESERVE;
236   }
237 
238   bool isUndefined() const { return st_shndx == ELF::SHN_UNDEF; }
239 
240   bool isExternal() const {
241     return getBinding() != ELF::STB_LOCAL;
242   }
243 
244   Expected<StringRef> getName(StringRef StrTab) const;
245 };
246 
247 template <class ELFT>
248 Expected<StringRef> Elf_Sym_Impl<ELFT>::getName(StringRef StrTab) const {
249   uint32_t Offset = this->st_name;
250   if (Offset >= StrTab.size())
251     return createStringError(object_error::parse_failed,
252                              "st_name (0x%" PRIx32
253                              ") is past the end of the string table"
254                              " of size 0x%zx",
255                              Offset, StrTab.size());
256   return StringRef(StrTab.data() + Offset);
257 }
258 
259 /// Elf_Versym: This is the structure of entries in the SHT_GNU_versym section
260 /// (.gnu.version). This structure is identical for ELF32 and ELF64.
261 template <class ELFT>
262 struct Elf_Versym_Impl {
263   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
264   Elf_Half vs_index; // Version index with flags (e.g. VERSYM_HIDDEN)
265 };
266 
267 /// Elf_Verdef: This is the structure of entries in the SHT_GNU_verdef section
268 /// (.gnu.version_d). This structure is identical for ELF32 and ELF64.
269 template <class ELFT>
270 struct Elf_Verdef_Impl {
271   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
272   using Elf_Verdaux = Elf_Verdaux_Impl<ELFT>;
273   Elf_Half vd_version; // Version of this structure (e.g. VER_DEF_CURRENT)
274   Elf_Half vd_flags;   // Bitwise flags (VER_DEF_*)
275   Elf_Half vd_ndx;     // Version index, used in .gnu.version entries
276   Elf_Half vd_cnt;     // Number of Verdaux entries
277   Elf_Word vd_hash;    // Hash of name
278   Elf_Word vd_aux;     // Offset to the first Verdaux entry (in bytes)
279   Elf_Word vd_next;    // Offset to the next Verdef entry (in bytes)
280 
281   /// Get the first Verdaux entry for this Verdef.
282   const Elf_Verdaux *getAux() const {
283     return reinterpret_cast<const Elf_Verdaux *>((const char *)this + vd_aux);
284   }
285 };
286 
287 /// Elf_Verdaux: This is the structure of auxiliary data in the SHT_GNU_verdef
288 /// section (.gnu.version_d). This structure is identical for ELF32 and ELF64.
289 template <class ELFT>
290 struct Elf_Verdaux_Impl {
291   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
292   Elf_Word vda_name; // Version name (offset in string table)
293   Elf_Word vda_next; // Offset to next Verdaux entry (in bytes)
294 };
295 
296 /// Elf_Verneed: This is the structure of entries in the SHT_GNU_verneed
297 /// section (.gnu.version_r). This structure is identical for ELF32 and ELF64.
298 template <class ELFT>
299 struct Elf_Verneed_Impl {
300   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
301   Elf_Half vn_version; // Version of this structure (e.g. VER_NEED_CURRENT)
302   Elf_Half vn_cnt;     // Number of associated Vernaux entries
303   Elf_Word vn_file;    // Library name (string table offset)
304   Elf_Word vn_aux;     // Offset to first Vernaux entry (in bytes)
305   Elf_Word vn_next;    // Offset to next Verneed entry (in bytes)
306 };
307 
308 /// Elf_Vernaux: This is the structure of auxiliary data in SHT_GNU_verneed
309 /// section (.gnu.version_r). This structure is identical for ELF32 and ELF64.
310 template <class ELFT>
311 struct Elf_Vernaux_Impl {
312   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
313   Elf_Word vna_hash;  // Hash of dependency name
314   Elf_Half vna_flags; // Bitwise Flags (VER_FLAG_*)
315   Elf_Half vna_other; // Version index, used in .gnu.version entries
316   Elf_Word vna_name;  // Dependency name
317   Elf_Word vna_next;  // Offset to next Vernaux entry (in bytes)
318 };
319 
320 /// Elf_Dyn_Base: This structure matches the form of entries in the dynamic
321 ///               table section (.dynamic) look like.
322 template <class ELFT> struct Elf_Dyn_Base;
323 
324 template <endianness TargetEndianness>
325 struct Elf_Dyn_Base<ELFType<TargetEndianness, false>> {
326   LLVM_ELF_IMPORT_TYPES(TargetEndianness, false)
327   Elf_Sword d_tag;
328   union {
329     Elf_Word d_val;
330     Elf_Addr d_ptr;
331   } d_un;
332 };
333 
334 template <endianness TargetEndianness>
335 struct Elf_Dyn_Base<ELFType<TargetEndianness, true>> {
336   LLVM_ELF_IMPORT_TYPES(TargetEndianness, true)
337   Elf_Sxword d_tag;
338   union {
339     Elf_Xword d_val;
340     Elf_Addr d_ptr;
341   } d_un;
342 };
343 
344 /// Elf_Dyn_Impl: This inherits from Elf_Dyn_Base, adding getters.
345 template <class ELFT>
346 struct Elf_Dyn_Impl : Elf_Dyn_Base<ELFT> {
347   using Elf_Dyn_Base<ELFT>::d_tag;
348   using Elf_Dyn_Base<ELFT>::d_un;
349   using intX_t = std::conditional_t<ELFT::Is64Bits, int64_t, int32_t>;
350   using uintX_t = std::conditional_t<ELFT::Is64Bits, uint64_t, uint32_t>;
351   intX_t getTag() const { return d_tag; }
352   uintX_t getVal() const { return d_un.d_val; }
353   uintX_t getPtr() const { return d_un.d_ptr; }
354 };
355 
356 template <endianness TargetEndianness>
357 struct Elf_Rel_Impl<ELFType<TargetEndianness, false>, false> {
358   LLVM_ELF_IMPORT_TYPES(TargetEndianness, false)
359   static const bool IsRela = false;
360   Elf_Addr r_offset; // Location (file byte offset, or program virtual addr)
361   Elf_Word r_info;   // Symbol table index and type of relocation to apply
362 
363   uint32_t getRInfo(bool isMips64EL) const {
364     assert(!isMips64EL);
365     return r_info;
366   }
367   void setRInfo(uint32_t R, bool IsMips64EL) {
368     assert(!IsMips64EL);
369     r_info = R;
370   }
371 
372   // These accessors and mutators correspond to the ELF32_R_SYM, ELF32_R_TYPE,
373   // and ELF32_R_INFO macros defined in the ELF specification:
374   uint32_t getSymbol(bool isMips64EL) const {
375     return this->getRInfo(isMips64EL) >> 8;
376   }
377   unsigned char getType(bool isMips64EL) const {
378     return (unsigned char)(this->getRInfo(isMips64EL) & 0x0ff);
379   }
380   void setSymbol(uint32_t s, bool IsMips64EL) {
381     setSymbolAndType(s, getType(IsMips64EL), IsMips64EL);
382   }
383   void setType(unsigned char t, bool IsMips64EL) {
384     setSymbolAndType(getSymbol(IsMips64EL), t, IsMips64EL);
385   }
386   void setSymbolAndType(uint32_t s, unsigned char t, bool IsMips64EL) {
387     this->setRInfo((s << 8) + t, IsMips64EL);
388   }
389 };
390 
391 template <endianness TargetEndianness>
392 struct Elf_Rel_Impl<ELFType<TargetEndianness, false>, true>
393     : public Elf_Rel_Impl<ELFType<TargetEndianness, false>, false> {
394   LLVM_ELF_IMPORT_TYPES(TargetEndianness, false)
395   static const bool IsRela = true;
396   Elf_Sword r_addend; // Compute value for relocatable field by adding this
397 };
398 
399 template <endianness TargetEndianness>
400 struct Elf_Rel_Impl<ELFType<TargetEndianness, true>, false> {
401   LLVM_ELF_IMPORT_TYPES(TargetEndianness, true)
402   static const bool IsRela = false;
403   Elf_Addr r_offset; // Location (file byte offset, or program virtual addr)
404   Elf_Xword r_info;  // Symbol table index and type of relocation to apply
405 
406   uint64_t getRInfo(bool isMips64EL) const {
407     uint64_t t = r_info;
408     if (!isMips64EL)
409       return t;
410     // Mips64 little endian has a "special" encoding of r_info. Instead of one
411     // 64 bit little endian number, it is a little endian 32 bit number followed
412     // by a 32 bit big endian number.
413     return (t << 32) | ((t >> 8) & 0xff000000) | ((t >> 24) & 0x00ff0000) |
414            ((t >> 40) & 0x0000ff00) | ((t >> 56) & 0x000000ff);
415   }
416 
417   void setRInfo(uint64_t R, bool IsMips64EL) {
418     if (IsMips64EL)
419       r_info = (R >> 32) | ((R & 0xff000000) << 8) | ((R & 0x00ff0000) << 24) |
420                ((R & 0x0000ff00) << 40) | ((R & 0x000000ff) << 56);
421     else
422       r_info = R;
423   }
424 
425   // These accessors and mutators correspond to the ELF64_R_SYM, ELF64_R_TYPE,
426   // and ELF64_R_INFO macros defined in the ELF specification:
427   uint32_t getSymbol(bool isMips64EL) const {
428     return (uint32_t)(this->getRInfo(isMips64EL) >> 32);
429   }
430   uint32_t getType(bool isMips64EL) const {
431     return (uint32_t)(this->getRInfo(isMips64EL) & 0xffffffffL);
432   }
433   void setSymbol(uint32_t s, bool IsMips64EL) {
434     setSymbolAndType(s, getType(IsMips64EL), IsMips64EL);
435   }
436   void setType(uint32_t t, bool IsMips64EL) {
437     setSymbolAndType(getSymbol(IsMips64EL), t, IsMips64EL);
438   }
439   void setSymbolAndType(uint32_t s, uint32_t t, bool IsMips64EL) {
440     this->setRInfo(((uint64_t)s << 32) + (t & 0xffffffffL), IsMips64EL);
441   }
442 };
443 
444 template <endianness TargetEndianness>
445 struct Elf_Rel_Impl<ELFType<TargetEndianness, true>, true>
446     : public Elf_Rel_Impl<ELFType<TargetEndianness, true>, false> {
447   LLVM_ELF_IMPORT_TYPES(TargetEndianness, true)
448   static const bool IsRela = true;
449   Elf_Sxword r_addend; // Compute value for relocatable field by adding this.
450 };
451 
452 template <class ELFT>
453 struct Elf_Ehdr_Impl {
454   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
455   unsigned char e_ident[ELF::EI_NIDENT]; // ELF Identification bytes
456   Elf_Half e_type;                       // Type of file (see ET_*)
457   Elf_Half e_machine;   // Required architecture for this file (see EM_*)
458   Elf_Word e_version;   // Must be equal to 1
459   Elf_Addr e_entry;     // Address to jump to in order to start program
460   Elf_Off e_phoff;      // Program header table's file offset, in bytes
461   Elf_Off e_shoff;      // Section header table's file offset, in bytes
462   Elf_Word e_flags;     // Processor-specific flags
463   Elf_Half e_ehsize;    // Size of ELF header, in bytes
464   Elf_Half e_phentsize; // Size of an entry in the program header table
465   Elf_Half e_phnum;     // Number of entries in the program header table
466   Elf_Half e_shentsize; // Size of an entry in the section header table
467   Elf_Half e_shnum;     // Number of entries in the section header table
468   Elf_Half e_shstrndx;  // Section header table index of section name
469                         // string table
470 
471   bool checkMagic() const {
472     return (memcmp(e_ident, ELF::ElfMagic, strlen(ELF::ElfMagic))) == 0;
473   }
474 
475   unsigned char getFileClass() const { return e_ident[ELF::EI_CLASS]; }
476   unsigned char getDataEncoding() const { return e_ident[ELF::EI_DATA]; }
477 };
478 
479 template <endianness TargetEndianness>
480 struct Elf_Phdr_Impl<ELFType<TargetEndianness, false>> {
481   LLVM_ELF_IMPORT_TYPES(TargetEndianness, false)
482   Elf_Word p_type;   // Type of segment
483   Elf_Off p_offset;  // FileOffset where segment is located, in bytes
484   Elf_Addr p_vaddr;  // Virtual Address of beginning of segment
485   Elf_Addr p_paddr;  // Physical address of beginning of segment (OS-specific)
486   Elf_Word p_filesz; // Num. of bytes in file image of segment (may be zero)
487   Elf_Word p_memsz;  // Num. of bytes in mem image of segment (may be zero)
488   Elf_Word p_flags;  // Segment flags
489   Elf_Word p_align;  // Segment alignment constraint
490 };
491 
492 template <endianness TargetEndianness>
493 struct Elf_Phdr_Impl<ELFType<TargetEndianness, true>> {
494   LLVM_ELF_IMPORT_TYPES(TargetEndianness, true)
495   Elf_Word p_type;    // Type of segment
496   Elf_Word p_flags;   // Segment flags
497   Elf_Off p_offset;   // FileOffset where segment is located, in bytes
498   Elf_Addr p_vaddr;   // Virtual Address of beginning of segment
499   Elf_Addr p_paddr;   // Physical address of beginning of segment (OS-specific)
500   Elf_Xword p_filesz; // Num. of bytes in file image of segment (may be zero)
501   Elf_Xword p_memsz;  // Num. of bytes in mem image of segment (may be zero)
502   Elf_Xword p_align;  // Segment alignment constraint
503 };
504 
505 // ELFT needed for endianness.
506 template <class ELFT>
507 struct Elf_Hash_Impl {
508   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
509   Elf_Word nbucket;
510   Elf_Word nchain;
511 
512   ArrayRef<Elf_Word> buckets() const {
513     return ArrayRef<Elf_Word>(&nbucket + 2, &nbucket + 2 + nbucket);
514   }
515 
516   ArrayRef<Elf_Word> chains() const {
517     return ArrayRef<Elf_Word>(&nbucket + 2 + nbucket,
518                               &nbucket + 2 + nbucket + nchain);
519   }
520 };
521 
522 // .gnu.hash section
523 template <class ELFT>
524 struct Elf_GnuHash_Impl {
525   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
526   Elf_Word nbuckets;
527   Elf_Word symndx;
528   Elf_Word maskwords;
529   Elf_Word shift2;
530 
531   ArrayRef<Elf_Off> filter() const {
532     return ArrayRef<Elf_Off>(reinterpret_cast<const Elf_Off *>(&shift2 + 1),
533                              maskwords);
534   }
535 
536   ArrayRef<Elf_Word> buckets() const {
537     return ArrayRef<Elf_Word>(
538         reinterpret_cast<const Elf_Word *>(filter().end()), nbuckets);
539   }
540 
541   ArrayRef<Elf_Word> values(unsigned DynamicSymCount) const {
542     assert(DynamicSymCount >= symndx);
543     return ArrayRef<Elf_Word>(buckets().end(), DynamicSymCount - symndx);
544   }
545 };
546 
547 // Compressed section headers.
548 // http://www.sco.com/developers/gabi/latest/ch4.sheader.html#compression_header
549 template <endianness TargetEndianness>
550 struct Elf_Chdr_Impl<ELFType<TargetEndianness, false>> {
551   LLVM_ELF_IMPORT_TYPES(TargetEndianness, false)
552   Elf_Word ch_type;
553   Elf_Word ch_size;
554   Elf_Word ch_addralign;
555 };
556 
557 template <endianness TargetEndianness>
558 struct Elf_Chdr_Impl<ELFType<TargetEndianness, true>> {
559   LLVM_ELF_IMPORT_TYPES(TargetEndianness, true)
560   Elf_Word ch_type;
561   Elf_Word ch_reserved;
562   Elf_Xword ch_size;
563   Elf_Xword ch_addralign;
564 };
565 
566 /// Note header
567 template <class ELFT>
568 struct Elf_Nhdr_Impl {
569   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
570   Elf_Word n_namesz;
571   Elf_Word n_descsz;
572   Elf_Word n_type;
573 
574   /// The alignment of the name and descriptor.
575   ///
576   /// Implementations differ from the specification here: in practice all
577   /// variants align both the name and descriptor to 4-bytes.
578   static const unsigned int Align = 4;
579 
580   /// Get the size of the note, including name, descriptor, and padding.
581   size_t getSize() const {
582     return sizeof(*this) + alignTo<Align>(n_namesz) + alignTo<Align>(n_descsz);
583   }
584 };
585 
586 /// An ELF note.
587 ///
588 /// Wraps a note header, providing methods for accessing the name and
589 /// descriptor safely.
590 template <class ELFT>
591 class Elf_Note_Impl {
592   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
593 
594   const Elf_Nhdr_Impl<ELFT> &Nhdr;
595 
596   template <class NoteIteratorELFT> friend class Elf_Note_Iterator_Impl;
597 
598 public:
599   Elf_Note_Impl(const Elf_Nhdr_Impl<ELFT> &Nhdr) : Nhdr(Nhdr) {}
600 
601   /// Get the note's name, excluding the terminating null byte.
602   StringRef getName() const {
603     if (!Nhdr.n_namesz)
604       return StringRef();
605     return StringRef(reinterpret_cast<const char *>(&Nhdr) + sizeof(Nhdr),
606                      Nhdr.n_namesz - 1);
607   }
608 
609   /// Get the note's descriptor.
610   ArrayRef<uint8_t> getDesc() const {
611     if (!Nhdr.n_descsz)
612       return ArrayRef<uint8_t>();
613     return ArrayRef<uint8_t>(
614         reinterpret_cast<const uint8_t *>(&Nhdr) + sizeof(Nhdr) +
615           alignTo<Elf_Nhdr_Impl<ELFT>::Align>(Nhdr.n_namesz),
616         Nhdr.n_descsz);
617   }
618 
619   /// Get the note's descriptor as StringRef
620   StringRef getDescAsStringRef() const {
621     ArrayRef<uint8_t> Desc = getDesc();
622     return StringRef(reinterpret_cast<const char *>(Desc.data()), Desc.size());
623   }
624 
625   /// Get the note's type.
626   Elf_Word getType() const { return Nhdr.n_type; }
627 };
628 
629 template <class ELFT>
630 class Elf_Note_Iterator_Impl
631     : std::iterator<std::forward_iterator_tag, Elf_Note_Impl<ELFT>> {
632   // Nhdr being a nullptr marks the end of iteration.
633   const Elf_Nhdr_Impl<ELFT> *Nhdr = nullptr;
634   size_t RemainingSize = 0u;
635   Error *Err = nullptr;
636 
637   template <class ELFFileELFT> friend class ELFFile;
638 
639   // Stop iteration and indicate an overflow.
640   void stopWithOverflowError() {
641     Nhdr = nullptr;
642     *Err = make_error<StringError>("ELF note overflows container",
643                                    object_error::parse_failed);
644   }
645 
646   // Advance Nhdr by NoteSize bytes, starting from NhdrPos.
647   //
648   // Assumes NoteSize <= RemainingSize. Ensures Nhdr->getSize() <= RemainingSize
649   // upon returning. Handles stopping iteration when reaching the end of the
650   // container, either cleanly or with an overflow error.
651   void advanceNhdr(const uint8_t *NhdrPos, size_t NoteSize) {
652     RemainingSize -= NoteSize;
653     if (RemainingSize == 0u) {
654       // Ensure that if the iterator walks to the end, the error is checked
655       // afterwards.
656       *Err = Error::success();
657       Nhdr = nullptr;
658     } else if (sizeof(*Nhdr) > RemainingSize)
659       stopWithOverflowError();
660     else {
661       Nhdr = reinterpret_cast<const Elf_Nhdr_Impl<ELFT> *>(NhdrPos + NoteSize);
662       if (Nhdr->getSize() > RemainingSize)
663         stopWithOverflowError();
664       else
665         *Err = Error::success();
666     }
667   }
668 
669   Elf_Note_Iterator_Impl() {}
670   explicit Elf_Note_Iterator_Impl(Error &Err) : Err(&Err) {}
671   Elf_Note_Iterator_Impl(const uint8_t *Start, size_t Size, Error &Err)
672       : RemainingSize(Size), Err(&Err) {
673     consumeError(std::move(Err));
674     assert(Start && "ELF note iterator starting at NULL");
675     advanceNhdr(Start, 0u);
676   }
677 
678 public:
679   Elf_Note_Iterator_Impl &operator++() {
680     assert(Nhdr && "incremented ELF note end iterator");
681     const uint8_t *NhdrPos = reinterpret_cast<const uint8_t *>(Nhdr);
682     size_t NoteSize = Nhdr->getSize();
683     advanceNhdr(NhdrPos, NoteSize);
684     return *this;
685   }
686   bool operator==(Elf_Note_Iterator_Impl Other) const {
687     if (!Nhdr && Other.Err)
688       (void)(bool)(*Other.Err);
689     if (!Other.Nhdr && Err)
690       (void)(bool)(*Err);
691     return Nhdr == Other.Nhdr;
692   }
693   bool operator!=(Elf_Note_Iterator_Impl Other) const {
694     return !(*this == Other);
695   }
696   Elf_Note_Impl<ELFT> operator*() const {
697     assert(Nhdr && "dereferenced ELF note end iterator");
698     return Elf_Note_Impl<ELFT>(*Nhdr);
699   }
700 };
701 
702 template <class ELFT> struct Elf_CGProfile_Impl {
703   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
704   Elf_Word cgp_from;
705   Elf_Word cgp_to;
706   Elf_Xword cgp_weight;
707 };
708 
709 // MIPS .reginfo section
710 template <class ELFT>
711 struct Elf_Mips_RegInfo;
712 
713 template <support::endianness TargetEndianness>
714 struct Elf_Mips_RegInfo<ELFType<TargetEndianness, false>> {
715   LLVM_ELF_IMPORT_TYPES(TargetEndianness, false)
716   Elf_Word ri_gprmask;     // bit-mask of used general registers
717   Elf_Word ri_cprmask[4];  // bit-mask of used co-processor registers
718   Elf_Addr ri_gp_value;    // gp register value
719 };
720 
721 template <support::endianness TargetEndianness>
722 struct Elf_Mips_RegInfo<ELFType<TargetEndianness, true>> {
723   LLVM_ELF_IMPORT_TYPES(TargetEndianness, true)
724   Elf_Word ri_gprmask;     // bit-mask of used general registers
725   Elf_Word ri_pad;         // unused padding field
726   Elf_Word ri_cprmask[4];  // bit-mask of used co-processor registers
727   Elf_Addr ri_gp_value;    // gp register value
728 };
729 
730 // .MIPS.options section
731 template <class ELFT> struct Elf_Mips_Options {
732   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
733   uint8_t kind;     // Determines interpretation of variable part of descriptor
734   uint8_t size;     // Byte size of descriptor, including this header
735   Elf_Half section; // Section header index of section affected,
736                     // or 0 for global options
737   Elf_Word info;    // Kind-specific information
738 
739   Elf_Mips_RegInfo<ELFT> &getRegInfo() {
740     assert(kind == ELF::ODK_REGINFO);
741     return *reinterpret_cast<Elf_Mips_RegInfo<ELFT> *>(
742         (uint8_t *)this + sizeof(Elf_Mips_Options));
743   }
744   const Elf_Mips_RegInfo<ELFT> &getRegInfo() const {
745     return const_cast<Elf_Mips_Options *>(this)->getRegInfo();
746   }
747 };
748 
749 // .MIPS.abiflags section content
750 template <class ELFT> struct Elf_Mips_ABIFlags {
751   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
752   Elf_Half version;  // Version of the structure
753   uint8_t isa_level; // ISA level: 1-5, 32, and 64
754   uint8_t isa_rev;   // ISA revision (0 for MIPS I - MIPS V)
755   uint8_t gpr_size;  // General purpose registers size
756   uint8_t cpr1_size; // Co-processor 1 registers size
757   uint8_t cpr2_size; // Co-processor 2 registers size
758   uint8_t fp_abi;    // Floating-point ABI flag
759   Elf_Word isa_ext;  // Processor-specific extension
760   Elf_Word ases;     // ASEs flags
761   Elf_Word flags1;   // General flags
762   Elf_Word flags2;   // General flags
763 };
764 
765 } // end namespace object.
766 } // end namespace llvm.
767 
768 #endif // LLVM_OBJECT_ELFTYPES_H
769