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