elf2yaml.cpp 52 KB

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