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"
25 #include "llvm/Support/system_error.h"
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(ArrayRef<UnwindCode>(I, E));
159 // Given a symbol sym this functions returns the address and section of it.
160 static error_code resolveSectionAndAddress(const COFFObjectFile *Obj,
161 const SymbolRef &Sym,
162 const coff_section *&ResolvedSection,
163 uint64_t &ResolvedAddr) {
164 if (error_code EC = Sym.getAddress(ResolvedAddr))
166 section_iterator iter(Obj->section_begin());
167 if (error_code EC = Sym.getSection(iter))
169 ResolvedSection = Obj->getCOFFSection(iter);
170 return object_error::success;
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.
175 static error_code resolveSymbol(const std::vector<RelocationRef> &Rels,
176 uint64_t Offset, SymbolRef &Sym) {
177 for (std::vector<RelocationRef>::const_iterator I = Rels.begin(),
181 if (error_code EC = I->getOffset(Ofs))
184 Sym = *I->getSymbol();
185 return object_error::success;
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 error_code getSectionContents(const COFFObjectFile *Obj,
196 const std::vector<RelocationRef> &Rels,
198 ArrayRef<uint8_t> &Contents,
201 if (error_code EC = resolveSymbol(Rels, Offset, Sym))
203 const coff_section *Section;
204 if (error_code EC = resolveSectionAndAddress(Obj, Sym, Section, Addr))
206 if (error_code EC = Obj->getSectionContents(Section, Contents))
208 return object_error::success;
211 // Given a vector of relocations for a section and an offset into this section
212 // the function returns the name of the symbol used for the relocation at the
214 static error_code resolveSymbolName(const std::vector<RelocationRef> &Rels,
215 uint64_t Offset, StringRef &Name) {
217 if (error_code EC = resolveSymbol(Rels, Offset, Sym))
219 if (error_code EC = Sym.getName(Name))
221 return object_error::success;
224 static void printCOFFSymbolAddress(llvm::raw_ostream &Out,
225 const std::vector<RelocationRef> &Rels,
226 uint64_t Offset, uint32_t Disp) {
228 if (!resolveSymbolName(Rels, Offset, Sym)) {
231 Out << format(" + 0x%04x", Disp);
233 Out << format("0x%04x", Disp);
238 printSEHTable(const COFFObjectFile *Obj, uint32_t TableVA, int Count) {
242 const pe32_header *PE32Header;
243 if (error(Obj->getPE32Header(PE32Header)))
245 uint32_t ImageBase = PE32Header->ImageBase;
246 uintptr_t IntPtr = 0;
247 if (error(Obj->getVaPtr(TableVA, IntPtr)))
249 const support::ulittle32_t *P = (const support::ulittle32_t *)IntPtr;
250 outs() << "SEH Table:";
251 for (int I = 0; I < Count; ++I)
252 outs() << format(" 0x%x", P[I] + ImageBase);
256 static void printLoadConfiguration(const COFFObjectFile *Obj) {
257 // Skip if it's not executable.
258 const pe32_header *PE32Header;
259 if (error(Obj->getPE32Header(PE32Header)))
264 const coff_file_header *Header;
265 if (error(Obj->getCOFFHeader(Header)))
267 // Currently only x86 is supported
268 if (Header->Machine != COFF::IMAGE_FILE_MACHINE_I386)
271 const data_directory *DataDir;
272 if (error(Obj->getDataDirectory(COFF::LOAD_CONFIG_TABLE, DataDir)))
274 uintptr_t IntPtr = 0;
275 if (DataDir->RelativeVirtualAddress == 0)
277 if (error(Obj->getRvaPtr(DataDir->RelativeVirtualAddress, IntPtr)))
280 const coff_load_configuration32 *LoadConf =
281 reinterpret_cast<const coff_load_configuration32 *>(IntPtr);
283 outs() << "Load configuration:"
284 << "\n Timestamp: " << LoadConf->TimeDateStamp
285 << "\n Major Version: " << LoadConf->MajorVersion
286 << "\n Minor Version: " << LoadConf->MinorVersion
287 << "\n GlobalFlags Clear: " << LoadConf->GlobalFlagsClear
288 << "\n GlobalFlags Set: " << LoadConf->GlobalFlagsSet
289 << "\n Critical Section Default Timeout: " << LoadConf->CriticalSectionDefaultTimeout
290 << "\n Decommit Free Block Threshold: " << LoadConf->DeCommitFreeBlockThreshold
291 << "\n Decommit Total Free Threshold: " << LoadConf->DeCommitTotalFreeThreshold
292 << "\n Lock Prefix Table: " << LoadConf->LockPrefixTable
293 << "\n Maximum Allocation Size: " << LoadConf->MaximumAllocationSize
294 << "\n Virtual Memory Threshold: " << LoadConf->VirtualMemoryThreshold
295 << "\n Process Affinity Mask: " << LoadConf->ProcessAffinityMask
296 << "\n Process Heap Flags: " << LoadConf->ProcessHeapFlags
297 << "\n CSD Version: " << LoadConf->CSDVersion
298 << "\n Security Cookie: " << LoadConf->SecurityCookie
299 << "\n SEH Table: " << LoadConf->SEHandlerTable
300 << "\n SEH Count: " << LoadConf->SEHandlerCount
302 printSEHTable(Obj, LoadConf->SEHandlerTable, LoadConf->SEHandlerCount);
306 // Prints import tables. The import table is a table containing the list of
307 // DLL name and symbol names which will be linked by the loader.
308 static void printImportTables(const COFFObjectFile *Obj) {
309 import_directory_iterator I = Obj->import_directory_begin();
310 import_directory_iterator E = Obj->import_directory_end();
313 outs() << "The Import Tables:\n";
314 for (; I != E; I = ++I) {
315 const import_directory_table_entry *Dir;
317 if (I->getImportTableEntry(Dir)) return;
318 if (I->getName(Name)) return;
320 outs() << format(" lookup %08x time %08x fwd %08x name %08x addr %08x\n\n",
321 static_cast<uint32_t>(Dir->ImportLookupTableRVA),
322 static_cast<uint32_t>(Dir->TimeDateStamp),
323 static_cast<uint32_t>(Dir->ForwarderChain),
324 static_cast<uint32_t>(Dir->NameRVA),
325 static_cast<uint32_t>(Dir->ImportAddressTableRVA));
326 outs() << " DLL Name: " << Name << "\n";
327 outs() << " Hint/Ord Name\n";
328 const import_lookup_table_entry32 *entry;
329 if (I->getImportLookupEntry(entry))
331 for (; entry->data; ++entry) {
332 if (entry->isOrdinal()) {
333 outs() << format(" % 6d\n", entry->getOrdinal());
338 if (Obj->getHintName(entry->getHintNameRVA(), Hint, Name))
340 outs() << format(" % 6d ", Hint) << Name << "\n";
346 // Prints export tables. The export table is a table containing the list of
347 // exported symbol from the DLL.
348 static void printExportTable(const COFFObjectFile *Obj) {
349 outs() << "Export Table:\n";
350 export_directory_iterator I = Obj->export_directory_begin();
351 export_directory_iterator E = Obj->export_directory_end();
355 uint32_t OrdinalBase;
356 if (I->getDllName(DllName))
358 if (I->getOrdinalBase(OrdinalBase))
360 outs() << " DLL name: " << DllName << "\n";
361 outs() << " Ordinal base: " << OrdinalBase << "\n";
362 outs() << " Ordinal RVA Name\n";
363 for (; I != E; I = ++I) {
365 if (I->getOrdinal(Ordinal))
368 if (I->getExportRVA(RVA))
370 outs() << format(" % 4d %# 8x", Ordinal, RVA);
373 if (I->getSymbolName(Name))
376 outs() << " " << Name;
381 void llvm::printCOFFUnwindInfo(const COFFObjectFile *Obj) {
382 const coff_file_header *Header;
383 if (error(Obj->getCOFFHeader(Header))) return;
385 if (Header->Machine != COFF::IMAGE_FILE_MACHINE_AMD64) {
386 errs() << "Unsupported image machine type "
387 "(currently only AMD64 is supported).\n";
391 const coff_section *Pdata = 0;
393 for (section_iterator SI = Obj->section_begin(), SE = Obj->section_end();
396 if (error(SI->getName(Name))) continue;
398 if (Name != ".pdata") continue;
400 Pdata = Obj->getCOFFSection(SI);
401 std::vector<RelocationRef> Rels;
402 for (relocation_iterator RI = SI->relocation_begin(),
403 RE = SI->relocation_end();
407 // Sort relocations by address.
408 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
410 ArrayRef<uint8_t> Contents;
411 if (error(Obj->getSectionContents(Pdata, Contents))) continue;
412 if (Contents.empty()) continue;
414 ArrayRef<RuntimeFunction> RFs(
415 reinterpret_cast<const RuntimeFunction *>(Contents.data()),
416 Contents.size() / sizeof(RuntimeFunction));
417 for (const RuntimeFunction &RF : RFs) {
418 const uint64_t SectionOffset =
419 std::distance(RFs.begin(), &RF) * sizeof(RuntimeFunction);
421 outs() << "Function Table:\n";
423 outs() << " Start Address: ";
424 printCOFFSymbolAddress(outs(), Rels,
426 /*offsetof(RuntimeFunction, StartAddress)*/ 0,
430 outs() << " End Address: ";
431 printCOFFSymbolAddress(outs(), Rels,
433 /*offsetof(RuntimeFunction, EndAddress)*/ 4,
437 outs() << " Unwind Info Address: ";
438 printCOFFSymbolAddress(
439 outs(), Rels, SectionOffset +
440 /*offsetof(RuntimeFunction, UnwindInfoOffset)*/ 8,
441 RF.UnwindInfoOffset);
444 ArrayRef<uint8_t> XContents;
445 uint64_t UnwindInfoOffset = 0;
446 if (error(getSectionContents(Obj, Rels, SectionOffset +
447 /*offsetof(RuntimeFunction, UnwindInfoOffset)*/ 8,
448 XContents, UnwindInfoOffset))) continue;
449 if (XContents.empty()) continue;
451 UnwindInfoOffset += RF.UnwindInfoOffset;
452 if (UnwindInfoOffset > XContents.size())
455 const Win64EH::UnwindInfo *UI =
456 reinterpret_cast<const Win64EH::UnwindInfo *>
457 (XContents.data() + UnwindInfoOffset);
459 // The casts to int are required in order to output the value as number.
460 // Without the casts the value would be interpreted as char data (which
461 // results in garbage output).
462 outs() << " Version: " << static_cast<int>(UI->getVersion()) << "\n";
463 outs() << " Flags: " << static_cast<int>(UI->getFlags());
464 if (UI->getFlags()) {
465 if (UI->getFlags() & UNW_ExceptionHandler)
466 outs() << " UNW_ExceptionHandler";
467 if (UI->getFlags() & UNW_TerminateHandler)
468 outs() << " UNW_TerminateHandler";
469 if (UI->getFlags() & UNW_ChainInfo)
470 outs() << " UNW_ChainInfo";
473 outs() << " Size of prolog: "
474 << static_cast<int>(UI->PrologSize) << "\n";
475 outs() << " Number of Codes: "
476 << static_cast<int>(UI->NumCodes) << "\n";
477 // Maybe this should move to output of UOP_SetFPReg?
478 if (UI->getFrameRegister()) {
479 outs() << " Frame register: "
480 << getUnwindRegisterName(UI->getFrameRegister())
482 outs() << " Frame offset: "
483 << 16 * UI->getFrameOffset()
486 outs() << " No frame pointer used\n";
488 if (UI->getFlags() & (UNW_ExceptionHandler | UNW_TerminateHandler)) {
489 // FIXME: Output exception handler data
490 } else if (UI->getFlags() & UNW_ChainInfo) {
491 // FIXME: Output chained unwind info
495 outs() << " Unwind Codes:\n";
497 printAllUnwindCodes(ArrayRef<UnwindCode>(&UI->UnwindCodes[0],
506 void llvm::printCOFFFileHeader(const object::ObjectFile *Obj) {
507 const COFFObjectFile *file = dyn_cast<const COFFObjectFile>(Obj);
508 printLoadConfiguration(file);
509 printImportTables(file);
510 printExportTable(file);