1 //===------ utils/elf2yaml.cpp - obj2yaml conversion tool -------*- 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 #include "obj2yaml.h"
10 #include "llvm/ADT/DenseSet.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/Twine.h"
13 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
14 #include "llvm/Object/ELFObjectFile.h"
15 #include "llvm/ObjectYAML/DWARFYAML.h"
16 #include "llvm/ObjectYAML/ELFYAML.h"
17 #include "llvm/Support/DataExtractor.h"
18 #include "llvm/Support/ErrorHandling.h"
19 #include "llvm/Support/YAMLTraits.h"
20 
21 using namespace llvm;
22 
23 namespace {
24 
25 template <class ELFT>
26 class ELFDumper {
27   LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
28 
29   ArrayRef<Elf_Shdr> Sections;
30   ArrayRef<Elf_Sym> SymTable;
31 
32   DenseMap<StringRef, uint32_t> UsedSectionNames;
33   std::vector<std::string> SectionNames;
34   Optional<uint32_t> ShStrTabIndex;
35 
36   DenseMap<StringRef, uint32_t> UsedSymbolNames;
37   std::vector<std::string> SymbolNames;
38 
39   BumpPtrAllocator StringAllocator;
40 
41   Expected<StringRef> getUniquedSectionName(const Elf_Shdr &Sec);
42   Expected<StringRef> getUniquedSymbolName(const Elf_Sym *Sym,
43                                            StringRef StrTable,
44                                            const Elf_Shdr *SymTab);
45   Expected<StringRef> getSymbolName(uint32_t SymtabNdx, uint32_t SymbolNdx);
46 
47   const object::ELFFile<ELFT> &Obj;
48   std::unique_ptr<DWARFContext> DWARFCtx;
49 
50   DenseMap<const Elf_Shdr *, ArrayRef<Elf_Word>> ShndxTables;
51 
52   Expected<std::vector<ELFYAML::ProgramHeader>>
53   dumpProgramHeaders(ArrayRef<std::unique_ptr<ELFYAML::Chunk>> Sections);
54 
55   Optional<DWARFYAML::Data>
56   dumpDWARFSections(std::vector<std::unique_ptr<ELFYAML::Chunk>> &Sections);
57 
58   Error dumpSymbols(const Elf_Shdr *Symtab,
59                     Optional<std::vector<ELFYAML::Symbol>> &Symbols);
60   Error dumpSymbol(const Elf_Sym *Sym, const Elf_Shdr *SymTab,
61                    StringRef StrTable, ELFYAML::Symbol &S);
62   Expected<std::vector<std::unique_ptr<ELFYAML::Chunk>>> dumpSections();
63   Error dumpCommonSection(const Elf_Shdr *Shdr, ELFYAML::Section &S);
64   Error dumpCommonRelocationSection(const Elf_Shdr *Shdr,
65                                     ELFYAML::RelocationSection &S);
66   template <class RelT>
67   Error dumpRelocation(const RelT *Rel, const Elf_Shdr *SymTab,
68                        ELFYAML::Relocation &R);
69 
70   Expected<ELFYAML::AddrsigSection *> dumpAddrsigSection(const Elf_Shdr *Shdr);
71   Expected<ELFYAML::LinkerOptionsSection *>
72   dumpLinkerOptionsSection(const Elf_Shdr *Shdr);
73   Expected<ELFYAML::DependentLibrariesSection *>
74   dumpDependentLibrariesSection(const Elf_Shdr *Shdr);
75   Expected<ELFYAML::CallGraphProfileSection *>
76   dumpCallGraphProfileSection(const Elf_Shdr *Shdr);
77   Expected<ELFYAML::DynamicSection *> dumpDynamicSection(const Elf_Shdr *Shdr);
78   Expected<ELFYAML::RelocationSection *> dumpRelocSection(const Elf_Shdr *Shdr);
79   Expected<ELFYAML::RelrSection *> dumpRelrSection(const Elf_Shdr *Shdr);
80   Expected<ELFYAML::RawContentSection *>
81   dumpContentSection(const Elf_Shdr *Shdr);
82   Expected<ELFYAML::SymtabShndxSection *>
83   dumpSymtabShndxSection(const Elf_Shdr *Shdr);
84   Expected<ELFYAML::NoBitsSection *> dumpNoBitsSection(const Elf_Shdr *Shdr);
85   Expected<ELFYAML::HashSection *> dumpHashSection(const Elf_Shdr *Shdr);
86   Expected<ELFYAML::NoteSection *> dumpNoteSection(const Elf_Shdr *Shdr);
87   Expected<ELFYAML::GnuHashSection *> dumpGnuHashSection(const Elf_Shdr *Shdr);
88   Expected<ELFYAML::VerdefSection *> dumpVerdefSection(const Elf_Shdr *Shdr);
89   Expected<ELFYAML::SymverSection *> dumpSymverSection(const Elf_Shdr *Shdr);
90   Expected<ELFYAML::VerneedSection *> dumpVerneedSection(const Elf_Shdr *Shdr);
91   Expected<ELFYAML::GroupSection *> dumpGroupSection(const Elf_Shdr *Shdr);
92   Expected<ELFYAML::ARMIndexTableSection *>
93   dumpARMIndexTableSection(const Elf_Shdr *Shdr);
94   Expected<ELFYAML::MipsABIFlags *> dumpMipsABIFlags(const Elf_Shdr *Shdr);
95   Expected<ELFYAML::StackSizesSection *>
96   dumpStackSizesSection(const Elf_Shdr *Shdr);
97   Expected<ELFYAML::BBAddrMapSection *>
98   dumpBBAddrMapSection(const Elf_Shdr *Shdr);
99   Expected<ELFYAML::RawContentSection *>
100   dumpPlaceholderSection(const Elf_Shdr *Shdr);
101 
102   bool shouldPrintSection(const ELFYAML::Section &S, const Elf_Shdr &SHdr,
103                           Optional<DWARFYAML::Data> DWARF);
104 
105 public:
106   ELFDumper(const object::ELFFile<ELFT> &O, std::unique_ptr<DWARFContext> DCtx);
107   Expected<ELFYAML::Object *> dump();
108 };
109 
110 }
111 
112 template <class ELFT>
113 ELFDumper<ELFT>::ELFDumper(const object::ELFFile<ELFT> &O,
114                            std::unique_ptr<DWARFContext> DCtx)
115     : Obj(O), DWARFCtx(std::move(DCtx)) {}
116 
117 template <class ELFT>
118 Expected<StringRef>
119 ELFDumper<ELFT>::getUniquedSectionName(const Elf_Shdr &Sec) {
120   unsigned SecIndex = &Sec - &Sections[0];
121   if (!SectionNames[SecIndex].empty())
122     return SectionNames[SecIndex];
123 
124   auto NameOrErr = Obj.getSectionName(Sec);
125   if (!NameOrErr)
126     return NameOrErr;
127   StringRef Name = *NameOrErr;
128   // In some specific cases we might have more than one section without a
129   // name (sh_name == 0). It normally doesn't happen, but when we have this case
130   // it doesn't make sense to uniquify their names and add noise to the output.
131   if (Name.empty())
132     return "";
133 
134   std::string &Ret = SectionNames[SecIndex];
135 
136   auto It = UsedSectionNames.insert({Name, 0});
137   if (!It.second)
138     Ret = ELFYAML::appendUniqueSuffix(Name, Twine(++It.first->second));
139   else
140     Ret = std::string(Name);
141   return Ret;
142 }
143 
144 template <class ELFT>
145 Expected<StringRef>
146 ELFDumper<ELFT>::getUniquedSymbolName(const Elf_Sym *Sym, StringRef StrTable,
147                                       const Elf_Shdr *SymTab) {
148   Expected<StringRef> SymbolNameOrErr = Sym->getName(StrTable);
149   if (!SymbolNameOrErr)
150     return SymbolNameOrErr;
151   StringRef Name = *SymbolNameOrErr;
152   if (Name.empty() && Sym->getType() == ELF::STT_SECTION) {
153     Expected<const Elf_Shdr *> ShdrOrErr =
154         Obj.getSection(*Sym, SymTab, ShndxTables.lookup(SymTab));
155     if (!ShdrOrErr)
156       return ShdrOrErr.takeError();
157     // The null section has no name.
158     return (*ShdrOrErr == nullptr) ? "" : getUniquedSectionName(**ShdrOrErr);
159   }
160 
161   // Symbols in .symtab can have duplicate names. For example, it is a common
162   // situation for local symbols in a relocatable object. Here we assign unique
163   // suffixes for such symbols so that we can differentiate them.
164   if (SymTab->sh_type == ELF::SHT_SYMTAB) {
165     unsigned Index = Sym - SymTable.data();
166     if (!SymbolNames[Index].empty())
167       return SymbolNames[Index];
168 
169     auto It = UsedSymbolNames.insert({Name, 0});
170     if (!It.second)
171       SymbolNames[Index] =
172           ELFYAML::appendUniqueSuffix(Name, Twine(++It.first->second));
173     else
174       SymbolNames[Index] = std::string(Name);
175     return SymbolNames[Index];
176   }
177 
178   return Name;
179 }
180 
181 template <class ELFT>
182 bool ELFDumper<ELFT>::shouldPrintSection(const ELFYAML::Section &S,
183                                          const Elf_Shdr &SHdr,
184                                          Optional<DWARFYAML::Data> DWARF) {
185   // We only print the SHT_NULL section at index 0 when it
186   // has at least one non-null field, because yaml2obj
187   // normally creates the zero section at index 0 implicitly.
188   if (S.Type == ELF::SHT_NULL && (&SHdr == &Sections[0])) {
189     const uint8_t *Begin = reinterpret_cast<const uint8_t *>(&SHdr);
190     const uint8_t *End = Begin + sizeof(Elf_Shdr);
191     return std::any_of(Begin, End, [](uint8_t V) { return V != 0; });
192   }
193 
194   // Normally we use "DWARF:" to describe contents of DWARF sections. Sometimes
195   // the content of DWARF sections can be successfully parsed into the "DWARF:"
196   // entry but their section headers may have special flags, entry size, address
197   // alignment, etc. We will preserve the header for them under such
198   // circumstances.
199   StringRef SecName = S.Name.substr(1);
200   if (DWARF && DWARF->getNonEmptySectionNames().count(SecName)) {
201     if (const ELFYAML::RawContentSection *RawSec =
202             dyn_cast<const ELFYAML::RawContentSection>(&S)) {
203       if (RawSec->Type != ELF::SHT_PROGBITS || RawSec->Link || RawSec->Info ||
204           RawSec->AddressAlign != 1 || RawSec->Address || RawSec->EntSize)
205         return true;
206 
207       ELFYAML::ELF_SHF ShFlags = RawSec->Flags.getValueOr(ELFYAML::ELF_SHF(0));
208 
209       if (SecName == "debug_str")
210         return ShFlags != ELFYAML::ELF_SHF(ELF::SHF_MERGE | ELF::SHF_STRINGS);
211 
212       return ShFlags != 0;
213     }
214   }
215 
216   // Normally we use "Symbols:" and "DynamicSymbols:" to describe contents of
217   // symbol tables. We also build and emit corresponding string tables
218   // implicitly. But sometimes it is important to preserve positions and virtual
219   // addresses of allocatable sections, e.g. for creating program headers.
220   // Generally we are trying to reduce noise in the YAML output. Because
221   // of that we do not print non-allocatable versions of such sections and
222   // assume they are placed at the end.
223   // We also dump symbol tables when the Size field is set. It happens when they
224   // are empty, which should not normally happen.
225   if (S.Type == ELF::SHT_STRTAB || S.Type == ELF::SHT_SYMTAB ||
226       S.Type == ELF::SHT_DYNSYM) {
227     return S.Size || S.Flags.getValueOr(ELFYAML::ELF_SHF(0)) & ELF::SHF_ALLOC;
228   }
229 
230   return true;
231 }
232 
233 template <class ELFT>
234 static void dumpSectionOffsets(const typename ELFT::Ehdr &Header,
235                                ArrayRef<ELFYAML::ProgramHeader> Phdrs,
236                                std::vector<std::unique_ptr<ELFYAML::Chunk>> &V,
237                                ArrayRef<typename ELFT::Shdr> S) {
238   if (V.empty())
239     return;
240 
241   uint64_t ExpectedOffset;
242   if (Header.e_phoff > 0)
243     ExpectedOffset = Header.e_phoff + Header.e_phentsize * Header.e_phnum;
244   else
245     ExpectedOffset = sizeof(typename ELFT::Ehdr);
246 
247   for (const std::unique_ptr<ELFYAML::Chunk> &C :
248        makeArrayRef(V).drop_front()) {
249     ELFYAML::Section &Sec = *cast<ELFYAML::Section>(C.get());
250     const typename ELFT::Shdr &SecHdr = S[Sec.OriginalSecNdx];
251 
252     ExpectedOffset = alignTo(ExpectedOffset,
253                              SecHdr.sh_addralign ? SecHdr.sh_addralign : 1uLL);
254 
255     // We only set the "Offset" field when it can't be naturally derived
256     // from the offset and size of the previous section. This reduces
257     // the noise in the YAML output.
258     if (SecHdr.sh_offset != ExpectedOffset)
259       Sec.Offset = (yaml::Hex64)SecHdr.sh_offset;
260 
261     if (Sec.Type == ELF::SHT_NOBITS &&
262         !ELFYAML::shouldAllocateFileSpace(Phdrs,
263                                           *cast<ELFYAML::NoBitsSection>(&Sec)))
264       ExpectedOffset = SecHdr.sh_offset;
265     else
266       ExpectedOffset = SecHdr.sh_offset + SecHdr.sh_size;
267   }
268 }
269 
270 template <class ELFT> Expected<ELFYAML::Object *> ELFDumper<ELFT>::dump() {
271   auto Y = std::make_unique<ELFYAML::Object>();
272 
273   // Dump header. We do not dump EPh* and ESh* fields. When not explicitly set,
274   // the values are set by yaml2obj automatically and there is no need to dump
275   // them here.
276   Y->Header.Class = ELFYAML::ELF_ELFCLASS(Obj.getHeader().getFileClass());
277   Y->Header.Data = ELFYAML::ELF_ELFDATA(Obj.getHeader().getDataEncoding());
278   Y->Header.OSABI = Obj.getHeader().e_ident[ELF::EI_OSABI];
279   Y->Header.ABIVersion = Obj.getHeader().e_ident[ELF::EI_ABIVERSION];
280   Y->Header.Type = Obj.getHeader().e_type;
281   if (Obj.getHeader().e_machine != 0)
282     Y->Header.Machine = ELFYAML::ELF_EM(Obj.getHeader().e_machine);
283   Y->Header.Flags = Obj.getHeader().e_flags;
284   Y->Header.Entry = Obj.getHeader().e_entry;
285 
286   // Dump sections
287   auto SectionsOrErr = Obj.sections();
288   if (!SectionsOrErr)
289     return SectionsOrErr.takeError();
290   Sections = *SectionsOrErr;
291   SectionNames.resize(Sections.size());
292 
293   if (Sections.size() > 0) {
294     ShStrTabIndex = Obj.getHeader().e_shstrndx;
295     if (*ShStrTabIndex == ELF::SHN_XINDEX)
296       ShStrTabIndex = Sections[0].sh_link;
297     // TODO: Set EShStrndx if the value doesn't represent a real section.
298   }
299 
300   // Normally an object that does not have sections has e_shnum == 0.
301   // Also, e_shnum might be 0, when the the number of entries in the section
302   // header table is larger than or equal to SHN_LORESERVE (0xff00). In this
303   // case the real number of entries is held in the sh_size member of the
304   // initial entry. We have a section header table when `e_shoff` is not 0.
305   if (Obj.getHeader().e_shoff != 0 && Obj.getHeader().e_shnum == 0)
306     Y->Header.EShNum = 0;
307 
308   // Dump symbols. We need to do this early because other sections might want
309   // to access the deduplicated symbol names that we also create here.
310   const Elf_Shdr *SymTab = nullptr;
311   const Elf_Shdr *DynSymTab = nullptr;
312 
313   for (const Elf_Shdr &Sec : Sections) {
314     if (Sec.sh_type == ELF::SHT_SYMTAB) {
315       SymTab = &Sec;
316     } else if (Sec.sh_type == ELF::SHT_DYNSYM) {
317       DynSymTab = &Sec;
318     } else if (Sec.sh_type == ELF::SHT_SYMTAB_SHNDX) {
319       // We need to locate SHT_SYMTAB_SHNDX sections early, because they
320       // might be needed for dumping symbols.
321       if (Expected<ArrayRef<Elf_Word>> TableOrErr = Obj.getSHNDXTable(Sec)) {
322         // The `getSHNDXTable` calls the `getSection` internally when validates
323         // the symbol table section linked to the SHT_SYMTAB_SHNDX section.
324         const Elf_Shdr *LinkedSymTab = cantFail(Obj.getSection(Sec.sh_link));
325         if (!ShndxTables.insert({LinkedSymTab, *TableOrErr}).second)
326           return createStringError(
327               errc::invalid_argument,
328               "multiple SHT_SYMTAB_SHNDX sections are "
329               "linked to the same symbol table with index " +
330                   Twine(Sec.sh_link));
331       } else {
332         return createStringError(errc::invalid_argument,
333                                  "unable to read extended section indexes: " +
334                                      toString(TableOrErr.takeError()));
335       }
336     }
337   }
338 
339   if (SymTab)
340     if (Error E = dumpSymbols(SymTab, Y->Symbols))
341       return std::move(E);
342 
343   if (DynSymTab)
344     if (Error E = dumpSymbols(DynSymTab, Y->DynamicSymbols))
345       return std::move(E);
346 
347   // We dump all sections first. It is simple and allows us to verify that all
348   // sections are valid and also to generalize the code. But we are not going to
349   // keep all of them in the final output (see comments for
350   // 'shouldPrintSection()'). Undesired chunks will be removed later.
351   Expected<std::vector<std::unique_ptr<ELFYAML::Chunk>>> ChunksOrErr =
352       dumpSections();
353   if (!ChunksOrErr)
354     return ChunksOrErr.takeError();
355   std::vector<std::unique_ptr<ELFYAML::Chunk>> Chunks = std::move(*ChunksOrErr);
356 
357   std::vector<ELFYAML::Section *> OriginalOrder;
358   if (!Chunks.empty())
359     for (const std::unique_ptr<ELFYAML::Chunk> &C :
360          makeArrayRef(Chunks).drop_front())
361       OriginalOrder.push_back(cast<ELFYAML::Section>(C.get()));
362 
363   // Sometimes the order of sections in the section header table does not match
364   // their actual order. Here we sort sections by the file offset.
365   llvm::stable_sort(Chunks, [&](const std::unique_ptr<ELFYAML::Chunk> &A,
366                                 const std::unique_ptr<ELFYAML::Chunk> &B) {
367     return Sections[cast<ELFYAML::Section>(A.get())->OriginalSecNdx].sh_offset <
368            Sections[cast<ELFYAML::Section>(B.get())->OriginalSecNdx].sh_offset;
369   });
370 
371   // Dump program headers.
372   Expected<std::vector<ELFYAML::ProgramHeader>> PhdrsOrErr =
373       dumpProgramHeaders(Chunks);
374   if (!PhdrsOrErr)
375     return PhdrsOrErr.takeError();
376   Y->ProgramHeaders = std::move(*PhdrsOrErr);
377 
378   dumpSectionOffsets<ELFT>(Obj.getHeader(), Y->ProgramHeaders, Chunks,
379                            Sections);
380 
381   // Dump DWARF sections.
382   Y->DWARF = dumpDWARFSections(Chunks);
383 
384   // We emit the "SectionHeaderTable" key when the order of sections in the
385   // sections header table doesn't match the file order.
386   const bool SectionsSorted =
387       llvm::is_sorted(Chunks, [&](const std::unique_ptr<ELFYAML::Chunk> &A,
388                                   const std::unique_ptr<ELFYAML::Chunk> &B) {
389         return cast<ELFYAML::Section>(A.get())->OriginalSecNdx <
390                cast<ELFYAML::Section>(B.get())->OriginalSecNdx;
391       });
392   if (!SectionsSorted) {
393     std::unique_ptr<ELFYAML::SectionHeaderTable> SHT =
394         std::make_unique<ELFYAML::SectionHeaderTable>(/*IsImplicit=*/false);
395     SHT->Sections.emplace();
396     for (ELFYAML::Section *S : OriginalOrder)
397       SHT->Sections->push_back({S->Name});
398     Chunks.push_back(std::move(SHT));
399   }
400 
401   llvm::erase_if(Chunks, [this, &Y](const std::unique_ptr<ELFYAML::Chunk> &C) {
402     if (isa<ELFYAML::SectionHeaderTable>(*C.get()))
403       return false;
404 
405     const ELFYAML::Section &S = cast<ELFYAML::Section>(*C.get());
406     return !shouldPrintSection(S, Sections[S.OriginalSecNdx], Y->DWARF);
407   });
408 
409   // The section header string table by default is assumed to be called
410   // ".shstrtab" and be in its own unique section. However, it's possible for it
411   // to be called something else and shared with another section. If the name
412   // isn't the default, provide this in the YAML.
413   if (ShStrTabIndex && *ShStrTabIndex != ELF::SHN_UNDEF &&
414       *ShStrTabIndex < Sections.size()) {
415     StringRef ShStrtabName;
416     if (SymTab && SymTab->sh_link == *ShStrTabIndex) {
417       // Section header string table is shared with the symbol table. Use that
418       // section's name (usually .strtab).
419       ShStrtabName = cantFail(Obj.getSectionName(Sections[SymTab->sh_link]));
420     } else if (DynSymTab && DynSymTab->sh_link == *ShStrTabIndex) {
421       // Section header string table is shared with the dynamic symbol table.
422       // Use that section's name (usually .dynstr).
423       ShStrtabName = cantFail(Obj.getSectionName(Sections[DynSymTab->sh_link]));
424     } else {
425       // Otherwise, the section name potentially needs uniquifying.
426       ShStrtabName = cantFail(getUniquedSectionName(Sections[*ShStrTabIndex]));
427     }
428     if (ShStrtabName != ".shstrtab")
429       Y->Header.SectionHeaderStringTable = ShStrtabName;
430   }
431 
432   Y->Chunks = std::move(Chunks);
433   return Y.release();
434 }
435 
436 template <class ELFT>
437 static bool isInSegment(const ELFYAML::Section &Sec,
438                         const typename ELFT::Shdr &SHdr,
439                         const typename ELFT::Phdr &Phdr) {
440   if (Sec.Type == ELF::SHT_NULL)
441     return false;
442 
443   // A section is within a segment when its location in a file is within the
444   // [p_offset, p_offset + p_filesz] region.
445   bool FileOffsetsMatch =
446       SHdr.sh_offset >= Phdr.p_offset &&
447       (SHdr.sh_offset + SHdr.sh_size <= Phdr.p_offset + Phdr.p_filesz);
448 
449   bool VirtualAddressesMatch = SHdr.sh_addr >= Phdr.p_vaddr &&
450                                SHdr.sh_addr <= Phdr.p_vaddr + Phdr.p_memsz;
451 
452   if (FileOffsetsMatch) {
453     // An empty section on the edges of a program header can be outside of the
454     // virtual address space of the segment. This means it is not included in
455     // the segment and we should ignore it.
456     if (SHdr.sh_size == 0 && (SHdr.sh_offset == Phdr.p_offset ||
457                               SHdr.sh_offset == Phdr.p_offset + Phdr.p_filesz))
458       return VirtualAddressesMatch;
459     return true;
460   }
461 
462   // SHT_NOBITS sections usually occupy no physical space in a file. Such
463   // sections belong to a segment when they reside in the segment's virtual
464   // address space.
465   if (Sec.Type != ELF::SHT_NOBITS)
466     return false;
467   return VirtualAddressesMatch;
468 }
469 
470 template <class ELFT>
471 Expected<std::vector<ELFYAML::ProgramHeader>>
472 ELFDumper<ELFT>::dumpProgramHeaders(
473     ArrayRef<std::unique_ptr<ELFYAML::Chunk>> Chunks) {
474   std::vector<ELFYAML::ProgramHeader> Ret;
475   Expected<typename ELFT::PhdrRange> PhdrsOrErr = Obj.program_headers();
476   if (!PhdrsOrErr)
477     return PhdrsOrErr.takeError();
478 
479   for (const typename ELFT::Phdr &Phdr : *PhdrsOrErr) {
480     ELFYAML::ProgramHeader PH;
481     PH.Type = Phdr.p_type;
482     PH.Flags = Phdr.p_flags;
483     PH.VAddr = Phdr.p_vaddr;
484     PH.PAddr = Phdr.p_paddr;
485 
486     // yaml2obj sets the alignment of a segment to 1 by default.
487     // We do not print the default alignment to reduce noise in the output.
488     if (Phdr.p_align != 1)
489       PH.Align = static_cast<llvm::yaml::Hex64>(Phdr.p_align);
490 
491     // Here we match sections with segments.
492     // It is not possible to have a non-Section chunk, because
493     // obj2yaml does not create Fill chunks.
494     for (const std::unique_ptr<ELFYAML::Chunk> &C : Chunks) {
495       ELFYAML::Section &S = cast<ELFYAML::Section>(*C.get());
496       if (isInSegment<ELFT>(S, Sections[S.OriginalSecNdx], Phdr)) {
497         if (!PH.FirstSec)
498           PH.FirstSec = S.Name;
499         PH.LastSec = S.Name;
500         PH.Chunks.push_back(C.get());
501       }
502     }
503 
504     Ret.push_back(PH);
505   }
506 
507   return Ret;
508 }
509 
510 template <class ELFT>
511 Optional<DWARFYAML::Data> ELFDumper<ELFT>::dumpDWARFSections(
512     std::vector<std::unique_ptr<ELFYAML::Chunk>> &Sections) {
513   DWARFYAML::Data DWARF;
514   for (std::unique_ptr<ELFYAML::Chunk> &C : Sections) {
515     if (!C->Name.startswith(".debug_"))
516       continue;
517 
518     if (ELFYAML::RawContentSection *RawSec =
519             dyn_cast<ELFYAML::RawContentSection>(C.get())) {
520       // FIXME: The dumpDebug* functions should take the content as stored in
521       // RawSec. Currently, they just use the last section with the matching
522       // name, which defeats this attempt to skip reading a section header
523       // string table with the same name as a DWARF section.
524       if (ShStrTabIndex && RawSec->OriginalSecNdx == *ShStrTabIndex)
525         continue;
526       Error Err = Error::success();
527       cantFail(std::move(Err));
528 
529       if (RawSec->Name == ".debug_aranges")
530         Err = dumpDebugARanges(*DWARFCtx.get(), DWARF);
531       else if (RawSec->Name == ".debug_str")
532         Err = dumpDebugStrings(*DWARFCtx.get(), DWARF);
533       else if (RawSec->Name == ".debug_ranges")
534         Err = dumpDebugRanges(*DWARFCtx.get(), DWARF);
535       else if (RawSec->Name == ".debug_addr")
536         Err = dumpDebugAddr(*DWARFCtx.get(), DWARF);
537       else
538         continue;
539 
540       // If the DWARF section cannot be successfully parsed, emit raw content
541       // instead of an entry in the DWARF section of the YAML.
542       if (Err)
543         consumeError(std::move(Err));
544       else
545         RawSec->Content.reset();
546     }
547   }
548 
549   if (DWARF.getNonEmptySectionNames().empty())
550     return None;
551   return DWARF;
552 }
553 
554 template <class ELFT>
555 Expected<ELFYAML::RawContentSection *>
556 ELFDumper<ELFT>::dumpPlaceholderSection(const Elf_Shdr *Shdr) {
557   auto S = std::make_unique<ELFYAML::RawContentSection>();
558   if (Error E = dumpCommonSection(Shdr, *S.get()))
559     return std::move(E);
560 
561   // Normally symbol tables should not be empty. We dump the "Size"
562   // key when they are.
563   if ((Shdr->sh_type == ELF::SHT_SYMTAB || Shdr->sh_type == ELF::SHT_DYNSYM) &&
564       !Shdr->sh_size)
565     S->Size.emplace();
566 
567   return S.release();
568 }
569 
570 template <class ELFT>
571 Expected<std::vector<std::unique_ptr<ELFYAML::Chunk>>>
572 ELFDumper<ELFT>::dumpSections() {
573   std::vector<std::unique_ptr<ELFYAML::Chunk>> Ret;
574   auto Add = [&](Expected<ELFYAML::Chunk *> SecOrErr) -> Error {
575     if (!SecOrErr)
576       return SecOrErr.takeError();
577     Ret.emplace_back(*SecOrErr);
578     return Error::success();
579   };
580 
581   auto GetDumper = [this](unsigned Type)
582       -> std::function<Expected<ELFYAML::Chunk *>(const Elf_Shdr *)> {
583     if (Obj.getHeader().e_machine == ELF::EM_ARM && Type == ELF::SHT_ARM_EXIDX)
584       return [this](const Elf_Shdr *S) { return dumpARMIndexTableSection(S); };
585 
586     if (Obj.getHeader().e_machine == ELF::EM_MIPS &&
587         Type == ELF::SHT_MIPS_ABIFLAGS)
588       return [this](const Elf_Shdr *S) { return dumpMipsABIFlags(S); };
589 
590     switch (Type) {
591     case ELF::SHT_DYNAMIC:
592       return [this](const Elf_Shdr *S) { return dumpDynamicSection(S); };
593     case ELF::SHT_SYMTAB_SHNDX:
594       return [this](const Elf_Shdr *S) { return dumpSymtabShndxSection(S); };
595     case ELF::SHT_REL:
596     case ELF::SHT_RELA:
597       return [this](const Elf_Shdr *S) { return dumpRelocSection(S); };
598     case ELF::SHT_RELR:
599       return [this](const Elf_Shdr *S) { return dumpRelrSection(S); };
600     case ELF::SHT_GROUP:
601       return [this](const Elf_Shdr *S) { return dumpGroupSection(S); };
602     case ELF::SHT_NOBITS:
603       return [this](const Elf_Shdr *S) { return dumpNoBitsSection(S); };
604     case ELF::SHT_NOTE:
605       return [this](const Elf_Shdr *S) { return dumpNoteSection(S); };
606     case ELF::SHT_HASH:
607       return [this](const Elf_Shdr *S) { return dumpHashSection(S); };
608     case ELF::SHT_GNU_HASH:
609       return [this](const Elf_Shdr *S) { return dumpGnuHashSection(S); };
610     case ELF::SHT_GNU_verdef:
611       return [this](const Elf_Shdr *S) { return dumpVerdefSection(S); };
612     case ELF::SHT_GNU_versym:
613       return [this](const Elf_Shdr *S) { return dumpSymverSection(S); };
614     case ELF::SHT_GNU_verneed:
615       return [this](const Elf_Shdr *S) { return dumpVerneedSection(S); };
616     case ELF::SHT_LLVM_ADDRSIG:
617       return [this](const Elf_Shdr *S) { return dumpAddrsigSection(S); };
618     case ELF::SHT_LLVM_LINKER_OPTIONS:
619       return [this](const Elf_Shdr *S) { return dumpLinkerOptionsSection(S); };
620     case ELF::SHT_LLVM_DEPENDENT_LIBRARIES:
621       return [this](const Elf_Shdr *S) {
622         return dumpDependentLibrariesSection(S);
623       };
624     case ELF::SHT_LLVM_CALL_GRAPH_PROFILE:
625       return
626           [this](const Elf_Shdr *S) { return dumpCallGraphProfileSection(S); };
627     case ELF::SHT_LLVM_BB_ADDR_MAP:
628       return [this](const Elf_Shdr *S) { return dumpBBAddrMapSection(S); };
629     case ELF::SHT_STRTAB:
630     case ELF::SHT_SYMTAB:
631     case ELF::SHT_DYNSYM:
632       // The contents of these sections are described by other parts of the YAML
633       // file. But we still want to dump them, because their properties can be
634       // important. See comments for 'shouldPrintSection()' for more details.
635       return [this](const Elf_Shdr *S) { return dumpPlaceholderSection(S); };
636     default:
637       return nullptr;
638     }
639   };
640 
641   for (const Elf_Shdr &Sec : Sections) {
642     // We have dedicated dumping functions for most of the section types.
643     // Try to use one of them first.
644     if (std::function<Expected<ELFYAML::Chunk *>(const Elf_Shdr *)> DumpFn =
645             GetDumper(Sec.sh_type)) {
646       if (Error E = Add(DumpFn(&Sec)))
647         return std::move(E);
648       continue;
649     }
650 
651     // Recognize some special SHT_PROGBITS sections by name.
652     if (Sec.sh_type == ELF::SHT_PROGBITS) {
653       auto NameOrErr = Obj.getSectionName(Sec);
654       if (!NameOrErr)
655         return NameOrErr.takeError();
656 
657       if (ELFYAML::StackSizesSection::nameMatches(*NameOrErr)) {
658         if (Error E = Add(dumpStackSizesSection(&Sec)))
659           return std::move(E);
660         continue;
661       }
662     }
663 
664     if (Error E = Add(dumpContentSection(&Sec)))
665       return std::move(E);
666   }
667 
668   return std::move(Ret);
669 }
670 
671 template <class ELFT>
672 Error ELFDumper<ELFT>::dumpSymbols(
673     const Elf_Shdr *Symtab, Optional<std::vector<ELFYAML::Symbol>> &Symbols) {
674   if (!Symtab)
675     return Error::success();
676 
677   auto SymtabOrErr = Obj.symbols(Symtab);
678   if (!SymtabOrErr)
679     return SymtabOrErr.takeError();
680 
681   if (SymtabOrErr->empty())
682     return Error::success();
683 
684   auto StrTableOrErr = Obj.getStringTableForSymtab(*Symtab);
685   if (!StrTableOrErr)
686     return StrTableOrErr.takeError();
687 
688   if (Symtab->sh_type == ELF::SHT_SYMTAB) {
689     SymTable = *SymtabOrErr;
690     SymbolNames.resize(SymTable.size());
691   }
692 
693   Symbols.emplace();
694   for (const auto &Sym : (*SymtabOrErr).drop_front()) {
695     ELFYAML::Symbol S;
696     if (auto EC = dumpSymbol(&Sym, Symtab, *StrTableOrErr, S))
697       return EC;
698     Symbols->push_back(S);
699   }
700 
701   return Error::success();
702 }
703 
704 template <class ELFT>
705 Error ELFDumper<ELFT>::dumpSymbol(const Elf_Sym *Sym, const Elf_Shdr *SymTab,
706                                   StringRef StrTable, ELFYAML::Symbol &S) {
707   S.Type = Sym->getType();
708   if (Sym->st_value)
709     S.Value = (yaml::Hex64)Sym->st_value;
710   if (Sym->st_size)
711     S.Size = (yaml::Hex64)Sym->st_size;
712   S.Other = Sym->st_other;
713   S.Binding = Sym->getBinding();
714 
715   Expected<StringRef> SymbolNameOrErr =
716       getUniquedSymbolName(Sym, StrTable, SymTab);
717   if (!SymbolNameOrErr)
718     return SymbolNameOrErr.takeError();
719   S.Name = SymbolNameOrErr.get();
720 
721   if (Sym->st_shndx >= ELF::SHN_LORESERVE) {
722     S.Index = (ELFYAML::ELF_SHN)Sym->st_shndx;
723     return Error::success();
724   }
725 
726   auto ShdrOrErr = Obj.getSection(*Sym, SymTab, ShndxTables.lookup(SymTab));
727   if (!ShdrOrErr)
728     return ShdrOrErr.takeError();
729   const Elf_Shdr *Shdr = *ShdrOrErr;
730   if (!Shdr)
731     return Error::success();
732 
733   auto NameOrErr = getUniquedSectionName(*Shdr);
734   if (!NameOrErr)
735     return NameOrErr.takeError();
736   S.Section = NameOrErr.get();
737 
738   return Error::success();
739 }
740 
741 template <class ELFT>
742 template <class RelT>
743 Error ELFDumper<ELFT>::dumpRelocation(const RelT *Rel, const Elf_Shdr *SymTab,
744                                       ELFYAML::Relocation &R) {
745   R.Type = Rel->getType(Obj.isMips64EL());
746   R.Offset = Rel->r_offset;
747   R.Addend = 0;
748 
749   auto SymOrErr = Obj.getRelocationSymbol(*Rel, SymTab);
750   if (!SymOrErr)
751     return SymOrErr.takeError();
752 
753   // We have might have a relocation with symbol index 0,
754   // e.g. R_X86_64_NONE or R_X86_64_GOTPC32.
755   const Elf_Sym *Sym = *SymOrErr;
756   if (!Sym)
757     return Error::success();
758 
759   auto StrTabSec = Obj.getSection(SymTab->sh_link);
760   if (!StrTabSec)
761     return StrTabSec.takeError();
762   auto StrTabOrErr = Obj.getStringTable(**StrTabSec);
763   if (!StrTabOrErr)
764     return StrTabOrErr.takeError();
765 
766   Expected<StringRef> NameOrErr =
767       getUniquedSymbolName(Sym, *StrTabOrErr, SymTab);
768   if (!NameOrErr)
769     return NameOrErr.takeError();
770   R.Symbol = NameOrErr.get();
771 
772   return Error::success();
773 }
774 
775 template <class ELFT>
776 Error ELFDumper<ELFT>::dumpCommonSection(const Elf_Shdr *Shdr,
777                                          ELFYAML::Section &S) {
778   // Dump fields. We do not dump the ShOffset field. When not explicitly
779   // set, the value is set by yaml2obj automatically.
780   S.Type = Shdr->sh_type;
781   if (Shdr->sh_flags)
782     S.Flags = static_cast<ELFYAML::ELF_SHF>(Shdr->sh_flags);
783   if (Shdr->sh_addr)
784     S.Address = static_cast<uint64_t>(Shdr->sh_addr);
785   S.AddressAlign = Shdr->sh_addralign;
786 
787   S.OriginalSecNdx = Shdr - &Sections[0];
788 
789   Expected<StringRef> NameOrErr = getUniquedSectionName(*Shdr);
790   if (!NameOrErr)
791     return NameOrErr.takeError();
792   S.Name = NameOrErr.get();
793 
794   if (Shdr->sh_entsize != ELFYAML::getDefaultShEntSize<ELFT>(
795                               Obj.getHeader().e_machine, S.Type, S.Name))
796     S.EntSize = static_cast<llvm::yaml::Hex64>(Shdr->sh_entsize);
797 
798   if (Shdr->sh_link != ELF::SHN_UNDEF) {
799     Expected<const Elf_Shdr *> LinkSection = Obj.getSection(Shdr->sh_link);
800     if (!LinkSection)
801       return make_error<StringError>(
802           "unable to resolve sh_link reference in section '" + S.Name +
803               "': " + toString(LinkSection.takeError()),
804           inconvertibleErrorCode());
805 
806     NameOrErr = getUniquedSectionName(**LinkSection);
807     if (!NameOrErr)
808       return NameOrErr.takeError();
809     S.Link = NameOrErr.get();
810   }
811 
812   return Error::success();
813 }
814 
815 template <class ELFT>
816 Error ELFDumper<ELFT>::dumpCommonRelocationSection(
817     const Elf_Shdr *Shdr, ELFYAML::RelocationSection &S) {
818   if (Error E = dumpCommonSection(Shdr, S))
819     return E;
820 
821   // Having a zero sh_info field is normal: .rela.dyn is a dynamic
822   // relocation section that normally has no value in this field.
823   if (!Shdr->sh_info)
824     return Error::success();
825 
826   auto InfoSection = Obj.getSection(Shdr->sh_info);
827   if (!InfoSection)
828     return InfoSection.takeError();
829 
830   Expected<StringRef> NameOrErr = getUniquedSectionName(**InfoSection);
831   if (!NameOrErr)
832     return NameOrErr.takeError();
833   S.RelocatableSec = NameOrErr.get();
834 
835   return Error::success();
836 }
837 
838 template <class ELFT>
839 Expected<ELFYAML::StackSizesSection *>
840 ELFDumper<ELFT>::dumpStackSizesSection(const Elf_Shdr *Shdr) {
841   auto S = std::make_unique<ELFYAML::StackSizesSection>();
842   if (Error E = dumpCommonSection(Shdr, *S))
843     return std::move(E);
844 
845   auto ContentOrErr = Obj.getSectionContents(*Shdr);
846   if (!ContentOrErr)
847     return ContentOrErr.takeError();
848 
849   ArrayRef<uint8_t> Content = *ContentOrErr;
850   DataExtractor Data(Content, Obj.isLE(), ELFT::Is64Bits ? 8 : 4);
851 
852   std::vector<ELFYAML::StackSizeEntry> Entries;
853   DataExtractor::Cursor Cur(0);
854   while (Cur && Cur.tell() < Content.size()) {
855     uint64_t Address = Data.getAddress(Cur);
856     uint64_t Size = Data.getULEB128(Cur);
857     Entries.push_back({Address, Size});
858   }
859 
860   if (Content.empty() || !Cur) {
861     // If .stack_sizes cannot be decoded, we dump it as an array of bytes.
862     consumeError(Cur.takeError());
863     S->Content = yaml::BinaryRef(Content);
864   } else {
865     S->Entries = std::move(Entries);
866   }
867 
868   return S.release();
869 }
870 
871 template <class ELFT>
872 Expected<ELFYAML::BBAddrMapSection *>
873 ELFDumper<ELFT>::dumpBBAddrMapSection(const Elf_Shdr *Shdr) {
874   auto S = std::make_unique<ELFYAML::BBAddrMapSection>();
875   if (Error E = dumpCommonSection(Shdr, *S))
876     return std::move(E);
877 
878   auto ContentOrErr = Obj.getSectionContents(*Shdr);
879   if (!ContentOrErr)
880     return ContentOrErr.takeError();
881 
882   ArrayRef<uint8_t> Content = *ContentOrErr;
883   if (Content.empty())
884     return S.release();
885 
886   DataExtractor Data(Content, Obj.isLE(), ELFT::Is64Bits ? 8 : 4);
887 
888   std::vector<ELFYAML::BBAddrMapEntry> Entries;
889   DataExtractor::Cursor Cur(0);
890   while (Cur && Cur.tell() < Content.size()) {
891     uint64_t Address = Data.getAddress(Cur);
892     uint64_t NumBlocks = Data.getULEB128(Cur);
893     std::vector<ELFYAML::BBAddrMapEntry::BBEntry> BBEntries;
894     // Read the specified number of BB entries, or until decoding fails.
895     for (uint64_t BlockID = 0; Cur && BlockID < NumBlocks; ++BlockID) {
896       uint64_t Offset = Data.getULEB128(Cur);
897       uint64_t Size = Data.getULEB128(Cur);
898       uint64_t Metadata = Data.getULEB128(Cur);
899       BBEntries.push_back({Offset, Size, Metadata});
900     }
901     Entries.push_back({Address, /*NumBlocks=*/{}, BBEntries});
902   }
903 
904   if (!Cur) {
905     // If the section cannot be decoded, we dump it as an array of bytes.
906     consumeError(Cur.takeError());
907     S->Content = yaml::BinaryRef(Content);
908   } else {
909     S->Entries = std::move(Entries);
910   }
911 
912   return S.release();
913 }
914 
915 template <class ELFT>
916 Expected<ELFYAML::AddrsigSection *>
917 ELFDumper<ELFT>::dumpAddrsigSection(const Elf_Shdr *Shdr) {
918   auto S = std::make_unique<ELFYAML::AddrsigSection>();
919   if (Error E = dumpCommonSection(Shdr, *S))
920     return std::move(E);
921 
922   auto ContentOrErr = Obj.getSectionContents(*Shdr);
923   if (!ContentOrErr)
924     return ContentOrErr.takeError();
925 
926   ArrayRef<uint8_t> Content = *ContentOrErr;
927   DataExtractor::Cursor Cur(0);
928   DataExtractor Data(Content, Obj.isLE(), /*AddressSize=*/0);
929   std::vector<ELFYAML::YAMLFlowString> Symbols;
930   while (Cur && Cur.tell() < Content.size()) {
931     uint64_t SymNdx = Data.getULEB128(Cur);
932     if (!Cur)
933       break;
934 
935     Expected<StringRef> SymbolName = getSymbolName(Shdr->sh_link, SymNdx);
936     if (!SymbolName || SymbolName->empty()) {
937       consumeError(SymbolName.takeError());
938       Symbols.emplace_back(
939           StringRef(std::to_string(SymNdx)).copy(StringAllocator));
940       continue;
941     }
942 
943     Symbols.emplace_back(*SymbolName);
944   }
945 
946   if (Cur) {
947     S->Symbols = std::move(Symbols);
948     return S.release();
949   }
950 
951   consumeError(Cur.takeError());
952   S->Content = yaml::BinaryRef(Content);
953   return S.release();
954 }
955 
956 template <class ELFT>
957 Expected<ELFYAML::LinkerOptionsSection *>
958 ELFDumper<ELFT>::dumpLinkerOptionsSection(const Elf_Shdr *Shdr) {
959   auto S = std::make_unique<ELFYAML::LinkerOptionsSection>();
960   if (Error E = dumpCommonSection(Shdr, *S))
961     return std::move(E);
962 
963   auto ContentOrErr = Obj.getSectionContents(*Shdr);
964   if (!ContentOrErr)
965     return ContentOrErr.takeError();
966 
967   ArrayRef<uint8_t> Content = *ContentOrErr;
968   if (Content.empty() || Content.back() != 0) {
969     S->Content = Content;
970     return S.release();
971   }
972 
973   SmallVector<StringRef, 16> Strings;
974   toStringRef(Content.drop_back()).split(Strings, '\0');
975   if (Strings.size() % 2 != 0) {
976     S->Content = Content;
977     return S.release();
978   }
979 
980   S->Options.emplace();
981   for (size_t I = 0, E = Strings.size(); I != E; I += 2)
982     S->Options->push_back({Strings[I], Strings[I + 1]});
983 
984   return S.release();
985 }
986 
987 template <class ELFT>
988 Expected<ELFYAML::DependentLibrariesSection *>
989 ELFDumper<ELFT>::dumpDependentLibrariesSection(const Elf_Shdr *Shdr) {
990   auto DL = std::make_unique<ELFYAML::DependentLibrariesSection>();
991   if (Error E = dumpCommonSection(Shdr, *DL))
992     return std::move(E);
993 
994   Expected<ArrayRef<uint8_t>> ContentOrErr = Obj.getSectionContents(*Shdr);
995   if (!ContentOrErr)
996     return ContentOrErr.takeError();
997 
998   ArrayRef<uint8_t> Content = *ContentOrErr;
999   if (!Content.empty() && Content.back() != 0) {
1000     DL->Content = Content;
1001     return DL.release();
1002   }
1003 
1004   DL->Libs.emplace();
1005   for (const uint8_t *I = Content.begin(), *E = Content.end(); I < E;) {
1006     StringRef Lib((const char *)I);
1007     DL->Libs->emplace_back(Lib);
1008     I += Lib.size() + 1;
1009   }
1010 
1011   return DL.release();
1012 }
1013 
1014 template <class ELFT>
1015 Expected<ELFYAML::CallGraphProfileSection *>
1016 ELFDumper<ELFT>::dumpCallGraphProfileSection(const Elf_Shdr *Shdr) {
1017   auto S = std::make_unique<ELFYAML::CallGraphProfileSection>();
1018   if (Error E = dumpCommonSection(Shdr, *S))
1019     return std::move(E);
1020 
1021   Expected<ArrayRef<uint8_t>> ContentOrErr = Obj.getSectionContents(*Shdr);
1022   if (!ContentOrErr)
1023     return ContentOrErr.takeError();
1024   ArrayRef<uint8_t> Content = *ContentOrErr;
1025   const uint32_t SizeOfEntry = ELFYAML::getDefaultShEntSize<ELFT>(
1026       Obj.getHeader().e_machine, S->Type, S->Name);
1027   // Dump the section by using the Content key when it is truncated.
1028   // There is no need to create either "Content" or "Entries" fields when the
1029   // section is empty.
1030   if (Content.empty() || Content.size() % SizeOfEntry != 0) {
1031     if (!Content.empty())
1032       S->Content = yaml::BinaryRef(Content);
1033     return S.release();
1034   }
1035 
1036   std::vector<ELFYAML::CallGraphEntryWeight> Entries(Content.size() /
1037                                                      SizeOfEntry);
1038   DataExtractor Data(Content, Obj.isLE(), /*AddressSize=*/0);
1039   DataExtractor::Cursor Cur(0);
1040   auto ReadEntry = [&](ELFYAML::CallGraphEntryWeight &E) {
1041     E.Weight = Data.getU64(Cur);
1042     if (!Cur) {
1043       consumeError(Cur.takeError());
1044       return false;
1045     }
1046     return true;
1047   };
1048 
1049   for (ELFYAML::CallGraphEntryWeight &E : Entries) {
1050     if (ReadEntry(E))
1051       continue;
1052     S->Content = yaml::BinaryRef(Content);
1053     return S.release();
1054   }
1055 
1056   S->Entries = std::move(Entries);
1057   return S.release();
1058 }
1059 
1060 template <class ELFT>
1061 Expected<ELFYAML::DynamicSection *>
1062 ELFDumper<ELFT>::dumpDynamicSection(const Elf_Shdr *Shdr) {
1063   auto S = std::make_unique<ELFYAML::DynamicSection>();
1064   if (Error E = dumpCommonSection(Shdr, *S))
1065     return std::move(E);
1066 
1067   auto DynTagsOrErr = Obj.template getSectionContentsAsArray<Elf_Dyn>(*Shdr);
1068   if (!DynTagsOrErr)
1069     return DynTagsOrErr.takeError();
1070 
1071   S->Entries.emplace();
1072   for (const Elf_Dyn &Dyn : *DynTagsOrErr)
1073     S->Entries->push_back({(ELFYAML::ELF_DYNTAG)Dyn.getTag(), Dyn.getVal()});
1074 
1075   return S.release();
1076 }
1077 
1078 template <class ELFT>
1079 Expected<ELFYAML::RelocationSection *>
1080 ELFDumper<ELFT>::dumpRelocSection(const Elf_Shdr *Shdr) {
1081   auto S = std::make_unique<ELFYAML::RelocationSection>();
1082   if (auto E = dumpCommonRelocationSection(Shdr, *S))
1083     return std::move(E);
1084 
1085   auto SymTabOrErr = Obj.getSection(Shdr->sh_link);
1086   if (!SymTabOrErr)
1087     return SymTabOrErr.takeError();
1088 
1089   if (Shdr->sh_size != 0)
1090     S->Relocations.emplace();
1091 
1092   if (Shdr->sh_type == ELF::SHT_REL) {
1093     auto Rels = Obj.rels(*Shdr);
1094     if (!Rels)
1095       return Rels.takeError();
1096     for (const Elf_Rel &Rel : *Rels) {
1097       ELFYAML::Relocation R;
1098       if (Error E = dumpRelocation(&Rel, *SymTabOrErr, R))
1099         return std::move(E);
1100       S->Relocations->push_back(R);
1101     }
1102   } else {
1103     auto Rels = Obj.relas(*Shdr);
1104     if (!Rels)
1105       return Rels.takeError();
1106     for (const Elf_Rela &Rel : *Rels) {
1107       ELFYAML::Relocation R;
1108       if (Error E = dumpRelocation(&Rel, *SymTabOrErr, R))
1109         return std::move(E);
1110       R.Addend = Rel.r_addend;
1111       S->Relocations->push_back(R);
1112     }
1113   }
1114 
1115   return S.release();
1116 }
1117 
1118 template <class ELFT>
1119 Expected<ELFYAML::RelrSection *>
1120 ELFDumper<ELFT>::dumpRelrSection(const Elf_Shdr *Shdr) {
1121   auto S = std::make_unique<ELFYAML::RelrSection>();
1122   if (auto E = dumpCommonSection(Shdr, *S))
1123     return std::move(E);
1124 
1125   if (Expected<ArrayRef<Elf_Relr>> Relrs = Obj.relrs(*Shdr)) {
1126     S->Entries.emplace();
1127     for (Elf_Relr Rel : *Relrs)
1128       S->Entries->emplace_back(Rel);
1129     return S.release();
1130   } else {
1131     // Ignore. We are going to dump the data as raw content below.
1132     consumeError(Relrs.takeError());
1133   }
1134 
1135   Expected<ArrayRef<uint8_t>> ContentOrErr = Obj.getSectionContents(*Shdr);
1136   if (!ContentOrErr)
1137     return ContentOrErr.takeError();
1138   S->Content = *ContentOrErr;
1139   return S.release();
1140 }
1141 
1142 template <class ELFT>
1143 Expected<ELFYAML::RawContentSection *>
1144 ELFDumper<ELFT>::dumpContentSection(const Elf_Shdr *Shdr) {
1145   auto S = std::make_unique<ELFYAML::RawContentSection>();
1146   if (Error E = dumpCommonSection(Shdr, *S))
1147     return std::move(E);
1148 
1149   unsigned SecIndex = Shdr - &Sections[0];
1150   if (SecIndex != 0 || Shdr->sh_type != ELF::SHT_NULL) {
1151     auto ContentOrErr = Obj.getSectionContents(*Shdr);
1152     if (!ContentOrErr)
1153       return ContentOrErr.takeError();
1154     ArrayRef<uint8_t> Content = *ContentOrErr;
1155     if (!Content.empty())
1156       S->Content = yaml::BinaryRef(Content);
1157   } else {
1158     S->Size = static_cast<llvm::yaml::Hex64>(Shdr->sh_size);
1159   }
1160 
1161   if (Shdr->sh_info)
1162     S->Info = static_cast<llvm::yaml::Hex64>(Shdr->sh_info);
1163   return S.release();
1164 }
1165 
1166 template <class ELFT>
1167 Expected<ELFYAML::SymtabShndxSection *>
1168 ELFDumper<ELFT>::dumpSymtabShndxSection(const Elf_Shdr *Shdr) {
1169   auto S = std::make_unique<ELFYAML::SymtabShndxSection>();
1170   if (Error E = dumpCommonSection(Shdr, *S))
1171     return std::move(E);
1172 
1173   auto EntriesOrErr = Obj.template getSectionContentsAsArray<Elf_Word>(*Shdr);
1174   if (!EntriesOrErr)
1175     return EntriesOrErr.takeError();
1176 
1177   S->Entries.emplace();
1178   for (const Elf_Word &E : *EntriesOrErr)
1179     S->Entries->push_back(E);
1180   return S.release();
1181 }
1182 
1183 template <class ELFT>
1184 Expected<ELFYAML::NoBitsSection *>
1185 ELFDumper<ELFT>::dumpNoBitsSection(const Elf_Shdr *Shdr) {
1186   auto S = std::make_unique<ELFYAML::NoBitsSection>();
1187   if (Error E = dumpCommonSection(Shdr, *S))
1188     return std::move(E);
1189   if (Shdr->sh_size)
1190     S->Size = static_cast<llvm::yaml::Hex64>(Shdr->sh_size);
1191   return S.release();
1192 }
1193 
1194 template <class ELFT>
1195 Expected<ELFYAML::NoteSection *>
1196 ELFDumper<ELFT>::dumpNoteSection(const Elf_Shdr *Shdr) {
1197   auto S = std::make_unique<ELFYAML::NoteSection>();
1198   if (Error E = dumpCommonSection(Shdr, *S))
1199     return std::move(E);
1200 
1201   auto ContentOrErr = Obj.getSectionContents(*Shdr);
1202   if (!ContentOrErr)
1203     return ContentOrErr.takeError();
1204 
1205   std::vector<ELFYAML::NoteEntry> Entries;
1206   ArrayRef<uint8_t> Content = *ContentOrErr;
1207   while (!Content.empty()) {
1208     if (Content.size() < sizeof(Elf_Nhdr)) {
1209       S->Content = yaml::BinaryRef(*ContentOrErr);
1210       return S.release();
1211     }
1212 
1213     const Elf_Nhdr *Header = reinterpret_cast<const Elf_Nhdr *>(Content.data());
1214     if (Content.size() < Header->getSize()) {
1215       S->Content = yaml::BinaryRef(*ContentOrErr);
1216       return S.release();
1217     }
1218 
1219     Elf_Note Note(*Header);
1220     Entries.push_back(
1221         {Note.getName(), Note.getDesc(), (ELFYAML::ELF_NT)Note.getType()});
1222 
1223     Content = Content.drop_front(Header->getSize());
1224   }
1225 
1226   S->Notes = std::move(Entries);
1227   return S.release();
1228 }
1229 
1230 template <class ELFT>
1231 Expected<ELFYAML::HashSection *>
1232 ELFDumper<ELFT>::dumpHashSection(const Elf_Shdr *Shdr) {
1233   auto S = std::make_unique<ELFYAML::HashSection>();
1234   if (Error E = dumpCommonSection(Shdr, *S))
1235     return std::move(E);
1236 
1237   auto ContentOrErr = Obj.getSectionContents(*Shdr);
1238   if (!ContentOrErr)
1239     return ContentOrErr.takeError();
1240 
1241   ArrayRef<uint8_t> Content = *ContentOrErr;
1242   if (Content.size() % 4 != 0 || Content.size() < 8) {
1243     S->Content = yaml::BinaryRef(Content);
1244     return S.release();
1245   }
1246 
1247   DataExtractor::Cursor Cur(0);
1248   DataExtractor Data(Content, Obj.isLE(), /*AddressSize=*/0);
1249   uint64_t NBucket = Data.getU32(Cur);
1250   uint64_t NChain = Data.getU32(Cur);
1251   if (Content.size() != (2 + NBucket + NChain) * 4) {
1252     S->Content = yaml::BinaryRef(Content);
1253     if (Cur)
1254       return S.release();
1255     llvm_unreachable("entries were not read correctly");
1256   }
1257 
1258   S->Bucket.emplace(NBucket);
1259   for (uint32_t &V : *S->Bucket)
1260     V = Data.getU32(Cur);
1261 
1262   S->Chain.emplace(NChain);
1263   for (uint32_t &V : *S->Chain)
1264     V = Data.getU32(Cur);
1265 
1266   if (Cur)
1267     return S.release();
1268   llvm_unreachable("entries were not read correctly");
1269 }
1270 
1271 template <class ELFT>
1272 Expected<ELFYAML::GnuHashSection *>
1273 ELFDumper<ELFT>::dumpGnuHashSection(const Elf_Shdr *Shdr) {
1274   auto S = std::make_unique<ELFYAML::GnuHashSection>();
1275   if (Error E = dumpCommonSection(Shdr, *S))
1276     return std::move(E);
1277 
1278   auto ContentOrErr = Obj.getSectionContents(*Shdr);
1279   if (!ContentOrErr)
1280     return ContentOrErr.takeError();
1281 
1282   unsigned AddrSize = ELFT::Is64Bits ? 8 : 4;
1283   ArrayRef<uint8_t> Content = *ContentOrErr;
1284   DataExtractor Data(Content, Obj.isLE(), AddrSize);
1285 
1286   ELFYAML::GnuHashHeader Header;
1287   DataExtractor::Cursor Cur(0);
1288   uint64_t NBuckets = Data.getU32(Cur);
1289   Header.SymNdx = Data.getU32(Cur);
1290   uint64_t MaskWords = Data.getU32(Cur);
1291   Header.Shift2 = Data.getU32(Cur);
1292 
1293   // Set just the raw binary content if we were unable to read the header
1294   // or when the section data is truncated or malformed.
1295   uint64_t Size = Data.getData().size() - Cur.tell();
1296   if (!Cur || (Size < MaskWords * AddrSize + NBuckets * 4) ||
1297       (Size % 4 != 0)) {
1298     consumeError(Cur.takeError());
1299     S->Content = yaml::BinaryRef(Content);
1300     return S.release();
1301   }
1302 
1303   S->Header = Header;
1304 
1305   S->BloomFilter.emplace(MaskWords);
1306   for (llvm::yaml::Hex64 &Val : *S->BloomFilter)
1307     Val = Data.getAddress(Cur);
1308 
1309   S->HashBuckets.emplace(NBuckets);
1310   for (llvm::yaml::Hex32 &Val : *S->HashBuckets)
1311     Val = Data.getU32(Cur);
1312 
1313   S->HashValues.emplace((Data.getData().size() - Cur.tell()) / 4);
1314   for (llvm::yaml::Hex32 &Val : *S->HashValues)
1315     Val = Data.getU32(Cur);
1316 
1317   if (Cur)
1318     return S.release();
1319   llvm_unreachable("GnuHashSection was not read correctly");
1320 }
1321 
1322 template <class ELFT>
1323 Expected<ELFYAML::VerdefSection *>
1324 ELFDumper<ELFT>::dumpVerdefSection(const Elf_Shdr *Shdr) {
1325   auto S = std::make_unique<ELFYAML::VerdefSection>();
1326   if (Error E = dumpCommonSection(Shdr, *S))
1327     return std::move(E);
1328 
1329   auto StringTableShdrOrErr = Obj.getSection(Shdr->sh_link);
1330   if (!StringTableShdrOrErr)
1331     return StringTableShdrOrErr.takeError();
1332 
1333   auto StringTableOrErr = Obj.getStringTable(**StringTableShdrOrErr);
1334   if (!StringTableOrErr)
1335     return StringTableOrErr.takeError();
1336 
1337   auto Contents = Obj.getSectionContents(*Shdr);
1338   if (!Contents)
1339     return Contents.takeError();
1340 
1341   S->Entries.emplace();
1342 
1343   llvm::ArrayRef<uint8_t> Data = *Contents;
1344   const uint8_t *Buf = Data.data();
1345   while (Buf) {
1346     const Elf_Verdef *Verdef = reinterpret_cast<const Elf_Verdef *>(Buf);
1347     ELFYAML::VerdefEntry Entry;
1348     if (Verdef->vd_version != 1)
1349       return createStringError(errc::invalid_argument,
1350                                "invalid SHT_GNU_verdef section version: " +
1351                                    Twine(Verdef->vd_version));
1352 
1353     if (Verdef->vd_flags != 0)
1354       Entry.Flags = Verdef->vd_flags;
1355 
1356     if (Verdef->vd_ndx != 0)
1357       Entry.VersionNdx = Verdef->vd_ndx;
1358 
1359     if (Verdef->vd_hash != 0)
1360       Entry.Hash = Verdef->vd_hash;
1361 
1362     const uint8_t *BufAux = Buf + Verdef->vd_aux;
1363     while (BufAux) {
1364       const Elf_Verdaux *Verdaux =
1365           reinterpret_cast<const Elf_Verdaux *>(BufAux);
1366       Entry.VerNames.push_back(
1367           StringTableOrErr->drop_front(Verdaux->vda_name).data());
1368       BufAux = Verdaux->vda_next ? BufAux + Verdaux->vda_next : nullptr;
1369     }
1370 
1371     S->Entries->push_back(Entry);
1372     Buf = Verdef->vd_next ? Buf + Verdef->vd_next : nullptr;
1373   }
1374 
1375   if (Shdr->sh_info != S->Entries->size())
1376     S->Info = (llvm::yaml::Hex64)Shdr->sh_info;
1377 
1378   return S.release();
1379 }
1380 
1381 template <class ELFT>
1382 Expected<ELFYAML::SymverSection *>
1383 ELFDumper<ELFT>::dumpSymverSection(const Elf_Shdr *Shdr) {
1384   auto S = std::make_unique<ELFYAML::SymverSection>();
1385   if (Error E = dumpCommonSection(Shdr, *S))
1386     return std::move(E);
1387 
1388   auto VersionsOrErr = Obj.template getSectionContentsAsArray<Elf_Half>(*Shdr);
1389   if (!VersionsOrErr)
1390     return VersionsOrErr.takeError();
1391 
1392   S->Entries.emplace();
1393   for (const Elf_Half &E : *VersionsOrErr)
1394     S->Entries->push_back(E);
1395 
1396   return S.release();
1397 }
1398 
1399 template <class ELFT>
1400 Expected<ELFYAML::VerneedSection *>
1401 ELFDumper<ELFT>::dumpVerneedSection(const Elf_Shdr *Shdr) {
1402   auto S = std::make_unique<ELFYAML::VerneedSection>();
1403   if (Error E = dumpCommonSection(Shdr, *S))
1404     return std::move(E);
1405 
1406   auto Contents = Obj.getSectionContents(*Shdr);
1407   if (!Contents)
1408     return Contents.takeError();
1409 
1410   auto StringTableShdrOrErr = Obj.getSection(Shdr->sh_link);
1411   if (!StringTableShdrOrErr)
1412     return StringTableShdrOrErr.takeError();
1413 
1414   auto StringTableOrErr = Obj.getStringTable(**StringTableShdrOrErr);
1415   if (!StringTableOrErr)
1416     return StringTableOrErr.takeError();
1417 
1418   S->VerneedV.emplace();
1419 
1420   llvm::ArrayRef<uint8_t> Data = *Contents;
1421   const uint8_t *Buf = Data.data();
1422   while (Buf) {
1423     const Elf_Verneed *Verneed = reinterpret_cast<const Elf_Verneed *>(Buf);
1424 
1425     ELFYAML::VerneedEntry Entry;
1426     Entry.Version = Verneed->vn_version;
1427     Entry.File =
1428         StringRef(StringTableOrErr->drop_front(Verneed->vn_file).data());
1429 
1430     const uint8_t *BufAux = Buf + Verneed->vn_aux;
1431     while (BufAux) {
1432       const Elf_Vernaux *Vernaux =
1433           reinterpret_cast<const Elf_Vernaux *>(BufAux);
1434 
1435       ELFYAML::VernauxEntry Aux;
1436       Aux.Hash = Vernaux->vna_hash;
1437       Aux.Flags = Vernaux->vna_flags;
1438       Aux.Other = Vernaux->vna_other;
1439       Aux.Name =
1440           StringRef(StringTableOrErr->drop_front(Vernaux->vna_name).data());
1441 
1442       Entry.AuxV.push_back(Aux);
1443       BufAux = Vernaux->vna_next ? BufAux + Vernaux->vna_next : nullptr;
1444     }
1445 
1446     S->VerneedV->push_back(Entry);
1447     Buf = Verneed->vn_next ? Buf + Verneed->vn_next : nullptr;
1448   }
1449 
1450   if (Shdr->sh_info != S->VerneedV->size())
1451     S->Info = (llvm::yaml::Hex64)Shdr->sh_info;
1452 
1453   return S.release();
1454 }
1455 
1456 template <class ELFT>
1457 Expected<StringRef> ELFDumper<ELFT>::getSymbolName(uint32_t SymtabNdx,
1458                                                    uint32_t SymbolNdx) {
1459   auto SymtabOrErr = Obj.getSection(SymtabNdx);
1460   if (!SymtabOrErr)
1461     return SymtabOrErr.takeError();
1462 
1463   const Elf_Shdr *Symtab = *SymtabOrErr;
1464   auto SymOrErr = Obj.getSymbol(Symtab, SymbolNdx);
1465   if (!SymOrErr)
1466     return SymOrErr.takeError();
1467 
1468   auto StrTabOrErr = Obj.getStringTableForSymtab(*Symtab);
1469   if (!StrTabOrErr)
1470     return StrTabOrErr.takeError();
1471   return getUniquedSymbolName(*SymOrErr, *StrTabOrErr, Symtab);
1472 }
1473 
1474 template <class ELFT>
1475 Expected<ELFYAML::GroupSection *>
1476 ELFDumper<ELFT>::dumpGroupSection(const Elf_Shdr *Shdr) {
1477   auto S = std::make_unique<ELFYAML::GroupSection>();
1478   if (Error E = dumpCommonSection(Shdr, *S))
1479     return std::move(E);
1480 
1481   // Get symbol with index sh_info. This symbol's name is the signature of the group.
1482   Expected<StringRef> SymbolName = getSymbolName(Shdr->sh_link, Shdr->sh_info);
1483   if (!SymbolName)
1484     return SymbolName.takeError();
1485   S->Signature = *SymbolName;
1486 
1487   auto MembersOrErr = Obj.template getSectionContentsAsArray<Elf_Word>(*Shdr);
1488   if (!MembersOrErr)
1489     return MembersOrErr.takeError();
1490 
1491   S->Members.emplace();
1492   for (Elf_Word Member : *MembersOrErr) {
1493     if (Member == llvm::ELF::GRP_COMDAT) {
1494       S->Members->push_back({"GRP_COMDAT"});
1495       continue;
1496     }
1497 
1498     Expected<const Elf_Shdr *> SHdrOrErr = Obj.getSection(Member);
1499     if (!SHdrOrErr)
1500       return SHdrOrErr.takeError();
1501     Expected<StringRef> NameOrErr = getUniquedSectionName(**SHdrOrErr);
1502     if (!NameOrErr)
1503       return NameOrErr.takeError();
1504     S->Members->push_back({*NameOrErr});
1505   }
1506   return S.release();
1507 }
1508 
1509 template <class ELFT>
1510 Expected<ELFYAML::ARMIndexTableSection *>
1511 ELFDumper<ELFT>::dumpARMIndexTableSection(const Elf_Shdr *Shdr) {
1512   auto S = std::make_unique<ELFYAML::ARMIndexTableSection>();
1513   if (Error E = dumpCommonSection(Shdr, *S))
1514     return std::move(E);
1515 
1516   Expected<ArrayRef<uint8_t>> ContentOrErr = Obj.getSectionContents(*Shdr);
1517   if (!ContentOrErr)
1518     return ContentOrErr.takeError();
1519 
1520   if (ContentOrErr->size() % (sizeof(Elf_Word) * 2) != 0) {
1521     S->Content = yaml::BinaryRef(*ContentOrErr);
1522     return S.release();
1523   }
1524 
1525   ArrayRef<Elf_Word> Words(
1526       reinterpret_cast<const Elf_Word *>(ContentOrErr->data()),
1527       ContentOrErr->size() / sizeof(Elf_Word));
1528 
1529   S->Entries.emplace();
1530   for (size_t I = 0, E = Words.size(); I != E; I += 2)
1531     S->Entries->push_back({(yaml::Hex32)Words[I], (yaml::Hex32)Words[I + 1]});
1532 
1533   return S.release();
1534 }
1535 
1536 template <class ELFT>
1537 Expected<ELFYAML::MipsABIFlags *>
1538 ELFDumper<ELFT>::dumpMipsABIFlags(const Elf_Shdr *Shdr) {
1539   assert(Shdr->sh_type == ELF::SHT_MIPS_ABIFLAGS &&
1540          "Section type is not SHT_MIPS_ABIFLAGS");
1541   auto S = std::make_unique<ELFYAML::MipsABIFlags>();
1542   if (Error E = dumpCommonSection(Shdr, *S))
1543     return std::move(E);
1544 
1545   auto ContentOrErr = Obj.getSectionContents(*Shdr);
1546   if (!ContentOrErr)
1547     return ContentOrErr.takeError();
1548 
1549   auto *Flags = reinterpret_cast<const object::Elf_Mips_ABIFlags<ELFT> *>(
1550       ContentOrErr.get().data());
1551   S->Version = Flags->version;
1552   S->ISALevel = Flags->isa_level;
1553   S->ISARevision = Flags->isa_rev;
1554   S->GPRSize = Flags->gpr_size;
1555   S->CPR1Size = Flags->cpr1_size;
1556   S->CPR2Size = Flags->cpr2_size;
1557   S->FpABI = Flags->fp_abi;
1558   S->ISAExtension = Flags->isa_ext;
1559   S->ASEs = Flags->ases;
1560   S->Flags1 = Flags->flags1;
1561   S->Flags2 = Flags->flags2;
1562   return S.release();
1563 }
1564 
1565 template <class ELFT>
1566 static Error elf2yaml(raw_ostream &Out, const object::ELFFile<ELFT> &Obj,
1567                       std::unique_ptr<DWARFContext> DWARFCtx) {
1568   ELFDumper<ELFT> Dumper(Obj, std::move(DWARFCtx));
1569   Expected<ELFYAML::Object *> YAMLOrErr = Dumper.dump();
1570   if (!YAMLOrErr)
1571     return YAMLOrErr.takeError();
1572 
1573   std::unique_ptr<ELFYAML::Object> YAML(YAMLOrErr.get());
1574   yaml::Output Yout(Out);
1575   Yout << *YAML;
1576 
1577   return Error::success();
1578 }
1579 
1580 Error elf2yaml(raw_ostream &Out, const object::ObjectFile &Obj) {
1581   std::unique_ptr<DWARFContext> DWARFCtx = DWARFContext::create(Obj);
1582   if (const auto *ELFObj = dyn_cast<object::ELF32LEObjectFile>(&Obj))
1583     return elf2yaml(Out, ELFObj->getELFFile(), std::move(DWARFCtx));
1584 
1585   if (const auto *ELFObj = dyn_cast<object::ELF32BEObjectFile>(&Obj))
1586     return elf2yaml(Out, ELFObj->getELFFile(), std::move(DWARFCtx));
1587 
1588   if (const auto *ELFObj = dyn_cast<object::ELF64LEObjectFile>(&Obj))
1589     return elf2yaml(Out, ELFObj->getELFFile(), std::move(DWARFCtx));
1590 
1591   if (const auto *ELFObj = dyn_cast<object::ELF64BEObjectFile>(&Obj))
1592     return elf2yaml(Out, ELFObj->getELFFile(), std::move(DWARFCtx));
1593 
1594   llvm_unreachable("unknown ELF file format");
1595 }
1596