elf2yaml.cpp 54 KB

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