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