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 "Error.h"
10 #include "llvm/ADT/DenseSet.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/Object/ELFObjectFile.h"
13 #include "llvm/ObjectYAML/ELFYAML.h"
14 #include "llvm/Support/DataExtractor.h"
15 #include "llvm/Support/ErrorHandling.h"
16 #include "llvm/Support/YAMLTraits.h"
17 
18 using namespace llvm;
19 
20 namespace {
21 
22 template <class ELFT>
23 class ELFDumper {
24   typedef object::Elf_Sym_Impl<ELFT> Elf_Sym;
25   typedef typename ELFT::Dyn Elf_Dyn;
26   typedef typename ELFT::Shdr Elf_Shdr;
27   typedef typename ELFT::Word Elf_Word;
28   typedef typename ELFT::Rel Elf_Rel;
29   typedef typename ELFT::Rela Elf_Rela;
30   using Elf_Nhdr = typename ELFT::Nhdr;
31   using Elf_Note = typename ELFT::Note;
32 
33   ArrayRef<Elf_Shdr> Sections;
34   ArrayRef<Elf_Sym> SymTable;
35 
36   DenseMap<StringRef, uint32_t> UsedSectionNames;
37   std::vector<std::string> SectionNames;
38 
39   DenseMap<StringRef, uint32_t> UsedSymbolNames;
40   std::vector<std::string> SymbolNames;
41 
42   Expected<StringRef> getUniquedSectionName(const Elf_Shdr *Sec);
43   Expected<StringRef> getUniquedSymbolName(const Elf_Sym *Sym,
44                                            StringRef StrTable,
45                                            const Elf_Shdr *SymTab);
46   Expected<StringRef> getSymbolName(uint32_t SymtabNdx, uint32_t SymbolNdx);
47 
48   const object::ELFFile<ELFT> &Obj;
49   ArrayRef<Elf_Word> ShndxTable;
50 
51   Error dumpSymbols(const Elf_Shdr *Symtab,
52                     std::vector<ELFYAML::Symbol> &Symbols);
53   Error dumpSymbol(const Elf_Sym *Sym, const Elf_Shdr *SymTab,
54                    StringRef StrTable, ELFYAML::Symbol &S);
55   Error dumpCommonSection(const Elf_Shdr *Shdr, ELFYAML::Section &S);
56   Error dumpCommonRelocationSection(const Elf_Shdr *Shdr,
57                                     ELFYAML::RelocationSection &S);
58   template <class RelT>
59   Error dumpRelocation(const RelT *Rel, const Elf_Shdr *SymTab,
60                        ELFYAML::Relocation &R);
61 
62   Expected<ELFYAML::AddrsigSection *> dumpAddrsigSection(const Elf_Shdr *Shdr);
63   Expected<ELFYAML::DynamicSection *> dumpDynamicSection(const Elf_Shdr *Shdr);
64   Expected<ELFYAML::RelocationSection *> dumpRelocSection(const Elf_Shdr *Shdr);
65   Expected<ELFYAML::RawContentSection *>
66   dumpContentSection(const Elf_Shdr *Shdr);
67   Expected<ELFYAML::SymtabShndxSection *>
68   dumpSymtabShndxSection(const Elf_Shdr *Shdr);
69   Expected<ELFYAML::NoBitsSection *> dumpNoBitsSection(const Elf_Shdr *Shdr);
70   Expected<ELFYAML::HashSection *> dumpHashSection(const Elf_Shdr *Shdr);
71   Expected<ELFYAML::NoteSection *> dumpNoteSection(const Elf_Shdr *Shdr);
72   Expected<ELFYAML::GnuHashSection *> dumpGnuHashSection(const Elf_Shdr *Shdr);
73   Expected<ELFYAML::VerdefSection *> dumpVerdefSection(const Elf_Shdr *Shdr);
74   Expected<ELFYAML::SymverSection *> dumpSymverSection(const Elf_Shdr *Shdr);
75   Expected<ELFYAML::VerneedSection *> dumpVerneedSection(const Elf_Shdr *Shdr);
76   Expected<ELFYAML::Group *> dumpGroup(const Elf_Shdr *Shdr);
77   Expected<ELFYAML::MipsABIFlags *> dumpMipsABIFlags(const Elf_Shdr *Shdr);
78   Expected<ELFYAML::StackSizesSection *>
79   dumpStackSizesSection(const Elf_Shdr *Shdr);
80 
81   Expected<ELFYAML::Section *> dumpSpecialSection(const Elf_Shdr *Shdr);
82 
83 public:
84   ELFDumper(const object::ELFFile<ELFT> &O);
85   Expected<ELFYAML::Object *> dump();
86 };
87 
88 }
89 
90 template <class ELFT>
91 ELFDumper<ELFT>::ELFDumper(const object::ELFFile<ELFT> &O)
92     : Obj(O) {}
93 
94 template <class ELFT>
95 Expected<StringRef>
96 ELFDumper<ELFT>::getUniquedSectionName(const Elf_Shdr *Sec) {
97   unsigned SecIndex = Sec - &Sections[0];
98   assert(&Sections[SecIndex] == Sec);
99   if (!SectionNames[SecIndex].empty())
100     return SectionNames[SecIndex];
101 
102   auto NameOrErr = Obj.getSectionName(Sec);
103   if (!NameOrErr)
104     return NameOrErr;
105   StringRef Name = *NameOrErr;
106   std::string &Ret = SectionNames[SecIndex];
107 
108   auto It = UsedSectionNames.insert({Name, 0});
109   if (!It.second)
110     Ret = (Name + " [" + Twine(++It.first->second) + "]").str();
111   else
112     Ret = Name;
113   return Ret;
114 }
115 
116 template <class ELFT>
117 Expected<StringRef>
118 ELFDumper<ELFT>::getUniquedSymbolName(const Elf_Sym *Sym, StringRef StrTable,
119                                       const Elf_Shdr *SymTab) {
120   Expected<StringRef> SymbolNameOrErr = Sym->getName(StrTable);
121   if (!SymbolNameOrErr)
122     return SymbolNameOrErr;
123   StringRef Name = *SymbolNameOrErr;
124   if (Name.empty() && Sym->getType() == ELF::STT_SECTION) {
125     auto ShdrOrErr = Obj.getSection(Sym, SymTab, ShndxTable);
126     if (!ShdrOrErr)
127       return ShdrOrErr.takeError();
128     return getUniquedSectionName(*ShdrOrErr);
129   }
130 
131   // Symbols in .symtab can have duplicate names. For example, it is a common
132   // situation for local symbols in a relocatable object. Here we assign unique
133   // suffixes for such symbols so that we can differentiate them.
134   if (SymTab->sh_type == ELF::SHT_SYMTAB) {
135     unsigned Index = Sym - SymTable.data();
136     if (!SymbolNames[Index].empty())
137       return SymbolNames[Index];
138 
139     auto It = UsedSymbolNames.insert({Name, 0});
140     if (!It.second)
141       SymbolNames[Index] =
142           (Name + " [" + Twine(++It.first->second) + "]").str();
143     else
144       SymbolNames[Index] = Name;
145     return SymbolNames[Index];
146   }
147 
148   return Name;
149 }
150 
151 template <class ELFT> Expected<ELFYAML::Object *> ELFDumper<ELFT>::dump() {
152   auto Y = std::make_unique<ELFYAML::Object>();
153 
154   // Dump header. We do not dump SHEntSize, SHOff, SHNum and SHStrNdx fields.
155   // When not explicitly set, the values are set by yaml2obj automatically
156   // and there is no need to dump them here.
157   Y->Header.Class = ELFYAML::ELF_ELFCLASS(Obj.getHeader()->getFileClass());
158   Y->Header.Data = ELFYAML::ELF_ELFDATA(Obj.getHeader()->getDataEncoding());
159   Y->Header.OSABI = Obj.getHeader()->e_ident[ELF::EI_OSABI];
160   Y->Header.ABIVersion = Obj.getHeader()->e_ident[ELF::EI_ABIVERSION];
161   Y->Header.Type = Obj.getHeader()->e_type;
162   Y->Header.Machine = Obj.getHeader()->e_machine;
163   Y->Header.Flags = Obj.getHeader()->e_flags;
164   Y->Header.Entry = Obj.getHeader()->e_entry;
165 
166   // Dump sections
167   auto SectionsOrErr = Obj.sections();
168   if (!SectionsOrErr)
169     return SectionsOrErr.takeError();
170   Sections = *SectionsOrErr;
171   SectionNames.resize(Sections.size());
172 
173   // Dump symbols. We need to do this early because other sections might want
174   // to access the deduplicated symbol names that we also create here.
175   const Elf_Shdr *SymTab = nullptr;
176   const Elf_Shdr *SymTabShndx = nullptr;
177   const Elf_Shdr *DynSymTab = nullptr;
178 
179   for (const Elf_Shdr &Sec : Sections) {
180     if (Sec.sh_type == ELF::SHT_SYMTAB) {
181       SymTab = &Sec;
182     } else if (Sec.sh_type == ELF::SHT_DYNSYM) {
183       DynSymTab = &Sec;
184     } else if (Sec.sh_type == ELF::SHT_SYMTAB_SHNDX) {
185       // ABI allows us to have one SHT_SYMTAB_SHNDX for each symbol table.
186       // We only support having the SHT_SYMTAB_SHNDX for SHT_SYMTAB now.
187       if (SymTabShndx)
188         return createStringError(obj2yaml_error::not_implemented,
189                                  "multiple SHT_SYMTAB_SHNDX sections are not supported");
190       SymTabShndx = &Sec;
191     }
192   }
193 
194   // We need to locate the SHT_SYMTAB_SHNDX section early, because it might be
195   // needed for dumping symbols.
196   if (SymTabShndx) {
197     if (!SymTab || SymTabShndx->sh_link != SymTab - Sections.begin())
198       return createStringError(
199           obj2yaml_error::not_implemented,
200           "only SHT_SYMTAB_SHNDX associated with SHT_SYMTAB are supported");
201 
202     auto TableOrErr = Obj.getSHNDXTable(*SymTabShndx);
203     if (!TableOrErr)
204       return TableOrErr.takeError();
205     ShndxTable = *TableOrErr;
206   }
207 
208   if (SymTab) {
209     Y->Symbols.emplace();
210     if (Error E = dumpSymbols(SymTab, *Y->Symbols))
211       return std::move(E);
212   }
213 
214   if (DynSymTab)
215     if (Error E = dumpSymbols(DynSymTab, Y->DynamicSymbols))
216       return std::move(E);
217 
218   for (const Elf_Shdr &Sec : Sections) {
219     switch (Sec.sh_type) {
220     case ELF::SHT_DYNAMIC: {
221       Expected<ELFYAML::DynamicSection *> SecOrErr = dumpDynamicSection(&Sec);
222       if (!SecOrErr)
223         return SecOrErr.takeError();
224       Y->Sections.emplace_back(*SecOrErr);
225       break;
226     }
227     case ELF::SHT_STRTAB:
228     case ELF::SHT_SYMTAB:
229     case ELF::SHT_DYNSYM:
230       // Do not dump these sections.
231       break;
232     case ELF::SHT_SYMTAB_SHNDX: {
233       Expected<ELFYAML::SymtabShndxSection *> SecOrErr =
234           dumpSymtabShndxSection(&Sec);
235       if (!SecOrErr)
236         return SecOrErr.takeError();
237       Y->Sections.emplace_back(*SecOrErr);
238       break;
239     }
240     case ELF::SHT_REL:
241     case ELF::SHT_RELA: {
242       Expected<ELFYAML::RelocationSection *> SecOrErr = dumpRelocSection(&Sec);
243       if (!SecOrErr)
244         return SecOrErr.takeError();
245       Y->Sections.emplace_back(*SecOrErr);
246       break;
247     }
248     case ELF::SHT_GROUP: {
249       Expected<ELFYAML::Group *> GroupOrErr = dumpGroup(&Sec);
250       if (!GroupOrErr)
251         return GroupOrErr.takeError();
252       Y->Sections.emplace_back(*GroupOrErr);
253       break;
254     }
255     case ELF::SHT_MIPS_ABIFLAGS: {
256       Expected<ELFYAML::MipsABIFlags *> SecOrErr = dumpMipsABIFlags(&Sec);
257       if (!SecOrErr)
258         return SecOrErr.takeError();
259       Y->Sections.emplace_back(*SecOrErr);
260       break;
261     }
262     case ELF::SHT_NOBITS: {
263       Expected<ELFYAML::NoBitsSection *> SecOrErr = dumpNoBitsSection(&Sec);
264       if (!SecOrErr)
265         return SecOrErr.takeError();
266       Y->Sections.emplace_back(*SecOrErr);
267       break;
268     }
269     case ELF::SHT_NOTE: {
270       Expected<ELFYAML::NoteSection *> SecOrErr = dumpNoteSection(&Sec);
271       if (!SecOrErr)
272         return SecOrErr.takeError();
273       Y->Sections.emplace_back(*SecOrErr);
274       break;
275     }
276     case ELF::SHT_HASH: {
277       Expected<ELFYAML::HashSection *> SecOrErr = dumpHashSection(&Sec);
278       if (!SecOrErr)
279         return SecOrErr.takeError();
280       Y->Sections.emplace_back(*SecOrErr);
281       break;
282     }
283     case ELF::SHT_GNU_HASH: {
284       Expected<ELFYAML::GnuHashSection *> SecOrErr = dumpGnuHashSection(&Sec);
285       if (!SecOrErr)
286         return SecOrErr.takeError();
287       Y->Sections.emplace_back(*SecOrErr);
288       break;
289     }
290     case ELF::SHT_GNU_verdef: {
291       Expected<ELFYAML::VerdefSection *> SecOrErr = dumpVerdefSection(&Sec);
292       if (!SecOrErr)
293         return SecOrErr.takeError();
294       Y->Sections.emplace_back(*SecOrErr);
295       break;
296     }
297     case ELF::SHT_GNU_versym: {
298       Expected<ELFYAML::SymverSection *> SecOrErr = dumpSymverSection(&Sec);
299       if (!SecOrErr)
300         return SecOrErr.takeError();
301       Y->Sections.emplace_back(*SecOrErr);
302       break;
303     }
304     case ELF::SHT_GNU_verneed: {
305       Expected<ELFYAML::VerneedSection *> SecOrErr = dumpVerneedSection(&Sec);
306       if (!SecOrErr)
307         return SecOrErr.takeError();
308       Y->Sections.emplace_back(*SecOrErr);
309       break;
310     }
311     case ELF::SHT_LLVM_ADDRSIG: {
312       Expected<ELFYAML::AddrsigSection *> SecOrErr = dumpAddrsigSection(&Sec);
313       if (!SecOrErr)
314         return SecOrErr.takeError();
315       Y->Sections.emplace_back(*SecOrErr);
316       break;
317     }
318     case ELF::SHT_NULL: {
319       // We only dump the SHT_NULL section at index 0 when it
320       // has at least one non-null field, because yaml2obj
321       // normally creates the zero section at index 0 implicitly.
322       if (&Sec == &Sections[0]) {
323         const uint8_t *Begin = reinterpret_cast<const uint8_t *>(&Sec);
324         const uint8_t *End = Begin + sizeof(Elf_Shdr);
325         if (std::find_if(Begin, End, [](uint8_t V) { return V != 0; }) == End)
326           break;
327       }
328       LLVM_FALLTHROUGH;
329     }
330     default: {
331       // Recognize some special SHT_PROGBITS sections by name.
332       if (Sec.sh_type == ELF::SHT_PROGBITS) {
333         Expected<ELFYAML::Section *> SpecialSecOrErr = dumpSpecialSection(&Sec);
334         if (!SpecialSecOrErr)
335           return SpecialSecOrErr.takeError();
336         if (*SpecialSecOrErr) {
337           Y->Sections.emplace_back(*SpecialSecOrErr);
338           break;
339         }
340       }
341 
342       Expected<ELFYAML::RawContentSection *> SecOrErr =
343           dumpContentSection(&Sec);
344       if (!SecOrErr)
345         return SecOrErr.takeError();
346       Y->Sections.emplace_back(*SecOrErr);
347     }
348     }
349   }
350 
351   return Y.release();
352 }
353 
354 template <class ELFT>
355 Error ELFDumper<ELFT>::dumpSymbols(const Elf_Shdr *Symtab,
356                              std::vector<ELFYAML::Symbol> &Symbols) {
357   if (!Symtab)
358     return Error::success();
359 
360   auto StrTableOrErr = Obj.getStringTableForSymtab(*Symtab);
361   if (!StrTableOrErr)
362     return StrTableOrErr.takeError();
363   StringRef StrTable = *StrTableOrErr;
364 
365   auto SymtabOrErr = Obj.symbols(Symtab);
366   if (!SymtabOrErr)
367     return SymtabOrErr.takeError();
368 
369   if (Symtab->sh_type == ELF::SHT_SYMTAB) {
370     SymTable = *SymtabOrErr;
371     SymbolNames.resize(SymTable.size());
372   }
373 
374   for (const auto &Sym : (*SymtabOrErr).drop_front()) {
375     ELFYAML::Symbol S;
376     if (auto EC = dumpSymbol(&Sym, Symtab, StrTable, S))
377       return EC;
378     Symbols.push_back(S);
379   }
380 
381   return Error::success();
382 }
383 
384 template <class ELFT>
385 Error ELFDumper<ELFT>::dumpSymbol(const Elf_Sym *Sym, const Elf_Shdr *SymTab,
386                                   StringRef StrTable, ELFYAML::Symbol &S) {
387   S.Type = Sym->getType();
388   S.Value = Sym->st_value;
389   S.Size = Sym->st_size;
390   S.Other = Sym->st_other;
391   S.Binding = Sym->getBinding();
392 
393   Expected<StringRef> SymbolNameOrErr =
394       getUniquedSymbolName(Sym, StrTable, SymTab);
395   if (!SymbolNameOrErr)
396     return SymbolNameOrErr.takeError();
397   S.Name = SymbolNameOrErr.get();
398 
399   if (Sym->st_shndx >= ELF::SHN_LORESERVE) {
400     S.Index = (ELFYAML::ELF_SHN)Sym->st_shndx;
401     return Error::success();
402   }
403 
404   auto ShdrOrErr = Obj.getSection(Sym, SymTab, ShndxTable);
405   if (!ShdrOrErr)
406     return ShdrOrErr.takeError();
407   const Elf_Shdr *Shdr = *ShdrOrErr;
408   if (!Shdr)
409     return Error::success();
410 
411   auto NameOrErr = getUniquedSectionName(Shdr);
412   if (!NameOrErr)
413     return NameOrErr.takeError();
414   S.Section = NameOrErr.get();
415 
416   return Error::success();
417 }
418 
419 template <class ELFT>
420 template <class RelT>
421 Error ELFDumper<ELFT>::dumpRelocation(const RelT *Rel, const Elf_Shdr *SymTab,
422                                       ELFYAML::Relocation &R) {
423   R.Type = Rel->getType(Obj.isMips64EL());
424   R.Offset = Rel->r_offset;
425   R.Addend = 0;
426 
427   auto SymOrErr = Obj.getRelocationSymbol(Rel, SymTab);
428   if (!SymOrErr)
429     return SymOrErr.takeError();
430 
431   // We have might have a relocation with symbol index 0,
432   // e.g. R_X86_64_NONE or R_X86_64_GOTPC32.
433   const Elf_Sym *Sym = *SymOrErr;
434   if (!Sym)
435     return Error::success();
436 
437   auto StrTabSec = Obj.getSection(SymTab->sh_link);
438   if (!StrTabSec)
439     return StrTabSec.takeError();
440   auto StrTabOrErr = Obj.getStringTable(*StrTabSec);
441   if (!StrTabOrErr)
442     return StrTabOrErr.takeError();
443 
444   Expected<StringRef> NameOrErr =
445       getUniquedSymbolName(Sym, *StrTabOrErr, SymTab);
446   if (!NameOrErr)
447     return NameOrErr.takeError();
448   R.Symbol = NameOrErr.get();
449 
450   return Error::success();
451 }
452 
453 template <class ELFT>
454 Error ELFDumper<ELFT>::dumpCommonSection(const Elf_Shdr *Shdr,
455                                          ELFYAML::Section &S) {
456   // Dump fields. We do not dump the ShOffset field. When not explicitly
457   // set, the value is set by yaml2obj automatically.
458   S.Type = Shdr->sh_type;
459   if (Shdr->sh_flags)
460     S.Flags = static_cast<ELFYAML::ELF_SHF>(Shdr->sh_flags);
461   S.Address = Shdr->sh_addr;
462   S.AddressAlign = Shdr->sh_addralign;
463   if (Shdr->sh_entsize)
464     S.EntSize = static_cast<llvm::yaml::Hex64>(Shdr->sh_entsize);
465 
466   auto NameOrErr = getUniquedSectionName(Shdr);
467   if (!NameOrErr)
468     return NameOrErr.takeError();
469   S.Name = NameOrErr.get();
470 
471   if (Shdr->sh_link != ELF::SHN_UNDEF) {
472     auto LinkSection = Obj.getSection(Shdr->sh_link);
473     if (!LinkSection)
474       return make_error<StringError>(
475           "unable to resolve sh_link reference in section '" + S.Name +
476               "': " + toString(LinkSection.takeError()),
477           inconvertibleErrorCode());
478 
479     NameOrErr = getUniquedSectionName(*LinkSection);
480     if (!NameOrErr)
481       return NameOrErr.takeError();
482     S.Link = NameOrErr.get();
483   }
484 
485   return Error::success();
486 }
487 
488 template <class ELFT>
489 Expected<ELFYAML::Section *>
490 ELFDumper<ELFT>::dumpSpecialSection(const Elf_Shdr *Shdr) {
491   auto NameOrErr = getUniquedSectionName(Shdr);
492   if (!NameOrErr)
493     return NameOrErr.takeError();
494 
495   if (ELFYAML::StackSizesSection::nameMatches(*NameOrErr))
496     return dumpStackSizesSection(Shdr);
497   return nullptr;
498 }
499 
500 template <class ELFT>
501 Error ELFDumper<ELFT>::dumpCommonRelocationSection(
502     const Elf_Shdr *Shdr, ELFYAML::RelocationSection &S) {
503   if (Error E = dumpCommonSection(Shdr, S))
504     return E;
505 
506   auto InfoSection = Obj.getSection(Shdr->sh_info);
507   if (!InfoSection)
508     return InfoSection.takeError();
509 
510   auto NameOrErr = getUniquedSectionName(*InfoSection);
511   if (!NameOrErr)
512     return NameOrErr.takeError();
513   S.RelocatableSec = NameOrErr.get();
514 
515   return Error::success();
516 }
517 
518 template <class ELFT>
519 Expected<ELFYAML::StackSizesSection *>
520 ELFDumper<ELFT>::dumpStackSizesSection(const Elf_Shdr *Shdr) {
521   auto S = std::make_unique<ELFYAML::StackSizesSection>();
522   if (Error E = dumpCommonSection(Shdr, *S))
523     return std::move(E);
524 
525   auto ContentOrErr = Obj.getSectionContents(Shdr);
526   if (!ContentOrErr)
527     return ContentOrErr.takeError();
528 
529   ArrayRef<uint8_t> Content = *ContentOrErr;
530   DataExtractor Data(Content, Obj.isLE(), ELFT::Is64Bits ? 8 : 4);
531 
532   std::vector<ELFYAML::StackSizeEntry> Entries;
533   DataExtractor::Cursor Cur(0);
534   while (Cur && Cur.tell() < Content.size()) {
535     uint64_t Address = Data.getAddress(Cur);
536     uint64_t Size = Data.getULEB128(Cur);
537     Entries.push_back({Address, Size});
538   }
539 
540   if (Content.empty() || !Cur) {
541     // If .stack_sizes cannot be decoded, we dump it as an array of bytes.
542     consumeError(Cur.takeError());
543     S->Content = yaml::BinaryRef(Content);
544   } else {
545     S->Entries = std::move(Entries);
546   }
547 
548   return S.release();
549 }
550 
551 template <class ELFT>
552 Expected<ELFYAML::AddrsigSection *>
553 ELFDumper<ELFT>::dumpAddrsigSection(const Elf_Shdr *Shdr) {
554   auto S = std::make_unique<ELFYAML::AddrsigSection>();
555   if (Error E = dumpCommonSection(Shdr, *S))
556     return std::move(E);
557 
558   auto ContentOrErr = Obj.getSectionContents(Shdr);
559   if (!ContentOrErr)
560     return ContentOrErr.takeError();
561 
562   ArrayRef<uint8_t> Content = *ContentOrErr;
563   DataExtractor::Cursor Cur(0);
564   DataExtractor Data(Content, Obj.isLE(), /*AddressSize=*/0);
565   std::vector<ELFYAML::AddrsigSymbol> Symbols;
566   while (Cur && Cur.tell() < Content.size()) {
567     uint64_t SymNdx = Data.getULEB128(Cur);
568     if (!Cur)
569       break;
570 
571     Expected<StringRef> SymbolName = getSymbolName(Shdr->sh_link, SymNdx);
572     if (!SymbolName || SymbolName->empty()) {
573       consumeError(SymbolName.takeError());
574       Symbols.emplace_back(SymNdx);
575       continue;
576     }
577 
578     Symbols.emplace_back(*SymbolName);
579   }
580 
581   if (Cur) {
582     S->Symbols = std::move(Symbols);
583     return S.release();
584   }
585 
586   consumeError(Cur.takeError());
587   S->Content = yaml::BinaryRef(Content);
588   return S.release();
589 }
590 
591 template <class ELFT>
592 Expected<ELFYAML::DynamicSection *>
593 ELFDumper<ELFT>::dumpDynamicSection(const Elf_Shdr *Shdr) {
594   auto S = std::make_unique<ELFYAML::DynamicSection>();
595   if (Error E = dumpCommonSection(Shdr, *S))
596     return std::move(E);
597 
598   auto DynTagsOrErr = Obj.template getSectionContentsAsArray<Elf_Dyn>(Shdr);
599   if (!DynTagsOrErr)
600     return DynTagsOrErr.takeError();
601 
602   for (const Elf_Dyn &Dyn : *DynTagsOrErr)
603     S->Entries.push_back({(ELFYAML::ELF_DYNTAG)Dyn.getTag(), Dyn.getVal()});
604 
605   return S.release();
606 }
607 
608 template <class ELFT>
609 Expected<ELFYAML::RelocationSection *>
610 ELFDumper<ELFT>::dumpRelocSection(const Elf_Shdr *Shdr) {
611   auto S = std::make_unique<ELFYAML::RelocationSection>();
612   if (auto E = dumpCommonRelocationSection(Shdr, *S))
613     return std::move(E);
614 
615   auto SymTabOrErr = Obj.getSection(Shdr->sh_link);
616   if (!SymTabOrErr)
617     return SymTabOrErr.takeError();
618   const Elf_Shdr *SymTab = *SymTabOrErr;
619 
620   if (Shdr->sh_type == ELF::SHT_REL) {
621     auto Rels = Obj.rels(Shdr);
622     if (!Rels)
623       return Rels.takeError();
624     for (const Elf_Rel &Rel : *Rels) {
625       ELFYAML::Relocation R;
626       if (Error E = dumpRelocation(&Rel, SymTab, R))
627         return std::move(E);
628       S->Relocations.push_back(R);
629     }
630   } else {
631     auto Rels = Obj.relas(Shdr);
632     if (!Rels)
633       return Rels.takeError();
634     for (const Elf_Rela &Rel : *Rels) {
635       ELFYAML::Relocation R;
636       if (Error E = dumpRelocation(&Rel, SymTab, R))
637         return std::move(E);
638       R.Addend = Rel.r_addend;
639       S->Relocations.push_back(R);
640     }
641   }
642 
643   return S.release();
644 }
645 
646 template <class ELFT>
647 Expected<ELFYAML::RawContentSection *>
648 ELFDumper<ELFT>::dumpContentSection(const Elf_Shdr *Shdr) {
649   auto S = std::make_unique<ELFYAML::RawContentSection>();
650   if (Error E = dumpCommonSection(Shdr, *S))
651     return std::move(E);
652 
653   unsigned SecIndex = Shdr - &Sections[0];
654   if (SecIndex != 0 || Shdr->sh_type != ELF::SHT_NULL) {
655     auto ContentOrErr = Obj.getSectionContents(Shdr);
656     if (!ContentOrErr)
657       return ContentOrErr.takeError();
658     ArrayRef<uint8_t> Content = *ContentOrErr;
659     if (!Content.empty())
660       S->Content = yaml::BinaryRef(Content);
661   } else {
662     S->Size = static_cast<llvm::yaml::Hex64>(Shdr->sh_size);
663   }
664 
665   if (Shdr->sh_info)
666     S->Info = static_cast<llvm::yaml::Hex64>(Shdr->sh_info);
667   return S.release();
668 }
669 
670 template <class ELFT>
671 Expected<ELFYAML::SymtabShndxSection *>
672 ELFDumper<ELFT>::dumpSymtabShndxSection(const Elf_Shdr *Shdr) {
673   auto S = std::make_unique<ELFYAML::SymtabShndxSection>();
674   if (Error E = dumpCommonSection(Shdr, *S))
675     return std::move(E);
676 
677   auto EntriesOrErr = Obj.template getSectionContentsAsArray<Elf_Word>(Shdr);
678   if (!EntriesOrErr)
679     return EntriesOrErr.takeError();
680   for (const Elf_Word &E : *EntriesOrErr)
681     S->Entries.push_back(E);
682   return S.release();
683 }
684 
685 template <class ELFT>
686 Expected<ELFYAML::NoBitsSection *>
687 ELFDumper<ELFT>::dumpNoBitsSection(const Elf_Shdr *Shdr) {
688   auto S = std::make_unique<ELFYAML::NoBitsSection>();
689   if (Error E = dumpCommonSection(Shdr, *S))
690     return std::move(E);
691   S->Size = Shdr->sh_size;
692 
693   return S.release();
694 }
695 
696 template <class ELFT>
697 Expected<ELFYAML::NoteSection *>
698 ELFDumper<ELFT>::dumpNoteSection(const Elf_Shdr *Shdr) {
699   auto S = std::make_unique<ELFYAML::NoteSection>();
700   if (Error E = dumpCommonSection(Shdr, *S))
701     return std::move(E);
702 
703   auto ContentOrErr = Obj.getSectionContents(Shdr);
704   if (!ContentOrErr)
705     return ContentOrErr.takeError();
706 
707   std::vector<ELFYAML::NoteEntry> Entries;
708   ArrayRef<uint8_t> Content = *ContentOrErr;
709   while (!Content.empty()) {
710     if (Content.size() < sizeof(Elf_Nhdr)) {
711       S->Content = yaml::BinaryRef(*ContentOrErr);
712       return S.release();
713     }
714 
715     const Elf_Nhdr *Header = reinterpret_cast<const Elf_Nhdr *>(Content.data());
716     if (Content.size() < Header->getSize()) {
717       S->Content = yaml::BinaryRef(*ContentOrErr);
718       return S.release();
719     }
720 
721     Elf_Note Note(*Header);
722     Entries.push_back(
723         {Note.getName(), Note.getDesc(), (llvm::yaml::Hex32)Note.getType()});
724 
725     Content = Content.drop_front(Header->getSize());
726   }
727 
728   S->Notes = std::move(Entries);
729   return S.release();
730 }
731 
732 template <class ELFT>
733 Expected<ELFYAML::HashSection *>
734 ELFDumper<ELFT>::dumpHashSection(const Elf_Shdr *Shdr) {
735   auto S = std::make_unique<ELFYAML::HashSection>();
736   if (Error E = dumpCommonSection(Shdr, *S))
737     return std::move(E);
738 
739   auto ContentOrErr = Obj.getSectionContents(Shdr);
740   if (!ContentOrErr)
741     return ContentOrErr.takeError();
742 
743   ArrayRef<uint8_t> Content = *ContentOrErr;
744   if (Content.size() % 4 != 0 || Content.size() < 8) {
745     S->Content = yaml::BinaryRef(Content);
746     return S.release();
747   }
748 
749   DataExtractor::Cursor Cur(0);
750   DataExtractor Data(Content, Obj.isLE(), /*AddressSize=*/0);
751   uint32_t NBucket = Data.getU32(Cur);
752   uint32_t NChain = Data.getU32(Cur);
753   if (Content.size() != (2 + NBucket + NChain) * 4) {
754     S->Content = yaml::BinaryRef(Content);
755     if (Cur)
756       return S.release();
757     llvm_unreachable("entries were not read correctly");
758   }
759 
760   S->Bucket.emplace(NBucket);
761   for (uint32_t &V : *S->Bucket)
762     V = Data.getU32(Cur);
763 
764   S->Chain.emplace(NChain);
765   for (uint32_t &V : *S->Chain)
766     V = Data.getU32(Cur);
767 
768   if (Cur)
769     return S.release();
770   llvm_unreachable("entries were not read correctly");
771 }
772 
773 template <class ELFT>
774 Expected<ELFYAML::GnuHashSection *>
775 ELFDumper<ELFT>::dumpGnuHashSection(const Elf_Shdr *Shdr) {
776   auto S = std::make_unique<ELFYAML::GnuHashSection>();
777   if (Error E = dumpCommonSection(Shdr, *S))
778     return std::move(E);
779 
780   auto ContentOrErr = Obj.getSectionContents(Shdr);
781   if (!ContentOrErr)
782     return ContentOrErr.takeError();
783 
784   unsigned AddrSize = ELFT::Is64Bits ? 8 : 4;
785   ArrayRef<uint8_t> Content = *ContentOrErr;
786   DataExtractor Data(Content, Obj.isLE(), AddrSize);
787 
788   ELFYAML::GnuHashHeader Header;
789   DataExtractor::Cursor Cur(0);
790   uint32_t NBuckets = Data.getU32(Cur);
791   Header.SymNdx = Data.getU32(Cur);
792   uint32_t MaskWords = Data.getU32(Cur);
793   Header.Shift2 = Data.getU32(Cur);
794 
795   // Set just the raw binary content if we were unable to read the header
796   // or when the section data is truncated or malformed.
797   uint64_t Size = Data.getData().size() - Cur.tell();
798   if (!Cur || (Size < MaskWords * AddrSize + NBuckets * 4) ||
799       (Size % 4 != 0)) {
800     consumeError(Cur.takeError());
801     S->Content = yaml::BinaryRef(Content);
802     return S.release();
803   }
804 
805   S->Header = Header;
806 
807   S->BloomFilter.emplace(MaskWords);
808   for (llvm::yaml::Hex64 &Val : *S->BloomFilter)
809     Val = Data.getAddress(Cur);
810 
811   S->HashBuckets.emplace(NBuckets);
812   for (llvm::yaml::Hex32 &Val : *S->HashBuckets)
813     Val = Data.getU32(Cur);
814 
815   S->HashValues.emplace((Data.getData().size() - Cur.tell()) / 4);
816   for (llvm::yaml::Hex32 &Val : *S->HashValues)
817     Val = Data.getU32(Cur);
818 
819   if (Cur)
820     return S.release();
821   llvm_unreachable("GnuHashSection was not read correctly");
822 }
823 
824 template <class ELFT>
825 Expected<ELFYAML::VerdefSection *>
826 ELFDumper<ELFT>::dumpVerdefSection(const Elf_Shdr *Shdr) {
827   typedef typename ELFT::Verdef Elf_Verdef;
828   typedef typename ELFT::Verdaux Elf_Verdaux;
829 
830   auto S = std::make_unique<ELFYAML::VerdefSection>();
831   if (Error E = dumpCommonSection(Shdr, *S))
832     return std::move(E);
833 
834   S->Info = Shdr->sh_info;
835 
836   auto StringTableShdrOrErr = Obj.getSection(Shdr->sh_link);
837   if (!StringTableShdrOrErr)
838     return StringTableShdrOrErr.takeError();
839 
840   auto StringTableOrErr = Obj.getStringTable(*StringTableShdrOrErr);
841   if (!StringTableOrErr)
842     return StringTableOrErr.takeError();
843 
844   auto Contents = Obj.getSectionContents(Shdr);
845   if (!Contents)
846     return Contents.takeError();
847 
848   llvm::ArrayRef<uint8_t> Data = *Contents;
849   const uint8_t *Buf = Data.data();
850   while (Buf) {
851     const Elf_Verdef *Verdef = reinterpret_cast<const Elf_Verdef *>(Buf);
852     ELFYAML::VerdefEntry Entry;
853     Entry.Version = Verdef->vd_version;
854     Entry.Flags = Verdef->vd_flags;
855     Entry.VersionNdx = Verdef->vd_ndx;
856     Entry.Hash = Verdef->vd_hash;
857 
858     const uint8_t *BufAux = Buf + Verdef->vd_aux;
859     while (BufAux) {
860       const Elf_Verdaux *Verdaux =
861           reinterpret_cast<const Elf_Verdaux *>(BufAux);
862       Entry.VerNames.push_back(
863           StringTableOrErr->drop_front(Verdaux->vda_name).data());
864       BufAux = Verdaux->vda_next ? BufAux + Verdaux->vda_next : nullptr;
865     }
866 
867     S->Entries.push_back(Entry);
868     Buf = Verdef->vd_next ? Buf + Verdef->vd_next : nullptr;
869   }
870 
871   return S.release();
872 }
873 
874 template <class ELFT>
875 Expected<ELFYAML::SymverSection *>
876 ELFDumper<ELFT>::dumpSymverSection(const Elf_Shdr *Shdr) {
877   typedef typename ELFT::Half Elf_Half;
878 
879   auto S = std::make_unique<ELFYAML::SymverSection>();
880   if (Error E = dumpCommonSection(Shdr, *S))
881     return std::move(E);
882 
883   auto VersionsOrErr = Obj.template getSectionContentsAsArray<Elf_Half>(Shdr);
884   if (!VersionsOrErr)
885     return VersionsOrErr.takeError();
886   for (const Elf_Half &E : *VersionsOrErr)
887     S->Entries.push_back(E);
888 
889   return S.release();
890 }
891 
892 template <class ELFT>
893 Expected<ELFYAML::VerneedSection *>
894 ELFDumper<ELFT>::dumpVerneedSection(const Elf_Shdr *Shdr) {
895   typedef typename ELFT::Verneed Elf_Verneed;
896   typedef typename ELFT::Vernaux Elf_Vernaux;
897 
898   auto S = std::make_unique<ELFYAML::VerneedSection>();
899   if (Error E = dumpCommonSection(Shdr, *S))
900     return std::move(E);
901 
902   S->Info = Shdr->sh_info;
903 
904   auto Contents = Obj.getSectionContents(Shdr);
905   if (!Contents)
906     return Contents.takeError();
907 
908   auto StringTableShdrOrErr = Obj.getSection(Shdr->sh_link);
909   if (!StringTableShdrOrErr)
910     return StringTableShdrOrErr.takeError();
911 
912   auto StringTableOrErr = Obj.getStringTable(*StringTableShdrOrErr);
913   if (!StringTableOrErr)
914     return StringTableOrErr.takeError();
915 
916   llvm::ArrayRef<uint8_t> Data = *Contents;
917   const uint8_t *Buf = Data.data();
918   while (Buf) {
919     const Elf_Verneed *Verneed = reinterpret_cast<const Elf_Verneed *>(Buf);
920 
921     ELFYAML::VerneedEntry Entry;
922     Entry.Version = Verneed->vn_version;
923     Entry.File =
924         StringRef(StringTableOrErr->drop_front(Verneed->vn_file).data());
925 
926     const uint8_t *BufAux = Buf + Verneed->vn_aux;
927     while (BufAux) {
928       const Elf_Vernaux *Vernaux =
929           reinterpret_cast<const Elf_Vernaux *>(BufAux);
930 
931       ELFYAML::VernauxEntry Aux;
932       Aux.Hash = Vernaux->vna_hash;
933       Aux.Flags = Vernaux->vna_flags;
934       Aux.Other = Vernaux->vna_other;
935       Aux.Name =
936           StringRef(StringTableOrErr->drop_front(Vernaux->vna_name).data());
937 
938       Entry.AuxV.push_back(Aux);
939       BufAux = Vernaux->vna_next ? BufAux + Vernaux->vna_next : nullptr;
940     }
941 
942     S->VerneedV.push_back(Entry);
943     Buf = Verneed->vn_next ? Buf + Verneed->vn_next : nullptr;
944   }
945 
946   return S.release();
947 }
948 
949 template <class ELFT>
950 Expected<StringRef> ELFDumper<ELFT>::getSymbolName(uint32_t SymtabNdx,
951                                                    uint32_t SymbolNdx) {
952   auto SymtabOrErr = Obj.getSection(SymtabNdx);
953   if (!SymtabOrErr)
954     return SymtabOrErr.takeError();
955 
956   const Elf_Shdr *Symtab = *SymtabOrErr;
957   auto SymOrErr = Obj.getSymbol(Symtab, SymbolNdx);
958   if (!SymOrErr)
959     return SymOrErr.takeError();
960 
961   auto StrTabOrErr = Obj.getStringTableForSymtab(*Symtab);
962   if (!StrTabOrErr)
963     return StrTabOrErr.takeError();
964   return getUniquedSymbolName(*SymOrErr, *StrTabOrErr, Symtab);
965 }
966 
967 template <class ELFT>
968 Expected<ELFYAML::Group *> ELFDumper<ELFT>::dumpGroup(const Elf_Shdr *Shdr) {
969   auto S = std::make_unique<ELFYAML::Group>();
970   if (Error E = dumpCommonSection(Shdr, *S))
971     return std::move(E);
972 
973   // Get symbol with index sh_info. This symbol's name is the signature of the group.
974   Expected<StringRef> SymbolName = getSymbolName(Shdr->sh_link, Shdr->sh_info);
975   if (!SymbolName)
976     return SymbolName.takeError();
977   S->Signature = *SymbolName;
978 
979   auto MembersOrErr = Obj.template getSectionContentsAsArray<Elf_Word>(Shdr);
980   if (!MembersOrErr)
981     return MembersOrErr.takeError();
982 
983   for (Elf_Word Member : *MembersOrErr) {
984     if (Member == llvm::ELF::GRP_COMDAT) {
985       S->Members.push_back({"GRP_COMDAT"});
986       continue;
987     }
988 
989     auto SHdrOrErr = Obj.getSection(Member);
990     if (!SHdrOrErr)
991       return SHdrOrErr.takeError();
992     auto NameOrErr = getUniquedSectionName(*SHdrOrErr);
993     if (!NameOrErr)
994       return NameOrErr.takeError();
995     S->Members.push_back({*NameOrErr});
996   }
997   return S.release();
998 }
999 
1000 template <class ELFT>
1001 Expected<ELFYAML::MipsABIFlags *>
1002 ELFDumper<ELFT>::dumpMipsABIFlags(const Elf_Shdr *Shdr) {
1003   assert(Shdr->sh_type == ELF::SHT_MIPS_ABIFLAGS &&
1004          "Section type is not SHT_MIPS_ABIFLAGS");
1005   auto S = std::make_unique<ELFYAML::MipsABIFlags>();
1006   if (Error E = dumpCommonSection(Shdr, *S))
1007     return std::move(E);
1008 
1009   auto ContentOrErr = Obj.getSectionContents(Shdr);
1010   if (!ContentOrErr)
1011     return ContentOrErr.takeError();
1012 
1013   auto *Flags = reinterpret_cast<const object::Elf_Mips_ABIFlags<ELFT> *>(
1014       ContentOrErr.get().data());
1015   S->Version = Flags->version;
1016   S->ISALevel = Flags->isa_level;
1017   S->ISARevision = Flags->isa_rev;
1018   S->GPRSize = Flags->gpr_size;
1019   S->CPR1Size = Flags->cpr1_size;
1020   S->CPR2Size = Flags->cpr2_size;
1021   S->FpABI = Flags->fp_abi;
1022   S->ISAExtension = Flags->isa_ext;
1023   S->ASEs = Flags->ases;
1024   S->Flags1 = Flags->flags1;
1025   S->Flags2 = Flags->flags2;
1026   return S.release();
1027 }
1028 
1029 template <class ELFT>
1030 static Error elf2yaml(raw_ostream &Out, const object::ELFFile<ELFT> &Obj) {
1031   ELFDumper<ELFT> Dumper(Obj);
1032   Expected<ELFYAML::Object *> YAMLOrErr = Dumper.dump();
1033   if (!YAMLOrErr)
1034     return YAMLOrErr.takeError();
1035 
1036   std::unique_ptr<ELFYAML::Object> YAML(YAMLOrErr.get());
1037   yaml::Output Yout(Out);
1038   Yout << *YAML;
1039 
1040   return Error::success();
1041 }
1042 
1043 Error elf2yaml(raw_ostream &Out, const object::ObjectFile &Obj) {
1044   if (const auto *ELFObj = dyn_cast<object::ELF32LEObjectFile>(&Obj))
1045     return elf2yaml(Out, *ELFObj->getELFFile());
1046 
1047   if (const auto *ELFObj = dyn_cast<object::ELF32BEObjectFile>(&Obj))
1048     return elf2yaml(Out, *ELFObj->getELFFile());
1049 
1050   if (const auto *ELFObj = dyn_cast<object::ELF64LEObjectFile>(&Obj))
1051     return elf2yaml(Out, *ELFObj->getELFFile());
1052 
1053   if (const auto *ELFObj = dyn_cast<object::ELF64BEObjectFile>(&Obj))
1054     return elf2yaml(Out, *ELFObj->getELFFile());
1055 
1056   llvm_unreachable("unknown ELF file format");
1057 }
1058