blob: 3503eda42f2a2389379b450d344c48d4a68dfceb [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"
Michael J. Spencer0c6ec482012-12-05 20:12:35 +000025#include "llvm/Support/raw_ostream.h"
Michael J. Spencer0c6ec482012-12-05 20:12:35 +000026
27using namespace llvm;
28using namespace object;
29using namespace llvm::Win64EH;
30
31// Returns the name of the unwind code.
32static StringRef getUnwindCodeTypeName(uint8_t Code) {
33 switch(Code) {
34 default: llvm_unreachable("Invalid unwind code");
35 case UOP_PushNonVol: return "UOP_PushNonVol";
36 case UOP_AllocLarge: return "UOP_AllocLarge";
37 case UOP_AllocSmall: return "UOP_AllocSmall";
38 case UOP_SetFPReg: return "UOP_SetFPReg";
39 case UOP_SaveNonVol: return "UOP_SaveNonVol";
40 case UOP_SaveNonVolBig: return "UOP_SaveNonVolBig";
41 case UOP_SaveXMM128: return "UOP_SaveXMM128";
42 case UOP_SaveXMM128Big: return "UOP_SaveXMM128Big";
43 case UOP_PushMachFrame: return "UOP_PushMachFrame";
44 }
45}
46
47// Returns the name of a referenced register.
48static StringRef getUnwindRegisterName(uint8_t Reg) {
49 switch(Reg) {
50 default: llvm_unreachable("Invalid register");
51 case 0: return "RAX";
52 case 1: return "RCX";
53 case 2: return "RDX";
54 case 3: return "RBX";
55 case 4: return "RSP";
56 case 5: return "RBP";
57 case 6: return "RSI";
58 case 7: return "RDI";
59 case 8: return "R8";
60 case 9: return "R9";
61 case 10: return "R10";
62 case 11: return "R11";
63 case 12: return "R12";
64 case 13: return "R13";
65 case 14: return "R14";
66 case 15: return "R15";
67 }
68}
69
70// Calculates the number of array slots required for the unwind code.
71static unsigned getNumUsedSlots(const UnwindCode &UnwindCode) {
72 switch (UnwindCode.getUnwindOp()) {
73 default: llvm_unreachable("Invalid unwind code");
74 case UOP_PushNonVol:
75 case UOP_AllocSmall:
76 case UOP_SetFPReg:
77 case UOP_PushMachFrame:
78 return 1;
79 case UOP_SaveNonVol:
80 case UOP_SaveXMM128:
81 return 2;
82 case UOP_SaveNonVolBig:
83 case UOP_SaveXMM128Big:
84 return 3;
85 case UOP_AllocLarge:
86 return (UnwindCode.getOpInfo() == 0) ? 2 : 3;
87 }
88}
89
90// Prints one unwind code. Because an unwind code can occupy up to 3 slots in
91// the unwind codes array, this function requires that the correct number of
92// slots is provided.
93static void printUnwindCode(ArrayRef<UnwindCode> UCs) {
94 assert(UCs.size() >= getNumUsedSlots(UCs[0]));
Rui Ueyama595932f2014-03-04 19:23:56 +000095 outs() << format(" 0x%02x: ", unsigned(UCs[0].u.CodeOffset))
Michael J. Spencer0c6ec482012-12-05 20:12:35 +000096 << getUnwindCodeTypeName(UCs[0].getUnwindOp());
97 switch (UCs[0].getUnwindOp()) {
98 case UOP_PushNonVol:
99 outs() << " " << getUnwindRegisterName(UCs[0].getOpInfo());
100 break;
101 case UOP_AllocLarge:
102 if (UCs[0].getOpInfo() == 0) {
103 outs() << " " << UCs[1].FrameOffset;
104 } else {
105 outs() << " " << UCs[1].FrameOffset
106 + (static_cast<uint32_t>(UCs[2].FrameOffset) << 16);
107 }
108 break;
109 case UOP_AllocSmall:
110 outs() << " " << ((UCs[0].getOpInfo() + 1) * 8);
111 break;
112 case UOP_SetFPReg:
113 outs() << " ";
114 break;
115 case UOP_SaveNonVol:
116 outs() << " " << getUnwindRegisterName(UCs[0].getOpInfo())
117 << format(" [0x%04x]", 8 * UCs[1].FrameOffset);
118 break;
119 case UOP_SaveNonVolBig:
120 outs() << " " << getUnwindRegisterName(UCs[0].getOpInfo())
121 << format(" [0x%08x]", UCs[1].FrameOffset
122 + (static_cast<uint32_t>(UCs[2].FrameOffset) << 16));
123 break;
124 case UOP_SaveXMM128:
125 outs() << " XMM" << static_cast<uint32_t>(UCs[0].getOpInfo())
126 << format(" [0x%04x]", 16 * UCs[1].FrameOffset);
127 break;
128 case UOP_SaveXMM128Big:
129 outs() << " XMM" << UCs[0].getOpInfo()
130 << format(" [0x%08x]", UCs[1].FrameOffset
131 + (static_cast<uint32_t>(UCs[2].FrameOffset) << 16));
132 break;
133 case UOP_PushMachFrame:
134 outs() << " " << (UCs[0].getOpInfo() ? "w/o" : "w")
135 << " error code";
136 break;
137 }
138 outs() << "\n";
139}
140
141static void printAllUnwindCodes(ArrayRef<UnwindCode> UCs) {
142 for (const UnwindCode *I = UCs.begin(), *E = UCs.end(); I < E; ) {
143 unsigned UsedSlots = getNumUsedSlots(*I);
144 if (UsedSlots > UCs.size()) {
145 outs() << "Unwind data corrupted: Encountered unwind op "
146 << getUnwindCodeTypeName((*I).getUnwindOp())
147 << " which requires " << UsedSlots
148 << " slots, but only " << UCs.size()
149 << " remaining in buffer";
150 return ;
151 }
Craig Topper0013be12015-09-21 05:32:41 +0000152 printUnwindCode(makeArrayRef(I, E));
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000153 I += UsedSlots;
154 }
155}
156
157// Given a symbol sym this functions returns the address and section of it.
Rafael Espindola4453e42942014-06-13 03:07:50 +0000158static std::error_code
159resolveSectionAndAddress(const COFFObjectFile *Obj, const SymbolRef &Sym,
160 const coff_section *&ResolvedSection,
161 uint64_t &ResolvedAddr) {
Kevin Enderby931cb652016-06-24 18:24:42 +0000162 Expected<uint64_t> ResolvedAddrOrErr = Sym.getAddress();
163 if (!ResolvedAddrOrErr)
164 return errorToErrorCode(ResolvedAddrOrErr.takeError());
Rafael Espindolaed067c42015-07-03 18:19:00 +0000165 ResolvedAddr = *ResolvedAddrOrErr;
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000166 Expected<section_iterator> Iter = Sym.getSection();
167 if (!Iter)
168 return errorToErrorCode(Iter.takeError());
Rafael Espindola8bab8892015-08-07 23:27:14 +0000169 ResolvedSection = Obj->getCOFFSection(**Iter);
Rui Ueyama7d099192015-06-09 15:20:42 +0000170 return std::error_code();
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000171}
172
173// Given a vector of relocations for a section and an offset into this section
174// the function returns the symbol used for the relocation at the offset.
Rafael Espindola4453e42942014-06-13 03:07:50 +0000175static std::error_code resolveSymbol(const std::vector<RelocationRef> &Rels,
176 uint64_t Offset, SymbolRef &Sym) {
Davide Italianoc7d771d2016-09-30 23:22:42 +0000177 for (auto &R : Rels) {
178 uint64_t Ofs = R.getOffset();
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000179 if (Ofs == Offset) {
Davide Italianoc7d771d2016-09-30 23:22:42 +0000180 Sym = *R.getSymbol();
Rui Ueyama7d099192015-06-09 15:20:42 +0000181 return std::error_code();
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000182 }
183 }
Rui Ueyamacf397842014-02-28 05:21:29 +0000184 return object_error::parse_failed;
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000185}
186
187// Given a vector of relocations for a section and an offset into this section
188// the function resolves the symbol used for the relocation at the offset and
189// returns the section content and the address inside the content pointed to
190// by the symbol.
Rafael Espindola4453e42942014-06-13 03:07:50 +0000191static std::error_code
192getSectionContents(const COFFObjectFile *Obj,
193 const std::vector<RelocationRef> &Rels, uint64_t Offset,
194 ArrayRef<uint8_t> &Contents, uint64_t &Addr) {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000195 SymbolRef Sym;
Rafael Espindola4453e42942014-06-13 03:07:50 +0000196 if (std::error_code EC = resolveSymbol(Rels, Offset, Sym))
Rui Ueyama1618fe22014-02-28 05:21:26 +0000197 return EC;
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000198 const coff_section *Section;
Rafael Espindola4453e42942014-06-13 03:07:50 +0000199 if (std::error_code EC = resolveSectionAndAddress(Obj, Sym, Section, Addr))
Rui Ueyamaef8dede2014-01-16 20:57:55 +0000200 return EC;
Rafael Espindola4453e42942014-06-13 03:07:50 +0000201 if (std::error_code EC = Obj->getSectionContents(Section, Contents))
Rui Ueyamaef8dede2014-01-16 20:57:55 +0000202 return EC;
Rui Ueyama7d099192015-06-09 15:20:42 +0000203 return std::error_code();
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000204}
205
206// Given a vector of relocations for a section and an offset into this section
207// the function returns the name of the symbol used for the relocation at the
208// offset.
Rafael Espindola4453e42942014-06-13 03:07:50 +0000209static std::error_code resolveSymbolName(const std::vector<RelocationRef> &Rels,
210 uint64_t Offset, StringRef &Name) {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000211 SymbolRef Sym;
Rafael Espindola4453e42942014-06-13 03:07:50 +0000212 if (std::error_code EC = resolveSymbol(Rels, Offset, Sym))
Rui Ueyamaef8dede2014-01-16 20:57:55 +0000213 return EC;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000214 Expected<StringRef> NameOrErr = Sym.getName();
215 if (!NameOrErr)
216 return errorToErrorCode(NameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000217 Name = *NameOrErr;
Rui Ueyama7d099192015-06-09 15:20:42 +0000218 return std::error_code();
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000219}
220
221static void printCOFFSymbolAddress(llvm::raw_ostream &Out,
222 const std::vector<RelocationRef> &Rels,
223 uint64_t Offset, uint32_t Disp) {
224 StringRef Sym;
Rui Ueyamacf397842014-02-28 05:21:29 +0000225 if (!resolveSymbolName(Rels, Offset, Sym)) {
226 Out << Sym;
227 if (Disp > 0)
228 Out << format(" + 0x%04x", Disp);
229 } else {
230 Out << format("0x%04x", Disp);
231 }
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000232}
233
Rui Ueyama215a5862014-02-20 06:51:07 +0000234static void
235printSEHTable(const COFFObjectFile *Obj, uint32_t TableVA, int Count) {
236 if (Count == 0)
237 return;
238
239 const pe32_header *PE32Header;
Davide Italianoccd53fe2015-08-05 07:18:31 +0000240 error(Obj->getPE32Header(PE32Header));
Rui Ueyama215a5862014-02-20 06:51:07 +0000241 uint32_t ImageBase = PE32Header->ImageBase;
242 uintptr_t IntPtr = 0;
Davide Italianoccd53fe2015-08-05 07:18:31 +0000243 error(Obj->getVaPtr(TableVA, IntPtr));
Rui Ueyama215a5862014-02-20 06:51:07 +0000244 const support::ulittle32_t *P = (const support::ulittle32_t *)IntPtr;
245 outs() << "SEH Table:";
246 for (int I = 0; I < Count; ++I)
247 outs() << format(" 0x%x", P[I] + ImageBase);
248 outs() << "\n\n";
249}
250
David Majnemer0ab61bf2016-03-15 06:14:01 +0000251template <typename T>
252static void printTLSDirectoryT(const coff_tls_directory<T> *TLSDir) {
253 size_t FormatWidth = sizeof(T) * 2;
254 outs() << "TLS directory:"
255 << "\n StartAddressOfRawData: "
256 << format_hex(TLSDir->StartAddressOfRawData, FormatWidth)
257 << "\n EndAddressOfRawData: "
258 << format_hex(TLSDir->EndAddressOfRawData, FormatWidth)
259 << "\n AddressOfIndex: "
260 << format_hex(TLSDir->AddressOfIndex, FormatWidth)
261 << "\n AddressOfCallBacks: "
262 << format_hex(TLSDir->AddressOfCallBacks, FormatWidth)
263 << "\n SizeOfZeroFill: "
264 << TLSDir->SizeOfZeroFill
265 << "\n Characteristics: "
266 << TLSDir->Characteristics
267 << "\n Alignment: "
268 << TLSDir->getAlignment()
269 << "\n\n";
270}
271
272static void printTLSDirectory(const COFFObjectFile *Obj) {
273 const pe32_header *PE32Header;
274 error(Obj->getPE32Header(PE32Header));
275
276 const pe32plus_header *PE32PlusHeader;
277 error(Obj->getPE32PlusHeader(PE32PlusHeader));
278
279 // Skip if it's not executable.
280 if (!PE32Header && !PE32PlusHeader)
281 return;
282
283 const data_directory *DataDir;
284 error(Obj->getDataDirectory(COFF::TLS_TABLE, DataDir));
285 uintptr_t IntPtr = 0;
286 if (DataDir->RelativeVirtualAddress == 0)
287 return;
288 error(Obj->getRvaPtr(DataDir->RelativeVirtualAddress, IntPtr));
289
290 if (PE32Header) {
291 auto *TLSDir = reinterpret_cast<const coff_tls_directory32 *>(IntPtr);
292 printTLSDirectoryT(TLSDir);
293 } else {
294 auto *TLSDir = reinterpret_cast<const coff_tls_directory64 *>(IntPtr);
295 printTLSDirectoryT(TLSDir);
296 }
297
298 outs() << "\n";
299}
300
Rui Ueyamac514a802014-02-19 03:53:11 +0000301static void printLoadConfiguration(const COFFObjectFile *Obj) {
Rui Ueyama5cf32852014-02-21 20:27:15 +0000302 // Skip if it's not executable.
303 const pe32_header *PE32Header;
Davide Italianoccd53fe2015-08-05 07:18:31 +0000304 error(Obj->getPE32Header(PE32Header));
Rui Ueyama5cf32852014-02-21 20:27:15 +0000305 if (!PE32Header)
306 return;
307
Rui Ueyamac514a802014-02-19 03:53:11 +0000308 // Currently only x86 is supported
David Majnemer44f51e52014-09-10 12:51:52 +0000309 if (Obj->getMachine() != COFF::IMAGE_FILE_MACHINE_I386)
Rui Ueyamac514a802014-02-19 03:53:11 +0000310 return;
311
312 const data_directory *DataDir;
Davide Italianoccd53fe2015-08-05 07:18:31 +0000313 error(Obj->getDataDirectory(COFF::LOAD_CONFIG_TABLE, DataDir));
Rui Ueyamac514a802014-02-19 03:53:11 +0000314 uintptr_t IntPtr = 0;
315 if (DataDir->RelativeVirtualAddress == 0)
316 return;
Davide Italianoccd53fe2015-08-05 07:18:31 +0000317 error(Obj->getRvaPtr(DataDir->RelativeVirtualAddress, IntPtr));
Rui Ueyama215a5862014-02-20 06:51:07 +0000318
Rui Ueyama8c1d4c92014-03-04 04:15:59 +0000319 auto *LoadConf = reinterpret_cast<const coff_load_configuration32 *>(IntPtr);
Rui Ueyamac514a802014-02-19 03:53:11 +0000320 outs() << "Load configuration:"
321 << "\n Timestamp: " << LoadConf->TimeDateStamp
322 << "\n Major Version: " << LoadConf->MajorVersion
323 << "\n Minor Version: " << LoadConf->MinorVersion
324 << "\n GlobalFlags Clear: " << LoadConf->GlobalFlagsClear
325 << "\n GlobalFlags Set: " << LoadConf->GlobalFlagsSet
326 << "\n Critical Section Default Timeout: " << LoadConf->CriticalSectionDefaultTimeout
327 << "\n Decommit Free Block Threshold: " << LoadConf->DeCommitFreeBlockThreshold
328 << "\n Decommit Total Free Threshold: " << LoadConf->DeCommitTotalFreeThreshold
329 << "\n Lock Prefix Table: " << LoadConf->LockPrefixTable
330 << "\n Maximum Allocation Size: " << LoadConf->MaximumAllocationSize
331 << "\n Virtual Memory Threshold: " << LoadConf->VirtualMemoryThreshold
332 << "\n Process Affinity Mask: " << LoadConf->ProcessAffinityMask
333 << "\n Process Heap Flags: " << LoadConf->ProcessHeapFlags
334 << "\n CSD Version: " << LoadConf->CSDVersion
335 << "\n Security Cookie: " << LoadConf->SecurityCookie
336 << "\n SEH Table: " << LoadConf->SEHandlerTable
337 << "\n SEH Count: " << LoadConf->SEHandlerCount
338 << "\n\n";
Rui Ueyama215a5862014-02-20 06:51:07 +0000339 printSEHTable(Obj, LoadConf->SEHandlerTable, LoadConf->SEHandlerCount);
340 outs() << "\n";
Rui Ueyamac514a802014-02-19 03:53:11 +0000341}
342
Rui Ueyamac2bed422013-09-27 21:04:00 +0000343// Prints import tables. The import table is a table containing the list of
344// DLL name and symbol names which will be linked by the loader.
345static void printImportTables(const COFFObjectFile *Obj) {
Rui Ueyamaef8dede2014-01-16 20:57:55 +0000346 import_directory_iterator I = Obj->import_directory_begin();
347 import_directory_iterator E = Obj->import_directory_end();
348 if (I == E)
Rui Ueyama908dfcd2014-01-15 23:46:18 +0000349 return;
Rui Ueyamac2bed422013-09-27 21:04:00 +0000350 outs() << "The Import Tables:\n";
David Majnemerad7b7e72016-06-26 04:36:32 +0000351 for (const ImportDirectoryEntryRef &DirRef : Obj->import_directories()) {
David Majnemer1c0aa042016-07-31 19:25:21 +0000352 const coff_import_directory_table_entry *Dir;
Rui Ueyamac2bed422013-09-27 21:04:00 +0000353 StringRef Name;
David Majnemerad7b7e72016-06-26 04:36:32 +0000354 if (DirRef.getImportTableEntry(Dir)) return;
355 if (DirRef.getName(Name)) return;
Rui Ueyamac2bed422013-09-27 21:04:00 +0000356
357 outs() << format(" lookup %08x time %08x fwd %08x name %08x addr %08x\n\n",
358 static_cast<uint32_t>(Dir->ImportLookupTableRVA),
359 static_cast<uint32_t>(Dir->TimeDateStamp),
360 static_cast<uint32_t>(Dir->ForwarderChain),
361 static_cast<uint32_t>(Dir->NameRVA),
362 static_cast<uint32_t>(Dir->ImportAddressTableRVA));
363 outs() << " DLL Name: " << Name << "\n";
364 outs() << " Hint/Ord Name\n";
David Majnemerad7b7e72016-06-26 04:36:32 +0000365 for (const ImportedSymbolRef &Entry : DirRef.imported_symbols()) {
366 bool IsOrdinal;
367 if (Entry.isOrdinal(IsOrdinal))
368 return;
369 if (IsOrdinal) {
370 uint16_t Ordinal;
371 if (Entry.getOrdinal(Ordinal))
372 return;
373 outs() << format(" % 6d\n", Ordinal);
Rui Ueyamac2bed422013-09-27 21:04:00 +0000374 continue;
375 }
David Majnemerad7b7e72016-06-26 04:36:32 +0000376 uint32_t HintNameRVA;
377 if (Entry.getHintNameRVA(HintNameRVA))
378 return;
Rui Ueyamac2bed422013-09-27 21:04:00 +0000379 uint16_t Hint;
380 StringRef Name;
David Majnemerad7b7e72016-06-26 04:36:32 +0000381 if (Obj->getHintName(HintNameRVA, Hint, Name))
Rui Ueyamac2bed422013-09-27 21:04:00 +0000382 return;
383 outs() << format(" % 6d ", Hint) << Name << "\n";
384 }
385 outs() << "\n";
386 }
387}
388
Rui Ueyamaad882ba2014-01-16 07:05:49 +0000389// Prints export tables. The export table is a table containing the list of
390// exported symbol from the DLL.
391static void printExportTable(const COFFObjectFile *Obj) {
392 outs() << "Export Table:\n";
393 export_directory_iterator I = Obj->export_directory_begin();
394 export_directory_iterator E = Obj->export_directory_end();
395 if (I == E)
396 return;
Rui Ueyamada49d0d2014-01-16 20:50:34 +0000397 StringRef DllName;
Rui Ueyamae5df6092014-01-17 22:02:24 +0000398 uint32_t OrdinalBase;
Rui Ueyamada49d0d2014-01-16 20:50:34 +0000399 if (I->getDllName(DllName))
400 return;
Rui Ueyamae5df6092014-01-17 22:02:24 +0000401 if (I->getOrdinalBase(OrdinalBase))
402 return;
Rui Ueyamada49d0d2014-01-16 20:50:34 +0000403 outs() << " DLL name: " << DllName << "\n";
Rui Ueyamae5df6092014-01-17 22:02:24 +0000404 outs() << " Ordinal base: " << OrdinalBase << "\n";
Rui Ueyamaad882ba2014-01-16 07:05:49 +0000405 outs() << " Ordinal RVA Name\n";
Rafael Espindola5e812af2014-01-30 02:49:50 +0000406 for (; I != E; I = ++I) {
Rui Ueyamaad882ba2014-01-16 07:05:49 +0000407 uint32_t Ordinal;
408 if (I->getOrdinal(Ordinal))
409 return;
410 uint32_t RVA;
411 if (I->getExportRVA(RVA))
412 return;
Rui Ueyama6161b382016-01-12 23:28:42 +0000413 bool IsForwarder;
414 if (I->isForwarder(IsForwarder))
415 return;
416
417 if (IsForwarder) {
418 // Export table entries can be used to re-export symbols that
419 // this COFF file is imported from some DLLs. This is rare.
420 // In most cases IsForwarder is false.
421 outs() << format(" % 4d ", Ordinal);
422 } else {
423 outs() << format(" % 4d %# 8x", Ordinal, RVA);
424 }
Rui Ueyamaad882ba2014-01-16 07:05:49 +0000425
426 StringRef Name;
Rui Ueyamada49d0d2014-01-16 20:50:34 +0000427 if (I->getSymbolName(Name))
Rui Ueyamaad882ba2014-01-16 07:05:49 +0000428 continue;
429 if (!Name.empty())
430 outs() << " " << Name;
Rui Ueyama6161b382016-01-12 23:28:42 +0000431 if (IsForwarder) {
432 StringRef S;
433 if (I->getForwardTo(S))
434 return;
435 outs() << " (forwarded to " << S << ")";
436 }
Rui Ueyamaad882ba2014-01-16 07:05:49 +0000437 outs() << "\n";
438 }
439}
440
Rui Ueyama39f1b972014-03-04 00:31:48 +0000441// Given the COFF object file, this function returns the relocations for .pdata
442// and the pointer to "runtime function" structs.
443static bool getPDataSection(const COFFObjectFile *Obj,
444 std::vector<RelocationRef> &Rels,
445 const RuntimeFunction *&RFStart, int &NumRFs) {
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000446 for (const SectionRef &Section : Obj->sections()) {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000447 StringRef Name;
Davide Italianoccd53fe2015-08-05 07:18:31 +0000448 error(Section.getName(Name));
Rui Ueyama39f1b972014-03-04 00:31:48 +0000449 if (Name != ".pdata")
450 continue;
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000451
Alexey Samsonov27dc8392014-03-18 06:53:02 +0000452 const coff_section *Pdata = Obj->getCOFFSection(Section);
453 for (const RelocationRef &Reloc : Section.relocations())
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000454 Rels.push_back(Reloc);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000455
456 // Sort relocations by address.
Fangrui Song0cac7262018-09-27 02:13:45 +0000457 llvm::sort(Rels, RelocAddressLess);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000458
459 ArrayRef<uint8_t> Contents;
Davide Italianoccd53fe2015-08-05 07:18:31 +0000460 error(Obj->getSectionContents(Pdata, Contents));
Rui Ueyama39f1b972014-03-04 00:31:48 +0000461 if (Contents.empty())
462 continue;
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000463
Rui Ueyama39f1b972014-03-04 00:31:48 +0000464 RFStart = reinterpret_cast<const RuntimeFunction *>(Contents.data());
465 NumRFs = Contents.size() / sizeof(RuntimeFunction);
466 return true;
467 }
468 return false;
469}
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000470
Rui Ueyama6dfd4e12014-03-04 03:08:45 +0000471static void printWin64EHUnwindInfo(const Win64EH::UnwindInfo *UI) {
Rui Ueyama39f1b972014-03-04 00:31:48 +0000472 // The casts to int are required in order to output the value as number.
473 // Without the casts the value would be interpreted as char data (which
474 // results in garbage output).
Rui Ueyama595932f2014-03-04 19:23:56 +0000475 outs() << " Version: " << static_cast<int>(UI->getVersion()) << "\n";
476 outs() << " Flags: " << static_cast<int>(UI->getFlags());
Rui Ueyama39f1b972014-03-04 00:31:48 +0000477 if (UI->getFlags()) {
478 if (UI->getFlags() & UNW_ExceptionHandler)
479 outs() << " UNW_ExceptionHandler";
480 if (UI->getFlags() & UNW_TerminateHandler)
481 outs() << " UNW_TerminateHandler";
482 if (UI->getFlags() & UNW_ChainInfo)
483 outs() << " UNW_ChainInfo";
484 }
485 outs() << "\n";
Rui Ueyama595932f2014-03-04 19:23:56 +0000486 outs() << " Size of prolog: " << static_cast<int>(UI->PrologSize) << "\n";
487 outs() << " Number of Codes: " << static_cast<int>(UI->NumCodes) << "\n";
Rui Ueyama39f1b972014-03-04 00:31:48 +0000488 // Maybe this should move to output of UOP_SetFPReg?
489 if (UI->getFrameRegister()) {
Rui Ueyama595932f2014-03-04 19:23:56 +0000490 outs() << " Frame register: "
Rui Ueyama39f1b972014-03-04 00:31:48 +0000491 << getUnwindRegisterName(UI->getFrameRegister()) << "\n";
Rui Ueyama595932f2014-03-04 19:23:56 +0000492 outs() << " Frame offset: " << 16 * UI->getFrameOffset() << "\n";
Rui Ueyama39f1b972014-03-04 00:31:48 +0000493 } else {
Rui Ueyama595932f2014-03-04 19:23:56 +0000494 outs() << " No frame pointer used\n";
Rui Ueyama39f1b972014-03-04 00:31:48 +0000495 }
496 if (UI->getFlags() & (UNW_ExceptionHandler | UNW_TerminateHandler)) {
497 // FIXME: Output exception handler data
498 } else if (UI->getFlags() & UNW_ChainInfo) {
499 // FIXME: Output chained unwind info
500 }
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000501
Rui Ueyama39f1b972014-03-04 00:31:48 +0000502 if (UI->NumCodes)
Rui Ueyama595932f2014-03-04 19:23:56 +0000503 outs() << " Unwind Codes:\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000504
Craig Topper0013be12015-09-21 05:32:41 +0000505 printAllUnwindCodes(makeArrayRef(&UI->UnwindCodes[0], UI->NumCodes));
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000506
Rui Ueyama595932f2014-03-04 19:23:56 +0000507 outs() << "\n";
Rui Ueyama39f1b972014-03-04 00:31:48 +0000508 outs().flush();
509}
510
Rui Ueyamafd3cb9e2014-03-04 04:22:41 +0000511/// Prints out the given RuntimeFunction struct for x64, assuming that Obj is
Rui Ueyama9c674e62014-03-04 04:00:55 +0000512/// pointing to an executable file.
Rui Ueyama6dfd4e12014-03-04 03:08:45 +0000513static void printRuntimeFunction(const COFFObjectFile *Obj,
Rui Ueyama9c674e62014-03-04 04:00:55 +0000514 const RuntimeFunction &RF) {
515 if (!RF.StartAddress)
516 return;
517 outs() << "Function Table:\n"
Rui Ueyamaad807652014-03-05 23:03:37 +0000518 << format(" Start Address: 0x%04x\n",
519 static_cast<uint32_t>(RF.StartAddress))
520 << format(" End Address: 0x%04x\n",
521 static_cast<uint32_t>(RF.EndAddress))
522 << format(" Unwind Info Address: 0x%04x\n",
523 static_cast<uint32_t>(RF.UnwindInfoOffset));
Rui Ueyama9c674e62014-03-04 04:00:55 +0000524 uintptr_t addr;
525 if (Obj->getRvaPtr(RF.UnwindInfoOffset, addr))
526 return;
527 printWin64EHUnwindInfo(reinterpret_cast<const Win64EH::UnwindInfo *>(addr));
528}
529
Rui Ueyamafd3cb9e2014-03-04 04:22:41 +0000530/// Prints out the given RuntimeFunction struct for x64, assuming that Obj is
531/// pointing to an object file. Unlike executable, fields in RuntimeFunction
Rui Ueyama9c674e62014-03-04 04:00:55 +0000532/// struct are filled with zeros, but instead there are relocations pointing to
533/// them so that the linker will fill targets' RVAs to the fields at link
534/// time. This function interprets the relocations to find the data to be used
535/// in the resulting executable.
536static void printRuntimeFunctionRels(const COFFObjectFile *Obj,
537 const RuntimeFunction &RF,
538 uint64_t SectionOffset,
539 const std::vector<RelocationRef> &Rels) {
Rui Ueyama6dfd4e12014-03-04 03:08:45 +0000540 outs() << "Function Table:\n";
541 outs() << " Start Address: ";
542 printCOFFSymbolAddress(outs(), Rels,
543 SectionOffset +
544 /*offsetof(RuntimeFunction, StartAddress)*/ 0,
545 RF.StartAddress);
546 outs() << "\n";
547
548 outs() << " End Address: ";
549 printCOFFSymbolAddress(outs(), Rels,
550 SectionOffset +
551 /*offsetof(RuntimeFunction, EndAddress)*/ 4,
552 RF.EndAddress);
553 outs() << "\n";
554
555 outs() << " Unwind Info Address: ";
556 printCOFFSymbolAddress(outs(), Rels,
557 SectionOffset +
558 /*offsetof(RuntimeFunction, UnwindInfoOffset)*/ 8,
559 RF.UnwindInfoOffset);
560 outs() << "\n";
561
562 ArrayRef<uint8_t> XContents;
563 uint64_t UnwindInfoOffset = 0;
Davide Italianoccd53fe2015-08-05 07:18:31 +0000564 error(getSectionContents(
Rui Ueyama6dfd4e12014-03-04 03:08:45 +0000565 Obj, Rels, SectionOffset +
566 /*offsetof(RuntimeFunction, UnwindInfoOffset)*/ 8,
Davide Italianoccd53fe2015-08-05 07:18:31 +0000567 XContents, UnwindInfoOffset));
Rui Ueyama6dfd4e12014-03-04 03:08:45 +0000568 if (XContents.empty())
569 return;
570
571 UnwindInfoOffset += RF.UnwindInfoOffset;
572 if (UnwindInfoOffset > XContents.size())
573 return;
574
Rui Ueyama8c1d4c92014-03-04 04:15:59 +0000575 auto *UI = reinterpret_cast<const Win64EH::UnwindInfo *>(XContents.data() +
576 UnwindInfoOffset);
Rui Ueyama6dfd4e12014-03-04 03:08:45 +0000577 printWin64EHUnwindInfo(UI);
578}
579
Rui Ueyama39f1b972014-03-04 00:31:48 +0000580void llvm::printCOFFUnwindInfo(const COFFObjectFile *Obj) {
David Majnemer44f51e52014-09-10 12:51:52 +0000581 if (Obj->getMachine() != COFF::IMAGE_FILE_MACHINE_AMD64) {
Rui Ueyama39f1b972014-03-04 00:31:48 +0000582 errs() << "Unsupported image machine type "
583 "(currently only AMD64 is supported).\n";
584 return;
585 }
586
587 std::vector<RelocationRef> Rels;
588 const RuntimeFunction *RFStart;
589 int NumRFs;
590 if (!getPDataSection(Obj, Rels, RFStart, NumRFs))
591 return;
592 ArrayRef<RuntimeFunction> RFs(RFStart, NumRFs);
593
Rui Ueyama9c674e62014-03-04 04:00:55 +0000594 bool IsExecutable = Rels.empty();
595 if (IsExecutable) {
596 for (const RuntimeFunction &RF : RFs)
597 printRuntimeFunction(Obj, RF);
598 return;
599 }
600
Rui Ueyama39f1b972014-03-04 00:31:48 +0000601 for (const RuntimeFunction &RF : RFs) {
602 uint64_t SectionOffset =
603 std::distance(RFs.begin(), &RF) * sizeof(RuntimeFunction);
Rui Ueyama9c674e62014-03-04 04:00:55 +0000604 printRuntimeFunctionRels(Obj, RF, SectionOffset, Rels);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000605 }
606}
Rui Ueyamac2bed422013-09-27 21:04:00 +0000607
608void llvm::printCOFFFileHeader(const object::ObjectFile *Obj) {
Rui Ueyamaad882ba2014-01-16 07:05:49 +0000609 const COFFObjectFile *file = dyn_cast<const COFFObjectFile>(Obj);
David Majnemer0ab61bf2016-03-15 06:14:01 +0000610 printTLSDirectory(file);
Rui Ueyamac514a802014-02-19 03:53:11 +0000611 printLoadConfiguration(file);
Rui Ueyamaad882ba2014-01-16 07:05:49 +0000612 printImportTables(file);
613 printExportTable(file);
Rui Ueyamac2bed422013-09-27 21:04:00 +0000614}
Davide Italianoe85abf72015-12-20 09:54:34 +0000615
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +0000616void llvm::printCOFFSymbolTable(const object::COFFImportFile *i) {
617 unsigned Index = 0;
618 bool IsCode = i->getCOFFImportHeader()->getType() == COFF::IMPORT_CODE;
619
620 for (const object::BasicSymbolRef &Sym : i->symbols()) {
621 std::string Name;
622 raw_string_ostream NS(Name);
623
624 Sym.printName(NS);
625 NS.flush();
626
627 outs() << "[" << format("%2d", Index) << "]"
628 << "(sec " << format("%2d", 0) << ")"
629 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
630 << "(ty " << format("%3x", (IsCode && Index) ? 32 : 0) << ")"
631 << "(scl " << format("%3x", 0) << ") "
632 << "(nx " << 0 << ") "
633 << "0x" << format("%08x", 0) << " " << Name << '\n';
634
635 ++Index;
636 }
637}
638
Davide Italianoe85abf72015-12-20 09:54:34 +0000639void llvm::printCOFFSymbolTable(const COFFObjectFile *coff) {
640 for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
Rafael Espindola74894922017-10-11 17:23:15 +0000641 Expected<COFFSymbolRef> Symbol = coff->getSymbol(SI);
Davide Italianoe85abf72015-12-20 09:54:34 +0000642 StringRef Name;
Rafael Espindola74894922017-10-11 17:23:15 +0000643 error(errorToErrorCode(Symbol.takeError()));
Davide Italianoe85abf72015-12-20 09:54:34 +0000644 error(coff->getSymbolName(*Symbol, Name));
645
646 outs() << "[" << format("%2d", SI) << "]"
647 << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
648 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
649 << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
Zachary Turner030ad372018-08-20 22:18:21 +0000650 << "(scl " << format("%3x", unsigned(Symbol->getStorageClass()))
651 << ") "
Davide Italianoe85abf72015-12-20 09:54:34 +0000652 << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
653 << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
Zachary Turner030ad372018-08-20 22:18:21 +0000654 << Name;
655 if (Demangle && Name.startswith("?")) {
656 char *DemangledSymbol = nullptr;
657 size_t Size = 0;
658 int Status = -1;
659 DemangledSymbol =
660 microsoftDemangle(Name.data(), DemangledSymbol, &Size, &Status);
661
662 if (Status == 0 && DemangledSymbol) {
663 outs() << " (" << StringRef(DemangledSymbol) << ")";
664 std::free(DemangledSymbol);
Zachary Turner4ca11212018-08-21 21:23:29 +0000665 } else {
666 outs() << " (invalid mangled name)";
Zachary Turner030ad372018-08-20 22:18:21 +0000667 }
668 }
669 outs() << "\n";
Davide Italianoe85abf72015-12-20 09:54:34 +0000670
671 for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
672 if (Symbol->isSectionDefinition()) {
673 const coff_aux_section_definition *asd;
674 error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd));
675
676 int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
677
678 outs() << "AUX "
679 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
680 , unsigned(asd->Length)
681 , unsigned(asd->NumberOfRelocations)
682 , unsigned(asd->NumberOfLinenumbers)
683 , unsigned(asd->CheckSum))
684 << format("assoc %d comdat %d\n"
685 , unsigned(AuxNumber)
686 , unsigned(asd->Selection));
687 } else if (Symbol->isFileRecord()) {
688 const char *FileName;
689 error(coff->getAuxSymbol<char>(SI + 1, FileName));
690
691 StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
692 coff->getSymbolTableEntrySize());
693 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
694
695 SI = SI + Symbol->getNumberOfAuxSymbols();
696 break;
Saleem Abdulrasoolfbf920f2016-05-26 01:45:12 +0000697 } else if (Symbol->isWeakExternal()) {
698 const coff_aux_weak_external *awe;
699 error(coff->getAuxSymbol<coff_aux_weak_external>(SI + 1, awe));
700
701 outs() << "AUX " << format("indx %d srch %d\n",
702 static_cast<uint32_t>(awe->TagIndex),
703 static_cast<uint32_t>(awe->Characteristics));
Davide Italianoe85abf72015-12-20 09:54:34 +0000704 } else {
705 outs() << "AUX Unknown\n";
706 }
707 }
708 }
709}