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>
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>
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 
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>
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 
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>
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> static void printProgramHeaders(const ELFFile<ELFT> *o) {
202   outs() << "Program Header:\n";
203   auto ProgramHeaderOrError = o->program_headers();
204   if (!ProgramHeaderOrError)
205     report_fatal_error(toString(ProgramHeaderOrError.takeError()));
206   for (const typename ELFT::Phdr &Phdr : *ProgramHeaderOrError) {
207     switch (Phdr.p_type) {
208     case ELF::PT_DYNAMIC:
209       outs() << " DYNAMIC ";
210       break;
211     case ELF::PT_GNU_EH_FRAME:
212       outs() << "EH_FRAME ";
213       break;
214     case ELF::PT_GNU_RELRO:
215       outs() << "   RELRO ";
216       break;
217     case ELF::PT_GNU_PROPERTY:
218       outs() << "   PROPERTY ";
219       break;
220     case ELF::PT_GNU_STACK:
221       outs() << "   STACK ";
222       break;
223     case ELF::PT_INTERP:
224       outs() << "  INTERP ";
225       break;
226     case ELF::PT_LOAD:
227       outs() << "    LOAD ";
228       break;
229     case ELF::PT_NOTE:
230       outs() << "    NOTE ";
231       break;
232     case ELF::PT_OPENBSD_BOOTDATA:
233       outs() << "    OPENBSD_BOOTDATA ";
234       break;
235     case ELF::PT_OPENBSD_RANDOMIZE:
236       outs() << "    OPENBSD_RANDOMIZE ";
237       break;
238     case ELF::PT_OPENBSD_WXNEEDED:
239       outs() << "    OPENBSD_WXNEEDED ";
240       break;
241     case ELF::PT_PHDR:
242       outs() << "    PHDR ";
243       break;
244     case ELF::PT_TLS:
245       outs() << "    TLS ";
246       break;
247     default:
248       outs() << " UNKNOWN ";
249     }
250 
251     const char *Fmt = ELFT::Is64Bits ? "0x%016" PRIx64 " " : "0x%08" PRIx64 " ";
252 
253     outs() << "off    " << format(Fmt, (uint64_t)Phdr.p_offset) << "vaddr "
254            << format(Fmt, (uint64_t)Phdr.p_vaddr) << "paddr "
255            << format(Fmt, (uint64_t)Phdr.p_paddr)
256            << format("align 2**%u\n",
257                      countTrailingZeros<uint64_t>(Phdr.p_align))
258            << "         filesz " << format(Fmt, (uint64_t)Phdr.p_filesz)
259            << "memsz " << format(Fmt, (uint64_t)Phdr.p_memsz) << "flags "
260            << ((Phdr.p_flags & ELF::PF_R) ? "r" : "-")
261            << ((Phdr.p_flags & ELF::PF_W) ? "w" : "-")
262            << ((Phdr.p_flags & ELF::PF_X) ? "x" : "-") << "\n";
263   }
264   outs() << "\n";
265 }
266 
267 template <class ELFT>
268 static void printSymbolVersionDependency(ArrayRef<uint8_t> Contents,
269                                          StringRef StrTab) {
270   outs() << "Version References:\n";
271 
272   const uint8_t *Buf = Contents.data();
273   while (Buf) {
274     auto *Verneed = reinterpret_cast<const typename ELFT::Verneed *>(Buf);
275     outs() << "  required from "
276            << StringRef(StrTab.drop_front(Verneed->vn_file).data()) << ":\n";
277 
278     const uint8_t *BufAux = Buf + Verneed->vn_aux;
279     while (BufAux) {
280       auto *Vernaux = reinterpret_cast<const typename ELFT::Vernaux *>(BufAux);
281       outs() << "    "
282              << format("0x%08" PRIx32 " ", (uint32_t)Vernaux->vna_hash)
283              << format("0x%02" PRIx16 " ", (uint16_t)Vernaux->vna_flags)
284              << format("%02" PRIu16 " ", (uint16_t)Vernaux->vna_other)
285              << StringRef(StrTab.drop_front(Vernaux->vna_name).data()) << '\n';
286       BufAux = Vernaux->vna_next ? BufAux + Vernaux->vna_next : nullptr;
287     }
288     Buf = Verneed->vn_next ? Buf + Verneed->vn_next : nullptr;
289   }
290 }
291 
292 template <class ELFT>
293 static void printSymbolVersionDefinition(const typename ELFT::Shdr &Shdr,
294                                          ArrayRef<uint8_t> Contents,
295                                          StringRef StrTab) {
296   outs() << "Version definitions:\n";
297 
298   const uint8_t *Buf = Contents.data();
299   uint32_t VerdefIndex = 1;
300   // sh_info contains the number of entries in the SHT_GNU_verdef section. To
301   // make the index column have consistent width, we should insert blank spaces
302   // according to sh_info.
303   uint16_t VerdefIndexWidth = std::to_string(Shdr.sh_info).size();
304   while (Buf) {
305     auto *Verdef = reinterpret_cast<const typename ELFT::Verdef *>(Buf);
306     outs() << format_decimal(VerdefIndex++, VerdefIndexWidth) << " "
307            << format("0x%02" PRIx16 " ", (uint16_t)Verdef->vd_flags)
308            << format("0x%08" PRIx32 " ", (uint32_t)Verdef->vd_hash);
309 
310     const uint8_t *BufAux = Buf + Verdef->vd_aux;
311     uint16_t VerdauxIndex = 0;
312     while (BufAux) {
313       auto *Verdaux = reinterpret_cast<const typename ELFT::Verdaux *>(BufAux);
314       if (VerdauxIndex)
315         outs() << std::string(VerdefIndexWidth + 17, ' ');
316       outs() << StringRef(StrTab.drop_front(Verdaux->vda_name).data()) << '\n';
317       BufAux = Verdaux->vda_next ? BufAux + Verdaux->vda_next : nullptr;
318       ++VerdauxIndex;
319     }
320     Buf = Verdef->vd_next ? Buf + Verdef->vd_next : nullptr;
321   }
322 }
323 
324 template <class ELFT>
325 static void printSymbolVersionInfo(const ELFFile<ELFT> *Elf,
326                                    StringRef FileName) {
327   ArrayRef<typename ELFT::Shdr> Sections =
328       unwrapOrError(Elf->sections(), FileName);
329   for (const typename ELFT::Shdr &Shdr : Sections) {
330     if (Shdr.sh_type != ELF::SHT_GNU_verneed &&
331         Shdr.sh_type != ELF::SHT_GNU_verdef)
332       continue;
333 
334     ArrayRef<uint8_t> Contents =
335         unwrapOrError(Elf->getSectionContents(&Shdr), FileName);
336     const typename ELFT::Shdr *StrTabSec =
337         unwrapOrError(Elf->getSection(Shdr.sh_link), FileName);
338     StringRef StrTab = unwrapOrError(Elf->getStringTable(StrTabSec), FileName);
339 
340     if (Shdr.sh_type == ELF::SHT_GNU_verneed)
341       printSymbolVersionDependency<ELFT>(Contents, StrTab);
342     else
343       printSymbolVersionDefinition<ELFT>(Shdr, Contents, StrTab);
344   }
345 }
346 
347 void objdump::printELFFileHeader(const object::ObjectFile *Obj) {
348   if (const auto *ELFObj = dyn_cast<ELF32LEObjectFile>(Obj))
349     printProgramHeaders(ELFObj->getELFFile());
350   else if (const auto *ELFObj = dyn_cast<ELF32BEObjectFile>(Obj))
351     printProgramHeaders(ELFObj->getELFFile());
352   else if (const auto *ELFObj = dyn_cast<ELF64LEObjectFile>(Obj))
353     printProgramHeaders(ELFObj->getELFFile());
354   else if (const auto *ELFObj = dyn_cast<ELF64BEObjectFile>(Obj))
355     printProgramHeaders(ELFObj->getELFFile());
356 }
357 
358 void objdump::printELFDynamicSection(const object::ObjectFile *Obj) {
359   if (const auto *ELFObj = dyn_cast<ELF32LEObjectFile>(Obj))
360     printDynamicSection(ELFObj->getELFFile(), Obj->getFileName());
361   else if (const auto *ELFObj = dyn_cast<ELF32BEObjectFile>(Obj))
362     printDynamicSection(ELFObj->getELFFile(), Obj->getFileName());
363   else if (const auto *ELFObj = dyn_cast<ELF64LEObjectFile>(Obj))
364     printDynamicSection(ELFObj->getELFFile(), Obj->getFileName());
365   else if (const auto *ELFObj = dyn_cast<ELF64BEObjectFile>(Obj))
366     printDynamicSection(ELFObj->getELFFile(), Obj->getFileName());
367 }
368 
369 void objdump::printELFSymbolVersionInfo(const object::ObjectFile *Obj) {
370   if (const auto *ELFObj = dyn_cast<ELF32LEObjectFile>(Obj))
371     printSymbolVersionInfo(ELFObj->getELFFile(), Obj->getFileName());
372   else if (const auto *ELFObj = dyn_cast<ELF32BEObjectFile>(Obj))
373     printSymbolVersionInfo(ELFObj->getELFFile(), Obj->getFileName());
374   else if (const auto *ELFObj = dyn_cast<ELF64LEObjectFile>(Obj))
375     printSymbolVersionInfo(ELFObj->getELFFile(), Obj->getFileName());
376   else if (const auto *ELFObj = dyn_cast<ELF64BEObjectFile>(Obj))
377     printSymbolVersionInfo(ELFObj->getELFFile(), Obj->getFileName());
378 }
379