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