elf2yaml.cpp 55 KB

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