1 //===-- COFFDump.cpp - COFF-specific dumper ---------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
16 //===----------------------------------------------------------------------===//
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"
27 #include <system_error>
30 using namespace object;
31 using namespace llvm::Win64EH;
33 // Returns the name of the unwind code.
34 static StringRef getUnwindCodeTypeName(uint8_t 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";
49 // Returns the name of a referenced register.
50 static StringRef getUnwindRegisterName(uint8_t Reg) {
52 default: llvm_unreachable("Invalid register");
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";
72 // Calculates the number of array slots required for the unwind code.
73 static unsigned getNumUsedSlots(const UnwindCode &UnwindCode) {
74 switch (UnwindCode.getUnwindOp()) {
75 default: llvm_unreachable("Invalid unwind code");
79 case UOP_PushMachFrame:
84 case UOP_SaveNonVolBig:
85 case UOP_SaveXMM128Big:
88 return (UnwindCode.getOpInfo() == 0) ? 2 : 3;
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
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()) {
101 outs() << " " << getUnwindRegisterName(UCs[0].getOpInfo());
104 if (UCs[0].getOpInfo() == 0) {
105 outs() << " " << UCs[1].FrameOffset;
107 outs() << " " << UCs[1].FrameOffset
108 + (static_cast<uint32_t>(UCs[2].FrameOffset) << 16);
112 outs() << " " << ((UCs[0].getOpInfo() + 1) * 8);
118 outs() << " " << getUnwindRegisterName(UCs[0].getOpInfo())
119 << format(" [0x%04x]", 8 * UCs[1].FrameOffset);
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));
127 outs() << " XMM" << static_cast<uint32_t>(UCs[0].getOpInfo())
128 << format(" [0x%04x]", 16 * UCs[1].FrameOffset);
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));
135 case UOP_PushMachFrame:
136 outs() << " " << (UCs[0].getOpInfo() ? "w/o" : "w")
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";
154 printUnwindCode(makeArrayRef(I, E));
159 // Given a symbol sym this functions returns the address and section of it.
160 static std::error_code
161 resolveSectionAndAddress(const COFFObjectFile *Obj, const SymbolRef &Sym,
162 const coff_section *&ResolvedSection,
163 uint64_t &ResolvedAddr) {
164 ErrorOr<uint64_t> ResolvedAddrOrErr = Sym.getAddress();
165 if (std::error_code EC = ResolvedAddrOrErr.getError())
167 ResolvedAddr = *ResolvedAddrOrErr;
168 ErrorOr<section_iterator> Iter = Sym.getSection();
169 if (std::error_code EC = Iter.getError())
171 ResolvedSection = Obj->getCOFFSection(**Iter);
172 return std::error_code();
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.
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(),
182 uint64_t Ofs = I->getOffset();
184 Sym = *I->getSymbol();
185 return std::error_code();
188 return object_error::parse_failed;
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
195 static std::error_code
196 getSectionContents(const COFFObjectFile *Obj,
197 const std::vector<RelocationRef> &Rels, uint64_t Offset,
198 ArrayRef<uint8_t> &Contents, uint64_t &Addr) {
200 if (std::error_code EC = resolveSymbol(Rels, Offset, Sym))
202 const coff_section *Section;
203 if (std::error_code EC = resolveSectionAndAddress(Obj, Sym, Section, Addr))
205 if (std::error_code EC = Obj->getSectionContents(Section, Contents))
207 return std::error_code();
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
213 static std::error_code resolveSymbolName(const std::vector<RelocationRef> &Rels,
214 uint64_t Offset, StringRef &Name) {
216 if (std::error_code EC = resolveSymbol(Rels, Offset, Sym))
218 ErrorOr<StringRef> NameOrErr = Sym.getName();
219 if (std::error_code EC = NameOrErr.getError())
222 return std::error_code();
225 static void printCOFFSymbolAddress(llvm::raw_ostream &Out,
226 const std::vector<RelocationRef> &Rels,
227 uint64_t Offset, uint32_t Disp) {
229 if (!resolveSymbolName(Rels, Offset, Sym)) {
232 Out << format(" + 0x%04x", Disp);
234 Out << format("0x%04x", Disp);
239 printSEHTable(const COFFObjectFile *Obj, uint32_t TableVA, int Count) {
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);
255 static void printLoadConfiguration(const COFFObjectFile *Obj) {
256 // Skip if it's not executable.
257 const pe32_header *PE32Header;
258 error(Obj->getPE32Header(PE32Header));
262 // Currently only x86 is supported
263 if (Obj->getMachine() != COFF::IMAGE_FILE_MACHINE_I386)
266 const data_directory *DataDir;
267 error(Obj->getDataDirectory(COFF::LOAD_CONFIG_TABLE, DataDir));
268 uintptr_t IntPtr = 0;
269 if (DataDir->RelativeVirtualAddress == 0)
271 error(Obj->getRvaPtr(DataDir->RelativeVirtualAddress, IntPtr));
273 auto *LoadConf = reinterpret_cast<const coff_load_configuration32 *>(IntPtr);
274 outs() << "Load configuration:"
275 << "\n Timestamp: " << LoadConf->TimeDateStamp
276 << "\n Major Version: " << LoadConf->MajorVersion
277 << "\n Minor Version: " << LoadConf->MinorVersion
278 << "\n GlobalFlags Clear: " << LoadConf->GlobalFlagsClear
279 << "\n GlobalFlags Set: " << LoadConf->GlobalFlagsSet
280 << "\n Critical Section Default Timeout: " << LoadConf->CriticalSectionDefaultTimeout
281 << "\n Decommit Free Block Threshold: " << LoadConf->DeCommitFreeBlockThreshold
282 << "\n Decommit Total Free Threshold: " << LoadConf->DeCommitTotalFreeThreshold
283 << "\n Lock Prefix Table: " << LoadConf->LockPrefixTable
284 << "\n Maximum Allocation Size: " << LoadConf->MaximumAllocationSize
285 << "\n Virtual Memory Threshold: " << LoadConf->VirtualMemoryThreshold
286 << "\n Process Affinity Mask: " << LoadConf->ProcessAffinityMask
287 << "\n Process Heap Flags: " << LoadConf->ProcessHeapFlags
288 << "\n CSD Version: " << LoadConf->CSDVersion
289 << "\n Security Cookie: " << LoadConf->SecurityCookie
290 << "\n SEH Table: " << LoadConf->SEHandlerTable
291 << "\n SEH Count: " << LoadConf->SEHandlerCount
293 printSEHTable(Obj, LoadConf->SEHandlerTable, LoadConf->SEHandlerCount);
297 // Prints import tables. The import table is a table containing the list of
298 // DLL name and symbol names which will be linked by the loader.
299 static void printImportTables(const COFFObjectFile *Obj) {
300 import_directory_iterator I = Obj->import_directory_begin();
301 import_directory_iterator E = Obj->import_directory_end();
304 outs() << "The Import Tables:\n";
305 for (; I != E; I = ++I) {
306 const import_directory_table_entry *Dir;
308 if (I->getImportTableEntry(Dir)) return;
309 if (I->getName(Name)) return;
311 outs() << format(" lookup %08x time %08x fwd %08x name %08x addr %08x\n\n",
312 static_cast<uint32_t>(Dir->ImportLookupTableRVA),
313 static_cast<uint32_t>(Dir->TimeDateStamp),
314 static_cast<uint32_t>(Dir->ForwarderChain),
315 static_cast<uint32_t>(Dir->NameRVA),
316 static_cast<uint32_t>(Dir->ImportAddressTableRVA));
317 outs() << " DLL Name: " << Name << "\n";
318 outs() << " Hint/Ord Name\n";
319 const import_lookup_table_entry32 *entry;
320 if (I->getImportLookupEntry(entry))
322 for (; entry->Data; ++entry) {
323 if (entry->isOrdinal()) {
324 outs() << format(" % 6d\n", entry->getOrdinal());
329 if (Obj->getHintName(entry->getHintNameRVA(), Hint, Name))
331 outs() << format(" % 6d ", Hint) << Name << "\n";
337 // Prints export tables. The export table is a table containing the list of
338 // exported symbol from the DLL.
339 static void printExportTable(const COFFObjectFile *Obj) {
340 outs() << "Export Table:\n";
341 export_directory_iterator I = Obj->export_directory_begin();
342 export_directory_iterator E = Obj->export_directory_end();
346 uint32_t OrdinalBase;
347 if (I->getDllName(DllName))
349 if (I->getOrdinalBase(OrdinalBase))
351 outs() << " DLL name: " << DllName << "\n";
352 outs() << " Ordinal base: " << OrdinalBase << "\n";
353 outs() << " Ordinal RVA Name\n";
354 for (; I != E; I = ++I) {
356 if (I->getOrdinal(Ordinal))
359 if (I->getExportRVA(RVA))
361 outs() << format(" % 4d %# 8x", Ordinal, RVA);
364 if (I->getSymbolName(Name))
367 outs() << " " << Name;
372 // Given the COFF object file, this function returns the relocations for .pdata
373 // and the pointer to "runtime function" structs.
374 static bool getPDataSection(const COFFObjectFile *Obj,
375 std::vector<RelocationRef> &Rels,
376 const RuntimeFunction *&RFStart, int &NumRFs) {
377 for (const SectionRef &Section : Obj->sections()) {
379 error(Section.getName(Name));
380 if (Name != ".pdata")
383 const coff_section *Pdata = Obj->getCOFFSection(Section);
384 for (const RelocationRef &Reloc : Section.relocations())
385 Rels.push_back(Reloc);
387 // Sort relocations by address.
388 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
390 ArrayRef<uint8_t> Contents;
391 error(Obj->getSectionContents(Pdata, Contents));
392 if (Contents.empty())
395 RFStart = reinterpret_cast<const RuntimeFunction *>(Contents.data());
396 NumRFs = Contents.size() / sizeof(RuntimeFunction);
402 static void printWin64EHUnwindInfo(const Win64EH::UnwindInfo *UI) {
403 // The casts to int are required in order to output the value as number.
404 // Without the casts the value would be interpreted as char data (which
405 // results in garbage output).
406 outs() << " Version: " << static_cast<int>(UI->getVersion()) << "\n";
407 outs() << " Flags: " << static_cast<int>(UI->getFlags());
408 if (UI->getFlags()) {
409 if (UI->getFlags() & UNW_ExceptionHandler)
410 outs() << " UNW_ExceptionHandler";
411 if (UI->getFlags() & UNW_TerminateHandler)
412 outs() << " UNW_TerminateHandler";
413 if (UI->getFlags() & UNW_ChainInfo)
414 outs() << " UNW_ChainInfo";
417 outs() << " Size of prolog: " << static_cast<int>(UI->PrologSize) << "\n";
418 outs() << " Number of Codes: " << static_cast<int>(UI->NumCodes) << "\n";
419 // Maybe this should move to output of UOP_SetFPReg?
420 if (UI->getFrameRegister()) {
421 outs() << " Frame register: "
422 << getUnwindRegisterName(UI->getFrameRegister()) << "\n";
423 outs() << " Frame offset: " << 16 * UI->getFrameOffset() << "\n";
425 outs() << " No frame pointer used\n";
427 if (UI->getFlags() & (UNW_ExceptionHandler | UNW_TerminateHandler)) {
428 // FIXME: Output exception handler data
429 } else if (UI->getFlags() & UNW_ChainInfo) {
430 // FIXME: Output chained unwind info
434 outs() << " Unwind Codes:\n";
436 printAllUnwindCodes(makeArrayRef(&UI->UnwindCodes[0], UI->NumCodes));
442 /// Prints out the given RuntimeFunction struct for x64, assuming that Obj is
443 /// pointing to an executable file.
444 static void printRuntimeFunction(const COFFObjectFile *Obj,
445 const RuntimeFunction &RF) {
446 if (!RF.StartAddress)
448 outs() << "Function Table:\n"
449 << format(" Start Address: 0x%04x\n",
450 static_cast<uint32_t>(RF.StartAddress))
451 << format(" End Address: 0x%04x\n",
452 static_cast<uint32_t>(RF.EndAddress))
453 << format(" Unwind Info Address: 0x%04x\n",
454 static_cast<uint32_t>(RF.UnwindInfoOffset));
456 if (Obj->getRvaPtr(RF.UnwindInfoOffset, addr))
458 printWin64EHUnwindInfo(reinterpret_cast<const Win64EH::UnwindInfo *>(addr));
461 /// Prints out the given RuntimeFunction struct for x64, assuming that Obj is
462 /// pointing to an object file. Unlike executable, fields in RuntimeFunction
463 /// struct are filled with zeros, but instead there are relocations pointing to
464 /// them so that the linker will fill targets' RVAs to the fields at link
465 /// time. This function interprets the relocations to find the data to be used
466 /// in the resulting executable.
467 static void printRuntimeFunctionRels(const COFFObjectFile *Obj,
468 const RuntimeFunction &RF,
469 uint64_t SectionOffset,
470 const std::vector<RelocationRef> &Rels) {
471 outs() << "Function Table:\n";
472 outs() << " Start Address: ";
473 printCOFFSymbolAddress(outs(), Rels,
475 /*offsetof(RuntimeFunction, StartAddress)*/ 0,
479 outs() << " End Address: ";
480 printCOFFSymbolAddress(outs(), Rels,
482 /*offsetof(RuntimeFunction, EndAddress)*/ 4,
486 outs() << " Unwind Info Address: ";
487 printCOFFSymbolAddress(outs(), Rels,
489 /*offsetof(RuntimeFunction, UnwindInfoOffset)*/ 8,
490 RF.UnwindInfoOffset);
493 ArrayRef<uint8_t> XContents;
494 uint64_t UnwindInfoOffset = 0;
495 error(getSectionContents(
496 Obj, Rels, SectionOffset +
497 /*offsetof(RuntimeFunction, UnwindInfoOffset)*/ 8,
498 XContents, UnwindInfoOffset));
499 if (XContents.empty())
502 UnwindInfoOffset += RF.UnwindInfoOffset;
503 if (UnwindInfoOffset > XContents.size())
506 auto *UI = reinterpret_cast<const Win64EH::UnwindInfo *>(XContents.data() +
508 printWin64EHUnwindInfo(UI);
511 void llvm::printCOFFUnwindInfo(const COFFObjectFile *Obj) {
512 if (Obj->getMachine() != COFF::IMAGE_FILE_MACHINE_AMD64) {
513 errs() << "Unsupported image machine type "
514 "(currently only AMD64 is supported).\n";
518 std::vector<RelocationRef> Rels;
519 const RuntimeFunction *RFStart;
521 if (!getPDataSection(Obj, Rels, RFStart, NumRFs))
523 ArrayRef<RuntimeFunction> RFs(RFStart, NumRFs);
525 bool IsExecutable = Rels.empty();
527 for (const RuntimeFunction &RF : RFs)
528 printRuntimeFunction(Obj, RF);
532 for (const RuntimeFunction &RF : RFs) {
533 uint64_t SectionOffset =
534 std::distance(RFs.begin(), &RF) * sizeof(RuntimeFunction);
535 printRuntimeFunctionRels(Obj, RF, SectionOffset, Rels);
539 void llvm::printCOFFFileHeader(const object::ObjectFile *Obj) {
540 const COFFObjectFile *file = dyn_cast<const COFFObjectFile>(Obj);
541 printLoadConfiguration(file);
542 printImportTables(file);
543 printExportTable(file);
546 void llvm::printCOFFSymbolTable(const COFFObjectFile *coff) {
547 for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
548 ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI);
550 error(Symbol.getError());
551 error(coff->getSymbolName(*Symbol, Name));
553 outs() << "[" << format("%2d", SI) << "]"
554 << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
555 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
556 << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
557 << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") "
558 << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
559 << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
562 for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
563 if (Symbol->isSectionDefinition()) {
564 const coff_aux_section_definition *asd;
565 error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd));
567 int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
570 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
571 , unsigned(asd->Length)
572 , unsigned(asd->NumberOfRelocations)
573 , unsigned(asd->NumberOfLinenumbers)
574 , unsigned(asd->CheckSum))
575 << format("assoc %d comdat %d\n"
576 , unsigned(AuxNumber)
577 , unsigned(asd->Selection));
578 } else if (Symbol->isFileRecord()) {
579 const char *FileName;
580 error(coff->getAuxSymbol<char>(SI + 1, FileName));
582 StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
583 coff->getSymbolTableEntrySize());
584 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
586 SI = SI + Symbol->getNumberOfAuxSymbols();
589 outs() << "AUX Unknown\n";