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