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