1 //===-- ELFDump.cpp - ELF-specific dumper -----------------------*- 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 /// \file
10 /// This file implements the ELF-specific dumper for llvm-objdump.
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #include "ELFDump.h"
15 
16 #include "llvm-objdump.h"
17 #include "llvm/Demangle/Demangle.h"
18 #include "llvm/Object/ELFObjectFile.h"
19 #include "llvm/Support/Format.h"
20 #include "llvm/Support/MathExtras.h"
21 #include "llvm/Support/raw_ostream.h"
22 
23 using namespace llvm;
24 using namespace llvm::object;
25 using namespace llvm::objdump;
26 
27 template <class ELFT>
getDynamicStrTab(const ELFFile<ELFT> & Elf)28 static Expected<StringRef> getDynamicStrTab(const ELFFile<ELFT> &Elf) {
29   auto DynamicEntriesOrError = Elf.dynamicEntries();
30   if (!DynamicEntriesOrError)
31     return DynamicEntriesOrError.takeError();
32 
33   for (const typename ELFT::Dyn &Dyn : *DynamicEntriesOrError) {
34     if (Dyn.d_tag == ELF::DT_STRTAB) {
35       auto MappedAddrOrError = Elf.toMappedAddr(Dyn.getPtr());
36       if (!MappedAddrOrError)
37         consumeError(MappedAddrOrError.takeError());
38       return StringRef(reinterpret_cast<const char *>(*MappedAddrOrError));
39     }
40   }
41 
42   // If the dynamic segment is not present, we fall back on the sections.
43   auto SectionsOrError = Elf.sections();
44   if (!SectionsOrError)
45     return SectionsOrError.takeError();
46 
47   for (const typename ELFT::Shdr &Sec : *SectionsOrError) {
48     if (Sec.sh_type == ELF::SHT_DYNSYM)
49       return Elf.getStringTableForSymtab(Sec);
50   }
51 
52   return createError("dynamic string table not found");
53 }
54 
55 template <class ELFT>
getRelocationValueString(const ELFObjectFile<ELFT> * Obj,const RelocationRef & RelRef,SmallVectorImpl<char> & Result)56 static Error getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
57                                       const RelocationRef &RelRef,
58                                       SmallVectorImpl<char> &Result) {
59   const ELFFile<ELFT> &EF = Obj->getELFFile();
60   DataRefImpl Rel = RelRef.getRawDataRefImpl();
61   auto SecOrErr = EF.getSection(Rel.d.a);
62   if (!SecOrErr)
63     return SecOrErr.takeError();
64 
65   int64_t Addend = 0;
66   // If there is no Symbol associated with the relocation, we set the undef
67   // boolean value to 'true'. This will prevent us from calling functions that
68   // requires the relocation to be associated with a symbol.
69   //
70   // In SHT_REL case we would need to read the addend from section data.
71   // GNU objdump does not do that and we just follow for simplicity atm.
72   bool Undef = false;
73   if ((*SecOrErr)->sh_type == ELF::SHT_RELA) {
74     const typename ELFT::Rela *ERela = Obj->getRela(Rel);
75     Addend = ERela->r_addend;
76     Undef = ERela->getSymbol(false) == 0;
77   } else if ((*SecOrErr)->sh_type == ELF::SHT_REL) {
78     const typename ELFT::Rel *ERel = Obj->getRel(Rel);
79     Undef = ERel->getSymbol(false) == 0;
80   } else {
81     return make_error<BinaryError>();
82   }
83 
84   // Default scheme is to print Target, as well as "+ <addend>" for nonzero
85   // addend. Should be acceptable for all normal purposes.
86   std::string FmtBuf;
87   raw_string_ostream Fmt(FmtBuf);
88 
89   if (!Undef) {
90     symbol_iterator SI = RelRef.getSymbol();
91     Expected<const typename ELFT::Sym *> SymOrErr =
92         Obj->getSymbol(SI->getRawDataRefImpl());
93     // TODO: test this error.
94     if (!SymOrErr)
95       return SymOrErr.takeError();
96 
97     if ((*SymOrErr)->getType() == ELF::STT_SECTION) {
98       Expected<section_iterator> SymSI = SI->getSection();
99       if (!SymSI)
100         return SymSI.takeError();
101       const typename ELFT::Shdr *SymSec =
102           Obj->getSection((*SymSI)->getRawDataRefImpl());
103       auto SecName = EF.getSectionName(*SymSec);
104       if (!SecName)
105         return SecName.takeError();
106       Fmt << *SecName;
107     } else {
108       Expected<StringRef> SymName = SI->getName();
109       if (!SymName)
110         return SymName.takeError();
111       if (Demangle)
112         Fmt << demangle(std::string(*SymName));
113       else
114         Fmt << *SymName;
115     }
116   } else {
117     Fmt << "*ABS*";
118   }
119   if (Addend != 0) {
120       Fmt << (Addend < 0
121           ? "-"
122           : "+") << format("0x%" PRIx64,
123                           (Addend < 0 ? -(uint64_t)Addend : (uint64_t)Addend));
124   }
125   Fmt.flush();
126   Result.append(FmtBuf.begin(), FmtBuf.end());
127   return Error::success();
128 }
129 
getELFRelocationValueString(const ELFObjectFileBase * Obj,const RelocationRef & Rel,SmallVectorImpl<char> & Result)130 Error objdump::getELFRelocationValueString(const ELFObjectFileBase *Obj,
131                                            const RelocationRef &Rel,
132                                            SmallVectorImpl<char> &Result) {
133   if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
134     return getRelocationValueString(ELF32LE, Rel, Result);
135   if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
136     return getRelocationValueString(ELF64LE, Rel, Result);
137   if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
138     return getRelocationValueString(ELF32BE, Rel, Result);
139   auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
140   return getRelocationValueString(ELF64BE, Rel, Result);
141 }
142 
143 template <class ELFT>
getSectionLMA(const ELFFile<ELFT> & Obj,const object::ELFSectionRef & Sec)144 static uint64_t getSectionLMA(const ELFFile<ELFT> &Obj,
145                               const object::ELFSectionRef &Sec) {
146   auto PhdrRangeOrErr = Obj.program_headers();
147   if (!PhdrRangeOrErr)
148     report_fatal_error(Twine(toString(PhdrRangeOrErr.takeError())));
149 
150   // Search for a PT_LOAD segment containing the requested section. Use this
151   // segment's p_addr to calculate the section's LMA.
152   for (const typename ELFT::Phdr &Phdr : *PhdrRangeOrErr)
153     if ((Phdr.p_type == ELF::PT_LOAD) && (Phdr.p_vaddr <= Sec.getAddress()) &&
154         (Phdr.p_vaddr + Phdr.p_memsz > Sec.getAddress()))
155       return Sec.getAddress() - Phdr.p_vaddr + Phdr.p_paddr;
156 
157   // Return section's VMA if it isn't in a PT_LOAD segment.
158   return Sec.getAddress();
159 }
160 
getELFSectionLMA(const object::ELFSectionRef & Sec)161 uint64_t objdump::getELFSectionLMA(const object::ELFSectionRef &Sec) {
162   if (const auto *ELFObj = dyn_cast<ELF32LEObjectFile>(Sec.getObject()))
163     return getSectionLMA(ELFObj->getELFFile(), Sec);
164   else if (const auto *ELFObj = dyn_cast<ELF32BEObjectFile>(Sec.getObject()))
165     return getSectionLMA(ELFObj->getELFFile(), Sec);
166   else if (const auto *ELFObj = dyn_cast<ELF64LEObjectFile>(Sec.getObject()))
167     return getSectionLMA(ELFObj->getELFFile(), Sec);
168   const auto *ELFObj = cast<ELF64BEObjectFile>(Sec.getObject());
169   return getSectionLMA(ELFObj->getELFFile(), Sec);
170 }
171 
172 template <class ELFT>
printDynamicSection(const ELFFile<ELFT> & Elf,StringRef Filename)173 static void printDynamicSection(const ELFFile<ELFT> &Elf, StringRef Filename) {
174   auto DynamicEntriesOrErr = Elf.dynamicEntries();
175   if (!DynamicEntriesOrErr) {
176     reportWarning(toString(DynamicEntriesOrErr.takeError()), Filename);
177     return;
178   }
179   ArrayRef<typename ELFT::Dyn> DynamicEntries = *DynamicEntriesOrErr;
180 
181   // Find the maximum tag name length to format the value column properly.
182   size_t MaxLen = 0;
183   for (const typename ELFT::Dyn &Dyn : DynamicEntries)
184     MaxLen = std::max(MaxLen, Elf.getDynamicTagAsString(Dyn.d_tag).size());
185   std::string TagFmt = "  %-" + std::to_string(MaxLen) + "s ";
186 
187   outs() << "\nDynamic Section:\n";
188   for (const typename ELFT::Dyn &Dyn : DynamicEntries) {
189     if (Dyn.d_tag == ELF::DT_NULL)
190       continue;
191 
192     std::string Str = Elf.getDynamicTagAsString(Dyn.d_tag);
193     outs() << format(TagFmt.c_str(), Str.c_str());
194 
195     const char *Fmt =
196         ELFT::Is64Bits ? "0x%016" PRIx64 "\n" : "0x%08" PRIx64 "\n";
197     if (Dyn.d_tag == ELF::DT_NEEDED || Dyn.d_tag == ELF::DT_RPATH ||
198         Dyn.d_tag == ELF::DT_RUNPATH || Dyn.d_tag == ELF::DT_SONAME ||
199         Dyn.d_tag == ELF::DT_AUXILIARY || Dyn.d_tag == ELF::DT_FILTER) {
200       Expected<StringRef> StrTabOrErr = getDynamicStrTab(Elf);
201       if (StrTabOrErr) {
202         const char *Data = StrTabOrErr.get().data();
203         outs() << (Data + Dyn.d_un.d_val) << "\n";
204         continue;
205       }
206       reportWarning(toString(StrTabOrErr.takeError()), Filename);
207       consumeError(StrTabOrErr.takeError());
208     }
209     outs() << format(Fmt, (uint64_t)Dyn.d_un.d_val);
210   }
211 }
212 
213 template <class ELFT>
printProgramHeaders(const ELFFile<ELFT> & Obj,StringRef FileName)214 static void printProgramHeaders(const ELFFile<ELFT> &Obj, StringRef FileName) {
215   outs() << "\nProgram Header:\n";
216   auto ProgramHeaderOrError = Obj.program_headers();
217   if (!ProgramHeaderOrError) {
218     reportWarning("unable to read program headers: " +
219                       toString(ProgramHeaderOrError.takeError()),
220                   FileName);
221     return;
222   }
223 
224   for (const typename ELFT::Phdr &Phdr : *ProgramHeaderOrError) {
225     switch (Phdr.p_type) {
226     case ELF::PT_DYNAMIC:
227       outs() << " DYNAMIC ";
228       break;
229     case ELF::PT_GNU_EH_FRAME:
230       outs() << "EH_FRAME ";
231       break;
232     case ELF::PT_GNU_RELRO:
233       outs() << "   RELRO ";
234       break;
235     case ELF::PT_GNU_PROPERTY:
236       outs() << "   PROPERTY ";
237       break;
238     case ELF::PT_GNU_STACK:
239       outs() << "   STACK ";
240       break;
241     case ELF::PT_INTERP:
242       outs() << "  INTERP ";
243       break;
244     case ELF::PT_LOAD:
245       outs() << "    LOAD ";
246       break;
247     case ELF::PT_NOTE:
248       outs() << "    NOTE ";
249       break;
250     case ELF::PT_OPENBSD_BOOTDATA:
251       outs() << "OPENBSD_BOOTDATA ";
252       break;
253     case ELF::PT_OPENBSD_MUTABLE:
254       outs() << "OPENBSD_MUTABLE ";
255       break;
256     case ELF::PT_OPENBSD_NOBTCFI:
257       outs() << "OPENBSD_NOBTCFI ";
258       break;
259     case ELF::PT_OPENBSD_RANDOMIZE:
260       outs() << "OPENBSD_RANDOMIZE ";
261       break;
262     case ELF::PT_OPENBSD_SYSCALLS:
263       outs() << "OPENBSD_SYSCALLS ";
264       break;
265     case ELF::PT_OPENBSD_WXNEEDED:
266       outs() << "OPENBSD_WXNEEDED ";
267       break;
268     case ELF::PT_PHDR:
269       outs() << "    PHDR ";
270       break;
271     case ELF::PT_TLS:
272       outs() << "    TLS ";
273       break;
274     default:
275       outs() << " UNKNOWN ";
276     }
277 
278     const char *Fmt = ELFT::Is64Bits ? "0x%016" PRIx64 " " : "0x%08" PRIx64 " ";
279 
280     outs() << "off    " << format(Fmt, (uint64_t)Phdr.p_offset) << "vaddr "
281            << format(Fmt, (uint64_t)Phdr.p_vaddr) << "paddr "
282            << format(Fmt, (uint64_t)Phdr.p_paddr)
283            << format("align 2**%u\n",
284                      countTrailingZeros<uint64_t>(Phdr.p_align))
285            << "         filesz " << format(Fmt, (uint64_t)Phdr.p_filesz)
286            << "memsz " << format(Fmt, (uint64_t)Phdr.p_memsz) << "flags "
287            << ((Phdr.p_flags & ELF::PF_R) ? "r" : "-")
288            << ((Phdr.p_flags & ELF::PF_W) ? "w" : "-")
289            << ((Phdr.p_flags & ELF::PF_X) ? "x" : "-") << "\n";
290   }
291 }
292 
293 template <class ELFT>
printSymbolVersionDependency(StringRef FileName,const ELFFile<ELFT> & Obj,const typename ELFT::Shdr & Sec)294 static void printSymbolVersionDependency(StringRef FileName,
295                                          const ELFFile<ELFT> &Obj,
296                                          const typename ELFT::Shdr &Sec) {
297   outs() << "\nVersion References:\n";
298 
299   auto WarningHandler = [&](const Twine &Msg) {
300     reportWarning(Msg, FileName);
301     return Error::success();
302   };
303   Expected<std::vector<VerNeed>> V =
304       Obj.getVersionDependencies(Sec, WarningHandler);
305   if (!V) {
306     reportWarning(toString(V.takeError()), FileName);
307     return;
308   }
309 
310   raw_fd_ostream &OS = outs();
311   for (const VerNeed &VN : *V) {
312     OS << "  required from " << VN.File << ":\n";
313     for (const VernAux &Aux : VN.AuxV)
314       OS << format("    0x%08x 0x%02x %02u %s\n", Aux.Hash, Aux.Flags,
315                    Aux.Other, Aux.Name.c_str());
316   }
317 }
318 
319 template <class ELFT>
printSymbolVersionDefinition(const typename ELFT::Shdr & Shdr,ArrayRef<uint8_t> Contents,StringRef StrTab)320 static void printSymbolVersionDefinition(const typename ELFT::Shdr &Shdr,
321                                          ArrayRef<uint8_t> Contents,
322                                          StringRef StrTab) {
323   outs() << "\nVersion definitions:\n";
324 
325   const uint8_t *Buf = Contents.data();
326   uint32_t VerdefIndex = 1;
327   // sh_info contains the number of entries in the SHT_GNU_verdef section. To
328   // make the index column have consistent width, we should insert blank spaces
329   // according to sh_info.
330   uint16_t VerdefIndexWidth = std::to_string(Shdr.sh_info).size();
331   while (Buf) {
332     auto *Verdef = reinterpret_cast<const typename ELFT::Verdef *>(Buf);
333     outs() << format_decimal(VerdefIndex++, VerdefIndexWidth) << " "
334            << format("0x%02" PRIx16 " ", (uint16_t)Verdef->vd_flags)
335            << format("0x%08" PRIx32 " ", (uint32_t)Verdef->vd_hash);
336 
337     const uint8_t *BufAux = Buf + Verdef->vd_aux;
338     uint16_t VerdauxIndex = 0;
339     while (BufAux) {
340       auto *Verdaux = reinterpret_cast<const typename ELFT::Verdaux *>(BufAux);
341       if (VerdauxIndex)
342         outs() << std::string(VerdefIndexWidth + 17, ' ');
343       outs() << StringRef(StrTab.drop_front(Verdaux->vda_name).data()) << '\n';
344       BufAux = Verdaux->vda_next ? BufAux + Verdaux->vda_next : nullptr;
345       ++VerdauxIndex;
346     }
347     Buf = Verdef->vd_next ? Buf + Verdef->vd_next : nullptr;
348   }
349 }
350 
351 template <class ELFT>
printSymbolVersionInfo(const ELFFile<ELFT> & Elf,StringRef FileName)352 static void printSymbolVersionInfo(const ELFFile<ELFT> &Elf,
353                                    StringRef FileName) {
354   ArrayRef<typename ELFT::Shdr> Sections =
355       unwrapOrError(Elf.sections(), FileName);
356   for (const typename ELFT::Shdr &Shdr : Sections) {
357     if (Shdr.sh_type != ELF::SHT_GNU_verneed &&
358         Shdr.sh_type != ELF::SHT_GNU_verdef)
359       continue;
360 
361     ArrayRef<uint8_t> Contents =
362         unwrapOrError(Elf.getSectionContents(Shdr), FileName);
363     const typename ELFT::Shdr *StrTabSec =
364         unwrapOrError(Elf.getSection(Shdr.sh_link), FileName);
365     StringRef StrTab = unwrapOrError(Elf.getStringTable(*StrTabSec), FileName);
366 
367     if (Shdr.sh_type == ELF::SHT_GNU_verneed)
368       printSymbolVersionDependency<ELFT>(FileName, Elf, Shdr);
369     else
370       printSymbolVersionDefinition<ELFT>(Shdr, Contents, StrTab);
371   }
372 }
373 
printELFFileHeader(const object::ObjectFile * Obj)374 void objdump::printELFFileHeader(const object::ObjectFile *Obj) {
375   if (const auto *ELFObj = dyn_cast<ELF32LEObjectFile>(Obj))
376     printProgramHeaders(ELFObj->getELFFile(), Obj->getFileName());
377   else if (const auto *ELFObj = dyn_cast<ELF32BEObjectFile>(Obj))
378     printProgramHeaders(ELFObj->getELFFile(), Obj->getFileName());
379   else if (const auto *ELFObj = dyn_cast<ELF64LEObjectFile>(Obj))
380     printProgramHeaders(ELFObj->getELFFile(), Obj->getFileName());
381   else if (const auto *ELFObj = dyn_cast<ELF64BEObjectFile>(Obj))
382     printProgramHeaders(ELFObj->getELFFile(), Obj->getFileName());
383 }
384 
printELFDynamicSection(const object::ObjectFile * Obj)385 void objdump::printELFDynamicSection(const object::ObjectFile *Obj) {
386   if (const auto *ELFObj = dyn_cast<ELF32LEObjectFile>(Obj))
387     printDynamicSection(ELFObj->getELFFile(), Obj->getFileName());
388   else if (const auto *ELFObj = dyn_cast<ELF32BEObjectFile>(Obj))
389     printDynamicSection(ELFObj->getELFFile(), Obj->getFileName());
390   else if (const auto *ELFObj = dyn_cast<ELF64LEObjectFile>(Obj))
391     printDynamicSection(ELFObj->getELFFile(), Obj->getFileName());
392   else if (const auto *ELFObj = dyn_cast<ELF64BEObjectFile>(Obj))
393     printDynamicSection(ELFObj->getELFFile(), Obj->getFileName());
394 }
395 
printELFSymbolVersionInfo(const object::ObjectFile * Obj)396 void objdump::printELFSymbolVersionInfo(const object::ObjectFile *Obj) {
397   if (const auto *ELFObj = dyn_cast<ELF32LEObjectFile>(Obj))
398     printSymbolVersionInfo(ELFObj->getELFFile(), Obj->getFileName());
399   else if (const auto *ELFObj = dyn_cast<ELF32BEObjectFile>(Obj))
400     printSymbolVersionInfo(ELFObj->getELFFile(), Obj->getFileName());
401   else if (const auto *ELFObj = dyn_cast<ELF64LEObjectFile>(Obj))
402     printSymbolVersionInfo(ELFObj->getELFFile(), Obj->getFileName());
403   else if (const auto *ELFObj = dyn_cast<ELF64BEObjectFile>(Obj))
404     printSymbolVersionInfo(ELFObj->getELFFile(), Obj->getFileName());
405 }
406