Bug Summary

File:tools/llvm-objdump/COFFDump.cpp
Warning:line 676, column 29
Called C++ object pointer is uninitialized

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name COFFDump.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-8/lib/clang/8.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/tools/llvm-objdump -I /build/llvm-toolchain-snapshot-8~svn345461/tools/llvm-objdump -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/include -I /build/llvm-toolchain-snapshot-8~svn345461/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/8.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-8/lib/clang/8.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/tools/llvm-objdump -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-10-27-211344-32123-1 -x c++ /build/llvm-toolchain-snapshot-8~svn345461/tools/llvm-objdump/COFFDump.cpp -faddrsig

/build/llvm-toolchain-snapshot-8~svn345461/tools/llvm-objdump/COFFDump.cpp

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/// 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/Demangle/Demangle.h"
20#include "llvm/Object/COFF.h"
21#include "llvm/Object/COFFImportFile.h"
22#include "llvm/Object/ObjectFile.h"
23#include "llvm/Support/Format.h"
24#include "llvm/Support/Win64EH.h"
25#include "llvm/Support/raw_ostream.h"
26
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")::llvm::llvm_unreachable_internal("Invalid unwind code", "/build/llvm-toolchain-snapshot-8~svn345461/tools/llvm-objdump/COFFDump.cpp"
, 34)
;
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")::llvm::llvm_unreachable_internal("Invalid register", "/build/llvm-toolchain-snapshot-8~svn345461/tools/llvm-objdump/COFFDump.cpp"
, 50)
;
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")::llvm::llvm_unreachable_internal("Invalid unwind code", "/build/llvm-toolchain-snapshot-8~svn345461/tools/llvm-objdump/COFFDump.cpp"
, 73)
;
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]))((UCs.size() >= getNumUsedSlots(UCs[0])) ? static_cast<
void> (0) : __assert_fail ("UCs.size() >= getNumUsedSlots(UCs[0])"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/llvm-objdump/COFFDump.cpp"
, 94, __PRETTY_FUNCTION__))
;
95 outs() << format(" 0x%02x: ", unsigned(UCs[0].u.CodeOffset))
96 << 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 }
152 printUnwindCode(makeArrayRef(I, E));
153 I += UsedSlots;
154 }
155}
156
157// Given a symbol sym this functions returns the address and section of it.
158static std::error_code
159resolveSectionAndAddress(const COFFObjectFile *Obj, const SymbolRef &Sym,
160 const coff_section *&ResolvedSection,
161 uint64_t &ResolvedAddr) {
162 Expected<uint64_t> ResolvedAddrOrErr = Sym.getAddress();
163 if (!ResolvedAddrOrErr)
164 return errorToErrorCode(ResolvedAddrOrErr.takeError());
165 ResolvedAddr = *ResolvedAddrOrErr;
166 Expected<section_iterator> Iter = Sym.getSection();
167 if (!Iter)
168 return errorToErrorCode(Iter.takeError());
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.
175static std::error_code resolveSymbol(const std::vector<RelocationRef> &Rels,
176 uint64_t Offset, SymbolRef &Sym) {
177 for (auto &R : Rels) {
178 uint64_t Ofs = R.getOffset();
179 if (Ofs == Offset) {
180 Sym = *R.getSymbol();
181 return std::error_code();
182 }
183 }
184 return object_error::parse_failed;
185}
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.
191static std::error_code
192getSectionContents(const COFFObjectFile *Obj,
193 const std::vector<RelocationRef> &Rels, uint64_t Offset,
194 ArrayRef<uint8_t> &Contents, uint64_t &Addr) {
195 SymbolRef Sym;
196 if (std::error_code EC = resolveSymbol(Rels, Offset, Sym))
197 return EC;
198 const coff_section *Section;
199 if (std::error_code EC = resolveSectionAndAddress(Obj, Sym, Section, Addr))
200 return EC;
201 if (std::error_code EC = Obj->getSectionContents(Section, Contents))
202 return EC;
203 return std::error_code();
204}
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.
209static std::error_code resolveSymbolName(const std::vector<RelocationRef> &Rels,
210 uint64_t Offset, StringRef &Name) {
211 SymbolRef Sym;
212 if (std::error_code EC = resolveSymbol(Rels, Offset, Sym))
213 return EC;
214 Expected<StringRef> NameOrErr = Sym.getName();
215 if (!NameOrErr)
216 return errorToErrorCode(NameOrErr.takeError());
217 Name = *NameOrErr;
218 return std::error_code();
219}
220
221static void printCOFFSymbolAddress(llvm::raw_ostream &Out,
222 const std::vector<RelocationRef> &Rels,
223 uint64_t Offset, uint32_t Disp) {
224 StringRef Sym;
225 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 }
232}
233
234static void
235printSEHTable(const COFFObjectFile *Obj, uint32_t TableVA, int Count) {
236 if (Count == 0)
237 return;
238
239 const pe32_header *PE32Header;
240 error(Obj->getPE32Header(PE32Header));
241 uint32_t ImageBase = PE32Header->ImageBase;
242 uintptr_t IntPtr = 0;
243 error(Obj->getVaPtr(TableVA, IntPtr));
244 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
251template <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
301static void printLoadConfiguration(const COFFObjectFile *Obj) {
302 // Skip if it's not executable.
303 const pe32_header *PE32Header;
304 error(Obj->getPE32Header(PE32Header));
305 if (!PE32Header)
306 return;
307
308 // Currently only x86 is supported
309 if (Obj->getMachine() != COFF::IMAGE_FILE_MACHINE_I386)
310 return;
311
312 const data_directory *DataDir;
313 error(Obj->getDataDirectory(COFF::LOAD_CONFIG_TABLE, DataDir));
314 uintptr_t IntPtr = 0;
315 if (DataDir->RelativeVirtualAddress == 0)
316 return;
317 error(Obj->getRvaPtr(DataDir->RelativeVirtualAddress, IntPtr));
318
319 auto *LoadConf = reinterpret_cast<const coff_load_configuration32 *>(IntPtr);
320 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";
339 printSEHTable(Obj, LoadConf->SEHandlerTable, LoadConf->SEHandlerCount);
340 outs() << "\n";
341}
342
343// 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) {
346 import_directory_iterator I = Obj->import_directory_begin();
347 import_directory_iterator E = Obj->import_directory_end();
348 if (I == E)
349 return;
350 outs() << "The Import Tables:\n";
351 for (const ImportDirectoryEntryRef &DirRef : Obj->import_directories()) {
352 const coff_import_directory_table_entry *Dir;
353 StringRef Name;
354 if (DirRef.getImportTableEntry(Dir)) return;
355 if (DirRef.getName(Name)) return;
356
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";
365 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);
374 continue;
375 }
376 uint32_t HintNameRVA;
377 if (Entry.getHintNameRVA(HintNameRVA))
378 return;
379 uint16_t Hint;
380 StringRef Name;
381 if (Obj->getHintName(HintNameRVA, Hint, Name))
382 return;
383 outs() << format(" % 6d ", Hint) << Name << "\n";
384 }
385 outs() << "\n";
386 }
387}
388
389// 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;
397 StringRef DllName;
398 uint32_t OrdinalBase;
399 if (I->getDllName(DllName))
400 return;
401 if (I->getOrdinalBase(OrdinalBase))
402 return;
403 outs() << " DLL name: " << DllName << "\n";
404 outs() << " Ordinal base: " << OrdinalBase << "\n";
405 outs() << " Ordinal RVA Name\n";
406 for (; I != E; I = ++I) {
407 uint32_t Ordinal;
408 if (I->getOrdinal(Ordinal))
409 return;
410 uint32_t RVA;
411 if (I->getExportRVA(RVA))
412 return;
413 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 }
425
426 StringRef Name;
427 if (I->getSymbolName(Name))
428 continue;
429 if (!Name.empty())
430 outs() << " " << Name;
431 if (IsForwarder) {
432 StringRef S;
433 if (I->getForwardTo(S))
434 return;
435 outs() << " (forwarded to " << S << ")";
436 }
437 outs() << "\n";
438 }
439}
440
441// 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) {
446 for (const SectionRef &Section : Obj->sections()) {
447 StringRef Name;
448 error(Section.getName(Name));
449 if (Name != ".pdata")
450 continue;
451
452 const coff_section *Pdata = Obj->getCOFFSection(Section);
453 for (const RelocationRef &Reloc : Section.relocations())
454 Rels.push_back(Reloc);
455
456 // Sort relocations by address.
457 llvm::sort(Rels, RelocAddressLess);
458
459 ArrayRef<uint8_t> Contents;
460 error(Obj->getSectionContents(Pdata, Contents));
461 if (Contents.empty())
462 continue;
463
464 RFStart = reinterpret_cast<const RuntimeFunction *>(Contents.data());
465 NumRFs = Contents.size() / sizeof(RuntimeFunction);
466 return true;
467 }
468 return false;
469}
470
471static void printWin64EHUnwindInfo(const Win64EH::UnwindInfo *UI) {
472 // 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).
475 outs() << " Version: " << static_cast<int>(UI->getVersion()) << "\n";
476 outs() << " Flags: " << static_cast<int>(UI->getFlags());
477 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";
486 outs() << " Size of prolog: " << static_cast<int>(UI->PrologSize) << "\n";
487 outs() << " Number of Codes: " << static_cast<int>(UI->NumCodes) << "\n";
488 // Maybe this should move to output of UOP_SetFPReg?
489 if (UI->getFrameRegister()) {
490 outs() << " Frame register: "
491 << getUnwindRegisterName(UI->getFrameRegister()) << "\n";
492 outs() << " Frame offset: " << 16 * UI->getFrameOffset() << "\n";
493 } else {
494 outs() << " No frame pointer used\n";
495 }
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 }
501
502 if (UI->NumCodes)
503 outs() << " Unwind Codes:\n";
504
505 printAllUnwindCodes(makeArrayRef(&UI->UnwindCodes[0], UI->NumCodes));
506
507 outs() << "\n";
508 outs().flush();
509}
510
511/// Prints out the given RuntimeFunction struct for x64, assuming that Obj is
512/// pointing to an executable file.
513static void printRuntimeFunction(const COFFObjectFile *Obj,
514 const RuntimeFunction &RF) {
515 if (!RF.StartAddress)
516 return;
517 outs() << "Function Table:\n"
518 << 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));
524 uintptr_t addr;
525 if (Obj->getRvaPtr(RF.UnwindInfoOffset, addr))
526 return;
527 printWin64EHUnwindInfo(reinterpret_cast<const Win64EH::UnwindInfo *>(addr));
528}
529
530/// Prints out the given RuntimeFunction struct for x64, assuming that Obj is
531/// pointing to an object file. Unlike executable, fields in RuntimeFunction
532/// 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) {
540 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;
564 error(getSectionContents(
565 Obj, Rels, SectionOffset +
566 /*offsetof(RuntimeFunction, UnwindInfoOffset)*/ 8,
567 XContents, UnwindInfoOffset));
568 if (XContents.empty())
569 return;
570
571 UnwindInfoOffset += RF.UnwindInfoOffset;
572 if (UnwindInfoOffset > XContents.size())
573 return;
574
575 auto *UI = reinterpret_cast<const Win64EH::UnwindInfo *>(XContents.data() +
576 UnwindInfoOffset);
577 printWin64EHUnwindInfo(UI);
578}
579
580void llvm::printCOFFUnwindInfo(const COFFObjectFile *Obj) {
581 if (Obj->getMachine() != COFF::IMAGE_FILE_MACHINE_AMD64) {
582 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
594 bool IsExecutable = Rels.empty();
595 if (IsExecutable) {
596 for (const RuntimeFunction &RF : RFs)
597 printRuntimeFunction(Obj, RF);
598 return;
599 }
600
601 for (const RuntimeFunction &RF : RFs) {
602 uint64_t SectionOffset =
603 std::distance(RFs.begin(), &RF) * sizeof(RuntimeFunction);
604 printRuntimeFunctionRels(Obj, RF, SectionOffset, Rels);
605 }
606}
607
608void llvm::printCOFFFileHeader(const object::ObjectFile *Obj) {
609 const COFFObjectFile *file = dyn_cast<const COFFObjectFile>(Obj);
610 printTLSDirectory(file);
611 printLoadConfiguration(file);
612 printImportTables(file);
613 printExportTable(file);
614}
615
616void 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
639void llvm::printCOFFSymbolTable(const COFFObjectFile *coff) {
640 for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
1
Assuming 'SI' is not equal to 'SE'
2
Loop condition is true. Entering loop body
641 Expected<COFFSymbolRef> Symbol = coff->getSymbol(SI);
642 StringRef Name;
643 error(errorToErrorCode(Symbol.takeError()));
644 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())) << ")"
650 << "(scl " << format("%3x", unsigned(Symbol->getStorageClass()))
651 << ") "
652 << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
653 << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
654 << Name;
655 if (Demangle && Name.startswith("?")) {
3
Assuming the condition is false
4
Taking false branch
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);
665 } else {
666 outs() << " (invalid mangled name)";
667 }
668 }
669 outs() << "\n";
670
671 for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
5
Assuming 'AI' is < 'AE'
6
Loop condition is true. Entering loop body
672 if (Symbol->isSectionDefinition()) {
7
Taking true branch
673 const coff_aux_section_definition *asd;
8
'asd' declared without an initial value
674 error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd));
9
Calling 'COFFObjectFile::getAuxSymbol'
12
Returning from 'COFFObjectFile::getAuxSymbol'
675
676 int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
13
Called C++ object pointer is uninitialized
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;
697 } 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));
704 } else {
705 outs() << "AUX Unknown\n";
706 }
707 }
708 }
709}

/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Object/COFF.h

1//===- COFF.h - COFF object file implementation -----------------*- 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// This file declares the COFFObjectFile class.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_OBJECT_COFF_H
15#define LLVM_OBJECT_COFF_H
16
17#include "llvm/ADT/iterator_range.h"
18#include "llvm/BinaryFormat/COFF.h"
19#include "llvm/MC/SubtargetFeature.h"
20#include "llvm/Object/Binary.h"
21#include "llvm/Object/CVDebugRecord.h"
22#include "llvm/Object/Error.h"
23#include "llvm/Object/ObjectFile.h"
24#include "llvm/Support/BinaryByteStream.h"
25#include "llvm/Support/ConvertUTF.h"
26#include "llvm/Support/Endian.h"
27#include "llvm/Support/ErrorHandling.h"
28#include <cassert>
29#include <cstddef>
30#include <cstdint>
31#include <system_error>
32
33namespace llvm {
34
35template <typename T> class ArrayRef;
36
37namespace object {
38
39class BaseRelocRef;
40class DelayImportDirectoryEntryRef;
41class ExportDirectoryEntryRef;
42class ImportDirectoryEntryRef;
43class ImportedSymbolRef;
44class ResourceSectionRef;
45
46using import_directory_iterator = content_iterator<ImportDirectoryEntryRef>;
47using delay_import_directory_iterator =
48 content_iterator<DelayImportDirectoryEntryRef>;
49using export_directory_iterator = content_iterator<ExportDirectoryEntryRef>;
50using imported_symbol_iterator = content_iterator<ImportedSymbolRef>;
51using base_reloc_iterator = content_iterator<BaseRelocRef>;
52
53/// The DOS compatible header at the front of all PE/COFF executables.
54struct dos_header {
55 char Magic[2];
56 support::ulittle16_t UsedBytesInTheLastPage;
57 support::ulittle16_t FileSizeInPages;
58 support::ulittle16_t NumberOfRelocationItems;
59 support::ulittle16_t HeaderSizeInParagraphs;
60 support::ulittle16_t MinimumExtraParagraphs;
61 support::ulittle16_t MaximumExtraParagraphs;
62 support::ulittle16_t InitialRelativeSS;
63 support::ulittle16_t InitialSP;
64 support::ulittle16_t Checksum;
65 support::ulittle16_t InitialIP;
66 support::ulittle16_t InitialRelativeCS;
67 support::ulittle16_t AddressOfRelocationTable;
68 support::ulittle16_t OverlayNumber;
69 support::ulittle16_t Reserved[4];
70 support::ulittle16_t OEMid;
71 support::ulittle16_t OEMinfo;
72 support::ulittle16_t Reserved2[10];
73 support::ulittle32_t AddressOfNewExeHeader;
74};
75
76struct coff_file_header {
77 support::ulittle16_t Machine;
78 support::ulittle16_t NumberOfSections;
79 support::ulittle32_t TimeDateStamp;
80 support::ulittle32_t PointerToSymbolTable;
81 support::ulittle32_t NumberOfSymbols;
82 support::ulittle16_t SizeOfOptionalHeader;
83 support::ulittle16_t Characteristics;
84
85 bool isImportLibrary() const { return NumberOfSections == 0xffff; }
86};
87
88struct coff_bigobj_file_header {
89 support::ulittle16_t Sig1;
90 support::ulittle16_t Sig2;
91 support::ulittle16_t Version;
92 support::ulittle16_t Machine;
93 support::ulittle32_t TimeDateStamp;
94 uint8_t UUID[16];
95 support::ulittle32_t unused1;
96 support::ulittle32_t unused2;
97 support::ulittle32_t unused3;
98 support::ulittle32_t unused4;
99 support::ulittle32_t NumberOfSections;
100 support::ulittle32_t PointerToSymbolTable;
101 support::ulittle32_t NumberOfSymbols;
102};
103
104/// The 32-bit PE header that follows the COFF header.
105struct pe32_header {
106 support::ulittle16_t Magic;
107 uint8_t MajorLinkerVersion;
108 uint8_t MinorLinkerVersion;
109 support::ulittle32_t SizeOfCode;
110 support::ulittle32_t SizeOfInitializedData;
111 support::ulittle32_t SizeOfUninitializedData;
112 support::ulittle32_t AddressOfEntryPoint;
113 support::ulittle32_t BaseOfCode;
114 support::ulittle32_t BaseOfData;
115 support::ulittle32_t ImageBase;
116 support::ulittle32_t SectionAlignment;
117 support::ulittle32_t FileAlignment;
118 support::ulittle16_t MajorOperatingSystemVersion;
119 support::ulittle16_t MinorOperatingSystemVersion;
120 support::ulittle16_t MajorImageVersion;
121 support::ulittle16_t MinorImageVersion;
122 support::ulittle16_t MajorSubsystemVersion;
123 support::ulittle16_t MinorSubsystemVersion;
124 support::ulittle32_t Win32VersionValue;
125 support::ulittle32_t SizeOfImage;
126 support::ulittle32_t SizeOfHeaders;
127 support::ulittle32_t CheckSum;
128 support::ulittle16_t Subsystem;
129 // FIXME: This should be DllCharacteristics.
130 support::ulittle16_t DLLCharacteristics;
131 support::ulittle32_t SizeOfStackReserve;
132 support::ulittle32_t SizeOfStackCommit;
133 support::ulittle32_t SizeOfHeapReserve;
134 support::ulittle32_t SizeOfHeapCommit;
135 support::ulittle32_t LoaderFlags;
136 // FIXME: This should be NumberOfRvaAndSizes.
137 support::ulittle32_t NumberOfRvaAndSize;
138};
139
140/// The 64-bit PE header that follows the COFF header.
141struct pe32plus_header {
142 support::ulittle16_t Magic;
143 uint8_t MajorLinkerVersion;
144 uint8_t MinorLinkerVersion;
145 support::ulittle32_t SizeOfCode;
146 support::ulittle32_t SizeOfInitializedData;
147 support::ulittle32_t SizeOfUninitializedData;
148 support::ulittle32_t AddressOfEntryPoint;
149 support::ulittle32_t BaseOfCode;
150 support::ulittle64_t ImageBase;
151 support::ulittle32_t SectionAlignment;
152 support::ulittle32_t FileAlignment;
153 support::ulittle16_t MajorOperatingSystemVersion;
154 support::ulittle16_t MinorOperatingSystemVersion;
155 support::ulittle16_t MajorImageVersion;
156 support::ulittle16_t MinorImageVersion;
157 support::ulittle16_t MajorSubsystemVersion;
158 support::ulittle16_t MinorSubsystemVersion;
159 support::ulittle32_t Win32VersionValue;
160 support::ulittle32_t SizeOfImage;
161 support::ulittle32_t SizeOfHeaders;
162 support::ulittle32_t CheckSum;
163 support::ulittle16_t Subsystem;
164 support::ulittle16_t DLLCharacteristics;
165 support::ulittle64_t SizeOfStackReserve;
166 support::ulittle64_t SizeOfStackCommit;
167 support::ulittle64_t SizeOfHeapReserve;
168 support::ulittle64_t SizeOfHeapCommit;
169 support::ulittle32_t LoaderFlags;
170 support::ulittle32_t NumberOfRvaAndSize;
171};
172
173struct data_directory {
174 support::ulittle32_t RelativeVirtualAddress;
175 support::ulittle32_t Size;
176};
177
178struct debug_directory {
179 support::ulittle32_t Characteristics;
180 support::ulittle32_t TimeDateStamp;
181 support::ulittle16_t MajorVersion;
182 support::ulittle16_t MinorVersion;
183 support::ulittle32_t Type;
184 support::ulittle32_t SizeOfData;
185 support::ulittle32_t AddressOfRawData;
186 support::ulittle32_t PointerToRawData;
187};
188
189template <typename IntTy>
190struct import_lookup_table_entry {
191 IntTy Data;
192
193 bool isOrdinal() const { return Data < 0; }
194
195 uint16_t getOrdinal() const {
196 assert(isOrdinal() && "ILT entry is not an ordinal!")((isOrdinal() && "ILT entry is not an ordinal!") ? static_cast
<void> (0) : __assert_fail ("isOrdinal() && \"ILT entry is not an ordinal!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Object/COFF.h"
, 196, __PRETTY_FUNCTION__))
;
197 return Data & 0xFFFF;
198 }
199
200 uint32_t getHintNameRVA() const {
201 assert(!isOrdinal() && "ILT entry is not a Hint/Name RVA!")((!isOrdinal() && "ILT entry is not a Hint/Name RVA!"
) ? static_cast<void> (0) : __assert_fail ("!isOrdinal() && \"ILT entry is not a Hint/Name RVA!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Object/COFF.h"
, 201, __PRETTY_FUNCTION__))
;
202 return Data & 0xFFFFFFFF;
203 }
204};
205
206using import_lookup_table_entry32 =
207 import_lookup_table_entry<support::little32_t>;
208using import_lookup_table_entry64 =
209 import_lookup_table_entry<support::little64_t>;
210
211struct delay_import_directory_table_entry {
212 // dumpbin reports this field as "Characteristics" instead of "Attributes".
213 support::ulittle32_t Attributes;
214 support::ulittle32_t Name;
215 support::ulittle32_t ModuleHandle;
216 support::ulittle32_t DelayImportAddressTable;
217 support::ulittle32_t DelayImportNameTable;
218 support::ulittle32_t BoundDelayImportTable;
219 support::ulittle32_t UnloadDelayImportTable;
220 support::ulittle32_t TimeStamp;
221};
222
223struct export_directory_table_entry {
224 support::ulittle32_t ExportFlags;
225 support::ulittle32_t TimeDateStamp;
226 support::ulittle16_t MajorVersion;
227 support::ulittle16_t MinorVersion;
228 support::ulittle32_t NameRVA;
229 support::ulittle32_t OrdinalBase;
230 support::ulittle32_t AddressTableEntries;
231 support::ulittle32_t NumberOfNamePointers;
232 support::ulittle32_t ExportAddressTableRVA;
233 support::ulittle32_t NamePointerRVA;
234 support::ulittle32_t OrdinalTableRVA;
235};
236
237union export_address_table_entry {
238 support::ulittle32_t ExportRVA;
239 support::ulittle32_t ForwarderRVA;
240};
241
242using export_name_pointer_table_entry = support::ulittle32_t;
243using export_ordinal_table_entry = support::ulittle16_t;
244
245struct StringTableOffset {
246 support::ulittle32_t Zeroes;
247 support::ulittle32_t Offset;
248};
249
250template <typename SectionNumberType>
251struct coff_symbol {
252 union {
253 char ShortName[COFF::NameSize];
254 StringTableOffset Offset;
255 } Name;
256
257 support::ulittle32_t Value;
258 SectionNumberType SectionNumber;
259
260 support::ulittle16_t Type;
261
262 uint8_t StorageClass;
263 uint8_t NumberOfAuxSymbols;
264};
265
266using coff_symbol16 = coff_symbol<support::ulittle16_t>;
267using coff_symbol32 = coff_symbol<support::ulittle32_t>;
268
269// Contains only common parts of coff_symbol16 and coff_symbol32.
270struct coff_symbol_generic {
271 union {
272 char ShortName[COFF::NameSize];
273 StringTableOffset Offset;
274 } Name;
275 support::ulittle32_t Value;
276};
277
278struct coff_aux_section_definition;
279struct coff_aux_weak_external;
280
281class COFFSymbolRef {
282public:
283 COFFSymbolRef() = default;
284 COFFSymbolRef(const coff_symbol16 *CS) : CS16(CS) {}
285 COFFSymbolRef(const coff_symbol32 *CS) : CS32(CS) {}
286
287 const void *getRawPtr() const {
288 return CS16 ? static_cast<const void *>(CS16) : CS32;
289 }
290
291 const coff_symbol_generic *getGeneric() const {
292 if (CS16)
293 return reinterpret_cast<const coff_symbol_generic *>(CS16);
294 return reinterpret_cast<const coff_symbol_generic *>(CS32);
295 }
296
297 friend bool operator<(COFFSymbolRef A, COFFSymbolRef B) {
298 return A.getRawPtr() < B.getRawPtr();
299 }
300
301 bool isBigObj() const {
302 if (CS16)
303 return false;
304 if (CS32)
305 return true;
306 llvm_unreachable("COFFSymbolRef points to nothing!")::llvm::llvm_unreachable_internal("COFFSymbolRef points to nothing!"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Object/COFF.h"
, 306)
;
307 }
308
309 const char *getShortName() const {
310 return CS16 ? CS16->Name.ShortName : CS32->Name.ShortName;
311 }
312
313 const StringTableOffset &getStringTableOffset() const {
314 assert(isSet() && "COFFSymbolRef points to nothing!")((isSet() && "COFFSymbolRef points to nothing!") ? static_cast
<void> (0) : __assert_fail ("isSet() && \"COFFSymbolRef points to nothing!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Object/COFF.h"
, 314, __PRETTY_FUNCTION__))
;
315 return CS16 ? CS16->Name.Offset : CS32->Name.Offset;
316 }
317
318 uint32_t getValue() const { return CS16 ? CS16->Value : CS32->Value; }
319
320 int32_t getSectionNumber() const {
321 assert(isSet() && "COFFSymbolRef points to nothing!")((isSet() && "COFFSymbolRef points to nothing!") ? static_cast
<void> (0) : __assert_fail ("isSet() && \"COFFSymbolRef points to nothing!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Object/COFF.h"
, 321, __PRETTY_FUNCTION__))
;
322 if (CS16) {
323 // Reserved sections are returned as negative numbers.
324 if (CS16->SectionNumber <= COFF::MaxNumberOfSections16)
325 return CS16->SectionNumber;
326 return static_cast<int16_t>(CS16->SectionNumber);
327 }
328 return static_cast<int32_t>(CS32->SectionNumber);
329 }
330
331 uint16_t getType() const {
332 assert(isSet() && "COFFSymbolRef points to nothing!")((isSet() && "COFFSymbolRef points to nothing!") ? static_cast
<void> (0) : __assert_fail ("isSet() && \"COFFSymbolRef points to nothing!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Object/COFF.h"
, 332, __PRETTY_FUNCTION__))
;
333 return CS16 ? CS16->Type : CS32->Type;
334 }
335
336 uint8_t getStorageClass() const {
337 assert(isSet() && "COFFSymbolRef points to nothing!")((isSet() && "COFFSymbolRef points to nothing!") ? static_cast
<void> (0) : __assert_fail ("isSet() && \"COFFSymbolRef points to nothing!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Object/COFF.h"
, 337, __PRETTY_FUNCTION__))
;
338 return CS16 ? CS16->StorageClass : CS32->StorageClass;
339 }
340
341 uint8_t getNumberOfAuxSymbols() const {
342 assert(isSet() && "COFFSymbolRef points to nothing!")((isSet() && "COFFSymbolRef points to nothing!") ? static_cast
<void> (0) : __assert_fail ("isSet() && \"COFFSymbolRef points to nothing!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Object/COFF.h"
, 342, __PRETTY_FUNCTION__))
;
343 return CS16 ? CS16->NumberOfAuxSymbols : CS32->NumberOfAuxSymbols;
344 }
345
346 uint8_t getBaseType() const { return getType() & 0x0F; }
347
348 uint8_t getComplexType() const {
349 return (getType() & 0xF0) >> COFF::SCT_COMPLEX_TYPE_SHIFT;
350 }
351
352 template <typename T> const T *getAux() const {
353 return CS16 ? reinterpret_cast<const T *>(CS16 + 1)
354 : reinterpret_cast<const T *>(CS32 + 1);
355 }
356
357 const coff_aux_section_definition *getSectionDefinition() const {
358 if (!getNumberOfAuxSymbols() ||
359 getStorageClass() != COFF::IMAGE_SYM_CLASS_STATIC)
360 return nullptr;
361 return getAux<coff_aux_section_definition>();
362 }
363
364 const coff_aux_weak_external *getWeakExternal() const {
365 if (!getNumberOfAuxSymbols() ||
366 getStorageClass() != COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL)
367 return nullptr;
368 return getAux<coff_aux_weak_external>();
369 }
370
371 bool isAbsolute() const {
372 return getSectionNumber() == -1;
373 }
374
375 bool isExternal() const {
376 return getStorageClass() == COFF::IMAGE_SYM_CLASS_EXTERNAL;
377 }
378
379 bool isCommon() const {
380 return isExternal() && getSectionNumber() == COFF::IMAGE_SYM_UNDEFINED &&
381 getValue() != 0;
382 }
383
384 bool isUndefined() const {
385 return isExternal() && getSectionNumber() == COFF::IMAGE_SYM_UNDEFINED &&
386 getValue() == 0;
387 }
388
389 bool isWeakExternal() const {
390 return getStorageClass() == COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL;
391 }
392
393 bool isFunctionDefinition() const {
394 return isExternal() && getBaseType() == COFF::IMAGE_SYM_TYPE_NULL &&
395 getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION &&
396 !COFF::isReservedSectionNumber(getSectionNumber());
397 }
398
399 bool isFunctionLineInfo() const {
400 return getStorageClass() == COFF::IMAGE_SYM_CLASS_FUNCTION;
401 }
402
403 bool isAnyUndefined() const {
404 return isUndefined() || isWeakExternal();
405 }
406
407 bool isFileRecord() const {
408 return getStorageClass() == COFF::IMAGE_SYM_CLASS_FILE;
409 }
410
411 bool isSection() const {
412 return getStorageClass() == COFF::IMAGE_SYM_CLASS_SECTION;
413 }
414
415 bool isSectionDefinition() const {
416 // C++/CLI creates external ABS symbols for non-const appdomain globals.
417 // These are also followed by an auxiliary section definition.
418 bool isAppdomainGlobal =
419 getStorageClass() == COFF::IMAGE_SYM_CLASS_EXTERNAL &&
420 getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE;
421 bool isOrdinarySection = getStorageClass() == COFF::IMAGE_SYM_CLASS_STATIC;
422 if (!getNumberOfAuxSymbols())
423 return false;
424 return isAppdomainGlobal || isOrdinarySection;
425 }
426
427 bool isCLRToken() const {
428 return getStorageClass() == COFF::IMAGE_SYM_CLASS_CLR_TOKEN;
429 }
430
431private:
432 bool isSet() const { return CS16 || CS32; }
433
434 const coff_symbol16 *CS16 = nullptr;
435 const coff_symbol32 *CS32 = nullptr;
436};
437
438struct coff_section {
439 char Name[COFF::NameSize];
440 support::ulittle32_t VirtualSize;
441 support::ulittle32_t VirtualAddress;
442 support::ulittle32_t SizeOfRawData;
443 support::ulittle32_t PointerToRawData;
444 support::ulittle32_t PointerToRelocations;
445 support::ulittle32_t PointerToLinenumbers;
446 support::ulittle16_t NumberOfRelocations;
447 support::ulittle16_t NumberOfLinenumbers;
448 support::ulittle32_t Characteristics;
449
450 // Returns true if the actual number of relocations is stored in
451 // VirtualAddress field of the first relocation table entry.
452 bool hasExtendedRelocations() const {
453 return (Characteristics & COFF::IMAGE_SCN_LNK_NRELOC_OVFL) &&
454 NumberOfRelocations == UINT16_MAX(65535);
455 }
456
457 uint32_t getAlignment() const {
458 // The IMAGE_SCN_TYPE_NO_PAD bit is a legacy way of getting to
459 // IMAGE_SCN_ALIGN_1BYTES.
460 if (Characteristics & COFF::IMAGE_SCN_TYPE_NO_PAD)
461 return 1;
462
463 // Bit [20:24] contains section alignment. 0 means use a default alignment
464 // of 16.
465 uint32_t Shift = (Characteristics >> 20) & 0xF;
466 if (Shift > 0)
467 return 1U << (Shift - 1);
468 return 16;
469 }
470};
471
472struct coff_relocation {
473 support::ulittle32_t VirtualAddress;
474 support::ulittle32_t SymbolTableIndex;
475 support::ulittle16_t Type;
476};
477
478struct coff_aux_function_definition {
479 support::ulittle32_t TagIndex;
480 support::ulittle32_t TotalSize;
481 support::ulittle32_t PointerToLinenumber;
482 support::ulittle32_t PointerToNextFunction;
483 char Unused1[2];
484};
485
486static_assert(sizeof(coff_aux_function_definition) == 18,
487 "auxiliary entry must be 18 bytes");
488
489struct coff_aux_bf_and_ef_symbol {
490 char Unused1[4];
491 support::ulittle16_t Linenumber;
492 char Unused2[6];
493 support::ulittle32_t PointerToNextFunction;
494 char Unused3[2];
495};
496
497static_assert(sizeof(coff_aux_bf_and_ef_symbol) == 18,
498 "auxiliary entry must be 18 bytes");
499
500struct coff_aux_weak_external {
501 support::ulittle32_t TagIndex;
502 support::ulittle32_t Characteristics;
503 char Unused1[10];
504};
505
506static_assert(sizeof(coff_aux_weak_external) == 18,
507 "auxiliary entry must be 18 bytes");
508
509struct coff_aux_section_definition {
510 support::ulittle32_t Length;
511 support::ulittle16_t NumberOfRelocations;
512 support::ulittle16_t NumberOfLinenumbers;
513 support::ulittle32_t CheckSum;
514 support::ulittle16_t NumberLowPart;
515 uint8_t Selection;
516 uint8_t Unused;
517 support::ulittle16_t NumberHighPart;
518 int32_t getNumber(bool IsBigObj) const {
519 uint32_t Number = static_cast<uint32_t>(NumberLowPart);
520 if (IsBigObj)
521 Number |= static_cast<uint32_t>(NumberHighPart) << 16;
522 return static_cast<int32_t>(Number);
523 }
524};
525
526static_assert(sizeof(coff_aux_section_definition) == 18,
527 "auxiliary entry must be 18 bytes");
528
529struct coff_aux_clr_token {
530 uint8_t AuxType;
531 uint8_t Reserved;
532 support::ulittle32_t SymbolTableIndex;
533 char MBZ[12];
534};
535
536static_assert(sizeof(coff_aux_clr_token) == 18,
537 "auxiliary entry must be 18 bytes");
538
539struct coff_import_header {
540 support::ulittle16_t Sig1;
541 support::ulittle16_t Sig2;
542 support::ulittle16_t Version;
543 support::ulittle16_t Machine;
544 support::ulittle32_t TimeDateStamp;
545 support::ulittle32_t SizeOfData;
546 support::ulittle16_t OrdinalHint;
547 support::ulittle16_t TypeInfo;
548
549 int getType() const { return TypeInfo & 0x3; }
550 int getNameType() const { return (TypeInfo >> 2) & 0x7; }
551};
552
553struct coff_import_directory_table_entry {
554 support::ulittle32_t ImportLookupTableRVA;
555 support::ulittle32_t TimeDateStamp;
556 support::ulittle32_t ForwarderChain;
557 support::ulittle32_t NameRVA;
558 support::ulittle32_t ImportAddressTableRVA;
559
560 bool isNull() const {
561 return ImportLookupTableRVA == 0 && TimeDateStamp == 0 &&
562 ForwarderChain == 0 && NameRVA == 0 && ImportAddressTableRVA == 0;
563 }
564};
565
566template <typename IntTy>
567struct coff_tls_directory {
568 IntTy StartAddressOfRawData;
569 IntTy EndAddressOfRawData;
570 IntTy AddressOfIndex;
571 IntTy AddressOfCallBacks;
572 support::ulittle32_t SizeOfZeroFill;
573 support::ulittle32_t Characteristics;
574
575 uint32_t getAlignment() const {
576 // Bit [20:24] contains section alignment.
577 uint32_t Shift = (Characteristics & 0x00F00000) >> 20;
578 if (Shift > 0)
579 return 1U << (Shift - 1);
580 return 0;
581 }
582};
583
584using coff_tls_directory32 = coff_tls_directory<support::little32_t>;
585using coff_tls_directory64 = coff_tls_directory<support::little64_t>;
586
587/// Bits in control flow guard flags as we understand them.
588enum class coff_guard_flags : uint32_t {
589 CFInstrumented = 0x00000100,
590 HasFidTable = 0x00000400,
591 ProtectDelayLoadIAT = 0x00001000,
592 DelayLoadIATSection = 0x00002000, // Delay load in separate section
593 HasLongJmpTable = 0x00010000,
594 FidTableHasFlags = 0x10000000, // Indicates that fid tables are 5 bytes
595};
596
597enum class frame_type : uint16_t { Fpo = 0, Trap = 1, Tss = 2, NonFpo = 3 };
598
599struct coff_load_config_code_integrity {
600 support::ulittle16_t Flags;
601 support::ulittle16_t Catalog;
602 support::ulittle32_t CatalogOffset;
603 support::ulittle32_t Reserved;
604};
605
606/// 32-bit load config (IMAGE_LOAD_CONFIG_DIRECTORY32)
607struct coff_load_configuration32 {
608 support::ulittle32_t Size;
609 support::ulittle32_t TimeDateStamp;
610 support::ulittle16_t MajorVersion;
611 support::ulittle16_t MinorVersion;
612 support::ulittle32_t GlobalFlagsClear;
613 support::ulittle32_t GlobalFlagsSet;
614 support::ulittle32_t CriticalSectionDefaultTimeout;
615 support::ulittle32_t DeCommitFreeBlockThreshold;
616 support::ulittle32_t DeCommitTotalFreeThreshold;
617 support::ulittle32_t LockPrefixTable;
618 support::ulittle32_t MaximumAllocationSize;
619 support::ulittle32_t VirtualMemoryThreshold;
620 support::ulittle32_t ProcessAffinityMask;
621 support::ulittle32_t ProcessHeapFlags;
622 support::ulittle16_t CSDVersion;
623 support::ulittle16_t DependentLoadFlags;
624 support::ulittle32_t EditList;
625 support::ulittle32_t SecurityCookie;
626 support::ulittle32_t SEHandlerTable;
627 support::ulittle32_t SEHandlerCount;
628
629 // Added in MSVC 2015 for /guard:cf.
630 support::ulittle32_t GuardCFCheckFunction;
631 support::ulittle32_t GuardCFCheckDispatch;
632 support::ulittle32_t GuardCFFunctionTable;
633 support::ulittle32_t GuardCFFunctionCount;
634 support::ulittle32_t GuardFlags; // coff_guard_flags
635
636 // Added in MSVC 2017
637 coff_load_config_code_integrity CodeIntegrity;
638 support::ulittle32_t GuardAddressTakenIatEntryTable;
639 support::ulittle32_t GuardAddressTakenIatEntryCount;
640 support::ulittle32_t GuardLongJumpTargetTable;
641 support::ulittle32_t GuardLongJumpTargetCount;
642 support::ulittle32_t DynamicValueRelocTable;
643 support::ulittle32_t CHPEMetadataPointer;
644 support::ulittle32_t GuardRFFailureRoutine;
645 support::ulittle32_t GuardRFFailureRoutineFunctionPointer;
646 support::ulittle32_t DynamicValueRelocTableOffset;
647 support::ulittle16_t DynamicValueRelocTableSection;
648 support::ulittle16_t Reserved2;
649 support::ulittle32_t GuardRFVerifyStackPointerFunctionPointer;
650 support::ulittle32_t HotPatchTableOffset;
651};
652
653/// 64-bit load config (IMAGE_LOAD_CONFIG_DIRECTORY64)
654struct coff_load_configuration64 {
655 support::ulittle32_t Size;
656 support::ulittle32_t TimeDateStamp;
657 support::ulittle16_t MajorVersion;
658 support::ulittle16_t MinorVersion;
659 support::ulittle32_t GlobalFlagsClear;
660 support::ulittle32_t GlobalFlagsSet;
661 support::ulittle32_t CriticalSectionDefaultTimeout;
662 support::ulittle64_t DeCommitFreeBlockThreshold;
663 support::ulittle64_t DeCommitTotalFreeThreshold;
664 support::ulittle64_t LockPrefixTable;
665 support::ulittle64_t MaximumAllocationSize;
666 support::ulittle64_t VirtualMemoryThreshold;
667 support::ulittle64_t ProcessAffinityMask;
668 support::ulittle32_t ProcessHeapFlags;
669 support::ulittle16_t CSDVersion;
670 support::ulittle16_t DependentLoadFlags;
671 support::ulittle64_t EditList;
672 support::ulittle64_t SecurityCookie;
673 support::ulittle64_t SEHandlerTable;
674 support::ulittle64_t SEHandlerCount;
675
676 // Added in MSVC 2015 for /guard:cf.
677 support::ulittle64_t GuardCFCheckFunction;
678 support::ulittle64_t GuardCFCheckDispatch;
679 support::ulittle64_t GuardCFFunctionTable;
680 support::ulittle64_t GuardCFFunctionCount;
681 support::ulittle32_t GuardFlags;
682
683 // Added in MSVC 2017
684 coff_load_config_code_integrity CodeIntegrity;
685 support::ulittle64_t GuardAddressTakenIatEntryTable;
686 support::ulittle64_t GuardAddressTakenIatEntryCount;
687 support::ulittle64_t GuardLongJumpTargetTable;
688 support::ulittle64_t GuardLongJumpTargetCount;
689 support::ulittle64_t DynamicValueRelocTable;
690 support::ulittle64_t CHPEMetadataPointer;
691 support::ulittle64_t GuardRFFailureRoutine;
692 support::ulittle64_t GuardRFFailureRoutineFunctionPointer;
693 support::ulittle32_t DynamicValueRelocTableOffset;
694 support::ulittle16_t DynamicValueRelocTableSection;
695 support::ulittle16_t Reserved2;
696 support::ulittle64_t GuardRFVerifyStackPointerFunctionPointer;
697 support::ulittle32_t HotPatchTableOffset;
698};
699
700struct coff_runtime_function_x64 {
701 support::ulittle32_t BeginAddress;
702 support::ulittle32_t EndAddress;
703 support::ulittle32_t UnwindInformation;
704};
705
706struct coff_base_reloc_block_header {
707 support::ulittle32_t PageRVA;
708 support::ulittle32_t BlockSize;
709};
710
711struct coff_base_reloc_block_entry {
712 support::ulittle16_t Data;
713
714 int getType() const { return Data >> 12; }
715 int getOffset() const { return Data & ((1 << 12) - 1); }
716};
717
718struct coff_resource_dir_entry {
719 union {
720 support::ulittle32_t NameOffset;
721 support::ulittle32_t ID;
722 uint32_t getNameOffset() const {
723 return maskTrailingOnes<uint32_t>(31) & NameOffset;
724 }
725 // Even though the PE/COFF spec doesn't mention this, the high bit of a name
726 // offset is set.
727 void setNameOffset(uint32_t Offset) { NameOffset = Offset | (1 << 31); }
728 } Identifier;
729 union {
730 support::ulittle32_t DataEntryOffset;
731 support::ulittle32_t SubdirOffset;
732
733 bool isSubDir() const { return SubdirOffset >> 31; }
734 uint32_t value() const {
735 return maskTrailingOnes<uint32_t>(31) & SubdirOffset;
736 }
737
738 } Offset;
739};
740
741struct coff_resource_data_entry {
742 support::ulittle32_t DataRVA;
743 support::ulittle32_t DataSize;
744 support::ulittle32_t Codepage;
745 support::ulittle32_t Reserved;
746};
747
748struct coff_resource_dir_table {
749 support::ulittle32_t Characteristics;
750 support::ulittle32_t TimeDateStamp;
751 support::ulittle16_t MajorVersion;
752 support::ulittle16_t MinorVersion;
753 support::ulittle16_t NumberOfNameEntries;
754 support::ulittle16_t NumberOfIDEntries;
755};
756
757struct debug_h_header {
758 support::ulittle32_t Magic;
759 support::ulittle16_t Version;
760 support::ulittle16_t HashAlgorithm;
761};
762
763class COFFObjectFile : public ObjectFile {
764private:
765 friend class ImportDirectoryEntryRef;
766 friend class ExportDirectoryEntryRef;
767 const coff_file_header *COFFHeader;
768 const coff_bigobj_file_header *COFFBigObjHeader;
769 const pe32_header *PE32Header;
770 const pe32plus_header *PE32PlusHeader;
771 const data_directory *DataDirectory;
772 const coff_section *SectionTable;
773 const coff_symbol16 *SymbolTable16;
774 const coff_symbol32 *SymbolTable32;
775 const char *StringTable;
776 uint32_t StringTableSize;
777 const coff_import_directory_table_entry *ImportDirectory;
778 const delay_import_directory_table_entry *DelayImportDirectory;
779 uint32_t NumberOfDelayImportDirectory;
780 const export_directory_table_entry *ExportDirectory;
781 const coff_base_reloc_block_header *BaseRelocHeader;
782 const coff_base_reloc_block_header *BaseRelocEnd;
783 const debug_directory *DebugDirectoryBegin;
784 const debug_directory *DebugDirectoryEnd;
785 // Either coff_load_configuration32 or coff_load_configuration64.
786 const void *LoadConfig = nullptr;
787
788 std::error_code getString(uint32_t offset, StringRef &Res) const;
789
790 template <typename coff_symbol_type>
791 const coff_symbol_type *toSymb(DataRefImpl Symb) const;
792 const coff_section *toSec(DataRefImpl Sec) const;
793 const coff_relocation *toRel(DataRefImpl Rel) const;
794
795 std::error_code initSymbolTablePtr();
796 std::error_code initImportTablePtr();
797 std::error_code initDelayImportTablePtr();
798 std::error_code initExportTablePtr();
799 std::error_code initBaseRelocPtr();
800 std::error_code initDebugDirectoryPtr();
801 std::error_code initLoadConfigPtr();
802
803public:
804 uintptr_t getSymbolTable() const {
805 if (SymbolTable16)
806 return reinterpret_cast<uintptr_t>(SymbolTable16);
807 if (SymbolTable32)
808 return reinterpret_cast<uintptr_t>(SymbolTable32);
809 return uintptr_t(0);
810 }
811
812 uint16_t getMachine() const {
813 if (COFFHeader)
814 return COFFHeader->Machine;
815 if (COFFBigObjHeader)
816 return COFFBigObjHeader->Machine;
817 llvm_unreachable("no COFF header!")::llvm::llvm_unreachable_internal("no COFF header!", "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Object/COFF.h"
, 817)
;
818 }
819
820 uint16_t getSizeOfOptionalHeader() const {
821 if (COFFHeader)
822 return COFFHeader->isImportLibrary() ? 0
823 : COFFHeader->SizeOfOptionalHeader;
824 // bigobj doesn't have this field.
825 if (COFFBigObjHeader)
826 return 0;
827 llvm_unreachable("no COFF header!")::llvm::llvm_unreachable_internal("no COFF header!", "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Object/COFF.h"
, 827)
;
828 }
829
830 uint16_t getCharacteristics() const {
831 if (COFFHeader)
832 return COFFHeader->isImportLibrary() ? 0 : COFFHeader->Characteristics;
833 // bigobj doesn't have characteristics to speak of,
834 // editbin will silently lie to you if you attempt to set any.
835 if (COFFBigObjHeader)
836 return 0;
837 llvm_unreachable("no COFF header!")::llvm::llvm_unreachable_internal("no COFF header!", "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Object/COFF.h"
, 837)
;
838 }
839
840 uint32_t getTimeDateStamp() const {
841 if (COFFHeader)
842 return COFFHeader->TimeDateStamp;
843 if (COFFBigObjHeader)
844 return COFFBigObjHeader->TimeDateStamp;
845 llvm_unreachable("no COFF header!")::llvm::llvm_unreachable_internal("no COFF header!", "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Object/COFF.h"
, 845)
;
846 }
847
848 uint32_t getNumberOfSections() const {
849 if (COFFHeader)
850 return COFFHeader->isImportLibrary() ? 0 : COFFHeader->NumberOfSections;
851 if (COFFBigObjHeader)
852 return COFFBigObjHeader->NumberOfSections;
853 llvm_unreachable("no COFF header!")::llvm::llvm_unreachable_internal("no COFF header!", "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Object/COFF.h"
, 853)
;
854 }
855
856 uint32_t getPointerToSymbolTable() const {
857 if (COFFHeader)
858 return COFFHeader->isImportLibrary() ? 0
859 : COFFHeader->PointerToSymbolTable;
860 if (COFFBigObjHeader)
861 return COFFBigObjHeader->PointerToSymbolTable;
862 llvm_unreachable("no COFF header!")::llvm::llvm_unreachable_internal("no COFF header!", "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Object/COFF.h"
, 862)
;
863 }
864
865 uint32_t getRawNumberOfSymbols() const {
866 if (COFFHeader)
867 return COFFHeader->isImportLibrary() ? 0 : COFFHeader->NumberOfSymbols;
868 if (COFFBigObjHeader)
869 return COFFBigObjHeader->NumberOfSymbols;
870 llvm_unreachable("no COFF header!")::llvm::llvm_unreachable_internal("no COFF header!", "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Object/COFF.h"
, 870)
;
871 }
872
873 uint32_t getNumberOfSymbols() const {
874 if (!SymbolTable16 && !SymbolTable32)
875 return 0;
876 return getRawNumberOfSymbols();
877 }
878
879 const coff_load_configuration32 *getLoadConfig32() const {
880 assert(!is64())((!is64()) ? static_cast<void> (0) : __assert_fail ("!is64()"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Object/COFF.h"
, 880, __PRETTY_FUNCTION__))
;
881 return reinterpret_cast<const coff_load_configuration32 *>(LoadConfig);
882 }
883
884 const coff_load_configuration64 *getLoadConfig64() const {
885 assert(is64())((is64()) ? static_cast<void> (0) : __assert_fail ("is64()"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Object/COFF.h"
, 885, __PRETTY_FUNCTION__))
;
886 return reinterpret_cast<const coff_load_configuration64 *>(LoadConfig);
887 }
888 StringRef getRelocationTypeName(uint16_t Type) const;
889
890protected:
891 void moveSymbolNext(DataRefImpl &Symb) const override;
892 Expected<StringRef> getSymbolName(DataRefImpl Symb) const override;
893 Expected<uint64_t> getSymbolAddress(DataRefImpl Symb) const override;
894 uint32_t getSymbolAlignment(DataRefImpl Symb) const override;
895 uint64_t getSymbolValueImpl(DataRefImpl Symb) const override;
896 uint64_t getCommonSymbolSizeImpl(DataRefImpl Symb) const override;
897 uint32_t getSymbolFlags(DataRefImpl Symb) const override;
898 Expected<SymbolRef::Type> getSymbolType(DataRefImpl Symb) const override;
899 Expected<section_iterator> getSymbolSection(DataRefImpl Symb) const override;
900 void moveSectionNext(DataRefImpl &Sec) const override;
901 std::error_code getSectionName(DataRefImpl Sec,
902 StringRef &Res) const override;
903 uint64_t getSectionAddress(DataRefImpl Sec) const override;
904 uint64_t getSectionIndex(DataRefImpl Sec) const override;
905 uint64_t getSectionSize(DataRefImpl Sec) const override;
906 std::error_code getSectionContents(DataRefImpl Sec,
907 StringRef &Res) const override;
908 uint64_t getSectionAlignment(DataRefImpl Sec) const override;
909 bool isSectionCompressed(DataRefImpl Sec) const override;
910 bool isSectionText(DataRefImpl Sec) const override;
911 bool isSectionData(DataRefImpl Sec) const override;
912 bool isSectionBSS(DataRefImpl Sec) const override;
913 bool isSectionVirtual(DataRefImpl Sec) const override;
914 relocation_iterator section_rel_begin(DataRefImpl Sec) const override;
915 relocation_iterator section_rel_end(DataRefImpl Sec) const override;
916
917 void moveRelocationNext(DataRefImpl &Rel) const override;
918 uint64_t getRelocationOffset(DataRefImpl Rel) const override;
919 symbol_iterator getRelocationSymbol(DataRefImpl Rel) const override;
920 uint64_t getRelocationType(DataRefImpl Rel) const override;
921 void getRelocationTypeName(DataRefImpl Rel,
922 SmallVectorImpl<char> &Result) const override;
923
924public:
925 COFFObjectFile(MemoryBufferRef Object, std::error_code &EC);
926
927 basic_symbol_iterator symbol_begin() const override;
928 basic_symbol_iterator symbol_end() const override;
929 section_iterator section_begin() const override;
930 section_iterator section_end() const override;
931
932 const coff_section *getCOFFSection(const SectionRef &Section) const;
933 COFFSymbolRef getCOFFSymbol(const DataRefImpl &Ref) const;
934 COFFSymbolRef getCOFFSymbol(const SymbolRef &Symbol) const;
935 const coff_relocation *getCOFFRelocation(const RelocationRef &Reloc) const;
936 unsigned getSectionID(SectionRef Sec) const;
937 unsigned getSymbolSectionID(SymbolRef Sym) const;
938
939 uint8_t getBytesInAddress() const override;
940 StringRef getFileFormatName() const override;
941 Triple::ArchType getArch() const override;
942 Expected<uint64_t> getStartAddress() const override;
943 SubtargetFeatures getFeatures() const override { return SubtargetFeatures(); }
944
945 import_directory_iterator import_directory_begin() const;
946 import_directory_iterator import_directory_end() const;
947 delay_import_directory_iterator delay_import_directory_begin() const;
948 delay_import_directory_iterator delay_import_directory_end() const;
949 export_directory_iterator export_directory_begin() const;
950 export_directory_iterator export_directory_end() const;
951 base_reloc_iterator base_reloc_begin() const;
952 base_reloc_iterator base_reloc_end() const;
953 const debug_directory *debug_directory_begin() const {
954 return DebugDirectoryBegin;
955 }
956 const debug_directory *debug_directory_end() const {
957 return DebugDirectoryEnd;
958 }
959
960 iterator_range<import_directory_iterator> import_directories() const;
961 iterator_range<delay_import_directory_iterator>
962 delay_import_directories() const;
963 iterator_range<export_directory_iterator> export_directories() const;
964 iterator_range<base_reloc_iterator> base_relocs() const;
965 iterator_range<const debug_directory *> debug_directories() const {
966 return make_range(debug_directory_begin(), debug_directory_end());
967 }
968
969 const dos_header *getDOSHeader() const {
970 if (!PE32Header && !PE32PlusHeader)
971 return nullptr;
972 return reinterpret_cast<const dos_header *>(base());
973 }
974 std::error_code getPE32Header(const pe32_header *&Res) const;
975 std::error_code getPE32PlusHeader(const pe32plus_header *&Res) const;
976 std::error_code getDataDirectory(uint32_t index,
977 const data_directory *&Res) const;
978 std::error_code getSection(int32_t index, const coff_section *&Res) const;
979 std::error_code getSection(StringRef SectionName,
980 const coff_section *&Res) const;
981
982 template <typename coff_symbol_type>
983 std::error_code getSymbol(uint32_t Index,
984 const coff_symbol_type *&Res) const {
985 if (Index >= getNumberOfSymbols())
986 return object_error::parse_failed;
987
988 Res = reinterpret_cast<coff_symbol_type *>(getSymbolTable()) + Index;
989 return std::error_code();
990 }
991 Expected<COFFSymbolRef> getSymbol(uint32_t index) const {
992 if (SymbolTable16) {
993 const coff_symbol16 *Symb = nullptr;
994 if (std::error_code EC = getSymbol(index, Symb))
995 return errorCodeToError(EC);
996 return COFFSymbolRef(Symb);
997 }
998 if (SymbolTable32) {
999 const coff_symbol32 *Symb = nullptr;
1000 if (std::error_code EC = getSymbol(index, Symb))
1001 return errorCodeToError(EC);
1002 return COFFSymbolRef(Symb);
1003 }
1004 return errorCodeToError(object_error::parse_failed);
1005 }
1006
1007 template <typename T>
1008 std::error_code getAuxSymbol(uint32_t index, const T *&Res) const {
1009 Expected<COFFSymbolRef> S = getSymbol(index);
1010 if (Error E = S.takeError())
10
Taking true branch
1011 return errorToErrorCode(std::move(E));
11
Returning without writing to 'Res'
1012 Res = reinterpret_cast<const T *>(S->getRawPtr());
1013 return std::error_code();
1014 }
1015
1016 std::error_code getSymbolName(COFFSymbolRef Symbol, StringRef &Res) const;
1017 std::error_code getSymbolName(const coff_symbol_generic *Symbol,
1018 StringRef &Res) const;
1019
1020 ArrayRef<uint8_t> getSymbolAuxData(COFFSymbolRef Symbol) const;
1021
1022 size_t getSymbolTableEntrySize() const {
1023 if (COFFHeader)
1024 return sizeof(coff_symbol16);
1025 if (COFFBigObjHeader)
1026 return sizeof(coff_symbol32);
1027 llvm_unreachable("null symbol table pointer!")::llvm::llvm_unreachable_internal("null symbol table pointer!"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Object/COFF.h"
, 1027)
;
1028 }
1029
1030 ArrayRef<coff_relocation> getRelocations(const coff_section *Sec) const;
1031
1032 std::error_code getSectionName(const coff_section *Sec, StringRef &Res) const;
1033 uint64_t getSectionSize(const coff_section *Sec) const;
1034 std::error_code getSectionContents(const coff_section *Sec,
1035 ArrayRef<uint8_t> &Res) const;
1036
1037 uint64_t getImageBase() const;
1038 std::error_code getVaPtr(uint64_t VA, uintptr_t &Res) const;
1039 std::error_code getRvaPtr(uint32_t Rva, uintptr_t &Res) const;
1040
1041 /// Given an RVA base and size, returns a valid array of bytes or an error
1042 /// code if the RVA and size is not contained completely within a valid
1043 /// section.
1044 std::error_code getRvaAndSizeAsBytes(uint32_t RVA, uint32_t Size,
1045 ArrayRef<uint8_t> &Contents) const;
1046
1047 std::error_code getHintName(uint32_t Rva, uint16_t &Hint,
1048 StringRef &Name) const;
1049
1050 /// Get PDB information out of a codeview debug directory entry.
1051 std::error_code getDebugPDBInfo(const debug_directory *DebugDir,
1052 const codeview::DebugInfo *&Info,
1053 StringRef &PDBFileName) const;
1054
1055 /// Get PDB information from an executable. If the information is not present,
1056 /// Info will be set to nullptr and PDBFileName will be empty. An error is
1057 /// returned only on corrupt object files. Convenience accessor that can be
1058 /// used if the debug directory is not already handy.
1059 std::error_code getDebugPDBInfo(const codeview::DebugInfo *&Info,
1060 StringRef &PDBFileName) const;
1061
1062 bool isRelocatableObject() const override;
1063 bool is64() const { return PE32PlusHeader; }
1064
1065 static bool classof(const Binary *v) { return v->isCOFF(); }
1066};
1067
1068// The iterator for the import directory table.
1069class ImportDirectoryEntryRef {
1070public:
1071 ImportDirectoryEntryRef() = default;
1072 ImportDirectoryEntryRef(const coff_import_directory_table_entry *Table,
1073 uint32_t I, const COFFObjectFile *Owner)
1074 : ImportTable(Table), Index(I), OwningObject(Owner) {}
1075
1076 bool operator==(const ImportDirectoryEntryRef &Other) const;
1077 void moveNext();
1078
1079 imported_symbol_iterator imported_symbol_begin() const;
1080 imported_symbol_iterator imported_symbol_end() const;
1081 iterator_range<imported_symbol_iterator> imported_symbols() const;
1082
1083 imported_symbol_iterator lookup_table_begin() const;
1084 imported_symbol_iterator lookup_table_end() const;
1085 iterator_range<imported_symbol_iterator> lookup_table_symbols() const;
1086
1087 std::error_code getName(StringRef &Result) const;
1088 std::error_code getImportLookupTableRVA(uint32_t &Result) const;
1089 std::error_code getImportAddressTableRVA(uint32_t &Result) const;
1090
1091 std::error_code
1092 getImportTableEntry(const coff_import_directory_table_entry *&Result) const;
1093
1094private:
1095 const coff_import_directory_table_entry *ImportTable;
1096 uint32_t Index;
1097 const COFFObjectFile *OwningObject = nullptr;
1098};
1099
1100class DelayImportDirectoryEntryRef {
1101public:
1102 DelayImportDirectoryEntryRef() = default;
1103 DelayImportDirectoryEntryRef(const delay_import_directory_table_entry *T,
1104 uint32_t I, const COFFObjectFile *Owner)
1105 : Table(T), Index(I), OwningObject(Owner) {}
1106
1107 bool operator==(const DelayImportDirectoryEntryRef &Other) const;
1108 void moveNext();
1109
1110 imported_symbol_iterator imported_symbol_begin() const;
1111 imported_symbol_iterator imported_symbol_end() const;
1112 iterator_range<imported_symbol_iterator> imported_symbols() const;
1113
1114 std::error_code getName(StringRef &Result) const;
1115 std::error_code getDelayImportTable(
1116 const delay_import_directory_table_entry *&Result) const;
1117 std::error_code getImportAddress(int AddrIndex, uint64_t &Result) const;
1118
1119private:
1120 const delay_import_directory_table_entry *Table;
1121 uint32_t Index;
1122 const COFFObjectFile *OwningObject = nullptr;
1123};
1124
1125// The iterator for the export directory table entry.
1126class ExportDirectoryEntryRef {
1127public:
1128 ExportDirectoryEntryRef() = default;
1129 ExportDirectoryEntryRef(const export_directory_table_entry *Table, uint32_t I,
1130 const COFFObjectFile *Owner)
1131 : ExportTable(Table), Index(I), OwningObject(Owner) {}
1132
1133 bool operator==(const ExportDirectoryEntryRef &Other) const;
1134 void moveNext();
1135
1136 std::error_code getDllName(StringRef &Result) const;
1137 std::error_code getOrdinalBase(uint32_t &Result) const;
1138 std::error_code getOrdinal(uint32_t &Result) const;
1139 std::error_code getExportRVA(uint32_t &Result) const;
1140 std::error_code getSymbolName(StringRef &Result) const;
1141
1142 std::error_code isForwarder(bool &Result) const;
1143 std::error_code getForwardTo(StringRef &Result) const;
1144
1145private:
1146 const export_directory_table_entry *ExportTable;
1147 uint32_t Index;
1148 const COFFObjectFile *OwningObject = nullptr;
1149};
1150
1151class ImportedSymbolRef {
1152public:
1153 ImportedSymbolRef() = default;
1154 ImportedSymbolRef(const import_lookup_table_entry32 *Entry, uint32_t I,
1155 const COFFObjectFile *Owner)
1156 : Entry32(Entry), Entry64(nullptr), Index(I), OwningObject(Owner) {}
1157 ImportedSymbolRef(const import_lookup_table_entry64 *Entry, uint32_t I,
1158 const COFFObjectFile *Owner)
1159 : Entry32(nullptr), Entry64(Entry), Index(I), OwningObject(Owner) {}
1160
1161 bool operator==(const ImportedSymbolRef &Other) const;
1162 void moveNext();
1163
1164 std::error_code getSymbolName(StringRef &Result) const;
1165 std::error_code isOrdinal(bool &Result) const;
1166 std::error_code getOrdinal(uint16_t &Result) const;
1167 std::error_code getHintNameRVA(uint32_t &Result) const;
1168
1169private:
1170 const import_lookup_table_entry32 *Entry32;
1171 const import_lookup_table_entry64 *Entry64;
1172 uint32_t Index;
1173 const COFFObjectFile *OwningObject = nullptr;
1174};
1175
1176class BaseRelocRef {
1177public:
1178 BaseRelocRef() = default;
1179 BaseRelocRef(const coff_base_reloc_block_header *Header,
1180 const COFFObjectFile *Owner)
1181 : Header(Header), Index(0) {}
1182
1183 bool operator==(const BaseRelocRef &Other) const;
1184 void moveNext();
1185
1186 std::error_code getType(uint8_t &Type) const;
1187 std::error_code getRVA(uint32_t &Result) const;
1188
1189private:
1190 const coff_base_reloc_block_header *Header;
1191 uint32_t Index;
1192};
1193
1194class ResourceSectionRef {
1195public:
1196 ResourceSectionRef() = default;
1197 explicit ResourceSectionRef(StringRef Ref) : BBS(Ref, support::little) {}
1198
1199 Expected<ArrayRef<UTF16>>
1200 getEntryNameString(const coff_resource_dir_entry &Entry);
1201 Expected<const coff_resource_dir_table &>
1202 getEntrySubDir(const coff_resource_dir_entry &Entry);
1203 Expected<const coff_resource_dir_table &> getBaseTable();
1204
1205private:
1206 BinaryByteStream BBS;
1207
1208 Expected<const coff_resource_dir_table &> getTableAtOffset(uint32_t Offset);
1209 Expected<ArrayRef<UTF16>> getDirStringAtOffset(uint32_t Offset);
1210};
1211
1212// Corresponds to `_FPO_DATA` structure in the PE/COFF spec.
1213struct FpoData {
1214 support::ulittle32_t Offset; // ulOffStart: Offset 1st byte of function code
1215 support::ulittle32_t Size; // cbProcSize: # bytes in function
1216 support::ulittle32_t NumLocals; // cdwLocals: # bytes in locals/4
1217 support::ulittle16_t NumParams; // cdwParams: # bytes in params/4
1218 support::ulittle16_t Attributes;
1219
1220 // cbProlog: # bytes in prolog
1221 int getPrologSize() const { return Attributes & 0xF; }
1222
1223 // cbRegs: # regs saved
1224 int getNumSavedRegs() const { return (Attributes >> 8) & 0x7; }
1225
1226 // fHasSEH: true if seh is func
1227 bool hasSEH() const { return (Attributes >> 9) & 1; }
1228
1229 // fUseBP: true if EBP has been allocated
1230 bool useBP() const { return (Attributes >> 10) & 1; }
1231
1232 // cbFrame: frame pointer
1233 frame_type getFP() const { return static_cast<frame_type>(Attributes >> 14); }
1234};
1235
1236} // end namespace object
1237
1238} // end namespace llvm
1239
1240#endif // LLVM_OBJECT_COFF_H