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::find_if(Begin, End, [](uint8_t V) { return V != 0; }) != End;
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 static unsigned getDefaultShEntSize(ELFYAML::ELF_SHT SecType,
735                                     StringRef SecName) {
736   switch (SecType) {
737   case ELF::SHT_GROUP:
738     return sizeof(typename ELFT::Word);
739   case ELF::SHT_REL:
740     return sizeof(typename ELFT::Rel);
741   case ELF::SHT_RELA:
742     return sizeof(typename ELFT::Rela);
743   case ELF::SHT_RELR:
744     return sizeof(typename ELFT::Relr);
745   case ELF::SHT_DYNAMIC:
746     return sizeof(typename ELFT::Dyn);
747   case ELF::SHT_HASH:
748     return sizeof(typename ELFT::Word);
749   default:
750     if (SecName == ".debug_str")
751       return 1;
752     return 0;
753   }
754 }
755 
756 template <class ELFT>
757 Error ELFDumper<ELFT>::dumpCommonSection(const Elf_Shdr *Shdr,
758                                          ELFYAML::Section &S) {
759   // Dump fields. We do not dump the ShOffset field. When not explicitly
760   // set, the value is set by yaml2obj automatically.
761   S.Type = Shdr->sh_type;
762   if (Shdr->sh_flags)
763     S.Flags = static_cast<ELFYAML::ELF_SHF>(Shdr->sh_flags);
764   if (Shdr->sh_addr)
765     S.Address = static_cast<uint64_t>(Shdr->sh_addr);
766   S.AddressAlign = Shdr->sh_addralign;
767 
768   S.OriginalSecNdx = Shdr - &Sections[0];
769 
770   Expected<StringRef> NameOrErr = getUniquedSectionName(*Shdr);
771   if (!NameOrErr)
772     return NameOrErr.takeError();
773   S.Name = NameOrErr.get();
774 
775   if (Shdr->sh_entsize != getDefaultShEntSize<ELFT>(S.Type, S.Name))
776     S.EntSize = static_cast<llvm::yaml::Hex64>(Shdr->sh_entsize);
777 
778   if (Shdr->sh_link != ELF::SHN_UNDEF) {
779     Expected<const Elf_Shdr *> LinkSection = Obj.getSection(Shdr->sh_link);
780     if (!LinkSection)
781       return make_error<StringError>(
782           "unable to resolve sh_link reference in section '" + S.Name +
783               "': " + toString(LinkSection.takeError()),
784           inconvertibleErrorCode());
785 
786     NameOrErr = getUniquedSectionName(**LinkSection);
787     if (!NameOrErr)
788       return NameOrErr.takeError();
789     S.Link = NameOrErr.get();
790   }
791 
792   return Error::success();
793 }
794 
795 template <class ELFT>
796 Error ELFDumper<ELFT>::dumpCommonRelocationSection(
797     const Elf_Shdr *Shdr, ELFYAML::RelocationSection &S) {
798   if (Error E = dumpCommonSection(Shdr, S))
799     return E;
800 
801   // Having a zero sh_info field is normal: .rela.dyn is a dynamic
802   // relocation section that normally has no value in this field.
803   if (!Shdr->sh_info)
804     return Error::success();
805 
806   auto InfoSection = Obj.getSection(Shdr->sh_info);
807   if (!InfoSection)
808     return InfoSection.takeError();
809 
810   Expected<StringRef> NameOrErr = getUniquedSectionName(**InfoSection);
811   if (!NameOrErr)
812     return NameOrErr.takeError();
813   S.RelocatableSec = NameOrErr.get();
814 
815   return Error::success();
816 }
817 
818 template <class ELFT>
819 Expected<ELFYAML::StackSizesSection *>
820 ELFDumper<ELFT>::dumpStackSizesSection(const Elf_Shdr *Shdr) {
821   auto S = std::make_unique<ELFYAML::StackSizesSection>();
822   if (Error E = dumpCommonSection(Shdr, *S))
823     return std::move(E);
824 
825   auto ContentOrErr = Obj.getSectionContents(*Shdr);
826   if (!ContentOrErr)
827     return ContentOrErr.takeError();
828 
829   ArrayRef<uint8_t> Content = *ContentOrErr;
830   DataExtractor Data(Content, Obj.isLE(), ELFT::Is64Bits ? 8 : 4);
831 
832   std::vector<ELFYAML::StackSizeEntry> Entries;
833   DataExtractor::Cursor Cur(0);
834   while (Cur && Cur.tell() < Content.size()) {
835     uint64_t Address = Data.getAddress(Cur);
836     uint64_t Size = Data.getULEB128(Cur);
837     Entries.push_back({Address, Size});
838   }
839 
840   if (Content.empty() || !Cur) {
841     // If .stack_sizes cannot be decoded, we dump it as an array of bytes.
842     consumeError(Cur.takeError());
843     S->Content = yaml::BinaryRef(Content);
844   } else {
845     S->Entries = std::move(Entries);
846   }
847 
848   return S.release();
849 }
850 
851 template <class ELFT>
852 Expected<ELFYAML::BBAddrMapSection *>
853 ELFDumper<ELFT>::dumpBBAddrMapSection(const Elf_Shdr *Shdr) {
854   auto S = std::make_unique<ELFYAML::BBAddrMapSection>();
855   if (Error E = dumpCommonSection(Shdr, *S))
856     return std::move(E);
857 
858   auto ContentOrErr = Obj.getSectionContents(*Shdr);
859   if (!ContentOrErr)
860     return ContentOrErr.takeError();
861 
862   ArrayRef<uint8_t> Content = *ContentOrErr;
863   if (Content.empty())
864     return S.release();
865 
866   DataExtractor Data(Content, Obj.isLE(), ELFT::Is64Bits ? 8 : 4);
867 
868   std::vector<ELFYAML::BBAddrMapEntry> Entries;
869   DataExtractor::Cursor Cur(0);
870   while (Cur && Cur.tell() < Content.size()) {
871     uint64_t Address = Data.getAddress(Cur);
872     uint32_t NumBlocks = Data.getULEB128(Cur);
873     std::vector<ELFYAML::BBAddrMapEntry::BBEntry> BBEntries;
874     // Read the specified number of BB entries, or until decoding fails.
875     for (uint32_t BlockID = 0; Cur && BlockID < NumBlocks; ++BlockID) {
876       uint32_t Offset = Data.getULEB128(Cur);
877       uint32_t Size = Data.getULEB128(Cur);
878       uint32_t Metadata = Data.getULEB128(Cur);
879       BBEntries.push_back({Offset, Size, Metadata});
880     }
881     Entries.push_back({Address, BBEntries});
882   }
883 
884   if (!Cur) {
885     // If the section cannot be decoded, we dump it as an array of bytes.
886     consumeError(Cur.takeError());
887     S->Content = yaml::BinaryRef(Content);
888   } else {
889     S->Entries = std::move(Entries);
890   }
891 
892   return S.release();
893 }
894 
895 template <class ELFT>
896 Expected<ELFYAML::AddrsigSection *>
897 ELFDumper<ELFT>::dumpAddrsigSection(const Elf_Shdr *Shdr) {
898   auto S = std::make_unique<ELFYAML::AddrsigSection>();
899   if (Error E = dumpCommonSection(Shdr, *S))
900     return std::move(E);
901 
902   auto ContentOrErr = Obj.getSectionContents(*Shdr);
903   if (!ContentOrErr)
904     return ContentOrErr.takeError();
905 
906   ArrayRef<uint8_t> Content = *ContentOrErr;
907   DataExtractor::Cursor Cur(0);
908   DataExtractor Data(Content, Obj.isLE(), /*AddressSize=*/0);
909   std::vector<ELFYAML::YAMLFlowString> Symbols;
910   while (Cur && Cur.tell() < Content.size()) {
911     uint64_t SymNdx = Data.getULEB128(Cur);
912     if (!Cur)
913       break;
914 
915     Expected<StringRef> SymbolName = getSymbolName(Shdr->sh_link, SymNdx);
916     if (!SymbolName || SymbolName->empty()) {
917       consumeError(SymbolName.takeError());
918       Symbols.emplace_back(
919           StringRef(std::to_string(SymNdx)).copy(StringAllocator));
920       continue;
921     }
922 
923     Symbols.emplace_back(*SymbolName);
924   }
925 
926   if (Cur) {
927     S->Symbols = std::move(Symbols);
928     return S.release();
929   }
930 
931   consumeError(Cur.takeError());
932   S->Content = yaml::BinaryRef(Content);
933   return S.release();
934 }
935 
936 template <class ELFT>
937 Expected<ELFYAML::LinkerOptionsSection *>
938 ELFDumper<ELFT>::dumpLinkerOptionsSection(const Elf_Shdr *Shdr) {
939   auto S = std::make_unique<ELFYAML::LinkerOptionsSection>();
940   if (Error E = dumpCommonSection(Shdr, *S))
941     return std::move(E);
942 
943   auto ContentOrErr = Obj.getSectionContents(*Shdr);
944   if (!ContentOrErr)
945     return ContentOrErr.takeError();
946 
947   ArrayRef<uint8_t> Content = *ContentOrErr;
948   if (Content.empty() || Content.back() != 0) {
949     S->Content = Content;
950     return S.release();
951   }
952 
953   SmallVector<StringRef, 16> Strings;
954   toStringRef(Content.drop_back()).split(Strings, '\0');
955   if (Strings.size() % 2 != 0) {
956     S->Content = Content;
957     return S.release();
958   }
959 
960   S->Options.emplace();
961   for (size_t I = 0, E = Strings.size(); I != E; I += 2)
962     S->Options->push_back({Strings[I], Strings[I + 1]});
963 
964   return S.release();
965 }
966 
967 template <class ELFT>
968 Expected<ELFYAML::DependentLibrariesSection *>
969 ELFDumper<ELFT>::dumpDependentLibrariesSection(const Elf_Shdr *Shdr) {
970   auto DL = std::make_unique<ELFYAML::DependentLibrariesSection>();
971   if (Error E = dumpCommonSection(Shdr, *DL))
972     return std::move(E);
973 
974   Expected<ArrayRef<uint8_t>> ContentOrErr = Obj.getSectionContents(*Shdr);
975   if (!ContentOrErr)
976     return ContentOrErr.takeError();
977 
978   ArrayRef<uint8_t> Content = *ContentOrErr;
979   if (!Content.empty() && Content.back() != 0) {
980     DL->Content = Content;
981     return DL.release();
982   }
983 
984   DL->Libs.emplace();
985   for (const uint8_t *I = Content.begin(), *E = Content.end(); I < E;) {
986     StringRef Lib((const char *)I);
987     DL->Libs->emplace_back(Lib);
988     I += Lib.size() + 1;
989   }
990 
991   return DL.release();
992 }
993 
994 template <class ELFT>
995 Expected<ELFYAML::CallGraphProfileSection *>
996 ELFDumper<ELFT>::dumpCallGraphProfileSection(const Elf_Shdr *Shdr) {
997   auto S = std::make_unique<ELFYAML::CallGraphProfileSection>();
998   if (Error E = dumpCommonSection(Shdr, *S))
999     return std::move(E);
1000 
1001   Expected<ArrayRef<uint8_t>> ContentOrErr = Obj.getSectionContents(*Shdr);
1002   if (!ContentOrErr)
1003     return ContentOrErr.takeError();
1004   ArrayRef<uint8_t> Content = *ContentOrErr;
1005 
1006   // Dump the section by using the Content key when it is truncated.
1007   // There is no need to create either "Content" or "Entries" fields when the
1008   // section is empty.
1009   if (Content.empty() || Content.size() % 16 != 0) {
1010     if (!Content.empty())
1011       S->Content = yaml::BinaryRef(Content);
1012     return S.release();
1013   }
1014 
1015   std::vector<ELFYAML::CallGraphEntry> Entries(Content.size() / 16);
1016   DataExtractor Data(Content, Obj.isLE(), /*AddressSize=*/0);
1017   DataExtractor::Cursor Cur(0);
1018   auto ReadEntry = [&](ELFYAML::CallGraphEntry &E) {
1019     uint32_t FromSymIndex = Data.getU32(Cur);
1020     uint32_t ToSymIndex = Data.getU32(Cur);
1021     E.Weight = Data.getU64(Cur);
1022     if (!Cur) {
1023       consumeError(Cur.takeError());
1024       return false;
1025     }
1026 
1027     Expected<StringRef> From = getSymbolName(Shdr->sh_link, FromSymIndex);
1028     Expected<StringRef> To = getSymbolName(Shdr->sh_link, ToSymIndex);
1029     if (From && To) {
1030       E.From = *From;
1031       E.To = *To;
1032       return true;
1033     }
1034     consumeError(From.takeError());
1035     consumeError(To.takeError());
1036     return false;
1037   };
1038 
1039   for (ELFYAML::CallGraphEntry &E : Entries) {
1040     if (ReadEntry(E))
1041       continue;
1042     S->Content = yaml::BinaryRef(Content);
1043     return S.release();
1044   }
1045 
1046   S->Entries = std::move(Entries);
1047   return S.release();
1048 }
1049 
1050 template <class ELFT>
1051 Expected<ELFYAML::DynamicSection *>
1052 ELFDumper<ELFT>::dumpDynamicSection(const Elf_Shdr *Shdr) {
1053   auto S = std::make_unique<ELFYAML::DynamicSection>();
1054   if (Error E = dumpCommonSection(Shdr, *S))
1055     return std::move(E);
1056 
1057   auto DynTagsOrErr = Obj.template getSectionContentsAsArray<Elf_Dyn>(*Shdr);
1058   if (!DynTagsOrErr)
1059     return DynTagsOrErr.takeError();
1060 
1061   S->Entries.emplace();
1062   for (const Elf_Dyn &Dyn : *DynTagsOrErr)
1063     S->Entries->push_back({(ELFYAML::ELF_DYNTAG)Dyn.getTag(), Dyn.getVal()});
1064 
1065   return S.release();
1066 }
1067 
1068 template <class ELFT>
1069 Expected<ELFYAML::RelocationSection *>
1070 ELFDumper<ELFT>::dumpRelocSection(const Elf_Shdr *Shdr) {
1071   auto S = std::make_unique<ELFYAML::RelocationSection>();
1072   if (auto E = dumpCommonRelocationSection(Shdr, *S))
1073     return std::move(E);
1074 
1075   auto SymTabOrErr = Obj.getSection(Shdr->sh_link);
1076   if (!SymTabOrErr)
1077     return SymTabOrErr.takeError();
1078 
1079   if (Shdr->sh_size != 0)
1080     S->Relocations.emplace();
1081 
1082   if (Shdr->sh_type == ELF::SHT_REL) {
1083     auto Rels = Obj.rels(*Shdr);
1084     if (!Rels)
1085       return Rels.takeError();
1086     for (const Elf_Rel &Rel : *Rels) {
1087       ELFYAML::Relocation R;
1088       if (Error E = dumpRelocation(&Rel, *SymTabOrErr, R))
1089         return std::move(E);
1090       S->Relocations->push_back(R);
1091     }
1092   } else {
1093     auto Rels = Obj.relas(*Shdr);
1094     if (!Rels)
1095       return Rels.takeError();
1096     for (const Elf_Rela &Rel : *Rels) {
1097       ELFYAML::Relocation R;
1098       if (Error E = dumpRelocation(&Rel, *SymTabOrErr, R))
1099         return std::move(E);
1100       R.Addend = Rel.r_addend;
1101       S->Relocations->push_back(R);
1102     }
1103   }
1104 
1105   return S.release();
1106 }
1107 
1108 template <class ELFT>
1109 Expected<ELFYAML::RelrSection *>
1110 ELFDumper<ELFT>::dumpRelrSection(const Elf_Shdr *Shdr) {
1111   auto S = std::make_unique<ELFYAML::RelrSection>();
1112   if (auto E = dumpCommonSection(Shdr, *S))
1113     return std::move(E);
1114 
1115   if (Expected<ArrayRef<Elf_Relr>> Relrs = Obj.relrs(*Shdr)) {
1116     S->Entries.emplace();
1117     for (Elf_Relr Rel : *Relrs)
1118       S->Entries->emplace_back(Rel);
1119     return S.release();
1120   } else {
1121     // Ignore. We are going to dump the data as raw content below.
1122     consumeError(Relrs.takeError());
1123   }
1124 
1125   Expected<ArrayRef<uint8_t>> ContentOrErr = Obj.getSectionContents(*Shdr);
1126   if (!ContentOrErr)
1127     return ContentOrErr.takeError();
1128   S->Content = *ContentOrErr;
1129   return S.release();
1130 }
1131 
1132 template <class ELFT>
1133 Expected<ELFYAML::RawContentSection *>
1134 ELFDumper<ELFT>::dumpContentSection(const Elf_Shdr *Shdr) {
1135   auto S = std::make_unique<ELFYAML::RawContentSection>();
1136   if (Error E = dumpCommonSection(Shdr, *S))
1137     return std::move(E);
1138 
1139   unsigned SecIndex = Shdr - &Sections[0];
1140   if (SecIndex != 0 || Shdr->sh_type != ELF::SHT_NULL) {
1141     auto ContentOrErr = Obj.getSectionContents(*Shdr);
1142     if (!ContentOrErr)
1143       return ContentOrErr.takeError();
1144     ArrayRef<uint8_t> Content = *ContentOrErr;
1145     if (!Content.empty())
1146       S->Content = yaml::BinaryRef(Content);
1147   } else {
1148     S->Size = static_cast<llvm::yaml::Hex64>(Shdr->sh_size);
1149   }
1150 
1151   if (Shdr->sh_info)
1152     S->Info = static_cast<llvm::yaml::Hex64>(Shdr->sh_info);
1153   return S.release();
1154 }
1155 
1156 template <class ELFT>
1157 Expected<ELFYAML::SymtabShndxSection *>
1158 ELFDumper<ELFT>::dumpSymtabShndxSection(const Elf_Shdr *Shdr) {
1159   auto S = std::make_unique<ELFYAML::SymtabShndxSection>();
1160   if (Error E = dumpCommonSection(Shdr, *S))
1161     return std::move(E);
1162 
1163   auto EntriesOrErr = Obj.template getSectionContentsAsArray<Elf_Word>(*Shdr);
1164   if (!EntriesOrErr)
1165     return EntriesOrErr.takeError();
1166 
1167   S->Entries.emplace();
1168   for (const Elf_Word &E : *EntriesOrErr)
1169     S->Entries->push_back(E);
1170   return S.release();
1171 }
1172 
1173 template <class ELFT>
1174 Expected<ELFYAML::NoBitsSection *>
1175 ELFDumper<ELFT>::dumpNoBitsSection(const Elf_Shdr *Shdr) {
1176   auto S = std::make_unique<ELFYAML::NoBitsSection>();
1177   if (Error E = dumpCommonSection(Shdr, *S))
1178     return std::move(E);
1179   if (Shdr->sh_size)
1180     S->Size = static_cast<llvm::yaml::Hex64>(Shdr->sh_size);
1181   return S.release();
1182 }
1183 
1184 template <class ELFT>
1185 Expected<ELFYAML::NoteSection *>
1186 ELFDumper<ELFT>::dumpNoteSection(const Elf_Shdr *Shdr) {
1187   auto S = std::make_unique<ELFYAML::NoteSection>();
1188   if (Error E = dumpCommonSection(Shdr, *S))
1189     return std::move(E);
1190 
1191   auto ContentOrErr = Obj.getSectionContents(*Shdr);
1192   if (!ContentOrErr)
1193     return ContentOrErr.takeError();
1194 
1195   std::vector<ELFYAML::NoteEntry> Entries;
1196   ArrayRef<uint8_t> Content = *ContentOrErr;
1197   while (!Content.empty()) {
1198     if (Content.size() < sizeof(Elf_Nhdr)) {
1199       S->Content = yaml::BinaryRef(*ContentOrErr);
1200       return S.release();
1201     }
1202 
1203     const Elf_Nhdr *Header = reinterpret_cast<const Elf_Nhdr *>(Content.data());
1204     if (Content.size() < Header->getSize()) {
1205       S->Content = yaml::BinaryRef(*ContentOrErr);
1206       return S.release();
1207     }
1208 
1209     Elf_Note Note(*Header);
1210     Entries.push_back(
1211         {Note.getName(), Note.getDesc(), (llvm::yaml::Hex32)Note.getType()});
1212 
1213     Content = Content.drop_front(Header->getSize());
1214   }
1215 
1216   S->Notes = std::move(Entries);
1217   return S.release();
1218 }
1219 
1220 template <class ELFT>
1221 Expected<ELFYAML::HashSection *>
1222 ELFDumper<ELFT>::dumpHashSection(const Elf_Shdr *Shdr) {
1223   auto S = std::make_unique<ELFYAML::HashSection>();
1224   if (Error E = dumpCommonSection(Shdr, *S))
1225     return std::move(E);
1226 
1227   auto ContentOrErr = Obj.getSectionContents(*Shdr);
1228   if (!ContentOrErr)
1229     return ContentOrErr.takeError();
1230 
1231   ArrayRef<uint8_t> Content = *ContentOrErr;
1232   if (Content.size() % 4 != 0 || Content.size() < 8) {
1233     S->Content = yaml::BinaryRef(Content);
1234     return S.release();
1235   }
1236 
1237   DataExtractor::Cursor Cur(0);
1238   DataExtractor Data(Content, Obj.isLE(), /*AddressSize=*/0);
1239   uint64_t NBucket = Data.getU32(Cur);
1240   uint64_t NChain = Data.getU32(Cur);
1241   if (Content.size() != (2 + NBucket + NChain) * 4) {
1242     S->Content = yaml::BinaryRef(Content);
1243     if (Cur)
1244       return S.release();
1245     llvm_unreachable("entries were not read correctly");
1246   }
1247 
1248   S->Bucket.emplace(NBucket);
1249   for (uint32_t &V : *S->Bucket)
1250     V = Data.getU32(Cur);
1251 
1252   S->Chain.emplace(NChain);
1253   for (uint32_t &V : *S->Chain)
1254     V = Data.getU32(Cur);
1255 
1256   if (Cur)
1257     return S.release();
1258   llvm_unreachable("entries were not read correctly");
1259 }
1260 
1261 template <class ELFT>
1262 Expected<ELFYAML::GnuHashSection *>
1263 ELFDumper<ELFT>::dumpGnuHashSection(const Elf_Shdr *Shdr) {
1264   auto S = std::make_unique<ELFYAML::GnuHashSection>();
1265   if (Error E = dumpCommonSection(Shdr, *S))
1266     return std::move(E);
1267 
1268   auto ContentOrErr = Obj.getSectionContents(*Shdr);
1269   if (!ContentOrErr)
1270     return ContentOrErr.takeError();
1271 
1272   unsigned AddrSize = ELFT::Is64Bits ? 8 : 4;
1273   ArrayRef<uint8_t> Content = *ContentOrErr;
1274   DataExtractor Data(Content, Obj.isLE(), AddrSize);
1275 
1276   ELFYAML::GnuHashHeader Header;
1277   DataExtractor::Cursor Cur(0);
1278   uint64_t NBuckets = Data.getU32(Cur);
1279   Header.SymNdx = Data.getU32(Cur);
1280   uint64_t MaskWords = Data.getU32(Cur);
1281   Header.Shift2 = Data.getU32(Cur);
1282 
1283   // Set just the raw binary content if we were unable to read the header
1284   // or when the section data is truncated or malformed.
1285   uint64_t Size = Data.getData().size() - Cur.tell();
1286   if (!Cur || (Size < MaskWords * AddrSize + NBuckets * 4) ||
1287       (Size % 4 != 0)) {
1288     consumeError(Cur.takeError());
1289     S->Content = yaml::BinaryRef(Content);
1290     return S.release();
1291   }
1292 
1293   S->Header = Header;
1294 
1295   S->BloomFilter.emplace(MaskWords);
1296   for (llvm::yaml::Hex64 &Val : *S->BloomFilter)
1297     Val = Data.getAddress(Cur);
1298 
1299   S->HashBuckets.emplace(NBuckets);
1300   for (llvm::yaml::Hex32 &Val : *S->HashBuckets)
1301     Val = Data.getU32(Cur);
1302 
1303   S->HashValues.emplace((Data.getData().size() - Cur.tell()) / 4);
1304   for (llvm::yaml::Hex32 &Val : *S->HashValues)
1305     Val = Data.getU32(Cur);
1306 
1307   if (Cur)
1308     return S.release();
1309   llvm_unreachable("GnuHashSection was not read correctly");
1310 }
1311 
1312 template <class ELFT>
1313 Expected<ELFYAML::VerdefSection *>
1314 ELFDumper<ELFT>::dumpVerdefSection(const Elf_Shdr *Shdr) {
1315   auto S = std::make_unique<ELFYAML::VerdefSection>();
1316   if (Error E = dumpCommonSection(Shdr, *S))
1317     return std::move(E);
1318 
1319   S->Info = Shdr->sh_info;
1320 
1321   auto StringTableShdrOrErr = Obj.getSection(Shdr->sh_link);
1322   if (!StringTableShdrOrErr)
1323     return StringTableShdrOrErr.takeError();
1324 
1325   auto StringTableOrErr = Obj.getStringTable(**StringTableShdrOrErr);
1326   if (!StringTableOrErr)
1327     return StringTableOrErr.takeError();
1328 
1329   auto Contents = Obj.getSectionContents(*Shdr);
1330   if (!Contents)
1331     return Contents.takeError();
1332 
1333   S->Entries.emplace();
1334 
1335   llvm::ArrayRef<uint8_t> Data = *Contents;
1336   const uint8_t *Buf = Data.data();
1337   while (Buf) {
1338     const Elf_Verdef *Verdef = reinterpret_cast<const Elf_Verdef *>(Buf);
1339     ELFYAML::VerdefEntry Entry;
1340     Entry.Version = Verdef->vd_version;
1341     Entry.Flags = Verdef->vd_flags;
1342     Entry.VersionNdx = Verdef->vd_ndx;
1343     Entry.Hash = Verdef->vd_hash;
1344 
1345     const uint8_t *BufAux = Buf + Verdef->vd_aux;
1346     while (BufAux) {
1347       const Elf_Verdaux *Verdaux =
1348           reinterpret_cast<const Elf_Verdaux *>(BufAux);
1349       Entry.VerNames.push_back(
1350           StringTableOrErr->drop_front(Verdaux->vda_name).data());
1351       BufAux = Verdaux->vda_next ? BufAux + Verdaux->vda_next : nullptr;
1352     }
1353 
1354     S->Entries->push_back(Entry);
1355     Buf = Verdef->vd_next ? Buf + Verdef->vd_next : nullptr;
1356   }
1357 
1358   return S.release();
1359 }
1360 
1361 template <class ELFT>
1362 Expected<ELFYAML::SymverSection *>
1363 ELFDumper<ELFT>::dumpSymverSection(const Elf_Shdr *Shdr) {
1364   auto S = std::make_unique<ELFYAML::SymverSection>();
1365   if (Error E = dumpCommonSection(Shdr, *S))
1366     return std::move(E);
1367 
1368   auto VersionsOrErr = Obj.template getSectionContentsAsArray<Elf_Half>(*Shdr);
1369   if (!VersionsOrErr)
1370     return VersionsOrErr.takeError();
1371 
1372   S->Entries.emplace();
1373   for (const Elf_Half &E : *VersionsOrErr)
1374     S->Entries->push_back(E);
1375 
1376   return S.release();
1377 }
1378 
1379 template <class ELFT>
1380 Expected<ELFYAML::VerneedSection *>
1381 ELFDumper<ELFT>::dumpVerneedSection(const Elf_Shdr *Shdr) {
1382   auto S = std::make_unique<ELFYAML::VerneedSection>();
1383   if (Error E = dumpCommonSection(Shdr, *S))
1384     return std::move(E);
1385 
1386   S->Info = Shdr->sh_info;
1387 
1388   auto Contents = Obj.getSectionContents(*Shdr);
1389   if (!Contents)
1390     return Contents.takeError();
1391 
1392   auto StringTableShdrOrErr = Obj.getSection(Shdr->sh_link);
1393   if (!StringTableShdrOrErr)
1394     return StringTableShdrOrErr.takeError();
1395 
1396   auto StringTableOrErr = Obj.getStringTable(**StringTableShdrOrErr);
1397   if (!StringTableOrErr)
1398     return StringTableOrErr.takeError();
1399 
1400   S->VerneedV.emplace();
1401 
1402   llvm::ArrayRef<uint8_t> Data = *Contents;
1403   const uint8_t *Buf = Data.data();
1404   while (Buf) {
1405     const Elf_Verneed *Verneed = reinterpret_cast<const Elf_Verneed *>(Buf);
1406 
1407     ELFYAML::VerneedEntry Entry;
1408     Entry.Version = Verneed->vn_version;
1409     Entry.File =
1410         StringRef(StringTableOrErr->drop_front(Verneed->vn_file).data());
1411 
1412     const uint8_t *BufAux = Buf + Verneed->vn_aux;
1413     while (BufAux) {
1414       const Elf_Vernaux *Vernaux =
1415           reinterpret_cast<const Elf_Vernaux *>(BufAux);
1416 
1417       ELFYAML::VernauxEntry Aux;
1418       Aux.Hash = Vernaux->vna_hash;
1419       Aux.Flags = Vernaux->vna_flags;
1420       Aux.Other = Vernaux->vna_other;
1421       Aux.Name =
1422           StringRef(StringTableOrErr->drop_front(Vernaux->vna_name).data());
1423 
1424       Entry.AuxV.push_back(Aux);
1425       BufAux = Vernaux->vna_next ? BufAux + Vernaux->vna_next : nullptr;
1426     }
1427 
1428     S->VerneedV->push_back(Entry);
1429     Buf = Verneed->vn_next ? Buf + Verneed->vn_next : nullptr;
1430   }
1431 
1432   return S.release();
1433 }
1434 
1435 template <class ELFT>
1436 Expected<StringRef> ELFDumper<ELFT>::getSymbolName(uint32_t SymtabNdx,
1437                                                    uint32_t SymbolNdx) {
1438   auto SymtabOrErr = Obj.getSection(SymtabNdx);
1439   if (!SymtabOrErr)
1440     return SymtabOrErr.takeError();
1441 
1442   const Elf_Shdr *Symtab = *SymtabOrErr;
1443   auto SymOrErr = Obj.getSymbol(Symtab, SymbolNdx);
1444   if (!SymOrErr)
1445     return SymOrErr.takeError();
1446 
1447   auto StrTabOrErr = Obj.getStringTableForSymtab(*Symtab);
1448   if (!StrTabOrErr)
1449     return StrTabOrErr.takeError();
1450   return getUniquedSymbolName(*SymOrErr, *StrTabOrErr, Symtab);
1451 }
1452 
1453 template <class ELFT>
1454 Expected<ELFYAML::GroupSection *>
1455 ELFDumper<ELFT>::dumpGroupSection(const Elf_Shdr *Shdr) {
1456   auto S = std::make_unique<ELFYAML::GroupSection>();
1457   if (Error E = dumpCommonSection(Shdr, *S))
1458     return std::move(E);
1459 
1460   // Get symbol with index sh_info. This symbol's name is the signature of the group.
1461   Expected<StringRef> SymbolName = getSymbolName(Shdr->sh_link, Shdr->sh_info);
1462   if (!SymbolName)
1463     return SymbolName.takeError();
1464   S->Signature = *SymbolName;
1465 
1466   auto MembersOrErr = Obj.template getSectionContentsAsArray<Elf_Word>(*Shdr);
1467   if (!MembersOrErr)
1468     return MembersOrErr.takeError();
1469 
1470   S->Members.emplace();
1471   for (Elf_Word Member : *MembersOrErr) {
1472     if (Member == llvm::ELF::GRP_COMDAT) {
1473       S->Members->push_back({"GRP_COMDAT"});
1474       continue;
1475     }
1476 
1477     Expected<const Elf_Shdr *> SHdrOrErr = Obj.getSection(Member);
1478     if (!SHdrOrErr)
1479       return SHdrOrErr.takeError();
1480     Expected<StringRef> NameOrErr = getUniquedSectionName(**SHdrOrErr);
1481     if (!NameOrErr)
1482       return NameOrErr.takeError();
1483     S->Members->push_back({*NameOrErr});
1484   }
1485   return S.release();
1486 }
1487 
1488 template <class ELFT>
1489 Expected<ELFYAML::ARMIndexTableSection *>
1490 ELFDumper<ELFT>::dumpARMIndexTableSection(const Elf_Shdr *Shdr) {
1491   auto S = std::make_unique<ELFYAML::ARMIndexTableSection>();
1492   if (Error E = dumpCommonSection(Shdr, *S))
1493     return std::move(E);
1494 
1495   Expected<ArrayRef<uint8_t>> ContentOrErr = Obj.getSectionContents(*Shdr);
1496   if (!ContentOrErr)
1497     return ContentOrErr.takeError();
1498 
1499   if (ContentOrErr->size() % (sizeof(Elf_Word) * 2) != 0) {
1500     S->Content = yaml::BinaryRef(*ContentOrErr);
1501     return S.release();
1502   }
1503 
1504   ArrayRef<Elf_Word> Words(
1505       reinterpret_cast<const Elf_Word *>(ContentOrErr->data()),
1506       ContentOrErr->size() / sizeof(Elf_Word));
1507 
1508   S->Entries.emplace();
1509   for (size_t I = 0, E = Words.size(); I != E; I += 2)
1510     S->Entries->push_back({(yaml::Hex32)Words[I], (yaml::Hex32)Words[I + 1]});
1511 
1512   return S.release();
1513 }
1514 
1515 template <class ELFT>
1516 Expected<ELFYAML::MipsABIFlags *>
1517 ELFDumper<ELFT>::dumpMipsABIFlags(const Elf_Shdr *Shdr) {
1518   assert(Shdr->sh_type == ELF::SHT_MIPS_ABIFLAGS &&
1519          "Section type is not SHT_MIPS_ABIFLAGS");
1520   auto S = std::make_unique<ELFYAML::MipsABIFlags>();
1521   if (Error E = dumpCommonSection(Shdr, *S))
1522     return std::move(E);
1523 
1524   auto ContentOrErr = Obj.getSectionContents(*Shdr);
1525   if (!ContentOrErr)
1526     return ContentOrErr.takeError();
1527 
1528   auto *Flags = reinterpret_cast<const object::Elf_Mips_ABIFlags<ELFT> *>(
1529       ContentOrErr.get().data());
1530   S->Version = Flags->version;
1531   S->ISALevel = Flags->isa_level;
1532   S->ISARevision = Flags->isa_rev;
1533   S->GPRSize = Flags->gpr_size;
1534   S->CPR1Size = Flags->cpr1_size;
1535   S->CPR2Size = Flags->cpr2_size;
1536   S->FpABI = Flags->fp_abi;
1537   S->ISAExtension = Flags->isa_ext;
1538   S->ASEs = Flags->ases;
1539   S->Flags1 = Flags->flags1;
1540   S->Flags2 = Flags->flags2;
1541   return S.release();
1542 }
1543 
1544 template <class ELFT>
1545 static Error elf2yaml(raw_ostream &Out, const object::ELFFile<ELFT> &Obj,
1546                       std::unique_ptr<DWARFContext> DWARFCtx) {
1547   ELFDumper<ELFT> Dumper(Obj, std::move(DWARFCtx));
1548   Expected<ELFYAML::Object *> YAMLOrErr = Dumper.dump();
1549   if (!YAMLOrErr)
1550     return YAMLOrErr.takeError();
1551 
1552   std::unique_ptr<ELFYAML::Object> YAML(YAMLOrErr.get());
1553   yaml::Output Yout(Out);
1554   Yout << *YAML;
1555 
1556   return Error::success();
1557 }
1558 
1559 Error elf2yaml(raw_ostream &Out, const object::ObjectFile &Obj) {
1560   std::unique_ptr<DWARFContext> DWARFCtx = DWARFContext::create(Obj);
1561   if (const auto *ELFObj = dyn_cast<object::ELF32LEObjectFile>(&Obj))
1562     return elf2yaml(Out, ELFObj->getELFFile(), std::move(DWARFCtx));
1563 
1564   if (const auto *ELFObj = dyn_cast<object::ELF32BEObjectFile>(&Obj))
1565     return elf2yaml(Out, ELFObj->getELFFile(), std::move(DWARFCtx));
1566 
1567   if (const auto *ELFObj = dyn_cast<object::ELF64LEObjectFile>(&Obj))
1568     return elf2yaml(Out, ELFObj->getELFFile(), std::move(DWARFCtx));
1569 
1570   if (const auto *ELFObj = dyn_cast<object::ELF64BEObjectFile>(&Obj))
1571     return elf2yaml(Out, ELFObj->getELFFile(), std::move(DWARFCtx));
1572 
1573   llvm_unreachable("unknown ELF file format");
1574 }
1575