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     return make_error<BinaryError>();
79   }
80 
81   // Default scheme is to print Target, as well as "+ <addend>" for nonzero
82   // addend. Should be acceptable for all normal purposes.
83   std::string FmtBuf;
84   raw_string_ostream Fmt(FmtBuf);
85 
86   if (!Undef) {
87     symbol_iterator SI = RelRef.getSymbol();
88     const typename ELFT::Sym *Sym = Obj->getSymbol(SI->getRawDataRefImpl());
89     if (Sym->getType() == ELF::STT_SECTION) {
90       Expected<section_iterator> SymSI = SI->getSection();
91       if (!SymSI)
92         return SymSI.takeError();
93       const typename ELFT::Shdr *SymSec =
94           Obj->getSection((*SymSI)->getRawDataRefImpl());
95       auto SecName = EF.getSectionName(*SymSec);
96       if (!SecName)
97         return SecName.takeError();
98       Fmt << *SecName;
99     } else {
100       Expected<StringRef> SymName = SI->getName();
101       if (!SymName)
102         return SymName.takeError();
103       if (Demangle)
104         Fmt << demangle(std::string(*SymName));
105       else
106         Fmt << *SymName;
107     }
108   } else {
109     Fmt << "*ABS*";
110   }
111   if (Addend != 0) {
112       Fmt << (Addend < 0
113           ? "-"
114           : "+") << format("0x%" PRIx64,
115                           (Addend < 0 ? -(uint64_t)Addend : (uint64_t)Addend));
116   }
117   Fmt.flush();
118   Result.append(FmtBuf.begin(), FmtBuf.end());
119   return Error::success();
120 }
121 
getELFRelocationValueString(const ELFObjectFileBase * Obj,const RelocationRef & Rel,SmallVectorImpl<char> & Result)122 Error objdump::getELFRelocationValueString(const ELFObjectFileBase *Obj,
123                                            const RelocationRef &Rel,
124                                            SmallVectorImpl<char> &Result) {
125   if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
126     return getRelocationValueString(ELF32LE, Rel, Result);
127   if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
128     return getRelocationValueString(ELF64LE, Rel, Result);
129   if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
130     return getRelocationValueString(ELF32BE, Rel, Result);
131   auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
132   return getRelocationValueString(ELF64BE, Rel, Result);
133 }
134 
135 template <class ELFT>
getSectionLMA(const ELFFile<ELFT> & Obj,const object::ELFSectionRef & Sec)136 static uint64_t getSectionLMA(const ELFFile<ELFT> &Obj,
137                               const object::ELFSectionRef &Sec) {
138   auto PhdrRangeOrErr = Obj.program_headers();
139   if (!PhdrRangeOrErr)
140     report_fatal_error(toString(PhdrRangeOrErr.takeError()));
141 
142   // Search for a PT_LOAD segment containing the requested section. Use this
143   // segment's p_addr to calculate the section's LMA.
144   for (const typename ELFT::Phdr &Phdr : *PhdrRangeOrErr)
145     if ((Phdr.p_type == ELF::PT_LOAD) && (Phdr.p_vaddr <= Sec.getAddress()) &&
146         (Phdr.p_vaddr + Phdr.p_memsz > Sec.getAddress()))
147       return Sec.getAddress() - Phdr.p_vaddr + Phdr.p_paddr;
148 
149   // Return section's VMA if it isn't in a PT_LOAD segment.
150   return Sec.getAddress();
151 }
152 
getELFSectionLMA(const object::ELFSectionRef & Sec)153 uint64_t objdump::getELFSectionLMA(const object::ELFSectionRef &Sec) {
154   if (const auto *ELFObj = dyn_cast<ELF32LEObjectFile>(Sec.getObject()))
155     return getSectionLMA(ELFObj->getELFFile(), Sec);
156   else if (const auto *ELFObj = dyn_cast<ELF32BEObjectFile>(Sec.getObject()))
157     return getSectionLMA(ELFObj->getELFFile(), Sec);
158   else if (const auto *ELFObj = dyn_cast<ELF64LEObjectFile>(Sec.getObject()))
159     return getSectionLMA(ELFObj->getELFFile(), Sec);
160   const auto *ELFObj = cast<ELF64BEObjectFile>(Sec.getObject());
161   return getSectionLMA(ELFObj->getELFFile(), Sec);
162 }
163 
164 template <class ELFT>
printDynamicSection(const ELFFile<ELFT> & Elf,StringRef Filename)165 static void printDynamicSection(const ELFFile<ELFT> &Elf, StringRef Filename) {
166   ArrayRef<typename ELFT::Dyn> DynamicEntries =
167       unwrapOrError(Elf.dynamicEntries(), Filename);
168 
169   // Find the maximum tag name length to format the value column properly.
170   size_t MaxLen = 0;
171   for (const typename ELFT::Dyn &Dyn : DynamicEntries)
172     MaxLen = std::max(MaxLen, Elf.getDynamicTagAsString(Dyn.d_tag).size());
173   std::string TagFmt = "  %-" + std::to_string(MaxLen) + "s ";
174 
175   outs() << "Dynamic Section:\n";
176   for (const typename ELFT::Dyn &Dyn : DynamicEntries) {
177     if (Dyn.d_tag == ELF::DT_NULL)
178       continue;
179 
180     std::string Str = Elf.getDynamicTagAsString(Dyn.d_tag);
181     outs() << format(TagFmt.c_str(), Str.c_str());
182 
183     const char *Fmt =
184         ELFT::Is64Bits ? "0x%016" PRIx64 "\n" : "0x%08" PRIx64 "\n";
185     if (Dyn.d_tag == ELF::DT_NEEDED || Dyn.d_tag == ELF::DT_RPATH ||
186         Dyn.d_tag == ELF::DT_RUNPATH || Dyn.d_tag == ELF::DT_SONAME ||
187         Dyn.d_tag == ELF::DT_AUXILIARY || Dyn.d_tag == ELF::DT_FILTER) {
188       Expected<StringRef> StrTabOrErr = getDynamicStrTab(Elf);
189       if (StrTabOrErr) {
190         const char *Data = StrTabOrErr.get().data();
191         outs() << (Data + Dyn.d_un.d_val) << "\n";
192         continue;
193       }
194       reportWarning(toString(StrTabOrErr.takeError()), Filename);
195       consumeError(StrTabOrErr.takeError());
196     }
197     outs() << format(Fmt, (uint64_t)Dyn.d_un.d_val);
198   }
199 }
200 
201 template <class ELFT>
printProgramHeaders(const ELFFile<ELFT> & Obj,StringRef FileName)202 static void printProgramHeaders(const ELFFile<ELFT> &Obj, StringRef FileName) {
203   outs() << "Program Header:\n";
204   auto ProgramHeaderOrError = Obj.program_headers();
205   if (!ProgramHeaderOrError) {
206     reportWarning("unable to read program headers: " +
207                       toString(ProgramHeaderOrError.takeError()),
208                   FileName);
209     return;
210   }
211 
212   for (const typename ELFT::Phdr &Phdr : *ProgramHeaderOrError) {
213     switch (Phdr.p_type) {
214     case ELF::PT_DYNAMIC:
215       outs() << " DYNAMIC ";
216       break;
217     case ELF::PT_GNU_EH_FRAME:
218       outs() << "EH_FRAME ";
219       break;
220     case ELF::PT_GNU_RELRO:
221       outs() << "   RELRO ";
222       break;
223     case ELF::PT_GNU_PROPERTY:
224       outs() << "   PROPERTY ";
225       break;
226     case ELF::PT_GNU_STACK:
227       outs() << "   STACK ";
228       break;
229     case ELF::PT_INTERP:
230       outs() << "  INTERP ";
231       break;
232     case ELF::PT_LOAD:
233       outs() << "    LOAD ";
234       break;
235     case ELF::PT_NOTE:
236       outs() << "    NOTE ";
237       break;
238     case ELF::PT_OPENBSD_BOOTDATA:
239       outs() << "    OPENBSD_BOOTDATA ";
240       break;
241     case ELF::PT_OPENBSD_RANDOMIZE:
242       outs() << "    OPENBSD_RANDOMIZE ";
243       break;
244     case ELF::PT_OPENBSD_WXNEEDED:
245       outs() << "    OPENBSD_WXNEEDED ";
246       break;
247     case ELF::PT_PHDR:
248       outs() << "    PHDR ";
249       break;
250     case ELF::PT_TLS:
251       outs() << "    TLS ";
252       break;
253     default:
254       outs() << " UNKNOWN ";
255     }
256 
257     const char *Fmt = ELFT::Is64Bits ? "0x%016" PRIx64 " " : "0x%08" PRIx64 " ";
258 
259     outs() << "off    " << format(Fmt, (uint64_t)Phdr.p_offset) << "vaddr "
260            << format(Fmt, (uint64_t)Phdr.p_vaddr) << "paddr "
261            << format(Fmt, (uint64_t)Phdr.p_paddr)
262            << format("align 2**%u\n",
263                      countTrailingZeros<uint64_t>(Phdr.p_align))
264            << "         filesz " << format(Fmt, (uint64_t)Phdr.p_filesz)
265            << "memsz " << format(Fmt, (uint64_t)Phdr.p_memsz) << "flags "
266            << ((Phdr.p_flags & ELF::PF_R) ? "r" : "-")
267            << ((Phdr.p_flags & ELF::PF_W) ? "w" : "-")
268            << ((Phdr.p_flags & ELF::PF_X) ? "x" : "-") << "\n";
269   }
270   outs() << "\n";
271 }
272 
273 template <class ELFT>
printSymbolVersionDependency(ArrayRef<uint8_t> Contents,StringRef StrTab)274 static void printSymbolVersionDependency(ArrayRef<uint8_t> Contents,
275                                          StringRef StrTab) {
276   outs() << "Version References:\n";
277 
278   const uint8_t *Buf = Contents.data();
279   while (Buf) {
280     auto *Verneed = reinterpret_cast<const typename ELFT::Verneed *>(Buf);
281     outs() << "  required from "
282            << StringRef(StrTab.drop_front(Verneed->vn_file).data()) << ":\n";
283 
284     const uint8_t *BufAux = Buf + Verneed->vn_aux;
285     while (BufAux) {
286       auto *Vernaux = reinterpret_cast<const typename ELFT::Vernaux *>(BufAux);
287       outs() << "    "
288              << format("0x%08" PRIx32 " ", (uint32_t)Vernaux->vna_hash)
289              << format("0x%02" PRIx16 " ", (uint16_t)Vernaux->vna_flags)
290              << format("%02" PRIu16 " ", (uint16_t)Vernaux->vna_other)
291              << StringRef(StrTab.drop_front(Vernaux->vna_name).data()) << '\n';
292       BufAux = Vernaux->vna_next ? BufAux + Vernaux->vna_next : nullptr;
293     }
294     Buf = Verneed->vn_next ? Buf + Verneed->vn_next : nullptr;
295   }
296 }
297 
298 template <class ELFT>
printSymbolVersionDefinition(const typename ELFT::Shdr & Shdr,ArrayRef<uint8_t> Contents,StringRef StrTab)299 static void printSymbolVersionDefinition(const typename ELFT::Shdr &Shdr,
300                                          ArrayRef<uint8_t> Contents,
301                                          StringRef StrTab) {
302   outs() << "Version definitions:\n";
303 
304   const uint8_t *Buf = Contents.data();
305   uint32_t VerdefIndex = 1;
306   // sh_info contains the number of entries in the SHT_GNU_verdef section. To
307   // make the index column have consistent width, we should insert blank spaces
308   // according to sh_info.
309   uint16_t VerdefIndexWidth = std::to_string(Shdr.sh_info).size();
310   while (Buf) {
311     auto *Verdef = reinterpret_cast<const typename ELFT::Verdef *>(Buf);
312     outs() << format_decimal(VerdefIndex++, VerdefIndexWidth) << " "
313            << format("0x%02" PRIx16 " ", (uint16_t)Verdef->vd_flags)
314            << format("0x%08" PRIx32 " ", (uint32_t)Verdef->vd_hash);
315 
316     const uint8_t *BufAux = Buf + Verdef->vd_aux;
317     uint16_t VerdauxIndex = 0;
318     while (BufAux) {
319       auto *Verdaux = reinterpret_cast<const typename ELFT::Verdaux *>(BufAux);
320       if (VerdauxIndex)
321         outs() << std::string(VerdefIndexWidth + 17, ' ');
322       outs() << StringRef(StrTab.drop_front(Verdaux->vda_name).data()) << '\n';
323       BufAux = Verdaux->vda_next ? BufAux + Verdaux->vda_next : nullptr;
324       ++VerdauxIndex;
325     }
326     Buf = Verdef->vd_next ? Buf + Verdef->vd_next : nullptr;
327   }
328 }
329 
330 template <class ELFT>
printSymbolVersionInfo(const ELFFile<ELFT> & Elf,StringRef FileName)331 static void printSymbolVersionInfo(const ELFFile<ELFT> &Elf,
332                                    StringRef FileName) {
333   ArrayRef<typename ELFT::Shdr> Sections =
334       unwrapOrError(Elf.sections(), FileName);
335   for (const typename ELFT::Shdr &Shdr : Sections) {
336     if (Shdr.sh_type != ELF::SHT_GNU_verneed &&
337         Shdr.sh_type != ELF::SHT_GNU_verdef)
338       continue;
339 
340     ArrayRef<uint8_t> Contents =
341         unwrapOrError(Elf.getSectionContents(Shdr), FileName);
342     const typename ELFT::Shdr *StrTabSec =
343         unwrapOrError(Elf.getSection(Shdr.sh_link), FileName);
344     StringRef StrTab = unwrapOrError(Elf.getStringTable(*StrTabSec), FileName);
345 
346     if (Shdr.sh_type == ELF::SHT_GNU_verneed)
347       printSymbolVersionDependency<ELFT>(Contents, StrTab);
348     else
349       printSymbolVersionDefinition<ELFT>(Shdr, Contents, StrTab);
350   }
351 }
352 
printELFFileHeader(const object::ObjectFile * Obj)353 void objdump::printELFFileHeader(const object::ObjectFile *Obj) {
354   if (const auto *ELFObj = dyn_cast<ELF32LEObjectFile>(Obj))
355     printProgramHeaders(ELFObj->getELFFile(), Obj->getFileName());
356   else if (const auto *ELFObj = dyn_cast<ELF32BEObjectFile>(Obj))
357     printProgramHeaders(ELFObj->getELFFile(), Obj->getFileName());
358   else if (const auto *ELFObj = dyn_cast<ELF64LEObjectFile>(Obj))
359     printProgramHeaders(ELFObj->getELFFile(), Obj->getFileName());
360   else if (const auto *ELFObj = dyn_cast<ELF64BEObjectFile>(Obj))
361     printProgramHeaders(ELFObj->getELFFile(), Obj->getFileName());
362 }
363 
printELFDynamicSection(const object::ObjectFile * Obj)364 void objdump::printELFDynamicSection(const object::ObjectFile *Obj) {
365   if (const auto *ELFObj = dyn_cast<ELF32LEObjectFile>(Obj))
366     printDynamicSection(ELFObj->getELFFile(), Obj->getFileName());
367   else if (const auto *ELFObj = dyn_cast<ELF32BEObjectFile>(Obj))
368     printDynamicSection(ELFObj->getELFFile(), Obj->getFileName());
369   else if (const auto *ELFObj = dyn_cast<ELF64LEObjectFile>(Obj))
370     printDynamicSection(ELFObj->getELFFile(), Obj->getFileName());
371   else if (const auto *ELFObj = dyn_cast<ELF64BEObjectFile>(Obj))
372     printDynamicSection(ELFObj->getELFFile(), Obj->getFileName());
373 }
374 
printELFSymbolVersionInfo(const object::ObjectFile * Obj)375 void objdump::printELFSymbolVersionInfo(const object::ObjectFile *Obj) {
376   if (const auto *ELFObj = dyn_cast<ELF32LEObjectFile>(Obj))
377     printSymbolVersionInfo(ELFObj->getELFFile(), Obj->getFileName());
378   else if (const auto *ELFObj = dyn_cast<ELF32BEObjectFile>(Obj))
379     printSymbolVersionInfo(ELFObj->getELFFile(), Obj->getFileName());
380   else if (const auto *ELFObj = dyn_cast<ELF64LEObjectFile>(Obj))
381     printSymbolVersionInfo(ELFObj->getELFFile(), Obj->getFileName());
382   else if (const auto *ELFObj = dyn_cast<ELF64BEObjectFile>(Obj))
383     printSymbolVersionInfo(ELFObj->getELFFile(), Obj->getFileName());
384 }
385