1 //===-- 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
11 /// \brief This file implements the COFF-specific dumper for llvm-objdump.
12 /// It outputs the Win64 EH data structures as plain text.
13 /// The encoding of the unwind codes is described in MSDN:
14 /// http://msdn.microsoft.com/en-us/library/ck9asaa9.aspx
15 ///
16 //===----------------------------------------------------------------------===//
17
18 #include "llvm-objdump.h"
19 #include "llvm/Object/COFF.h"
20 #include "llvm/Object/ObjectFile.h"
21 #include "llvm/Support/Format.h"
22 #include "llvm/Support/SourceMgr.h"
23 #include "llvm/Support/Win64EH.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include <algorithm>
26 #include <cstring>
27 #include <system_error>
28
29 using namespace llvm;
30 using namespace object;
31 using namespace llvm::Win64EH;
32
33 // Returns the name of the unwind code.
getUnwindCodeTypeName(uint8_t Code)34 static StringRef getUnwindCodeTypeName(uint8_t Code) {
35 switch(Code) {
36 default: llvm_unreachable("Invalid unwind code");
37 case UOP_PushNonVol: return "UOP_PushNonVol";
38 case UOP_AllocLarge: return "UOP_AllocLarge";
39 case UOP_AllocSmall: return "UOP_AllocSmall";
40 case UOP_SetFPReg: return "UOP_SetFPReg";
41 case UOP_SaveNonVol: return "UOP_SaveNonVol";
42 case UOP_SaveNonVolBig: return "UOP_SaveNonVolBig";
43 case UOP_SaveXMM128: return "UOP_SaveXMM128";
44 case UOP_SaveXMM128Big: return "UOP_SaveXMM128Big";
45 case UOP_PushMachFrame: return "UOP_PushMachFrame";
46 }
47 }
48
49 // Returns the name of a referenced register.
getUnwindRegisterName(uint8_t Reg)50 static StringRef getUnwindRegisterName(uint8_t Reg) {
51 switch(Reg) {
52 default: llvm_unreachable("Invalid register");
53 case 0: return "RAX";
54 case 1: return "RCX";
55 case 2: return "RDX";
56 case 3: return "RBX";
57 case 4: return "RSP";
58 case 5: return "RBP";
59 case 6: return "RSI";
60 case 7: return "RDI";
61 case 8: return "R8";
62 case 9: return "R9";
63 case 10: return "R10";
64 case 11: return "R11";
65 case 12: return "R12";
66 case 13: return "R13";
67 case 14: return "R14";
68 case 15: return "R15";
69 }
70 }
71
72 // Calculates the number of array slots required for the unwind code.
getNumUsedSlots(const UnwindCode & UnwindCode)73 static unsigned getNumUsedSlots(const UnwindCode &UnwindCode) {
74 switch (UnwindCode.getUnwindOp()) {
75 default: llvm_unreachable("Invalid unwind code");
76 case UOP_PushNonVol:
77 case UOP_AllocSmall:
78 case UOP_SetFPReg:
79 case UOP_PushMachFrame:
80 return 1;
81 case UOP_SaveNonVol:
82 case UOP_SaveXMM128:
83 return 2;
84 case UOP_SaveNonVolBig:
85 case UOP_SaveXMM128Big:
86 return 3;
87 case UOP_AllocLarge:
88 return (UnwindCode.getOpInfo() == 0) ? 2 : 3;
89 }
90 }
91
92 // Prints one unwind code. Because an unwind code can occupy up to 3 slots in
93 // the unwind codes array, this function requires that the correct number of
94 // slots is provided.
printUnwindCode(ArrayRef<UnwindCode> UCs)95 static void printUnwindCode(ArrayRef<UnwindCode> UCs) {
96 assert(UCs.size() >= getNumUsedSlots(UCs[0]));
97 outs() << format(" 0x%02x: ", unsigned(UCs[0].u.CodeOffset))
98 << getUnwindCodeTypeName(UCs[0].getUnwindOp());
99 switch (UCs[0].getUnwindOp()) {
100 case UOP_PushNonVol:
101 outs() << " " << getUnwindRegisterName(UCs[0].getOpInfo());
102 break;
103 case UOP_AllocLarge:
104 if (UCs[0].getOpInfo() == 0) {
105 outs() << " " << UCs[1].FrameOffset;
106 } else {
107 outs() << " " << UCs[1].FrameOffset
108 + (static_cast<uint32_t>(UCs[2].FrameOffset) << 16);
109 }
110 break;
111 case UOP_AllocSmall:
112 outs() << " " << ((UCs[0].getOpInfo() + 1) * 8);
113 break;
114 case UOP_SetFPReg:
115 outs() << " ";
116 break;
117 case UOP_SaveNonVol:
118 outs() << " " << getUnwindRegisterName(UCs[0].getOpInfo())
119 << format(" [0x%04x]", 8 * UCs[1].FrameOffset);
120 break;
121 case UOP_SaveNonVolBig:
122 outs() << " " << getUnwindRegisterName(UCs[0].getOpInfo())
123 << format(" [0x%08x]", UCs[1].FrameOffset
124 + (static_cast<uint32_t>(UCs[2].FrameOffset) << 16));
125 break;
126 case UOP_SaveXMM128:
127 outs() << " XMM" << static_cast<uint32_t>(UCs[0].getOpInfo())
128 << format(" [0x%04x]", 16 * UCs[1].FrameOffset);
129 break;
130 case UOP_SaveXMM128Big:
131 outs() << " XMM" << UCs[0].getOpInfo()
132 << format(" [0x%08x]", UCs[1].FrameOffset
133 + (static_cast<uint32_t>(UCs[2].FrameOffset) << 16));
134 break;
135 case UOP_PushMachFrame:
136 outs() << " " << (UCs[0].getOpInfo() ? "w/o" : "w")
137 << " error code";
138 break;
139 }
140 outs() << "\n";
141 }
142
printAllUnwindCodes(ArrayRef<UnwindCode> UCs)143 static void printAllUnwindCodes(ArrayRef<UnwindCode> UCs) {
144 for (const UnwindCode *I = UCs.begin(), *E = UCs.end(); I < E; ) {
145 unsigned UsedSlots = getNumUsedSlots(*I);
146 if (UsedSlots > UCs.size()) {
147 outs() << "Unwind data corrupted: Encountered unwind op "
148 << getUnwindCodeTypeName((*I).getUnwindOp())
149 << " which requires " << UsedSlots
150 << " slots, but only " << UCs.size()
151 << " remaining in buffer";
152 return ;
153 }
154 printUnwindCode(makeArrayRef(I, E));
155 I += UsedSlots;
156 }
157 }
158
159 // Given a symbol sym this functions returns the address and section of it.
160 static std::error_code
resolveSectionAndAddress(const COFFObjectFile * Obj,const SymbolRef & Sym,const coff_section * & ResolvedSection,uint64_t & ResolvedAddr)161 resolveSectionAndAddress(const COFFObjectFile *Obj, const SymbolRef &Sym,
162 const coff_section *&ResolvedSection,
163 uint64_t &ResolvedAddr) {
164 Expected<uint64_t> ResolvedAddrOrErr = Sym.getAddress();
165 if (!ResolvedAddrOrErr)
166 return errorToErrorCode(ResolvedAddrOrErr.takeError());
167 ResolvedAddr = *ResolvedAddrOrErr;
168 Expected<section_iterator> Iter = Sym.getSection();
169 if (!Iter)
170 return errorToErrorCode(Iter.takeError());
171 ResolvedSection = Obj->getCOFFSection(**Iter);
172 return std::error_code();
173 }
174
175 // Given a vector of relocations for a section and an offset into this section
176 // the function returns the symbol used for the relocation at the offset.
resolveSymbol(const std::vector<RelocationRef> & Rels,uint64_t Offset,SymbolRef & Sym)177 static std::error_code resolveSymbol(const std::vector<RelocationRef> &Rels,
178 uint64_t Offset, SymbolRef &Sym) {
179 for (std::vector<RelocationRef>::const_iterator I = Rels.begin(),
180 E = Rels.end();
181 I != E; ++I) {
182 uint64_t Ofs = I->getOffset();
183 if (Ofs == Offset) {
184 Sym = *I->getSymbol();
185 return std::error_code();
186 }
187 }
188 return object_error::parse_failed;
189 }
190
191 // Given a vector of relocations for a section and an offset into this section
192 // the function resolves the symbol used for the relocation at the offset and
193 // returns the section content and the address inside the content pointed to
194 // by the symbol.
195 static std::error_code
getSectionContents(const COFFObjectFile * Obj,const std::vector<RelocationRef> & Rels,uint64_t Offset,ArrayRef<uint8_t> & Contents,uint64_t & Addr)196 getSectionContents(const COFFObjectFile *Obj,
197 const std::vector<RelocationRef> &Rels, uint64_t Offset,
198 ArrayRef<uint8_t> &Contents, uint64_t &Addr) {
199 SymbolRef Sym;
200 if (std::error_code EC = resolveSymbol(Rels, Offset, Sym))
201 return EC;
202 const coff_section *Section;
203 if (std::error_code EC = resolveSectionAndAddress(Obj, Sym, Section, Addr))
204 return EC;
205 if (std::error_code EC = Obj->getSectionContents(Section, Contents))
206 return EC;
207 return std::error_code();
208 }
209
210 // Given a vector of relocations for a section and an offset into this section
211 // the function returns the name of the symbol used for the relocation at the
212 // offset.
resolveSymbolName(const std::vector<RelocationRef> & Rels,uint64_t Offset,StringRef & Name)213 static std::error_code resolveSymbolName(const std::vector<RelocationRef> &Rels,
214 uint64_t Offset, StringRef &Name) {
215 SymbolRef Sym;
216 if (std::error_code EC = resolveSymbol(Rels, Offset, Sym))
217 return EC;
218 Expected<StringRef> NameOrErr = Sym.getName();
219 if (!NameOrErr)
220 return errorToErrorCode(NameOrErr.takeError());
221 Name = *NameOrErr;
222 return std::error_code();
223 }
224
printCOFFSymbolAddress(llvm::raw_ostream & Out,const std::vector<RelocationRef> & Rels,uint64_t Offset,uint32_t Disp)225 static void printCOFFSymbolAddress(llvm::raw_ostream &Out,
226 const std::vector<RelocationRef> &Rels,
227 uint64_t Offset, uint32_t Disp) {
228 StringRef Sym;
229 if (!resolveSymbolName(Rels, Offset, Sym)) {
230 Out << Sym;
231 if (Disp > 0)
232 Out << format(" + 0x%04x", Disp);
233 } else {
234 Out << format("0x%04x", Disp);
235 }
236 }
237
238 static void
printSEHTable(const COFFObjectFile * Obj,uint32_t TableVA,int Count)239 printSEHTable(const COFFObjectFile *Obj, uint32_t TableVA, int Count) {
240 if (Count == 0)
241 return;
242
243 const pe32_header *PE32Header;
244 error(Obj->getPE32Header(PE32Header));
245 uint32_t ImageBase = PE32Header->ImageBase;
246 uintptr_t IntPtr = 0;
247 error(Obj->getVaPtr(TableVA, IntPtr));
248 const support::ulittle32_t *P = (const support::ulittle32_t *)IntPtr;
249 outs() << "SEH Table:";
250 for (int I = 0; I < Count; ++I)
251 outs() << format(" 0x%x", P[I] + ImageBase);
252 outs() << "\n\n";
253 }
254
255 template <typename T>
printTLSDirectoryT(const coff_tls_directory<T> * TLSDir)256 static void printTLSDirectoryT(const coff_tls_directory<T> *TLSDir) {
257 size_t FormatWidth = sizeof(T) * 2;
258 outs() << "TLS directory:"
259 << "\n StartAddressOfRawData: "
260 << format_hex(TLSDir->StartAddressOfRawData, FormatWidth)
261 << "\n EndAddressOfRawData: "
262 << format_hex(TLSDir->EndAddressOfRawData, FormatWidth)
263 << "\n AddressOfIndex: "
264 << format_hex(TLSDir->AddressOfIndex, FormatWidth)
265 << "\n AddressOfCallBacks: "
266 << format_hex(TLSDir->AddressOfCallBacks, FormatWidth)
267 << "\n SizeOfZeroFill: "
268 << TLSDir->SizeOfZeroFill
269 << "\n Characteristics: "
270 << TLSDir->Characteristics
271 << "\n Alignment: "
272 << TLSDir->getAlignment()
273 << "\n\n";
274 }
275
printTLSDirectory(const COFFObjectFile * Obj)276 static void printTLSDirectory(const COFFObjectFile *Obj) {
277 const pe32_header *PE32Header;
278 error(Obj->getPE32Header(PE32Header));
279
280 const pe32plus_header *PE32PlusHeader;
281 error(Obj->getPE32PlusHeader(PE32PlusHeader));
282
283 // Skip if it's not executable.
284 if (!PE32Header && !PE32PlusHeader)
285 return;
286
287 const data_directory *DataDir;
288 error(Obj->getDataDirectory(COFF::TLS_TABLE, DataDir));
289 uintptr_t IntPtr = 0;
290 if (DataDir->RelativeVirtualAddress == 0)
291 return;
292 error(Obj->getRvaPtr(DataDir->RelativeVirtualAddress, IntPtr));
293
294 if (PE32Header) {
295 auto *TLSDir = reinterpret_cast<const coff_tls_directory32 *>(IntPtr);
296 printTLSDirectoryT(TLSDir);
297 } else {
298 auto *TLSDir = reinterpret_cast<const coff_tls_directory64 *>(IntPtr);
299 printTLSDirectoryT(TLSDir);
300 }
301
302 outs() << "\n";
303 }
304
printLoadConfiguration(const COFFObjectFile * Obj)305 static void printLoadConfiguration(const COFFObjectFile *Obj) {
306 // Skip if it's not executable.
307 const pe32_header *PE32Header;
308 error(Obj->getPE32Header(PE32Header));
309 if (!PE32Header)
310 return;
311
312 // Currently only x86 is supported
313 if (Obj->getMachine() != COFF::IMAGE_FILE_MACHINE_I386)
314 return;
315
316 const data_directory *DataDir;
317 error(Obj->getDataDirectory(COFF::LOAD_CONFIG_TABLE, DataDir));
318 uintptr_t IntPtr = 0;
319 if (DataDir->RelativeVirtualAddress == 0)
320 return;
321 error(Obj->getRvaPtr(DataDir->RelativeVirtualAddress, IntPtr));
322
323 auto *LoadConf = reinterpret_cast<const coff_load_configuration32 *>(IntPtr);
324 outs() << "Load configuration:"
325 << "\n Timestamp: " << LoadConf->TimeDateStamp
326 << "\n Major Version: " << LoadConf->MajorVersion
327 << "\n Minor Version: " << LoadConf->MinorVersion
328 << "\n GlobalFlags Clear: " << LoadConf->GlobalFlagsClear
329 << "\n GlobalFlags Set: " << LoadConf->GlobalFlagsSet
330 << "\n Critical Section Default Timeout: " << LoadConf->CriticalSectionDefaultTimeout
331 << "\n Decommit Free Block Threshold: " << LoadConf->DeCommitFreeBlockThreshold
332 << "\n Decommit Total Free Threshold: " << LoadConf->DeCommitTotalFreeThreshold
333 << "\n Lock Prefix Table: " << LoadConf->LockPrefixTable
334 << "\n Maximum Allocation Size: " << LoadConf->MaximumAllocationSize
335 << "\n Virtual Memory Threshold: " << LoadConf->VirtualMemoryThreshold
336 << "\n Process Affinity Mask: " << LoadConf->ProcessAffinityMask
337 << "\n Process Heap Flags: " << LoadConf->ProcessHeapFlags
338 << "\n CSD Version: " << LoadConf->CSDVersion
339 << "\n Security Cookie: " << LoadConf->SecurityCookie
340 << "\n SEH Table: " << LoadConf->SEHandlerTable
341 << "\n SEH Count: " << LoadConf->SEHandlerCount
342 << "\n\n";
343 printSEHTable(Obj, LoadConf->SEHandlerTable, LoadConf->SEHandlerCount);
344 outs() << "\n";
345 }
346
347 // Prints import tables. The import table is a table containing the list of
348 // DLL name and symbol names which will be linked by the loader.
printImportTables(const COFFObjectFile * Obj)349 static void printImportTables(const COFFObjectFile *Obj) {
350 import_directory_iterator I = Obj->import_directory_begin();
351 import_directory_iterator E = Obj->import_directory_end();
352 if (I == E)
353 return;
354 outs() << "The Import Tables:\n";
355 for (const ImportDirectoryEntryRef &DirRef : Obj->import_directories()) {
356 const import_directory_table_entry *Dir;
357 StringRef Name;
358 if (DirRef.getImportTableEntry(Dir)) return;
359 if (DirRef.getName(Name)) return;
360
361 outs() << format(" lookup %08x time %08x fwd %08x name %08x addr %08x\n\n",
362 static_cast<uint32_t>(Dir->ImportLookupTableRVA),
363 static_cast<uint32_t>(Dir->TimeDateStamp),
364 static_cast<uint32_t>(Dir->ForwarderChain),
365 static_cast<uint32_t>(Dir->NameRVA),
366 static_cast<uint32_t>(Dir->ImportAddressTableRVA));
367 outs() << " DLL Name: " << Name << "\n";
368 outs() << " Hint/Ord Name\n";
369 for (const ImportedSymbolRef &Entry : DirRef.imported_symbols()) {
370 bool IsOrdinal;
371 if (Entry.isOrdinal(IsOrdinal))
372 return;
373 if (IsOrdinal) {
374 uint16_t Ordinal;
375 if (Entry.getOrdinal(Ordinal))
376 return;
377 outs() << format(" % 6d\n", Ordinal);
378 continue;
379 }
380 uint32_t HintNameRVA;
381 if (Entry.getHintNameRVA(HintNameRVA))
382 return;
383 uint16_t Hint;
384 StringRef Name;
385 if (Obj->getHintName(HintNameRVA, Hint, Name))
386 return;
387 outs() << format(" % 6d ", Hint) << Name << "\n";
388 }
389 outs() << "\n";
390 }
391 }
392
393 // Prints export tables. The export table is a table containing the list of
394 // exported symbol from the DLL.
printExportTable(const COFFObjectFile * Obj)395 static void printExportTable(const COFFObjectFile *Obj) {
396 outs() << "Export Table:\n";
397 export_directory_iterator I = Obj->export_directory_begin();
398 export_directory_iterator E = Obj->export_directory_end();
399 if (I == E)
400 return;
401 StringRef DllName;
402 uint32_t OrdinalBase;
403 if (I->getDllName(DllName))
404 return;
405 if (I->getOrdinalBase(OrdinalBase))
406 return;
407 outs() << " DLL name: " << DllName << "\n";
408 outs() << " Ordinal base: " << OrdinalBase << "\n";
409 outs() << " Ordinal RVA Name\n";
410 for (; I != E; I = ++I) {
411 uint32_t Ordinal;
412 if (I->getOrdinal(Ordinal))
413 return;
414 uint32_t RVA;
415 if (I->getExportRVA(RVA))
416 return;
417 bool IsForwarder;
418 if (I->isForwarder(IsForwarder))
419 return;
420
421 if (IsForwarder) {
422 // Export table entries can be used to re-export symbols that
423 // this COFF file is imported from some DLLs. This is rare.
424 // In most cases IsForwarder is false.
425 outs() << format(" % 4d ", Ordinal);
426 } else {
427 outs() << format(" % 4d %# 8x", Ordinal, RVA);
428 }
429
430 StringRef Name;
431 if (I->getSymbolName(Name))
432 continue;
433 if (!Name.empty())
434 outs() << " " << Name;
435 if (IsForwarder) {
436 StringRef S;
437 if (I->getForwardTo(S))
438 return;
439 outs() << " (forwarded to " << S << ")";
440 }
441 outs() << "\n";
442 }
443 }
444
445 // Given the COFF object file, this function returns the relocations for .pdata
446 // and the pointer to "runtime function" structs.
getPDataSection(const COFFObjectFile * Obj,std::vector<RelocationRef> & Rels,const RuntimeFunction * & RFStart,int & NumRFs)447 static bool getPDataSection(const COFFObjectFile *Obj,
448 std::vector<RelocationRef> &Rels,
449 const RuntimeFunction *&RFStart, int &NumRFs) {
450 for (const SectionRef &Section : Obj->sections()) {
451 StringRef Name;
452 error(Section.getName(Name));
453 if (Name != ".pdata")
454 continue;
455
456 const coff_section *Pdata = Obj->getCOFFSection(Section);
457 for (const RelocationRef &Reloc : Section.relocations())
458 Rels.push_back(Reloc);
459
460 // Sort relocations by address.
461 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
462
463 ArrayRef<uint8_t> Contents;
464 error(Obj->getSectionContents(Pdata, Contents));
465 if (Contents.empty())
466 continue;
467
468 RFStart = reinterpret_cast<const RuntimeFunction *>(Contents.data());
469 NumRFs = Contents.size() / sizeof(RuntimeFunction);
470 return true;
471 }
472 return false;
473 }
474
printWin64EHUnwindInfo(const Win64EH::UnwindInfo * UI)475 static void printWin64EHUnwindInfo(const Win64EH::UnwindInfo *UI) {
476 // The casts to int are required in order to output the value as number.
477 // Without the casts the value would be interpreted as char data (which
478 // results in garbage output).
479 outs() << " Version: " << static_cast<int>(UI->getVersion()) << "\n";
480 outs() << " Flags: " << static_cast<int>(UI->getFlags());
481 if (UI->getFlags()) {
482 if (UI->getFlags() & UNW_ExceptionHandler)
483 outs() << " UNW_ExceptionHandler";
484 if (UI->getFlags() & UNW_TerminateHandler)
485 outs() << " UNW_TerminateHandler";
486 if (UI->getFlags() & UNW_ChainInfo)
487 outs() << " UNW_ChainInfo";
488 }
489 outs() << "\n";
490 outs() << " Size of prolog: " << static_cast<int>(UI->PrologSize) << "\n";
491 outs() << " Number of Codes: " << static_cast<int>(UI->NumCodes) << "\n";
492 // Maybe this should move to output of UOP_SetFPReg?
493 if (UI->getFrameRegister()) {
494 outs() << " Frame register: "
495 << getUnwindRegisterName(UI->getFrameRegister()) << "\n";
496 outs() << " Frame offset: " << 16 * UI->getFrameOffset() << "\n";
497 } else {
498 outs() << " No frame pointer used\n";
499 }
500 if (UI->getFlags() & (UNW_ExceptionHandler | UNW_TerminateHandler)) {
501 // FIXME: Output exception handler data
502 } else if (UI->getFlags() & UNW_ChainInfo) {
503 // FIXME: Output chained unwind info
504 }
505
506 if (UI->NumCodes)
507 outs() << " Unwind Codes:\n";
508
509 printAllUnwindCodes(makeArrayRef(&UI->UnwindCodes[0], UI->NumCodes));
510
511 outs() << "\n";
512 outs().flush();
513 }
514
515 /// Prints out the given RuntimeFunction struct for x64, assuming that Obj is
516 /// pointing to an executable file.
printRuntimeFunction(const COFFObjectFile * Obj,const RuntimeFunction & RF)517 static void printRuntimeFunction(const COFFObjectFile *Obj,
518 const RuntimeFunction &RF) {
519 if (!RF.StartAddress)
520 return;
521 outs() << "Function Table:\n"
522 << format(" Start Address: 0x%04x\n",
523 static_cast<uint32_t>(RF.StartAddress))
524 << format(" End Address: 0x%04x\n",
525 static_cast<uint32_t>(RF.EndAddress))
526 << format(" Unwind Info Address: 0x%04x\n",
527 static_cast<uint32_t>(RF.UnwindInfoOffset));
528 uintptr_t addr;
529 if (Obj->getRvaPtr(RF.UnwindInfoOffset, addr))
530 return;
531 printWin64EHUnwindInfo(reinterpret_cast<const Win64EH::UnwindInfo *>(addr));
532 }
533
534 /// Prints out the given RuntimeFunction struct for x64, assuming that Obj is
535 /// pointing to an object file. Unlike executable, fields in RuntimeFunction
536 /// struct are filled with zeros, but instead there are relocations pointing to
537 /// them so that the linker will fill targets' RVAs to the fields at link
538 /// time. This function interprets the relocations to find the data to be used
539 /// in the resulting executable.
printRuntimeFunctionRels(const COFFObjectFile * Obj,const RuntimeFunction & RF,uint64_t SectionOffset,const std::vector<RelocationRef> & Rels)540 static void printRuntimeFunctionRels(const COFFObjectFile *Obj,
541 const RuntimeFunction &RF,
542 uint64_t SectionOffset,
543 const std::vector<RelocationRef> &Rels) {
544 outs() << "Function Table:\n";
545 outs() << " Start Address: ";
546 printCOFFSymbolAddress(outs(), Rels,
547 SectionOffset +
548 /*offsetof(RuntimeFunction, StartAddress)*/ 0,
549 RF.StartAddress);
550 outs() << "\n";
551
552 outs() << " End Address: ";
553 printCOFFSymbolAddress(outs(), Rels,
554 SectionOffset +
555 /*offsetof(RuntimeFunction, EndAddress)*/ 4,
556 RF.EndAddress);
557 outs() << "\n";
558
559 outs() << " Unwind Info Address: ";
560 printCOFFSymbolAddress(outs(), Rels,
561 SectionOffset +
562 /*offsetof(RuntimeFunction, UnwindInfoOffset)*/ 8,
563 RF.UnwindInfoOffset);
564 outs() << "\n";
565
566 ArrayRef<uint8_t> XContents;
567 uint64_t UnwindInfoOffset = 0;
568 error(getSectionContents(
569 Obj, Rels, SectionOffset +
570 /*offsetof(RuntimeFunction, UnwindInfoOffset)*/ 8,
571 XContents, UnwindInfoOffset));
572 if (XContents.empty())
573 return;
574
575 UnwindInfoOffset += RF.UnwindInfoOffset;
576 if (UnwindInfoOffset > XContents.size())
577 return;
578
579 auto *UI = reinterpret_cast<const Win64EH::UnwindInfo *>(XContents.data() +
580 UnwindInfoOffset);
581 printWin64EHUnwindInfo(UI);
582 }
583
printCOFFUnwindInfo(const COFFObjectFile * Obj)584 void llvm::printCOFFUnwindInfo(const COFFObjectFile *Obj) {
585 if (Obj->getMachine() != COFF::IMAGE_FILE_MACHINE_AMD64) {
586 errs() << "Unsupported image machine type "
587 "(currently only AMD64 is supported).\n";
588 return;
589 }
590
591 std::vector<RelocationRef> Rels;
592 const RuntimeFunction *RFStart;
593 int NumRFs;
594 if (!getPDataSection(Obj, Rels, RFStart, NumRFs))
595 return;
596 ArrayRef<RuntimeFunction> RFs(RFStart, NumRFs);
597
598 bool IsExecutable = Rels.empty();
599 if (IsExecutable) {
600 for (const RuntimeFunction &RF : RFs)
601 printRuntimeFunction(Obj, RF);
602 return;
603 }
604
605 for (const RuntimeFunction &RF : RFs) {
606 uint64_t SectionOffset =
607 std::distance(RFs.begin(), &RF) * sizeof(RuntimeFunction);
608 printRuntimeFunctionRels(Obj, RF, SectionOffset, Rels);
609 }
610 }
611
printCOFFFileHeader(const object::ObjectFile * Obj)612 void llvm::printCOFFFileHeader(const object::ObjectFile *Obj) {
613 const COFFObjectFile *file = dyn_cast<const COFFObjectFile>(Obj);
614 printTLSDirectory(file);
615 printLoadConfiguration(file);
616 printImportTables(file);
617 printExportTable(file);
618 }
619
printCOFFSymbolTable(const COFFObjectFile * coff)620 void llvm::printCOFFSymbolTable(const COFFObjectFile *coff) {
621 for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
622 ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI);
623 StringRef Name;
624 error(Symbol.getError());
625 error(coff->getSymbolName(*Symbol, Name));
626
627 outs() << "[" << format("%2d", SI) << "]"
628 << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
629 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
630 << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
631 << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") "
632 << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
633 << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
634 << Name << "\n";
635
636 for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
637 if (Symbol->isSectionDefinition()) {
638 const coff_aux_section_definition *asd;
639 error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd));
640
641 int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
642
643 outs() << "AUX "
644 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
645 , unsigned(asd->Length)
646 , unsigned(asd->NumberOfRelocations)
647 , unsigned(asd->NumberOfLinenumbers)
648 , unsigned(asd->CheckSum))
649 << format("assoc %d comdat %d\n"
650 , unsigned(AuxNumber)
651 , unsigned(asd->Selection));
652 } else if (Symbol->isFileRecord()) {
653 const char *FileName;
654 error(coff->getAuxSymbol<char>(SI + 1, FileName));
655
656 StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
657 coff->getSymbolTableEntrySize());
658 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
659
660 SI = SI + Symbol->getNumberOfAuxSymbols();
661 break;
662 } else if (Symbol->isWeakExternal()) {
663 const coff_aux_weak_external *awe;
664 error(coff->getAuxSymbol<coff_aux_weak_external>(SI + 1, awe));
665
666 outs() << "AUX " << format("indx %d srch %d\n",
667 static_cast<uint32_t>(awe->TagIndex),
668 static_cast<uint32_t>(awe->Characteristics));
669 } else {
670 outs() << "AUX Unknown\n";
671 }
672 }
673 }
674 }
675