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