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