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