blob: f5a8cf75490418b4281879e74e82fe8230f577ec [file] [log] [blame]
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001//===-- COFFDump.cpp - COFF-specific dumper ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000011/// This file implements the COFF-specific dumper for llvm-objdump.
Michael J. Spencer0c6ec482012-12-05 20:12:35 +000012/// It outputs the Win64 EH data structures as plain text.
Alp Tokercb402912014-01-24 17:20:08 +000013/// The encoding of the unwind codes is described in MSDN:
Michael J. Spencer0c6ec482012-12-05 20:12:35 +000014/// http://msdn.microsoft.com/en-us/library/ck9asaa9.aspx
15///
16//===----------------------------------------------------------------------===//
17
18#include "llvm-objdump.h"
Zachary Turner030ad372018-08-20 22:18:21 +000019#include "llvm/Demangle/Demangle.h"
Michael J. Spencer0c6ec482012-12-05 20:12:35 +000020#include "llvm/Object/COFF.h"
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +000021#include "llvm/Object/COFFImportFile.h"
Michael J. Spencer0c6ec482012-12-05 20:12:35 +000022#include "llvm/Object/ObjectFile.h"
23#include "llvm/Support/Format.h"
Chandler Carruthb034cb72013-01-02 10:26:28 +000024#include "llvm/Support/Win64EH.h"
Jonas Devliegheree787efd2018-11-11 22:12:04 +000025#include "llvm/Support/WithColor.h"
Michael J. Spencer0c6ec482012-12-05 20:12:35 +000026#include "llvm/Support/raw_ostream.h"
Michael J. Spencer0c6ec482012-12-05 20:12:35 +000027
28using namespace llvm;
29using namespace object;
30using namespace llvm::Win64EH;
31
32// Returns the name of the unwind code.
33static StringRef getUnwindCodeTypeName(uint8_t Code) {
34 switch(Code) {
35 default: llvm_unreachable("Invalid unwind code");
36 case UOP_PushNonVol: return "UOP_PushNonVol";
37 case UOP_AllocLarge: return "UOP_AllocLarge";
38 case UOP_AllocSmall: return "UOP_AllocSmall";
39 case UOP_SetFPReg: return "UOP_SetFPReg";
40 case UOP_SaveNonVol: return "UOP_SaveNonVol";
41 case UOP_SaveNonVolBig: return "UOP_SaveNonVolBig";
42 case UOP_SaveXMM128: return "UOP_SaveXMM128";
43 case UOP_SaveXMM128Big: return "UOP_SaveXMM128Big";
44 case UOP_PushMachFrame: return "UOP_PushMachFrame";
45 }
46}
47
48// Returns the name of a referenced register.
49static StringRef getUnwindRegisterName(uint8_t Reg) {
50 switch(Reg) {
51 default: llvm_unreachable("Invalid register");
52 case 0: return "RAX";
53 case 1: return "RCX";
54 case 2: return "RDX";
55 case 3: return "RBX";
56 case 4: return "RSP";
57 case 5: return "RBP";
58 case 6: return "RSI";
59 case 7: return "RDI";
60 case 8: return "R8";
61 case 9: return "R9";
62 case 10: return "R10";
63 case 11: return "R11";
64 case 12: return "R12";
65 case 13: return "R13";
66 case 14: return "R14";
67 case 15: return "R15";
68 }
69}
70
71// Calculates the number of array slots required for the unwind code.
72static unsigned getNumUsedSlots(const UnwindCode &UnwindCode) {
73 switch (UnwindCode.getUnwindOp()) {
74 default: llvm_unreachable("Invalid unwind code");
75 case UOP_PushNonVol:
76 case UOP_AllocSmall:
77 case UOP_SetFPReg:
78 case UOP_PushMachFrame:
79 return 1;
80 case UOP_SaveNonVol:
81 case UOP_SaveXMM128:
82 return 2;
83 case UOP_SaveNonVolBig:
84 case UOP_SaveXMM128Big:
85 return 3;
86 case UOP_AllocLarge:
87 return (UnwindCode.getOpInfo() == 0) ? 2 : 3;
88 }
89}
90
91// Prints one unwind code. Because an unwind code can occupy up to 3 slots in
92// the unwind codes array, this function requires that the correct number of
93// slots is provided.
94static void printUnwindCode(ArrayRef<UnwindCode> UCs) {
95 assert(UCs.size() >= getNumUsedSlots(UCs[0]));
Rui Ueyama595932f2014-03-04 19:23:56 +000096 outs() << format(" 0x%02x: ", unsigned(UCs[0].u.CodeOffset))
Michael J. Spencer0c6ec482012-12-05 20:12:35 +000097 << getUnwindCodeTypeName(UCs[0].getUnwindOp());
98 switch (UCs[0].getUnwindOp()) {
99 case UOP_PushNonVol:
100 outs() << " " << getUnwindRegisterName(UCs[0].getOpInfo());
101 break;
102 case UOP_AllocLarge:
103 if (UCs[0].getOpInfo() == 0) {
104 outs() << " " << UCs[1].FrameOffset;
105 } else {
106 outs() << " " << UCs[1].FrameOffset
107 + (static_cast<uint32_t>(UCs[2].FrameOffset) << 16);
108 }
109 break;
110 case UOP_AllocSmall:
111 outs() << " " << ((UCs[0].getOpInfo() + 1) * 8);
112 break;
113 case UOP_SetFPReg:
114 outs() << " ";
115 break;
116 case UOP_SaveNonVol:
117 outs() << " " << getUnwindRegisterName(UCs[0].getOpInfo())
118 << format(" [0x%04x]", 8 * UCs[1].FrameOffset);
119 break;
120 case UOP_SaveNonVolBig:
121 outs() << " " << getUnwindRegisterName(UCs[0].getOpInfo())
122 << format(" [0x%08x]", UCs[1].FrameOffset
123 + (static_cast<uint32_t>(UCs[2].FrameOffset) << 16));
124 break;
125 case UOP_SaveXMM128:
126 outs() << " XMM" << static_cast<uint32_t>(UCs[0].getOpInfo())
127 << format(" [0x%04x]", 16 * UCs[1].FrameOffset);
128 break;
129 case UOP_SaveXMM128Big:
130 outs() << " XMM" << UCs[0].getOpInfo()
131 << format(" [0x%08x]", UCs[1].FrameOffset
132 + (static_cast<uint32_t>(UCs[2].FrameOffset) << 16));
133 break;
134 case UOP_PushMachFrame:
135 outs() << " " << (UCs[0].getOpInfo() ? "w/o" : "w")
136 << " error code";
137 break;
138 }
139 outs() << "\n";
140}
141
142static void printAllUnwindCodes(ArrayRef<UnwindCode> UCs) {
143 for (const UnwindCode *I = UCs.begin(), *E = UCs.end(); I < E; ) {
144 unsigned UsedSlots = getNumUsedSlots(*I);
145 if (UsedSlots > UCs.size()) {
146 outs() << "Unwind data corrupted: Encountered unwind op "
147 << getUnwindCodeTypeName((*I).getUnwindOp())
148 << " which requires " << UsedSlots
149 << " slots, but only " << UCs.size()
150 << " remaining in buffer";
151 return ;
152 }
Craig Topper0013be12015-09-21 05:32:41 +0000153 printUnwindCode(makeArrayRef(I, E));
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000154 I += UsedSlots;
155 }
156}
157
158// Given a symbol sym this functions returns the address and section of it.
Rafael Espindola4453e42942014-06-13 03:07:50 +0000159static std::error_code
160resolveSectionAndAddress(const COFFObjectFile *Obj, const SymbolRef &Sym,
161 const coff_section *&ResolvedSection,
162 uint64_t &ResolvedAddr) {
Kevin Enderby931cb652016-06-24 18:24:42 +0000163 Expected<uint64_t> ResolvedAddrOrErr = Sym.getAddress();
164 if (!ResolvedAddrOrErr)
165 return errorToErrorCode(ResolvedAddrOrErr.takeError());
Rafael Espindolaed067c42015-07-03 18:19:00 +0000166 ResolvedAddr = *ResolvedAddrOrErr;
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000167 Expected<section_iterator> Iter = Sym.getSection();
168 if (!Iter)
169 return errorToErrorCode(Iter.takeError());
Rafael Espindola8bab8892015-08-07 23:27:14 +0000170 ResolvedSection = Obj->getCOFFSection(**Iter);
Rui Ueyama7d099192015-06-09 15:20:42 +0000171 return std::error_code();
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000172}
173
174// Given a vector of relocations for a section and an offset into this section
175// the function returns the symbol used for the relocation at the offset.
Rafael Espindola4453e42942014-06-13 03:07:50 +0000176static std::error_code resolveSymbol(const std::vector<RelocationRef> &Rels,
177 uint64_t Offset, SymbolRef &Sym) {
Davide Italianoc7d771d2016-09-30 23:22:42 +0000178 for (auto &R : Rels) {
179 uint64_t Ofs = R.getOffset();
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000180 if (Ofs == Offset) {
Davide Italianoc7d771d2016-09-30 23:22:42 +0000181 Sym = *R.getSymbol();
Rui Ueyama7d099192015-06-09 15:20:42 +0000182 return std::error_code();
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000183 }
184 }
Rui Ueyamacf397842014-02-28 05:21:29 +0000185 return object_error::parse_failed;
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000186}
187
188// Given a vector of relocations for a section and an offset into this section
189// the function resolves the symbol used for the relocation at the offset and
190// returns the section content and the address inside the content pointed to
191// by the symbol.
Rafael Espindola4453e42942014-06-13 03:07:50 +0000192static std::error_code
193getSectionContents(const COFFObjectFile *Obj,
194 const std::vector<RelocationRef> &Rels, uint64_t Offset,
195 ArrayRef<uint8_t> &Contents, uint64_t &Addr) {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000196 SymbolRef Sym;
Rafael Espindola4453e42942014-06-13 03:07:50 +0000197 if (std::error_code EC = resolveSymbol(Rels, Offset, Sym))
Rui Ueyama1618fe22014-02-28 05:21:26 +0000198 return EC;
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000199 const coff_section *Section;
Rafael Espindola4453e42942014-06-13 03:07:50 +0000200 if (std::error_code EC = resolveSectionAndAddress(Obj, Sym, Section, Addr))
Rui Ueyamaef8dede2014-01-16 20:57:55 +0000201 return EC;
Rafael Espindola4453e42942014-06-13 03:07:50 +0000202 if (std::error_code EC = Obj->getSectionContents(Section, Contents))
Rui Ueyamaef8dede2014-01-16 20:57:55 +0000203 return EC;
Rui Ueyama7d099192015-06-09 15:20:42 +0000204 return std::error_code();
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000205}
206
207// Given a vector of relocations for a section and an offset into this section
208// the function returns the name of the symbol used for the relocation at the
209// offset.
Rafael Espindola4453e42942014-06-13 03:07:50 +0000210static std::error_code resolveSymbolName(const std::vector<RelocationRef> &Rels,
211 uint64_t Offset, StringRef &Name) {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000212 SymbolRef Sym;
Rafael Espindola4453e42942014-06-13 03:07:50 +0000213 if (std::error_code EC = resolveSymbol(Rels, Offset, Sym))
Rui Ueyamaef8dede2014-01-16 20:57:55 +0000214 return EC;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000215 Expected<StringRef> NameOrErr = Sym.getName();
216 if (!NameOrErr)
217 return errorToErrorCode(NameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000218 Name = *NameOrErr;
Rui Ueyama7d099192015-06-09 15:20:42 +0000219 return std::error_code();
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000220}
221
222static void printCOFFSymbolAddress(llvm::raw_ostream &Out,
223 const std::vector<RelocationRef> &Rels,
224 uint64_t Offset, uint32_t Disp) {
225 StringRef Sym;
Rui Ueyamacf397842014-02-28 05:21:29 +0000226 if (!resolveSymbolName(Rels, Offset, Sym)) {
227 Out << Sym;
228 if (Disp > 0)
229 Out << format(" + 0x%04x", Disp);
230 } else {
231 Out << format("0x%04x", Disp);
232 }
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000233}
234
Rui Ueyama215a5862014-02-20 06:51:07 +0000235static void
236printSEHTable(const COFFObjectFile *Obj, uint32_t TableVA, int Count) {
237 if (Count == 0)
238 return;
239
240 const pe32_header *PE32Header;
Davide Italianoccd53fe2015-08-05 07:18:31 +0000241 error(Obj->getPE32Header(PE32Header));
Rui Ueyama215a5862014-02-20 06:51:07 +0000242 uint32_t ImageBase = PE32Header->ImageBase;
243 uintptr_t IntPtr = 0;
Davide Italianoccd53fe2015-08-05 07:18:31 +0000244 error(Obj->getVaPtr(TableVA, IntPtr));
Rui Ueyama215a5862014-02-20 06:51:07 +0000245 const support::ulittle32_t *P = (const support::ulittle32_t *)IntPtr;
246 outs() << "SEH Table:";
247 for (int I = 0; I < Count; ++I)
248 outs() << format(" 0x%x", P[I] + ImageBase);
249 outs() << "\n\n";
250}
251
David Majnemer0ab61bf2016-03-15 06:14:01 +0000252template <typename T>
253static void printTLSDirectoryT(const coff_tls_directory<T> *TLSDir) {
254 size_t FormatWidth = sizeof(T) * 2;
255 outs() << "TLS directory:"
256 << "\n StartAddressOfRawData: "
257 << format_hex(TLSDir->StartAddressOfRawData, FormatWidth)
258 << "\n EndAddressOfRawData: "
259 << format_hex(TLSDir->EndAddressOfRawData, FormatWidth)
260 << "\n AddressOfIndex: "
261 << format_hex(TLSDir->AddressOfIndex, FormatWidth)
262 << "\n AddressOfCallBacks: "
263 << format_hex(TLSDir->AddressOfCallBacks, FormatWidth)
264 << "\n SizeOfZeroFill: "
265 << TLSDir->SizeOfZeroFill
266 << "\n Characteristics: "
267 << TLSDir->Characteristics
268 << "\n Alignment: "
269 << TLSDir->getAlignment()
270 << "\n\n";
271}
272
273static void printTLSDirectory(const COFFObjectFile *Obj) {
274 const pe32_header *PE32Header;
275 error(Obj->getPE32Header(PE32Header));
276
277 const pe32plus_header *PE32PlusHeader;
278 error(Obj->getPE32PlusHeader(PE32PlusHeader));
279
280 // Skip if it's not executable.
281 if (!PE32Header && !PE32PlusHeader)
282 return;
283
284 const data_directory *DataDir;
285 error(Obj->getDataDirectory(COFF::TLS_TABLE, DataDir));
286 uintptr_t IntPtr = 0;
287 if (DataDir->RelativeVirtualAddress == 0)
288 return;
289 error(Obj->getRvaPtr(DataDir->RelativeVirtualAddress, IntPtr));
290
291 if (PE32Header) {
292 auto *TLSDir = reinterpret_cast<const coff_tls_directory32 *>(IntPtr);
293 printTLSDirectoryT(TLSDir);
294 } else {
295 auto *TLSDir = reinterpret_cast<const coff_tls_directory64 *>(IntPtr);
296 printTLSDirectoryT(TLSDir);
297 }
298
299 outs() << "\n";
300}
301
Rui Ueyamac514a802014-02-19 03:53:11 +0000302static void printLoadConfiguration(const COFFObjectFile *Obj) {
Rui Ueyama5cf32852014-02-21 20:27:15 +0000303 // Skip if it's not executable.
304 const pe32_header *PE32Header;
Davide Italianoccd53fe2015-08-05 07:18:31 +0000305 error(Obj->getPE32Header(PE32Header));
Rui Ueyama5cf32852014-02-21 20:27:15 +0000306 if (!PE32Header)
307 return;
308
Rui Ueyamac514a802014-02-19 03:53:11 +0000309 // Currently only x86 is supported
David Majnemer44f51e52014-09-10 12:51:52 +0000310 if (Obj->getMachine() != COFF::IMAGE_FILE_MACHINE_I386)
Rui Ueyamac514a802014-02-19 03:53:11 +0000311 return;
312
313 const data_directory *DataDir;
Davide Italianoccd53fe2015-08-05 07:18:31 +0000314 error(Obj->getDataDirectory(COFF::LOAD_CONFIG_TABLE, DataDir));
Rui Ueyamac514a802014-02-19 03:53:11 +0000315 uintptr_t IntPtr = 0;
316 if (DataDir->RelativeVirtualAddress == 0)
317 return;
Davide Italianoccd53fe2015-08-05 07:18:31 +0000318 error(Obj->getRvaPtr(DataDir->RelativeVirtualAddress, IntPtr));
Rui Ueyama215a5862014-02-20 06:51:07 +0000319
Rui Ueyama8c1d4c92014-03-04 04:15:59 +0000320 auto *LoadConf = reinterpret_cast<const coff_load_configuration32 *>(IntPtr);
Rui Ueyamac514a802014-02-19 03:53:11 +0000321 outs() << "Load configuration:"
322 << "\n Timestamp: " << LoadConf->TimeDateStamp
323 << "\n Major Version: " << LoadConf->MajorVersion
324 << "\n Minor Version: " << LoadConf->MinorVersion
325 << "\n GlobalFlags Clear: " << LoadConf->GlobalFlagsClear
326 << "\n GlobalFlags Set: " << LoadConf->GlobalFlagsSet
327 << "\n Critical Section Default Timeout: " << LoadConf->CriticalSectionDefaultTimeout
328 << "\n Decommit Free Block Threshold: " << LoadConf->DeCommitFreeBlockThreshold
329 << "\n Decommit Total Free Threshold: " << LoadConf->DeCommitTotalFreeThreshold
330 << "\n Lock Prefix Table: " << LoadConf->LockPrefixTable
331 << "\n Maximum Allocation Size: " << LoadConf->MaximumAllocationSize
332 << "\n Virtual Memory Threshold: " << LoadConf->VirtualMemoryThreshold
333 << "\n Process Affinity Mask: " << LoadConf->ProcessAffinityMask
334 << "\n Process Heap Flags: " << LoadConf->ProcessHeapFlags
335 << "\n CSD Version: " << LoadConf->CSDVersion
336 << "\n Security Cookie: " << LoadConf->SecurityCookie
337 << "\n SEH Table: " << LoadConf->SEHandlerTable
338 << "\n SEH Count: " << LoadConf->SEHandlerCount
339 << "\n\n";
Rui Ueyama215a5862014-02-20 06:51:07 +0000340 printSEHTable(Obj, LoadConf->SEHandlerTable, LoadConf->SEHandlerCount);
341 outs() << "\n";
Rui Ueyamac514a802014-02-19 03:53:11 +0000342}
343
Rui Ueyamac2bed422013-09-27 21:04:00 +0000344// Prints import tables. The import table is a table containing the list of
345// DLL name and symbol names which will be linked by the loader.
346static void printImportTables(const COFFObjectFile *Obj) {
Rui Ueyamaef8dede2014-01-16 20:57:55 +0000347 import_directory_iterator I = Obj->import_directory_begin();
348 import_directory_iterator E = Obj->import_directory_end();
349 if (I == E)
Rui Ueyama908dfcd2014-01-15 23:46:18 +0000350 return;
Rui Ueyamac2bed422013-09-27 21:04:00 +0000351 outs() << "The Import Tables:\n";
David Majnemerad7b7e72016-06-26 04:36:32 +0000352 for (const ImportDirectoryEntryRef &DirRef : Obj->import_directories()) {
David Majnemer1c0aa042016-07-31 19:25:21 +0000353 const coff_import_directory_table_entry *Dir;
Rui Ueyamac2bed422013-09-27 21:04:00 +0000354 StringRef Name;
David Majnemerad7b7e72016-06-26 04:36:32 +0000355 if (DirRef.getImportTableEntry(Dir)) return;
356 if (DirRef.getName(Name)) return;
Rui Ueyamac2bed422013-09-27 21:04:00 +0000357
358 outs() << format(" lookup %08x time %08x fwd %08x name %08x addr %08x\n\n",
359 static_cast<uint32_t>(Dir->ImportLookupTableRVA),
360 static_cast<uint32_t>(Dir->TimeDateStamp),
361 static_cast<uint32_t>(Dir->ForwarderChain),
362 static_cast<uint32_t>(Dir->NameRVA),
363 static_cast<uint32_t>(Dir->ImportAddressTableRVA));
364 outs() << " DLL Name: " << Name << "\n";
365 outs() << " Hint/Ord Name\n";
David Majnemerad7b7e72016-06-26 04:36:32 +0000366 for (const ImportedSymbolRef &Entry : DirRef.imported_symbols()) {
367 bool IsOrdinal;
368 if (Entry.isOrdinal(IsOrdinal))
369 return;
370 if (IsOrdinal) {
371 uint16_t Ordinal;
372 if (Entry.getOrdinal(Ordinal))
373 return;
374 outs() << format(" % 6d\n", Ordinal);
Rui Ueyamac2bed422013-09-27 21:04:00 +0000375 continue;
376 }
David Majnemerad7b7e72016-06-26 04:36:32 +0000377 uint32_t HintNameRVA;
378 if (Entry.getHintNameRVA(HintNameRVA))
379 return;
Rui Ueyamac2bed422013-09-27 21:04:00 +0000380 uint16_t Hint;
381 StringRef Name;
David Majnemerad7b7e72016-06-26 04:36:32 +0000382 if (Obj->getHintName(HintNameRVA, Hint, Name))
Rui Ueyamac2bed422013-09-27 21:04:00 +0000383 return;
384 outs() << format(" % 6d ", Hint) << Name << "\n";
385 }
386 outs() << "\n";
387 }
388}
389
Rui Ueyamaad882ba2014-01-16 07:05:49 +0000390// Prints export tables. The export table is a table containing the list of
391// exported symbol from the DLL.
392static void printExportTable(const COFFObjectFile *Obj) {
393 outs() << "Export Table:\n";
394 export_directory_iterator I = Obj->export_directory_begin();
395 export_directory_iterator E = Obj->export_directory_end();
396 if (I == E)
397 return;
Rui Ueyamada49d0d2014-01-16 20:50:34 +0000398 StringRef DllName;
Rui Ueyamae5df6092014-01-17 22:02:24 +0000399 uint32_t OrdinalBase;
Rui Ueyamada49d0d2014-01-16 20:50:34 +0000400 if (I->getDllName(DllName))
401 return;
Rui Ueyamae5df6092014-01-17 22:02:24 +0000402 if (I->getOrdinalBase(OrdinalBase))
403 return;
Rui Ueyamada49d0d2014-01-16 20:50:34 +0000404 outs() << " DLL name: " << DllName << "\n";
Rui Ueyamae5df6092014-01-17 22:02:24 +0000405 outs() << " Ordinal base: " << OrdinalBase << "\n";
Rui Ueyamaad882ba2014-01-16 07:05:49 +0000406 outs() << " Ordinal RVA Name\n";
Rafael Espindola5e812af2014-01-30 02:49:50 +0000407 for (; I != E; I = ++I) {
Rui Ueyamaad882ba2014-01-16 07:05:49 +0000408 uint32_t Ordinal;
409 if (I->getOrdinal(Ordinal))
410 return;
411 uint32_t RVA;
412 if (I->getExportRVA(RVA))
413 return;
Rui Ueyama6161b382016-01-12 23:28:42 +0000414 bool IsForwarder;
415 if (I->isForwarder(IsForwarder))
416 return;
417
418 if (IsForwarder) {
419 // Export table entries can be used to re-export symbols that
420 // this COFF file is imported from some DLLs. This is rare.
421 // In most cases IsForwarder is false.
422 outs() << format(" % 4d ", Ordinal);
423 } else {
424 outs() << format(" % 4d %# 8x", Ordinal, RVA);
425 }
Rui Ueyamaad882ba2014-01-16 07:05:49 +0000426
427 StringRef Name;
Rui Ueyamada49d0d2014-01-16 20:50:34 +0000428 if (I->getSymbolName(Name))
Rui Ueyamaad882ba2014-01-16 07:05:49 +0000429 continue;
430 if (!Name.empty())
431 outs() << " " << Name;
Rui Ueyama6161b382016-01-12 23:28:42 +0000432 if (IsForwarder) {
433 StringRef S;
434 if (I->getForwardTo(S))
435 return;
436 outs() << " (forwarded to " << S << ")";
437 }
Rui Ueyamaad882ba2014-01-16 07:05:49 +0000438 outs() << "\n";
439 }
440}
441
Rui Ueyama39f1b972014-03-04 00:31:48 +0000442// Given the COFF object file, this function returns the relocations for .pdata
443// and the pointer to "runtime function" structs.
444static bool getPDataSection(const COFFObjectFile *Obj,
445 std::vector<RelocationRef> &Rels,
446 const RuntimeFunction *&RFStart, int &NumRFs) {
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000447 for (const SectionRef &Section : Obj->sections()) {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000448 StringRef Name;
Davide Italianoccd53fe2015-08-05 07:18:31 +0000449 error(Section.getName(Name));
Rui Ueyama39f1b972014-03-04 00:31:48 +0000450 if (Name != ".pdata")
451 continue;
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000452
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000453 const coff_section *Pdata = Obj->getCOFFSection(Section);
454 for (const RelocationRef &Reloc : Section.relocations())
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000455 Rels.push_back(Reloc);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000456
457 // Sort relocations by address.
George Rimar73a27232019-01-15 09:19:18 +0000458 llvm::sort(Rels, isRelocAddressLess);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000459
460 ArrayRef<uint8_t> Contents;
Davide Italianoccd53fe2015-08-05 07:18:31 +0000461 error(Obj->getSectionContents(Pdata, Contents));
Rui Ueyama39f1b972014-03-04 00:31:48 +0000462 if (Contents.empty())
463 continue;
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000464
Rui Ueyama39f1b972014-03-04 00:31:48 +0000465 RFStart = reinterpret_cast<const RuntimeFunction *>(Contents.data());
466 NumRFs = Contents.size() / sizeof(RuntimeFunction);
467 return true;
468 }
469 return false;
470}
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000471
George Rimarc1964882019-01-18 11:33:26 +0000472std::error_code
473llvm::getCOFFRelocationValueString(const COFFObjectFile *Obj,
474 const RelocationRef &Rel,
475 SmallVectorImpl<char> &Result) {
476 symbol_iterator SymI = Rel.getSymbol();
477 Expected<StringRef> SymNameOrErr = SymI->getName();
478 if (!SymNameOrErr)
479 return errorToErrorCode(SymNameOrErr.takeError());
480 StringRef SymName = *SymNameOrErr;
481 Result.append(SymName.begin(), SymName.end());
482 return std::error_code();
483}
484
Rui Ueyama6dfd4e12014-03-04 03:08:45 +0000485static void printWin64EHUnwindInfo(const Win64EH::UnwindInfo *UI) {
Rui Ueyama39f1b972014-03-04 00:31:48 +0000486 // The casts to int are required in order to output the value as number.
487 // Without the casts the value would be interpreted as char data (which
488 // results in garbage output).
Rui Ueyama595932f2014-03-04 19:23:56 +0000489 outs() << " Version: " << static_cast<int>(UI->getVersion()) << "\n";
490 outs() << " Flags: " << static_cast<int>(UI->getFlags());
Rui Ueyama39f1b972014-03-04 00:31:48 +0000491 if (UI->getFlags()) {
492 if (UI->getFlags() & UNW_ExceptionHandler)
493 outs() << " UNW_ExceptionHandler";
494 if (UI->getFlags() & UNW_TerminateHandler)
495 outs() << " UNW_TerminateHandler";
496 if (UI->getFlags() & UNW_ChainInfo)
497 outs() << " UNW_ChainInfo";
498 }
499 outs() << "\n";
Rui Ueyama595932f2014-03-04 19:23:56 +0000500 outs() << " Size of prolog: " << static_cast<int>(UI->PrologSize) << "\n";
501 outs() << " Number of Codes: " << static_cast<int>(UI->NumCodes) << "\n";
Rui Ueyama39f1b972014-03-04 00:31:48 +0000502 // Maybe this should move to output of UOP_SetFPReg?
503 if (UI->getFrameRegister()) {
Rui Ueyama595932f2014-03-04 19:23:56 +0000504 outs() << " Frame register: "
Rui Ueyama39f1b972014-03-04 00:31:48 +0000505 << getUnwindRegisterName(UI->getFrameRegister()) << "\n";
Rui Ueyama595932f2014-03-04 19:23:56 +0000506 outs() << " Frame offset: " << 16 * UI->getFrameOffset() << "\n";
Rui Ueyama39f1b972014-03-04 00:31:48 +0000507 } else {
Rui Ueyama595932f2014-03-04 19:23:56 +0000508 outs() << " No frame pointer used\n";
Rui Ueyama39f1b972014-03-04 00:31:48 +0000509 }
510 if (UI->getFlags() & (UNW_ExceptionHandler | UNW_TerminateHandler)) {
511 // FIXME: Output exception handler data
512 } else if (UI->getFlags() & UNW_ChainInfo) {
513 // FIXME: Output chained unwind info
514 }
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000515
Rui Ueyama39f1b972014-03-04 00:31:48 +0000516 if (UI->NumCodes)
Rui Ueyama595932f2014-03-04 19:23:56 +0000517 outs() << " Unwind Codes:\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000518
Craig Topper0013be12015-09-21 05:32:41 +0000519 printAllUnwindCodes(makeArrayRef(&UI->UnwindCodes[0], UI->NumCodes));
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000520
Rui Ueyama595932f2014-03-04 19:23:56 +0000521 outs() << "\n";
Rui Ueyama39f1b972014-03-04 00:31:48 +0000522 outs().flush();
523}
524
Rui Ueyamafd3cb9e2014-03-04 04:22:41 +0000525/// Prints out the given RuntimeFunction struct for x64, assuming that Obj is
Rui Ueyama9c674e62014-03-04 04:00:55 +0000526/// pointing to an executable file.
Rui Ueyama6dfd4e12014-03-04 03:08:45 +0000527static void printRuntimeFunction(const COFFObjectFile *Obj,
Rui Ueyama9c674e62014-03-04 04:00:55 +0000528 const RuntimeFunction &RF) {
529 if (!RF.StartAddress)
530 return;
531 outs() << "Function Table:\n"
Rui Ueyamaad807652014-03-05 23:03:37 +0000532 << format(" Start Address: 0x%04x\n",
533 static_cast<uint32_t>(RF.StartAddress))
534 << format(" End Address: 0x%04x\n",
535 static_cast<uint32_t>(RF.EndAddress))
536 << format(" Unwind Info Address: 0x%04x\n",
537 static_cast<uint32_t>(RF.UnwindInfoOffset));
Rui Ueyama9c674e62014-03-04 04:00:55 +0000538 uintptr_t addr;
539 if (Obj->getRvaPtr(RF.UnwindInfoOffset, addr))
540 return;
541 printWin64EHUnwindInfo(reinterpret_cast<const Win64EH::UnwindInfo *>(addr));
542}
543
Rui Ueyamafd3cb9e2014-03-04 04:22:41 +0000544/// Prints out the given RuntimeFunction struct for x64, assuming that Obj is
545/// pointing to an object file. Unlike executable, fields in RuntimeFunction
Rui Ueyama9c674e62014-03-04 04:00:55 +0000546/// struct are filled with zeros, but instead there are relocations pointing to
547/// them so that the linker will fill targets' RVAs to the fields at link
548/// time. This function interprets the relocations to find the data to be used
549/// in the resulting executable.
550static void printRuntimeFunctionRels(const COFFObjectFile *Obj,
551 const RuntimeFunction &RF,
552 uint64_t SectionOffset,
553 const std::vector<RelocationRef> &Rels) {
Rui Ueyama6dfd4e12014-03-04 03:08:45 +0000554 outs() << "Function Table:\n";
555 outs() << " Start Address: ";
556 printCOFFSymbolAddress(outs(), Rels,
557 SectionOffset +
558 /*offsetof(RuntimeFunction, StartAddress)*/ 0,
559 RF.StartAddress);
560 outs() << "\n";
561
562 outs() << " End Address: ";
563 printCOFFSymbolAddress(outs(), Rels,
564 SectionOffset +
565 /*offsetof(RuntimeFunction, EndAddress)*/ 4,
566 RF.EndAddress);
567 outs() << "\n";
568
569 outs() << " Unwind Info Address: ";
570 printCOFFSymbolAddress(outs(), Rels,
571 SectionOffset +
572 /*offsetof(RuntimeFunction, UnwindInfoOffset)*/ 8,
573 RF.UnwindInfoOffset);
574 outs() << "\n";
575
576 ArrayRef<uint8_t> XContents;
577 uint64_t UnwindInfoOffset = 0;
Davide Italianoccd53fe2015-08-05 07:18:31 +0000578 error(getSectionContents(
Rui Ueyama6dfd4e12014-03-04 03:08:45 +0000579 Obj, Rels, SectionOffset +
580 /*offsetof(RuntimeFunction, UnwindInfoOffset)*/ 8,
Davide Italianoccd53fe2015-08-05 07:18:31 +0000581 XContents, UnwindInfoOffset));
Rui Ueyama6dfd4e12014-03-04 03:08:45 +0000582 if (XContents.empty())
583 return;
584
585 UnwindInfoOffset += RF.UnwindInfoOffset;
586 if (UnwindInfoOffset > XContents.size())
587 return;
588
Rui Ueyama8c1d4c92014-03-04 04:15:59 +0000589 auto *UI = reinterpret_cast<const Win64EH::UnwindInfo *>(XContents.data() +
590 UnwindInfoOffset);
Rui Ueyama6dfd4e12014-03-04 03:08:45 +0000591 printWin64EHUnwindInfo(UI);
592}
593
Rui Ueyama39f1b972014-03-04 00:31:48 +0000594void llvm::printCOFFUnwindInfo(const COFFObjectFile *Obj) {
David Majnemer44f51e52014-09-10 12:51:52 +0000595 if (Obj->getMachine() != COFF::IMAGE_FILE_MACHINE_AMD64) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000596 WithColor::error(errs(), "llvm-objdump")
597 << "unsupported image machine type "
598 "(currently only AMD64 is supported).\n";
Rui Ueyama39f1b972014-03-04 00:31:48 +0000599 return;
600 }
601
602 std::vector<RelocationRef> Rels;
603 const RuntimeFunction *RFStart;
604 int NumRFs;
605 if (!getPDataSection(Obj, Rels, RFStart, NumRFs))
606 return;
607 ArrayRef<RuntimeFunction> RFs(RFStart, NumRFs);
608
Rui Ueyama9c674e62014-03-04 04:00:55 +0000609 bool IsExecutable = Rels.empty();
610 if (IsExecutable) {
611 for (const RuntimeFunction &RF : RFs)
612 printRuntimeFunction(Obj, RF);
613 return;
614 }
615
Rui Ueyama39f1b972014-03-04 00:31:48 +0000616 for (const RuntimeFunction &RF : RFs) {
617 uint64_t SectionOffset =
618 std::distance(RFs.begin(), &RF) * sizeof(RuntimeFunction);
Rui Ueyama9c674e62014-03-04 04:00:55 +0000619 printRuntimeFunctionRels(Obj, RF, SectionOffset, Rels);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000620 }
621}
Rui Ueyamac2bed422013-09-27 21:04:00 +0000622
623void llvm::printCOFFFileHeader(const object::ObjectFile *Obj) {
Rui Ueyamaad882ba2014-01-16 07:05:49 +0000624 const COFFObjectFile *file = dyn_cast<const COFFObjectFile>(Obj);
David Majnemer0ab61bf2016-03-15 06:14:01 +0000625 printTLSDirectory(file);
Rui Ueyamac514a802014-02-19 03:53:11 +0000626 printLoadConfiguration(file);
Rui Ueyamaad882ba2014-01-16 07:05:49 +0000627 printImportTables(file);
628 printExportTable(file);
Rui Ueyamac2bed422013-09-27 21:04:00 +0000629}
Davide Italianoe85abf72015-12-20 09:54:34 +0000630
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +0000631void llvm::printCOFFSymbolTable(const object::COFFImportFile *i) {
632 unsigned Index = 0;
633 bool IsCode = i->getCOFFImportHeader()->getType() == COFF::IMPORT_CODE;
634
635 for (const object::BasicSymbolRef &Sym : i->symbols()) {
636 std::string Name;
637 raw_string_ostream NS(Name);
638
639 Sym.printName(NS);
640 NS.flush();
641
642 outs() << "[" << format("%2d", Index) << "]"
643 << "(sec " << format("%2d", 0) << ")"
644 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
645 << "(ty " << format("%3x", (IsCode && Index) ? 32 : 0) << ")"
646 << "(scl " << format("%3x", 0) << ") "
647 << "(nx " << 0 << ") "
648 << "0x" << format("%08x", 0) << " " << Name << '\n';
649
650 ++Index;
651 }
652}
653
Davide Italianoe85abf72015-12-20 09:54:34 +0000654void llvm::printCOFFSymbolTable(const COFFObjectFile *coff) {
655 for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
Rafael Espindola74894922017-10-11 17:23:15 +0000656 Expected<COFFSymbolRef> Symbol = coff->getSymbol(SI);
Davide Italianoe85abf72015-12-20 09:54:34 +0000657 StringRef Name;
Rafael Espindola74894922017-10-11 17:23:15 +0000658 error(errorToErrorCode(Symbol.takeError()));
Davide Italianoe85abf72015-12-20 09:54:34 +0000659 error(coff->getSymbolName(*Symbol, Name));
660
661 outs() << "[" << format("%2d", SI) << "]"
662 << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
663 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
664 << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
Zachary Turner030ad372018-08-20 22:18:21 +0000665 << "(scl " << format("%3x", unsigned(Symbol->getStorageClass()))
666 << ") "
Davide Italianoe85abf72015-12-20 09:54:34 +0000667 << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
668 << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
Zachary Turner030ad372018-08-20 22:18:21 +0000669 << Name;
670 if (Demangle && Name.startswith("?")) {
671 char *DemangledSymbol = nullptr;
672 size_t Size = 0;
673 int Status = -1;
674 DemangledSymbol =
675 microsoftDemangle(Name.data(), DemangledSymbol, &Size, &Status);
676
677 if (Status == 0 && DemangledSymbol) {
678 outs() << " (" << StringRef(DemangledSymbol) << ")";
679 std::free(DemangledSymbol);
Zachary Turner4ca11212018-08-21 21:23:29 +0000680 } else {
681 outs() << " (invalid mangled name)";
Zachary Turner030ad372018-08-20 22:18:21 +0000682 }
683 }
684 outs() << "\n";
Davide Italianoe85abf72015-12-20 09:54:34 +0000685
686 for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
687 if (Symbol->isSectionDefinition()) {
688 const coff_aux_section_definition *asd;
689 error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd));
690
691 int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
692
693 outs() << "AUX "
694 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
695 , unsigned(asd->Length)
696 , unsigned(asd->NumberOfRelocations)
697 , unsigned(asd->NumberOfLinenumbers)
698 , unsigned(asd->CheckSum))
699 << format("assoc %d comdat %d\n"
700 , unsigned(AuxNumber)
701 , unsigned(asd->Selection));
702 } else if (Symbol->isFileRecord()) {
703 const char *FileName;
704 error(coff->getAuxSymbol<char>(SI + 1, FileName));
705
706 StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
707 coff->getSymbolTableEntrySize());
708 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
709
710 SI = SI + Symbol->getNumberOfAuxSymbols();
711 break;
Saleem Abdulrasoolfbf920f2016-05-26 01:45:12 +0000712 } else if (Symbol->isWeakExternal()) {
713 const coff_aux_weak_external *awe;
714 error(coff->getAuxSymbol<coff_aux_weak_external>(SI + 1, awe));
715
716 outs() << "AUX " << format("indx %d srch %d\n",
717 static_cast<uint32_t>(awe->TagIndex),
718 static_cast<uint32_t>(awe->Characteristics));
Davide Italianoe85abf72015-12-20 09:54:34 +0000719 } else {
720 outs() << "AUX Unknown\n";
721 }
722 }
723 }
724}