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