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 
1026   // Dump the section by using the Content key when it is truncated.
1027   // There is no need to create either "Content" or "Entries" fields when the
1028   // section is empty.
1029   if (Content.empty() || Content.size() % 16 != 0) {
1030     if (!Content.empty())
1031       S->Content = yaml::BinaryRef(Content);
1032     return S.release();
1033   }
1034 
1035   std::vector<ELFYAML::CallGraphEntry> Entries(Content.size() / 16);
1036   DataExtractor Data(Content, Obj.isLE(), /*AddressSize=*/0);
1037   DataExtractor::Cursor Cur(0);
1038   auto ReadEntry = [&](ELFYAML::CallGraphEntry &E) {
1039     uint32_t FromSymIndex = Data.getU32(Cur);
1040     uint32_t ToSymIndex = Data.getU32(Cur);
1041     E.Weight = Data.getU64(Cur);
1042     if (!Cur) {
1043       consumeError(Cur.takeError());
1044       return false;
1045     }
1046 
1047     Expected<StringRef> From = getSymbolName(Shdr->sh_link, FromSymIndex);
1048     Expected<StringRef> To = getSymbolName(Shdr->sh_link, ToSymIndex);
1049     if (From && To) {
1050       E.From = *From;
1051       E.To = *To;
1052       return true;
1053     }
1054     consumeError(From.takeError());
1055     consumeError(To.takeError());
1056     return false;
1057   };
1058 
1059   for (ELFYAML::CallGraphEntry &E : Entries) {
1060     if (ReadEntry(E))
1061       continue;
1062     S->Content = yaml::BinaryRef(Content);
1063     return S.release();
1064   }
1065 
1066   S->Entries = std::move(Entries);
1067   return S.release();
1068 }
1069 
1070 template <class ELFT>
1071 Expected<ELFYAML::DynamicSection *>
1072 ELFDumper<ELFT>::dumpDynamicSection(const Elf_Shdr *Shdr) {
1073   auto S = std::make_unique<ELFYAML::DynamicSection>();
1074   if (Error E = dumpCommonSection(Shdr, *S))
1075     return std::move(E);
1076 
1077   auto DynTagsOrErr = Obj.template getSectionContentsAsArray<Elf_Dyn>(*Shdr);
1078   if (!DynTagsOrErr)
1079     return DynTagsOrErr.takeError();
1080 
1081   S->Entries.emplace();
1082   for (const Elf_Dyn &Dyn : *DynTagsOrErr)
1083     S->Entries->push_back({(ELFYAML::ELF_DYNTAG)Dyn.getTag(), Dyn.getVal()});
1084 
1085   return S.release();
1086 }
1087 
1088 template <class ELFT>
1089 Expected<ELFYAML::RelocationSection *>
1090 ELFDumper<ELFT>::dumpRelocSection(const Elf_Shdr *Shdr) {
1091   auto S = std::make_unique<ELFYAML::RelocationSection>();
1092   if (auto E = dumpCommonRelocationSection(Shdr, *S))
1093     return std::move(E);
1094 
1095   auto SymTabOrErr = Obj.getSection(Shdr->sh_link);
1096   if (!SymTabOrErr)
1097     return SymTabOrErr.takeError();
1098 
1099   if (Shdr->sh_size != 0)
1100     S->Relocations.emplace();
1101 
1102   if (Shdr->sh_type == ELF::SHT_REL) {
1103     auto Rels = Obj.rels(*Shdr);
1104     if (!Rels)
1105       return Rels.takeError();
1106     for (const Elf_Rel &Rel : *Rels) {
1107       ELFYAML::Relocation R;
1108       if (Error E = dumpRelocation(&Rel, *SymTabOrErr, R))
1109         return std::move(E);
1110       S->Relocations->push_back(R);
1111     }
1112   } else {
1113     auto Rels = Obj.relas(*Shdr);
1114     if (!Rels)
1115       return Rels.takeError();
1116     for (const Elf_Rela &Rel : *Rels) {
1117       ELFYAML::Relocation R;
1118       if (Error E = dumpRelocation(&Rel, *SymTabOrErr, R))
1119         return std::move(E);
1120       R.Addend = Rel.r_addend;
1121       S->Relocations->push_back(R);
1122     }
1123   }
1124 
1125   return S.release();
1126 }
1127 
1128 template <class ELFT>
1129 Expected<ELFYAML::RelrSection *>
1130 ELFDumper<ELFT>::dumpRelrSection(const Elf_Shdr *Shdr) {
1131   auto S = std::make_unique<ELFYAML::RelrSection>();
1132   if (auto E = dumpCommonSection(Shdr, *S))
1133     return std::move(E);
1134 
1135   if (Expected<ArrayRef<Elf_Relr>> Relrs = Obj.relrs(*Shdr)) {
1136     S->Entries.emplace();
1137     for (Elf_Relr Rel : *Relrs)
1138       S->Entries->emplace_back(Rel);
1139     return S.release();
1140   } else {
1141     // Ignore. We are going to dump the data as raw content below.
1142     consumeError(Relrs.takeError());
1143   }
1144 
1145   Expected<ArrayRef<uint8_t>> ContentOrErr = Obj.getSectionContents(*Shdr);
1146   if (!ContentOrErr)
1147     return ContentOrErr.takeError();
1148   S->Content = *ContentOrErr;
1149   return S.release();
1150 }
1151 
1152 template <class ELFT>
1153 Expected<ELFYAML::RawContentSection *>
1154 ELFDumper<ELFT>::dumpContentSection(const Elf_Shdr *Shdr) {
1155   auto S = std::make_unique<ELFYAML::RawContentSection>();
1156   if (Error E = dumpCommonSection(Shdr, *S))
1157     return std::move(E);
1158 
1159   unsigned SecIndex = Shdr - &Sections[0];
1160   if (SecIndex != 0 || Shdr->sh_type != ELF::SHT_NULL) {
1161     auto ContentOrErr = Obj.getSectionContents(*Shdr);
1162     if (!ContentOrErr)
1163       return ContentOrErr.takeError();
1164     ArrayRef<uint8_t> Content = *ContentOrErr;
1165     if (!Content.empty())
1166       S->Content = yaml::BinaryRef(Content);
1167   } else {
1168     S->Size = static_cast<llvm::yaml::Hex64>(Shdr->sh_size);
1169   }
1170 
1171   if (Shdr->sh_info)
1172     S->Info = static_cast<llvm::yaml::Hex64>(Shdr->sh_info);
1173   return S.release();
1174 }
1175 
1176 template <class ELFT>
1177 Expected<ELFYAML::SymtabShndxSection *>
1178 ELFDumper<ELFT>::dumpSymtabShndxSection(const Elf_Shdr *Shdr) {
1179   auto S = std::make_unique<ELFYAML::SymtabShndxSection>();
1180   if (Error E = dumpCommonSection(Shdr, *S))
1181     return std::move(E);
1182 
1183   auto EntriesOrErr = Obj.template getSectionContentsAsArray<Elf_Word>(*Shdr);
1184   if (!EntriesOrErr)
1185     return EntriesOrErr.takeError();
1186 
1187   S->Entries.emplace();
1188   for (const Elf_Word &E : *EntriesOrErr)
1189     S->Entries->push_back(E);
1190   return S.release();
1191 }
1192 
1193 template <class ELFT>
1194 Expected<ELFYAML::NoBitsSection *>
1195 ELFDumper<ELFT>::dumpNoBitsSection(const Elf_Shdr *Shdr) {
1196   auto S = std::make_unique<ELFYAML::NoBitsSection>();
1197   if (Error E = dumpCommonSection(Shdr, *S))
1198     return std::move(E);
1199   if (Shdr->sh_size)
1200     S->Size = static_cast<llvm::yaml::Hex64>(Shdr->sh_size);
1201   return S.release();
1202 }
1203 
1204 template <class ELFT>
1205 Expected<ELFYAML::NoteSection *>
1206 ELFDumper<ELFT>::dumpNoteSection(const Elf_Shdr *Shdr) {
1207   auto S = std::make_unique<ELFYAML::NoteSection>();
1208   if (Error E = dumpCommonSection(Shdr, *S))
1209     return std::move(E);
1210 
1211   auto ContentOrErr = Obj.getSectionContents(*Shdr);
1212   if (!ContentOrErr)
1213     return ContentOrErr.takeError();
1214 
1215   std::vector<ELFYAML::NoteEntry> Entries;
1216   ArrayRef<uint8_t> Content = *ContentOrErr;
1217   while (!Content.empty()) {
1218     if (Content.size() < sizeof(Elf_Nhdr)) {
1219       S->Content = yaml::BinaryRef(*ContentOrErr);
1220       return S.release();
1221     }
1222 
1223     const Elf_Nhdr *Header = reinterpret_cast<const Elf_Nhdr *>(Content.data());
1224     if (Content.size() < Header->getSize()) {
1225       S->Content = yaml::BinaryRef(*ContentOrErr);
1226       return S.release();
1227     }
1228 
1229     Elf_Note Note(*Header);
1230     Entries.push_back(
1231         {Note.getName(), Note.getDesc(), (ELFYAML::ELF_NT)Note.getType()});
1232 
1233     Content = Content.drop_front(Header->getSize());
1234   }
1235 
1236   S->Notes = std::move(Entries);
1237   return S.release();
1238 }
1239 
1240 template <class ELFT>
1241 Expected<ELFYAML::HashSection *>
1242 ELFDumper<ELFT>::dumpHashSection(const Elf_Shdr *Shdr) {
1243   auto S = std::make_unique<ELFYAML::HashSection>();
1244   if (Error E = dumpCommonSection(Shdr, *S))
1245     return std::move(E);
1246 
1247   auto ContentOrErr = Obj.getSectionContents(*Shdr);
1248   if (!ContentOrErr)
1249     return ContentOrErr.takeError();
1250 
1251   ArrayRef<uint8_t> Content = *ContentOrErr;
1252   if (Content.size() % 4 != 0 || Content.size() < 8) {
1253     S->Content = yaml::BinaryRef(Content);
1254     return S.release();
1255   }
1256 
1257   DataExtractor::Cursor Cur(0);
1258   DataExtractor Data(Content, Obj.isLE(), /*AddressSize=*/0);
1259   uint64_t NBucket = Data.getU32(Cur);
1260   uint64_t NChain = Data.getU32(Cur);
1261   if (Content.size() != (2 + NBucket + NChain) * 4) {
1262     S->Content = yaml::BinaryRef(Content);
1263     if (Cur)
1264       return S.release();
1265     llvm_unreachable("entries were not read correctly");
1266   }
1267 
1268   S->Bucket.emplace(NBucket);
1269   for (uint32_t &V : *S->Bucket)
1270     V = Data.getU32(Cur);
1271 
1272   S->Chain.emplace(NChain);
1273   for (uint32_t &V : *S->Chain)
1274     V = Data.getU32(Cur);
1275 
1276   if (Cur)
1277     return S.release();
1278   llvm_unreachable("entries were not read correctly");
1279 }
1280 
1281 template <class ELFT>
1282 Expected<ELFYAML::GnuHashSection *>
1283 ELFDumper<ELFT>::dumpGnuHashSection(const Elf_Shdr *Shdr) {
1284   auto S = std::make_unique<ELFYAML::GnuHashSection>();
1285   if (Error E = dumpCommonSection(Shdr, *S))
1286     return std::move(E);
1287 
1288   auto ContentOrErr = Obj.getSectionContents(*Shdr);
1289   if (!ContentOrErr)
1290     return ContentOrErr.takeError();
1291 
1292   unsigned AddrSize = ELFT::Is64Bits ? 8 : 4;
1293   ArrayRef<uint8_t> Content = *ContentOrErr;
1294   DataExtractor Data(Content, Obj.isLE(), AddrSize);
1295 
1296   ELFYAML::GnuHashHeader Header;
1297   DataExtractor::Cursor Cur(0);
1298   uint64_t NBuckets = Data.getU32(Cur);
1299   Header.SymNdx = Data.getU32(Cur);
1300   uint64_t MaskWords = Data.getU32(Cur);
1301   Header.Shift2 = Data.getU32(Cur);
1302 
1303   // Set just the raw binary content if we were unable to read the header
1304   // or when the section data is truncated or malformed.
1305   uint64_t Size = Data.getData().size() - Cur.tell();
1306   if (!Cur || (Size < MaskWords * AddrSize + NBuckets * 4) ||
1307       (Size % 4 != 0)) {
1308     consumeError(Cur.takeError());
1309     S->Content = yaml::BinaryRef(Content);
1310     return S.release();
1311   }
1312 
1313   S->Header = Header;
1314 
1315   S->BloomFilter.emplace(MaskWords);
1316   for (llvm::yaml::Hex64 &Val : *S->BloomFilter)
1317     Val = Data.getAddress(Cur);
1318 
1319   S->HashBuckets.emplace(NBuckets);
1320   for (llvm::yaml::Hex32 &Val : *S->HashBuckets)
1321     Val = Data.getU32(Cur);
1322 
1323   S->HashValues.emplace((Data.getData().size() - Cur.tell()) / 4);
1324   for (llvm::yaml::Hex32 &Val : *S->HashValues)
1325     Val = Data.getU32(Cur);
1326 
1327   if (Cur)
1328     return S.release();
1329   llvm_unreachable("GnuHashSection was not read correctly");
1330 }
1331 
1332 template <class ELFT>
1333 Expected<ELFYAML::VerdefSection *>
1334 ELFDumper<ELFT>::dumpVerdefSection(const Elf_Shdr *Shdr) {
1335   auto S = std::make_unique<ELFYAML::VerdefSection>();
1336   if (Error E = dumpCommonSection(Shdr, *S))
1337     return std::move(E);
1338 
1339   auto StringTableShdrOrErr = Obj.getSection(Shdr->sh_link);
1340   if (!StringTableShdrOrErr)
1341     return StringTableShdrOrErr.takeError();
1342 
1343   auto StringTableOrErr = Obj.getStringTable(**StringTableShdrOrErr);
1344   if (!StringTableOrErr)
1345     return StringTableOrErr.takeError();
1346 
1347   auto Contents = Obj.getSectionContents(*Shdr);
1348   if (!Contents)
1349     return Contents.takeError();
1350 
1351   S->Entries.emplace();
1352 
1353   llvm::ArrayRef<uint8_t> Data = *Contents;
1354   const uint8_t *Buf = Data.data();
1355   while (Buf) {
1356     const Elf_Verdef *Verdef = reinterpret_cast<const Elf_Verdef *>(Buf);
1357     ELFYAML::VerdefEntry Entry;
1358     if (Verdef->vd_version != 1)
1359       return createStringError(errc::invalid_argument,
1360                                "invalid SHT_GNU_verdef section version: " +
1361                                    Twine(Verdef->vd_version));
1362 
1363     if (Verdef->vd_flags != 0)
1364       Entry.Flags = Verdef->vd_flags;
1365 
1366     if (Verdef->vd_ndx != 0)
1367       Entry.VersionNdx = Verdef->vd_ndx;
1368 
1369     if (Verdef->vd_hash != 0)
1370       Entry.Hash = Verdef->vd_hash;
1371 
1372     const uint8_t *BufAux = Buf + Verdef->vd_aux;
1373     while (BufAux) {
1374       const Elf_Verdaux *Verdaux =
1375           reinterpret_cast<const Elf_Verdaux *>(BufAux);
1376       Entry.VerNames.push_back(
1377           StringTableOrErr->drop_front(Verdaux->vda_name).data());
1378       BufAux = Verdaux->vda_next ? BufAux + Verdaux->vda_next : nullptr;
1379     }
1380 
1381     S->Entries->push_back(Entry);
1382     Buf = Verdef->vd_next ? Buf + Verdef->vd_next : nullptr;
1383   }
1384 
1385   if (Shdr->sh_info != S->Entries->size())
1386     S->Info = (llvm::yaml::Hex64)Shdr->sh_info;
1387 
1388   return S.release();
1389 }
1390 
1391 template <class ELFT>
1392 Expected<ELFYAML::SymverSection *>
1393 ELFDumper<ELFT>::dumpSymverSection(const Elf_Shdr *Shdr) {
1394   auto S = std::make_unique<ELFYAML::SymverSection>();
1395   if (Error E = dumpCommonSection(Shdr, *S))
1396     return std::move(E);
1397 
1398   auto VersionsOrErr = Obj.template getSectionContentsAsArray<Elf_Half>(*Shdr);
1399   if (!VersionsOrErr)
1400     return VersionsOrErr.takeError();
1401 
1402   S->Entries.emplace();
1403   for (const Elf_Half &E : *VersionsOrErr)
1404     S->Entries->push_back(E);
1405 
1406   return S.release();
1407 }
1408 
1409 template <class ELFT>
1410 Expected<ELFYAML::VerneedSection *>
1411 ELFDumper<ELFT>::dumpVerneedSection(const Elf_Shdr *Shdr) {
1412   auto S = std::make_unique<ELFYAML::VerneedSection>();
1413   if (Error E = dumpCommonSection(Shdr, *S))
1414     return std::move(E);
1415 
1416   auto Contents = Obj.getSectionContents(*Shdr);
1417   if (!Contents)
1418     return Contents.takeError();
1419 
1420   auto StringTableShdrOrErr = Obj.getSection(Shdr->sh_link);
1421   if (!StringTableShdrOrErr)
1422     return StringTableShdrOrErr.takeError();
1423 
1424   auto StringTableOrErr = Obj.getStringTable(**StringTableShdrOrErr);
1425   if (!StringTableOrErr)
1426     return StringTableOrErr.takeError();
1427 
1428   S->VerneedV.emplace();
1429 
1430   llvm::ArrayRef<uint8_t> Data = *Contents;
1431   const uint8_t *Buf = Data.data();
1432   while (Buf) {
1433     const Elf_Verneed *Verneed = reinterpret_cast<const Elf_Verneed *>(Buf);
1434 
1435     ELFYAML::VerneedEntry Entry;
1436     Entry.Version = Verneed->vn_version;
1437     Entry.File =
1438         StringRef(StringTableOrErr->drop_front(Verneed->vn_file).data());
1439 
1440     const uint8_t *BufAux = Buf + Verneed->vn_aux;
1441     while (BufAux) {
1442       const Elf_Vernaux *Vernaux =
1443           reinterpret_cast<const Elf_Vernaux *>(BufAux);
1444 
1445       ELFYAML::VernauxEntry Aux;
1446       Aux.Hash = Vernaux->vna_hash;
1447       Aux.Flags = Vernaux->vna_flags;
1448       Aux.Other = Vernaux->vna_other;
1449       Aux.Name =
1450           StringRef(StringTableOrErr->drop_front(Vernaux->vna_name).data());
1451 
1452       Entry.AuxV.push_back(Aux);
1453       BufAux = Vernaux->vna_next ? BufAux + Vernaux->vna_next : nullptr;
1454     }
1455 
1456     S->VerneedV->push_back(Entry);
1457     Buf = Verneed->vn_next ? Buf + Verneed->vn_next : nullptr;
1458   }
1459 
1460   if (Shdr->sh_info != S->VerneedV->size())
1461     S->Info = (llvm::yaml::Hex64)Shdr->sh_info;
1462 
1463   return S.release();
1464 }
1465 
1466 template <class ELFT>
1467 Expected<StringRef> ELFDumper<ELFT>::getSymbolName(uint32_t SymtabNdx,
1468                                                    uint32_t SymbolNdx) {
1469   auto SymtabOrErr = Obj.getSection(SymtabNdx);
1470   if (!SymtabOrErr)
1471     return SymtabOrErr.takeError();
1472 
1473   const Elf_Shdr *Symtab = *SymtabOrErr;
1474   auto SymOrErr = Obj.getSymbol(Symtab, SymbolNdx);
1475   if (!SymOrErr)
1476     return SymOrErr.takeError();
1477 
1478   auto StrTabOrErr = Obj.getStringTableForSymtab(*Symtab);
1479   if (!StrTabOrErr)
1480     return StrTabOrErr.takeError();
1481   return getUniquedSymbolName(*SymOrErr, *StrTabOrErr, Symtab);
1482 }
1483 
1484 template <class ELFT>
1485 Expected<ELFYAML::GroupSection *>
1486 ELFDumper<ELFT>::dumpGroupSection(const Elf_Shdr *Shdr) {
1487   auto S = std::make_unique<ELFYAML::GroupSection>();
1488   if (Error E = dumpCommonSection(Shdr, *S))
1489     return std::move(E);
1490 
1491   // Get symbol with index sh_info. This symbol's name is the signature of the group.
1492   Expected<StringRef> SymbolName = getSymbolName(Shdr->sh_link, Shdr->sh_info);
1493   if (!SymbolName)
1494     return SymbolName.takeError();
1495   S->Signature = *SymbolName;
1496 
1497   auto MembersOrErr = Obj.template getSectionContentsAsArray<Elf_Word>(*Shdr);
1498   if (!MembersOrErr)
1499     return MembersOrErr.takeError();
1500 
1501   S->Members.emplace();
1502   for (Elf_Word Member : *MembersOrErr) {
1503     if (Member == llvm::ELF::GRP_COMDAT) {
1504       S->Members->push_back({"GRP_COMDAT"});
1505       continue;
1506     }
1507 
1508     Expected<const Elf_Shdr *> SHdrOrErr = Obj.getSection(Member);
1509     if (!SHdrOrErr)
1510       return SHdrOrErr.takeError();
1511     Expected<StringRef> NameOrErr = getUniquedSectionName(**SHdrOrErr);
1512     if (!NameOrErr)
1513       return NameOrErr.takeError();
1514     S->Members->push_back({*NameOrErr});
1515   }
1516   return S.release();
1517 }
1518 
1519 template <class ELFT>
1520 Expected<ELFYAML::ARMIndexTableSection *>
1521 ELFDumper<ELFT>::dumpARMIndexTableSection(const Elf_Shdr *Shdr) {
1522   auto S = std::make_unique<ELFYAML::ARMIndexTableSection>();
1523   if (Error E = dumpCommonSection(Shdr, *S))
1524     return std::move(E);
1525 
1526   Expected<ArrayRef<uint8_t>> ContentOrErr = Obj.getSectionContents(*Shdr);
1527   if (!ContentOrErr)
1528     return ContentOrErr.takeError();
1529 
1530   if (ContentOrErr->size() % (sizeof(Elf_Word) * 2) != 0) {
1531     S->Content = yaml::BinaryRef(*ContentOrErr);
1532     return S.release();
1533   }
1534 
1535   ArrayRef<Elf_Word> Words(
1536       reinterpret_cast<const Elf_Word *>(ContentOrErr->data()),
1537       ContentOrErr->size() / sizeof(Elf_Word));
1538 
1539   S->Entries.emplace();
1540   for (size_t I = 0, E = Words.size(); I != E; I += 2)
1541     S->Entries->push_back({(yaml::Hex32)Words[I], (yaml::Hex32)Words[I + 1]});
1542 
1543   return S.release();
1544 }
1545 
1546 template <class ELFT>
1547 Expected<ELFYAML::MipsABIFlags *>
1548 ELFDumper<ELFT>::dumpMipsABIFlags(const Elf_Shdr *Shdr) {
1549   assert(Shdr->sh_type == ELF::SHT_MIPS_ABIFLAGS &&
1550          "Section type is not SHT_MIPS_ABIFLAGS");
1551   auto S = std::make_unique<ELFYAML::MipsABIFlags>();
1552   if (Error E = dumpCommonSection(Shdr, *S))
1553     return std::move(E);
1554 
1555   auto ContentOrErr = Obj.getSectionContents(*Shdr);
1556   if (!ContentOrErr)
1557     return ContentOrErr.takeError();
1558 
1559   auto *Flags = reinterpret_cast<const object::Elf_Mips_ABIFlags<ELFT> *>(
1560       ContentOrErr.get().data());
1561   S->Version = Flags->version;
1562   S->ISALevel = Flags->isa_level;
1563   S->ISARevision = Flags->isa_rev;
1564   S->GPRSize = Flags->gpr_size;
1565   S->CPR1Size = Flags->cpr1_size;
1566   S->CPR2Size = Flags->cpr2_size;
1567   S->FpABI = Flags->fp_abi;
1568   S->ISAExtension = Flags->isa_ext;
1569   S->ASEs = Flags->ases;
1570   S->Flags1 = Flags->flags1;
1571   S->Flags2 = Flags->flags2;
1572   return S.release();
1573 }
1574 
1575 template <class ELFT>
1576 static Error elf2yaml(raw_ostream &Out, const object::ELFFile<ELFT> &Obj,
1577                       std::unique_ptr<DWARFContext> DWARFCtx) {
1578   ELFDumper<ELFT> Dumper(Obj, std::move(DWARFCtx));
1579   Expected<ELFYAML::Object *> YAMLOrErr = Dumper.dump();
1580   if (!YAMLOrErr)
1581     return YAMLOrErr.takeError();
1582 
1583   std::unique_ptr<ELFYAML::Object> YAML(YAMLOrErr.get());
1584   yaml::Output Yout(Out);
1585   Yout << *YAML;
1586 
1587   return Error::success();
1588 }
1589 
1590 Error elf2yaml(raw_ostream &Out, const object::ObjectFile &Obj) {
1591   std::unique_ptr<DWARFContext> DWARFCtx = DWARFContext::create(Obj);
1592   if (const auto *ELFObj = dyn_cast<object::ELF32LEObjectFile>(&Obj))
1593     return elf2yaml(Out, ELFObj->getELFFile(), std::move(DWARFCtx));
1594 
1595   if (const auto *ELFObj = dyn_cast<object::ELF32BEObjectFile>(&Obj))
1596     return elf2yaml(Out, ELFObj->getELFFile(), std::move(DWARFCtx));
1597 
1598   if (const auto *ELFObj = dyn_cast<object::ELF64LEObjectFile>(&Obj))
1599     return elf2yaml(Out, ELFObj->getELFFile(), std::move(DWARFCtx));
1600 
1601   if (const auto *ELFObj = dyn_cast<object::ELF64BEObjectFile>(&Obj))
1602     return elf2yaml(Out, ELFObj->getELFFile(), std::move(DWARFCtx));
1603 
1604   llvm_unreachable("unknown ELF file format");
1605 }
1606