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