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. 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. 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. 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. 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 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(ArrayRef<UnwindCode>(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 161 resolveSectionAndAddress(const COFFObjectFile *Obj, const SymbolRef &Sym, 162 const coff_section *&ResolvedSection, 163 uint64_t &ResolvedAddr) { 164 if (std::error_code EC = Sym.getAddress(ResolvedAddr)) 165 return EC; 166 section_iterator iter(Obj->section_begin()); 167 if (std::error_code EC = Sym.getSection(iter)) 168 return EC; 169 ResolvedSection = Obj->getCOFFSection(*iter); 170 return std::error_code(); 171 } 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. 175 static std::error_code resolveSymbol(const std::vector<RelocationRef> &Rels, 176 uint64_t Offset, SymbolRef &Sym) { 177 for (std::vector<RelocationRef>::const_iterator I = Rels.begin(), 178 E = Rels.end(); 179 I != E; ++I) { 180 uint64_t Ofs; 181 if (std::error_code EC = I->getOffset(Ofs)) 182 return EC; 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 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. 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 if (std::error_code EC = Sym.getName(Name)) 219 return EC; 220 return std::error_code(); 221 } 222 223 static void printCOFFSymbolAddress(llvm::raw_ostream &Out, 224 const std::vector<RelocationRef> &Rels, 225 uint64_t Offset, uint32_t Disp) { 226 StringRef Sym; 227 if (!resolveSymbolName(Rels, Offset, Sym)) { 228 Out << Sym; 229 if (Disp > 0) 230 Out << format(" + 0x%04x", Disp); 231 } else { 232 Out << format("0x%04x", Disp); 233 } 234 } 235 236 static void 237 printSEHTable(const COFFObjectFile *Obj, uint32_t TableVA, int Count) { 238 if (Count == 0) 239 return; 240 241 const pe32_header *PE32Header; 242 if (error(Obj->getPE32Header(PE32Header))) 243 return; 244 uint32_t ImageBase = PE32Header->ImageBase; 245 uintptr_t IntPtr = 0; 246 if (error(Obj->getVaPtr(TableVA, IntPtr))) 247 return; 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 static void printLoadConfiguration(const COFFObjectFile *Obj) { 256 // Skip if it's not executable. 257 const pe32_header *PE32Header; 258 if (error(Obj->getPE32Header(PE32Header))) 259 return; 260 if (!PE32Header) 261 return; 262 263 // Currently only x86 is supported 264 if (Obj->getMachine() != COFF::IMAGE_FILE_MACHINE_I386) 265 return; 266 267 const data_directory *DataDir; 268 if (error(Obj->getDataDirectory(COFF::LOAD_CONFIG_TABLE, DataDir))) 269 return; 270 uintptr_t IntPtr = 0; 271 if (DataDir->RelativeVirtualAddress == 0) 272 return; 273 if (error(Obj->getRvaPtr(DataDir->RelativeVirtualAddress, IntPtr))) 274 return; 275 276 auto *LoadConf = reinterpret_cast<const coff_load_configuration32 *>(IntPtr); 277 outs() << "Load configuration:" 278 << "\n Timestamp: " << LoadConf->TimeDateStamp 279 << "\n Major Version: " << LoadConf->MajorVersion 280 << "\n Minor Version: " << LoadConf->MinorVersion 281 << "\n GlobalFlags Clear: " << LoadConf->GlobalFlagsClear 282 << "\n GlobalFlags Set: " << LoadConf->GlobalFlagsSet 283 << "\n Critical Section Default Timeout: " << LoadConf->CriticalSectionDefaultTimeout 284 << "\n Decommit Free Block Threshold: " << LoadConf->DeCommitFreeBlockThreshold 285 << "\n Decommit Total Free Threshold: " << LoadConf->DeCommitTotalFreeThreshold 286 << "\n Lock Prefix Table: " << LoadConf->LockPrefixTable 287 << "\n Maximum Allocation Size: " << LoadConf->MaximumAllocationSize 288 << "\n Virtual Memory Threshold: " << LoadConf->VirtualMemoryThreshold 289 << "\n Process Affinity Mask: " << LoadConf->ProcessAffinityMask 290 << "\n Process Heap Flags: " << LoadConf->ProcessHeapFlags 291 << "\n CSD Version: " << LoadConf->CSDVersion 292 << "\n Security Cookie: " << LoadConf->SecurityCookie 293 << "\n SEH Table: " << LoadConf->SEHandlerTable 294 << "\n SEH Count: " << LoadConf->SEHandlerCount 295 << "\n\n"; 296 printSEHTable(Obj, LoadConf->SEHandlerTable, LoadConf->SEHandlerCount); 297 outs() << "\n"; 298 } 299 300 // Prints import tables. The import table is a table containing the list of 301 // DLL name and symbol names which will be linked by the loader. 302 static void printImportTables(const COFFObjectFile *Obj) { 303 import_directory_iterator I = Obj->import_directory_begin(); 304 import_directory_iterator E = Obj->import_directory_end(); 305 if (I == E) 306 return; 307 outs() << "The Import Tables:\n"; 308 for (; I != E; I = ++I) { 309 const import_directory_table_entry *Dir; 310 StringRef Name; 311 if (I->getImportTableEntry(Dir)) return; 312 if (I->getName(Name)) return; 313 314 outs() << format(" lookup %08x time %08x fwd %08x name %08x addr %08x\n\n", 315 static_cast<uint32_t>(Dir->ImportLookupTableRVA), 316 static_cast<uint32_t>(Dir->TimeDateStamp), 317 static_cast<uint32_t>(Dir->ForwarderChain), 318 static_cast<uint32_t>(Dir->NameRVA), 319 static_cast<uint32_t>(Dir->ImportAddressTableRVA)); 320 outs() << " DLL Name: " << Name << "\n"; 321 outs() << " Hint/Ord Name\n"; 322 const import_lookup_table_entry32 *entry; 323 if (I->getImportLookupEntry(entry)) 324 return; 325 for (; entry->Data; ++entry) { 326 if (entry->isOrdinal()) { 327 outs() << format(" % 6d\n", entry->getOrdinal()); 328 continue; 329 } 330 uint16_t Hint; 331 StringRef Name; 332 if (Obj->getHintName(entry->getHintNameRVA(), Hint, Name)) 333 return; 334 outs() << format(" % 6d ", Hint) << Name << "\n"; 335 } 336 outs() << "\n"; 337 } 338 } 339 340 // Prints export tables. The export table is a table containing the list of 341 // exported symbol from the DLL. 342 static void printExportTable(const COFFObjectFile *Obj) { 343 outs() << "Export Table:\n"; 344 export_directory_iterator I = Obj->export_directory_begin(); 345 export_directory_iterator E = Obj->export_directory_end(); 346 if (I == E) 347 return; 348 StringRef DllName; 349 uint32_t OrdinalBase; 350 if (I->getDllName(DllName)) 351 return; 352 if (I->getOrdinalBase(OrdinalBase)) 353 return; 354 outs() << " DLL name: " << DllName << "\n"; 355 outs() << " Ordinal base: " << OrdinalBase << "\n"; 356 outs() << " Ordinal RVA Name\n"; 357 for (; I != E; I = ++I) { 358 uint32_t Ordinal; 359 if (I->getOrdinal(Ordinal)) 360 return; 361 uint32_t RVA; 362 if (I->getExportRVA(RVA)) 363 return; 364 outs() << format(" % 4d %# 8x", Ordinal, RVA); 365 366 StringRef Name; 367 if (I->getSymbolName(Name)) 368 continue; 369 if (!Name.empty()) 370 outs() << " " << Name; 371 outs() << "\n"; 372 } 373 } 374 375 // Given the COFF object file, this function returns the relocations for .pdata 376 // and the pointer to "runtime function" structs. 377 static bool getPDataSection(const COFFObjectFile *Obj, 378 std::vector<RelocationRef> &Rels, 379 const RuntimeFunction *&RFStart, int &NumRFs) { 380 for (const SectionRef &Section : Obj->sections()) { 381 StringRef Name; 382 if (error(Section.getName(Name))) 383 continue; 384 if (Name != ".pdata") 385 continue; 386 387 const coff_section *Pdata = Obj->getCOFFSection(Section); 388 for (const RelocationRef &Reloc : Section.relocations()) 389 Rels.push_back(Reloc); 390 391 // Sort relocations by address. 392 std::sort(Rels.begin(), Rels.end(), RelocAddressLess); 393 394 ArrayRef<uint8_t> Contents; 395 if (error(Obj->getSectionContents(Pdata, Contents))) 396 continue; 397 if (Contents.empty()) 398 continue; 399 400 RFStart = reinterpret_cast<const RuntimeFunction *>(Contents.data()); 401 NumRFs = Contents.size() / sizeof(RuntimeFunction); 402 return true; 403 } 404 return false; 405 } 406 407 static void printWin64EHUnwindInfo(const Win64EH::UnwindInfo *UI) { 408 // The casts to int are required in order to output the value as number. 409 // Without the casts the value would be interpreted as char data (which 410 // results in garbage output). 411 outs() << " Version: " << static_cast<int>(UI->getVersion()) << "\n"; 412 outs() << " Flags: " << static_cast<int>(UI->getFlags()); 413 if (UI->getFlags()) { 414 if (UI->getFlags() & UNW_ExceptionHandler) 415 outs() << " UNW_ExceptionHandler"; 416 if (UI->getFlags() & UNW_TerminateHandler) 417 outs() << " UNW_TerminateHandler"; 418 if (UI->getFlags() & UNW_ChainInfo) 419 outs() << " UNW_ChainInfo"; 420 } 421 outs() << "\n"; 422 outs() << " Size of prolog: " << static_cast<int>(UI->PrologSize) << "\n"; 423 outs() << " Number of Codes: " << static_cast<int>(UI->NumCodes) << "\n"; 424 // Maybe this should move to output of UOP_SetFPReg? 425 if (UI->getFrameRegister()) { 426 outs() << " Frame register: " 427 << getUnwindRegisterName(UI->getFrameRegister()) << "\n"; 428 outs() << " Frame offset: " << 16 * UI->getFrameOffset() << "\n"; 429 } else { 430 outs() << " No frame pointer used\n"; 431 } 432 if (UI->getFlags() & (UNW_ExceptionHandler | UNW_TerminateHandler)) { 433 // FIXME: Output exception handler data 434 } else if (UI->getFlags() & UNW_ChainInfo) { 435 // FIXME: Output chained unwind info 436 } 437 438 if (UI->NumCodes) 439 outs() << " Unwind Codes:\n"; 440 441 printAllUnwindCodes(ArrayRef<UnwindCode>(&UI->UnwindCodes[0], UI->NumCodes)); 442 443 outs() << "\n"; 444 outs().flush(); 445 } 446 447 /// Prints out the given RuntimeFunction struct for x64, assuming that Obj is 448 /// pointing to an executable file. 449 static void printRuntimeFunction(const COFFObjectFile *Obj, 450 const RuntimeFunction &RF) { 451 if (!RF.StartAddress) 452 return; 453 outs() << "Function Table:\n" 454 << format(" Start Address: 0x%04x\n", 455 static_cast<uint32_t>(RF.StartAddress)) 456 << format(" End Address: 0x%04x\n", 457 static_cast<uint32_t>(RF.EndAddress)) 458 << format(" Unwind Info Address: 0x%04x\n", 459 static_cast<uint32_t>(RF.UnwindInfoOffset)); 460 uintptr_t addr; 461 if (Obj->getRvaPtr(RF.UnwindInfoOffset, addr)) 462 return; 463 printWin64EHUnwindInfo(reinterpret_cast<const Win64EH::UnwindInfo *>(addr)); 464 } 465 466 /// Prints out the given RuntimeFunction struct for x64, assuming that Obj is 467 /// pointing to an object file. Unlike executable, fields in RuntimeFunction 468 /// struct are filled with zeros, but instead there are relocations pointing to 469 /// them so that the linker will fill targets' RVAs to the fields at link 470 /// time. This function interprets the relocations to find the data to be used 471 /// in the resulting executable. 472 static void printRuntimeFunctionRels(const COFFObjectFile *Obj, 473 const RuntimeFunction &RF, 474 uint64_t SectionOffset, 475 const std::vector<RelocationRef> &Rels) { 476 outs() << "Function Table:\n"; 477 outs() << " Start Address: "; 478 printCOFFSymbolAddress(outs(), Rels, 479 SectionOffset + 480 /*offsetof(RuntimeFunction, StartAddress)*/ 0, 481 RF.StartAddress); 482 outs() << "\n"; 483 484 outs() << " End Address: "; 485 printCOFFSymbolAddress(outs(), Rels, 486 SectionOffset + 487 /*offsetof(RuntimeFunction, EndAddress)*/ 4, 488 RF.EndAddress); 489 outs() << "\n"; 490 491 outs() << " Unwind Info Address: "; 492 printCOFFSymbolAddress(outs(), Rels, 493 SectionOffset + 494 /*offsetof(RuntimeFunction, UnwindInfoOffset)*/ 8, 495 RF.UnwindInfoOffset); 496 outs() << "\n"; 497 498 ArrayRef<uint8_t> XContents; 499 uint64_t UnwindInfoOffset = 0; 500 if (error(getSectionContents( 501 Obj, Rels, SectionOffset + 502 /*offsetof(RuntimeFunction, UnwindInfoOffset)*/ 8, 503 XContents, UnwindInfoOffset))) 504 return; 505 if (XContents.empty()) 506 return; 507 508 UnwindInfoOffset += RF.UnwindInfoOffset; 509 if (UnwindInfoOffset > XContents.size()) 510 return; 511 512 auto *UI = reinterpret_cast<const Win64EH::UnwindInfo *>(XContents.data() + 513 UnwindInfoOffset); 514 printWin64EHUnwindInfo(UI); 515 } 516 517 void llvm::printCOFFUnwindInfo(const COFFObjectFile *Obj) { 518 if (Obj->getMachine() != COFF::IMAGE_FILE_MACHINE_AMD64) { 519 errs() << "Unsupported image machine type " 520 "(currently only AMD64 is supported).\n"; 521 return; 522 } 523 524 std::vector<RelocationRef> Rels; 525 const RuntimeFunction *RFStart; 526 int NumRFs; 527 if (!getPDataSection(Obj, Rels, RFStart, NumRFs)) 528 return; 529 ArrayRef<RuntimeFunction> RFs(RFStart, NumRFs); 530 531 bool IsExecutable = Rels.empty(); 532 if (IsExecutable) { 533 for (const RuntimeFunction &RF : RFs) 534 printRuntimeFunction(Obj, RF); 535 return; 536 } 537 538 for (const RuntimeFunction &RF : RFs) { 539 uint64_t SectionOffset = 540 std::distance(RFs.begin(), &RF) * sizeof(RuntimeFunction); 541 printRuntimeFunctionRels(Obj, RF, SectionOffset, Rels); 542 } 543 } 544 545 void llvm::printCOFFFileHeader(const object::ObjectFile *Obj) { 546 const COFFObjectFile *file = dyn_cast<const COFFObjectFile>(Obj); 547 printLoadConfiguration(file); 548 printImportTables(file); 549 printExportTable(file); 550 } 551