Bug Summary

File:tools/llvm-objdump/COFFDump.cpp
Warning:line 685, column 58
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-eagerly-assume -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-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/tools/llvm-objdump -I /build/llvm-toolchain-snapshot-7~svn338205/tools/llvm-objdump -I /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn338205/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/x86_64-linux-gnu/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/x86_64-linux-gnu/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/lib/gcc/x86_64-linux-gnu/8/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-class-memaccess -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn338205/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-07-29-043837-17923-1 -x c++ /build/llvm-toolchain-snapshot-7~svn338205/tools/llvm-objdump/COFFDump.cpp -faddrsig

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

/build/llvm-toolchain-snapshot-7~svn338205/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!")(static_cast <bool> (isOrdinal() && "ILT entry is not an ordinal!"
) ? void (0) : __assert_fail ("isOrdinal() && \"ILT entry is not an ordinal!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/Object/COFF.h"
, 196, __extension__ __PRETTY_FUNCTION__))
;
197 return Data & 0xFFFF;
198 }
199
200 uint32_t getHintNameRVA() const {
201 assert(!isOrdinal() && "ILT entry is not a Hint/Name RVA!")(static_cast <bool> (!isOrdinal() && "ILT entry is not a Hint/Name RVA!"
) ? void (0) : __assert_fail ("!isOrdinal() && \"ILT entry is not a Hint/Name RVA!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/Object/COFF.h"
, 201, __extension__ __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-7~svn338205/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!")(static_cast <bool> (isSet() && "COFFSymbolRef points to nothing!"
) ? void (0) : __assert_fail ("isSet() && \"COFFSymbolRef points to nothing!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/Object/COFF.h"
, 314, __extension__ __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!")(static_cast <bool> (isSet() && "COFFSymbolRef points to nothing!"
) ? void (0) : __assert_fail ("isSet() && \"COFFSymbolRef points to nothing!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/Object/COFF.h"
, 321, __extension__ __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!")(static_cast <bool> (isSet() && "COFFSymbolRef points to nothing!"
) ? void (0) : __assert_fail ("isSet() && \"COFFSymbolRef points to nothing!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/Object/COFF.h"
, 332, __extension__ __PRETTY_FUNCTION__))
;
333 return CS16 ? CS16->Type : CS32->Type;
334 }
335
336 uint8_t getStorageClass() const {
337 assert(isSet() && "COFFSymbolRef points to nothing!")(static_cast <bool> (isSet() && "COFFSymbolRef points to nothing!"
) ? void (0) : __assert_fail ("isSet() && \"COFFSymbolRef points to nothing!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/Object/COFF.h"
, 337, __extension__ __PRETTY_FUNCTION__))
;
338 return CS16 ? CS16->StorageClass : CS32->StorageClass;
339 }
340
341 uint8_t getNumberOfAuxSymbols() const {
342 assert(isSet() && "COFFSymbolRef points to nothing!")(static_cast <bool> (isSet() && "COFFSymbolRef points to nothing!"
) ? void (0) : __assert_fail ("isSet() && \"COFFSymbolRef points to nothing!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/Object/COFF.h"
, 342, __extension__ __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
597struct coff_load_config_code_integrity {
598 support::ulittle16_t Flags;
599 support::ulittle16_t Catalog;
600 support::ulittle32_t CatalogOffset;
601 support::ulittle32_t Reserved;
602};
603
604/// 32-bit load config (IMAGE_LOAD_CONFIG_DIRECTORY32)
605struct coff_load_configuration32 {
606 support::ulittle32_t Size;
607 support::ulittle32_t TimeDateStamp;
608 support::ulittle16_t MajorVersion;
609 support::ulittle16_t MinorVersion;
610 support::ulittle32_t GlobalFlagsClear;
611 support::ulittle32_t GlobalFlagsSet;
612 support::ulittle32_t CriticalSectionDefaultTimeout;
613 support::ulittle32_t DeCommitFreeBlockThreshold;
614 support::ulittle32_t DeCommitTotalFreeThreshold;
615 support::ulittle32_t LockPrefixTable;
616 support::ulittle32_t MaximumAllocationSize;
617 support::ulittle32_t VirtualMemoryThreshold;
618 support::ulittle32_t ProcessAffinityMask;
619 support::ulittle32_t ProcessHeapFlags;
620 support::ulittle16_t CSDVersion;
621 support::ulittle16_t DependentLoadFlags;
622 support::ulittle32_t EditList;
623 support::ulittle32_t SecurityCookie;
624 support::ulittle32_t SEHandlerTable;
625 support::ulittle32_t SEHandlerCount;
626
627 // Added in MSVC 2015 for /guard:cf.
628 support::ulittle32_t GuardCFCheckFunction;
629 support::ulittle32_t GuardCFCheckDispatch;
630 support::ulittle32_t GuardCFFunctionTable;
631 support::ulittle32_t GuardCFFunctionCount;
632 support::ulittle32_t GuardFlags; // coff_guard_flags
633
634 // Added in MSVC 2017
635 coff_load_config_code_integrity CodeIntegrity;
636 support::ulittle32_t GuardAddressTakenIatEntryTable;
637 support::ulittle32_t GuardAddressTakenIatEntryCount;
638 support::ulittle32_t GuardLongJumpTargetTable;
639 support::ulittle32_t GuardLongJumpTargetCount;
640 support::ulittle32_t DynamicValueRelocTable;
641 support::ulittle32_t CHPEMetadataPointer;
642 support::ulittle32_t GuardRFFailureRoutine;
643 support::ulittle32_t GuardRFFailureRoutineFunctionPointer;
644 support::ulittle32_t DynamicValueRelocTableOffset;
645 support::ulittle16_t DynamicValueRelocTableSection;
646 support::ulittle16_t Reserved2;
647 support::ulittle32_t GuardRFVerifyStackPointerFunctionPointer;
648 support::ulittle32_t HotPatchTableOffset;
649};
650
651/// 64-bit load config (IMAGE_LOAD_CONFIG_DIRECTORY64)
652struct coff_load_configuration64 {
653 support::ulittle32_t Size;
654 support::ulittle32_t TimeDateStamp;
655 support::ulittle16_t MajorVersion;
656 support::ulittle16_t MinorVersion;
657 support::ulittle32_t GlobalFlagsClear;
658 support::ulittle32_t GlobalFlagsSet;
659 support::ulittle32_t CriticalSectionDefaultTimeout;
660 support::ulittle64_t DeCommitFreeBlockThreshold;
661 support::ulittle64_t DeCommitTotalFreeThreshold;
662 support::ulittle64_t LockPrefixTable;
663 support::ulittle64_t MaximumAllocationSize;
664 support::ulittle64_t VirtualMemoryThreshold;
665 support::ulittle64_t ProcessAffinityMask;
666 support::ulittle32_t ProcessHeapFlags;
667 support::ulittle16_t CSDVersion;
668 support::ulittle16_t DependentLoadFlags;
669 support::ulittle64_t EditList;
670 support::ulittle64_t SecurityCookie;
671 support::ulittle64_t SEHandlerTable;
672 support::ulittle64_t SEHandlerCount;
673
674 // Added in MSVC 2015 for /guard:cf.
675 support::ulittle64_t GuardCFCheckFunction;
676 support::ulittle64_t GuardCFCheckDispatch;
677 support::ulittle64_t GuardCFFunctionTable;
678 support::ulittle64_t GuardCFFunctionCount;
679 support::ulittle32_t GuardFlags;
680
681 // Added in MSVC 2017
682 coff_load_config_code_integrity CodeIntegrity;
683 support::ulittle64_t GuardAddressTakenIatEntryTable;
684 support::ulittle64_t GuardAddressTakenIatEntryCount;
685 support::ulittle64_t GuardLongJumpTargetTable;
686 support::ulittle64_t GuardLongJumpTargetCount;
687 support::ulittle64_t DynamicValueRelocTable;
688 support::ulittle64_t CHPEMetadataPointer;
689 support::ulittle64_t GuardRFFailureRoutine;
690 support::ulittle64_t GuardRFFailureRoutineFunctionPointer;
691 support::ulittle32_t DynamicValueRelocTableOffset;
692 support::ulittle16_t DynamicValueRelocTableSection;
693 support::ulittle16_t Reserved2;
694 support::ulittle64_t GuardRFVerifyStackPointerFunctionPointer;
695 support::ulittle32_t HotPatchTableOffset;
696};
697
698struct coff_runtime_function_x64 {
699 support::ulittle32_t BeginAddress;
700 support::ulittle32_t EndAddress;
701 support::ulittle32_t UnwindInformation;
702};
703
704struct coff_base_reloc_block_header {
705 support::ulittle32_t PageRVA;
706 support::ulittle32_t BlockSize;
707};
708
709struct coff_base_reloc_block_entry {
710 support::ulittle16_t Data;
711
712 int getType() const { return Data >> 12; }
713 int getOffset() const { return Data & ((1 << 12) - 1); }
714};
715
716struct coff_resource_dir_entry {
717 union {
718 support::ulittle32_t NameOffset;
719 support::ulittle32_t ID;
720 uint32_t getNameOffset() const {
721 return maskTrailingOnes<uint32_t>(31) & NameOffset;
722 }
723 // Even though the PE/COFF spec doesn't mention this, the high bit of a name
724 // offset is set.
725 void setNameOffset(uint32_t Offset) { NameOffset = Offset | (1 << 31); }
726 } Identifier;
727 union {
728 support::ulittle32_t DataEntryOffset;
729 support::ulittle32_t SubdirOffset;
730
731 bool isSubDir() const { return SubdirOffset >> 31; }
732 uint32_t value() const {
733 return maskTrailingOnes<uint32_t>(31) & SubdirOffset;
734 }
735
736 } Offset;
737};
738
739struct coff_resource_data_entry {
740 support::ulittle32_t DataRVA;
741 support::ulittle32_t DataSize;
742 support::ulittle32_t Codepage;
743 support::ulittle32_t Reserved;
744};
745
746struct coff_resource_dir_table {
747 support::ulittle32_t Characteristics;
748 support::ulittle32_t TimeDateStamp;
749 support::ulittle16_t MajorVersion;
750 support::ulittle16_t MinorVersion;
751 support::ulittle16_t NumberOfNameEntries;
752 support::ulittle16_t NumberOfIDEntries;
753};
754
755struct debug_h_header {
756 support::ulittle32_t Magic;
757 support::ulittle16_t Version;
758 support::ulittle16_t HashAlgorithm;
759};
760
761class COFFObjectFile : public ObjectFile {
762private:
763 friend class ImportDirectoryEntryRef;
764 friend class ExportDirectoryEntryRef;
765 const coff_file_header *COFFHeader;
766 const coff_bigobj_file_header *COFFBigObjHeader;
767 const pe32_header *PE32Header;
768 const pe32plus_header *PE32PlusHeader;
769 const data_directory *DataDirectory;
770 const coff_section *SectionTable;
771 const coff_symbol16 *SymbolTable16;
772 const coff_symbol32 *SymbolTable32;
773 const char *StringTable;
774 uint32_t StringTableSize;
775 const coff_import_directory_table_entry *ImportDirectory;
776 const delay_import_directory_table_entry *DelayImportDirectory;
777 uint32_t NumberOfDelayImportDirectory;
778 const export_directory_table_entry *ExportDirectory;
779 const coff_base_reloc_block_header *BaseRelocHeader;
780 const coff_base_reloc_block_header *BaseRelocEnd;
781 const debug_directory *DebugDirectoryBegin;
782 const debug_directory *DebugDirectoryEnd;
783 // Either coff_load_configuration32 or coff_load_configuration64.
784 const void *LoadConfig = nullptr;
785
786 std::error_code getString(uint32_t offset, StringRef &Res) const;
787
788 template <typename coff_symbol_type>
789 const coff_symbol_type *toSymb(DataRefImpl Symb) const;
790 const coff_section *toSec(DataRefImpl Sec) const;
791 const coff_relocation *toRel(DataRefImpl Rel) const;
792
793 std::error_code initSymbolTablePtr();
794 std::error_code initImportTablePtr();
795 std::error_code initDelayImportTablePtr();
796 std::error_code initExportTablePtr();
797 std::error_code initBaseRelocPtr();
798 std::error_code initDebugDirectoryPtr();
799 std::error_code initLoadConfigPtr();
800
801public:
802 uintptr_t getSymbolTable() const {
803 if (SymbolTable16)
804 return reinterpret_cast<uintptr_t>(SymbolTable16);
805 if (SymbolTable32)
806 return reinterpret_cast<uintptr_t>(SymbolTable32);
807 return uintptr_t(0);
808 }
809
810 uint16_t getMachine() const {
811 if (COFFHeader)
812 return COFFHeader->Machine;
813 if (COFFBigObjHeader)
814 return COFFBigObjHeader->Machine;
815 llvm_unreachable("no COFF header!")::llvm::llvm_unreachable_internal("no COFF header!", "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/Object/COFF.h"
, 815)
;
816 }
817
818 uint16_t getSizeOfOptionalHeader() const {
819 if (COFFHeader)
820 return COFFHeader->isImportLibrary() ? 0
821 : COFFHeader->SizeOfOptionalHeader;
822 // bigobj doesn't have this field.
823 if (COFFBigObjHeader)
824 return 0;
825 llvm_unreachable("no COFF header!")::llvm::llvm_unreachable_internal("no COFF header!", "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/Object/COFF.h"
, 825)
;
826 }
827
828 uint16_t getCharacteristics() const {
829 if (COFFHeader)
830 return COFFHeader->isImportLibrary() ? 0 : COFFHeader->Characteristics;
831 // bigobj doesn't have characteristics to speak of,
832 // editbin will silently lie to you if you attempt to set any.
833 if (COFFBigObjHeader)
834 return 0;
835 llvm_unreachable("no COFF header!")::llvm::llvm_unreachable_internal("no COFF header!", "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/Object/COFF.h"
, 835)
;
836 }
837
838 uint32_t getTimeDateStamp() const {
839 if (COFFHeader)
840 return COFFHeader->TimeDateStamp;
841 if (COFFBigObjHeader)
842 return COFFBigObjHeader->TimeDateStamp;
843 llvm_unreachable("no COFF header!")::llvm::llvm_unreachable_internal("no COFF header!", "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/Object/COFF.h"
, 843)
;
844 }
845
846 uint32_t getNumberOfSections() const {
847 if (COFFHeader)
848 return COFFHeader->isImportLibrary() ? 0 : COFFHeader->NumberOfSections;
849 if (COFFBigObjHeader)
850 return COFFBigObjHeader->NumberOfSections;
851 llvm_unreachable("no COFF header!")::llvm::llvm_unreachable_internal("no COFF header!", "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/Object/COFF.h"
, 851)
;
852 }
853
854 uint32_t getPointerToSymbolTable() const {
855 if (COFFHeader)
856 return COFFHeader->isImportLibrary() ? 0
857 : COFFHeader->PointerToSymbolTable;
858 if (COFFBigObjHeader)
859 return COFFBigObjHeader->PointerToSymbolTable;
860 llvm_unreachable("no COFF header!")::llvm::llvm_unreachable_internal("no COFF header!", "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/Object/COFF.h"
, 860)
;
861 }
862
863 uint32_t getRawNumberOfSymbols() const {
864 if (COFFHeader)
865 return COFFHeader->isImportLibrary() ? 0 : COFFHeader->NumberOfSymbols;
866 if (COFFBigObjHeader)
867 return COFFBigObjHeader->NumberOfSymbols;
868 llvm_unreachable("no COFF header!")::llvm::llvm_unreachable_internal("no COFF header!", "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/Object/COFF.h"
, 868)
;
869 }
870
871 uint32_t getNumberOfSymbols() const {
872 if (!SymbolTable16 && !SymbolTable32)
873 return 0;
874 return getRawNumberOfSymbols();
875 }
876
877 const coff_load_configuration32 *getLoadConfig32() const {
878 assert(!is64())(static_cast <bool> (!is64()) ? void (0) : __assert_fail
("!is64()", "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/Object/COFF.h"
, 878, __extension__ __PRETTY_FUNCTION__))
;
879 return reinterpret_cast<const coff_load_configuration32 *>(LoadConfig);
880 }
881
882 const coff_load_configuration64 *getLoadConfig64() const {
883 assert(is64())(static_cast <bool> (is64()) ? void (0) : __assert_fail
("is64()", "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/Object/COFF.h"
, 883, __extension__ __PRETTY_FUNCTION__))
;
884 return reinterpret_cast<const coff_load_configuration64 *>(LoadConfig);
885 }
886
887protected:
888 void moveSymbolNext(DataRefImpl &Symb) const override;
889 Expected<StringRef> getSymbolName(DataRefImpl Symb) const override;
890 Expected<uint64_t> getSymbolAddress(DataRefImpl Symb) const override;
891 uint32_t getSymbolAlignment(DataRefImpl Symb) const override;
892 uint64_t getSymbolValueImpl(DataRefImpl Symb) const override;
893 uint64_t getCommonSymbolSizeImpl(DataRefImpl Symb) const override;
894 uint32_t getSymbolFlags(DataRefImpl Symb) const override;
895 Expected<SymbolRef::Type> getSymbolType(DataRefImpl Symb) const override;
896 Expected<section_iterator> getSymbolSection(DataRefImpl Symb) const override;
897 void moveSectionNext(DataRefImpl &Sec) const override;
898 std::error_code getSectionName(DataRefImpl Sec,
899 StringRef &Res) const override;
900 uint64_t getSectionAddress(DataRefImpl Sec) const override;
901 uint64_t getSectionIndex(DataRefImpl Sec) const override;
902 uint64_t getSectionSize(DataRefImpl Sec) const override;
903 std::error_code getSectionContents(DataRefImpl Sec,
904 StringRef &Res) const override;
905 uint64_t getSectionAlignment(DataRefImpl Sec) const override;
906 bool isSectionCompressed(DataRefImpl Sec) const override;
907 bool isSectionText(DataRefImpl Sec) const override;
908 bool isSectionData(DataRefImpl Sec) const override;
909 bool isSectionBSS(DataRefImpl Sec) const override;
910 bool isSectionVirtual(DataRefImpl Sec) const override;
911 relocation_iterator section_rel_begin(DataRefImpl Sec) const override;
912 relocation_iterator section_rel_end(DataRefImpl Sec) const override;
913
914 void moveRelocationNext(DataRefImpl &Rel) const override;
915 uint64_t getRelocationOffset(DataRefImpl Rel) const override;
916 symbol_iterator getRelocationSymbol(DataRefImpl Rel) const override;
917 uint64_t getRelocationType(DataRefImpl Rel) const override;
918 void getRelocationTypeName(DataRefImpl Rel,
919 SmallVectorImpl<char> &Result) const override;
920
921public:
922 COFFObjectFile(MemoryBufferRef Object, std::error_code &EC);
923
924 basic_symbol_iterator symbol_begin() const override;
925 basic_symbol_iterator symbol_end() const override;
926 section_iterator section_begin() const override;
927 section_iterator section_end() const override;
928
929 const coff_section *getCOFFSection(const SectionRef &Section) const;
930 COFFSymbolRef getCOFFSymbol(const DataRefImpl &Ref) const;
931 COFFSymbolRef getCOFFSymbol(const SymbolRef &Symbol) const;
932 const coff_relocation *getCOFFRelocation(const RelocationRef &Reloc) const;
933 unsigned getSectionID(SectionRef Sec) const;
934 unsigned getSymbolSectionID(SymbolRef Sym) const;
935
936 uint8_t getBytesInAddress() const override;
937 StringRef getFileFormatName() const override;
938 Triple::ArchType getArch() const override;
939 Expected<uint64_t> getStartAddress() const override;
940 SubtargetFeatures getFeatures() const override { return SubtargetFeatures(); }
941
942 import_directory_iterator import_directory_begin() const;
943 import_directory_iterator import_directory_end() const;
944 delay_import_directory_iterator delay_import_directory_begin() const;
945 delay_import_directory_iterator delay_import_directory_end() const;
946 export_directory_iterator export_directory_begin() const;
947 export_directory_iterator export_directory_end() const;
948 base_reloc_iterator base_reloc_begin() const;
949 base_reloc_iterator base_reloc_end() const;
950 const debug_directory *debug_directory_begin() const {
951 return DebugDirectoryBegin;
952 }
953 const debug_directory *debug_directory_end() const {
954 return DebugDirectoryEnd;
955 }
956
957 iterator_range<import_directory_iterator> import_directories() const;
958 iterator_range<delay_import_directory_iterator>
959 delay_import_directories() const;
960 iterator_range<export_directory_iterator> export_directories() const;
961 iterator_range<base_reloc_iterator> base_relocs() const;
962 iterator_range<const debug_directory *> debug_directories() const {
963 return make_range(debug_directory_begin(), debug_directory_end());
964 }
965
966 const dos_header *getDOSHeader() const {
967 if (!PE32Header && !PE32PlusHeader)
968 return nullptr;
969 return reinterpret_cast<const dos_header *>(base());
970 }
971 std::error_code getPE32Header(const pe32_header *&Res) const;
972 std::error_code getPE32PlusHeader(const pe32plus_header *&Res) const;
973 std::error_code getDataDirectory(uint32_t index,
974 const data_directory *&Res) const;
975 std::error_code getSection(int32_t index, const coff_section *&Res) const;
976 std::error_code getSection(StringRef SectionName,
977 const coff_section *&Res) const;
978
979 template <typename coff_symbol_type>
980 std::error_code getSymbol(uint32_t Index,
981 const coff_symbol_type *&Res) const {
982 if (Index >= getNumberOfSymbols())
983 return object_error::parse_failed;
984
985 Res = reinterpret_cast<coff_symbol_type *>(getSymbolTable()) + Index;
986 return std::error_code();
987 }
988 Expected<COFFSymbolRef> getSymbol(uint32_t index) const {
989 if (SymbolTable16) {
990 const coff_symbol16 *Symb = nullptr;
991 if (std::error_code EC = getSymbol(index, Symb))
992 return errorCodeToError(EC);
993 return COFFSymbolRef(Symb);
994 }
995 if (SymbolTable32) {
996 const coff_symbol32 *Symb = nullptr;
997 if (std::error_code EC = getSymbol(index, Symb))
998 return errorCodeToError(EC);
999 return COFFSymbolRef(Symb);
1000 }
1001 return errorCodeToError(object_error::parse_failed);
1002 }
1003
1004 template <typename T>
1005 std::error_code getAuxSymbol(uint32_t index, const T *&Res) const {
1006 Expected<COFFSymbolRef> S = getSymbol(index);
1007 if (Error E = S.takeError())
10
Taking true branch
1008 return errorToErrorCode(std::move(E));
1009 Res = reinterpret_cast<const T *>(S->getRawPtr());
1010 return std::error_code();
1011 }
11
Returning without writing to 'Res'
1012
1013 std::error_code getSymbolName(COFFSymbolRef Symbol, StringRef &Res) const;
1014 std::error_code getSymbolName(const coff_symbol_generic *Symbol,
1015 StringRef &Res) const;
1016
1017 ArrayRef<uint8_t> getSymbolAuxData(COFFSymbolRef Symbol) const;
1018
1019 size_t getSymbolTableEntrySize() const {
1020 if (COFFHeader)
1021 return sizeof(coff_symbol16);
1022 if (COFFBigObjHeader)
1023 return sizeof(coff_symbol32);
1024 llvm_unreachable("null symbol table pointer!")::llvm::llvm_unreachable_internal("null symbol table pointer!"
, "/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/Object/COFF.h"
, 1024)
;
1025 }
1026
1027 ArrayRef<coff_relocation> getRelocations(const coff_section *Sec) const;
1028
1029 std::error_code getSectionName(const coff_section *Sec, StringRef &Res) const;
1030 uint64_t getSectionSize(const coff_section *Sec) const;
1031 std::error_code getSectionContents(const coff_section *Sec,
1032 ArrayRef<uint8_t> &Res) const;
1033
1034 uint64_t getImageBase() const;
1035 std::error_code getVaPtr(uint64_t VA, uintptr_t &Res) const;
1036 std::error_code getRvaPtr(uint32_t Rva, uintptr_t &Res) const;
1037
1038 /// Given an RVA base and size, returns a valid array of bytes or an error
1039 /// code if the RVA and size is not contained completely within a valid
1040 /// section.
1041 std::error_code getRvaAndSizeAsBytes(uint32_t RVA, uint32_t Size,
1042 ArrayRef<uint8_t> &Contents) const;
1043
1044 std::error_code getHintName(uint32_t Rva, uint16_t &Hint,
1045 StringRef &Name) const;
1046
1047 /// Get PDB information out of a codeview debug directory entry.
1048 std::error_code getDebugPDBInfo(const debug_directory *DebugDir,
1049 const codeview::DebugInfo *&Info,
1050 StringRef &PDBFileName) const;
1051
1052 /// Get PDB information from an executable. If the information is not present,
1053 /// Info will be set to nullptr and PDBFileName will be empty. An error is
1054 /// returned only on corrupt object files. Convenience accessor that can be
1055 /// used if the debug directory is not already handy.
1056 std::error_code getDebugPDBInfo(const codeview::DebugInfo *&Info,
1057 StringRef &PDBFileName) const;
1058
1059 bool isRelocatableObject() const override;
1060 bool is64() const { return PE32PlusHeader; }
1061
1062 static bool classof(const Binary *v) { return v->isCOFF(); }
1063};
1064
1065// The iterator for the import directory table.
1066class ImportDirectoryEntryRef {
1067public:
1068 ImportDirectoryEntryRef() = default;
1069 ImportDirectoryEntryRef(const coff_import_directory_table_entry *Table,
1070 uint32_t I, const COFFObjectFile *Owner)
1071 : ImportTable(Table), Index(I), OwningObject(Owner) {}
1072
1073 bool operator==(const ImportDirectoryEntryRef &Other) const;
1074 void moveNext();
1075
1076 imported_symbol_iterator imported_symbol_begin() const;
1077 imported_symbol_iterator imported_symbol_end() const;
1078 iterator_range<imported_symbol_iterator> imported_symbols() const;
1079
1080 imported_symbol_iterator lookup_table_begin() const;
1081 imported_symbol_iterator lookup_table_end() const;
1082 iterator_range<imported_symbol_iterator> lookup_table_symbols() const;
1083
1084 std::error_code getName(StringRef &Result) const;
1085 std::error_code getImportLookupTableRVA(uint32_t &Result) const;
1086 std::error_code getImportAddressTableRVA(uint32_t &Result) const;
1087
1088 std::error_code
1089 getImportTableEntry(const coff_import_directory_table_entry *&Result) const;
1090
1091private:
1092 const coff_import_directory_table_entry *ImportTable;
1093 uint32_t Index;
1094 const COFFObjectFile *OwningObject = nullptr;
1095};
1096
1097class DelayImportDirectoryEntryRef {
1098public:
1099 DelayImportDirectoryEntryRef() = default;
1100 DelayImportDirectoryEntryRef(const delay_import_directory_table_entry *T,
1101 uint32_t I, const COFFObjectFile *Owner)
1102 : Table(T), Index(I), OwningObject(Owner) {}
1103
1104 bool operator==(const DelayImportDirectoryEntryRef &Other) const;
1105 void moveNext();
1106
1107 imported_symbol_iterator imported_symbol_begin() const;
1108 imported_symbol_iterator imported_symbol_end() const;
1109 iterator_range<imported_symbol_iterator> imported_symbols() const;
1110
1111 std::error_code getName(StringRef &Result) const;
1112 std::error_code getDelayImportTable(
1113 const delay_import_directory_table_entry *&Result) const;
1114 std::error_code getImportAddress(int AddrIndex, uint64_t &Result) const;
1115
1116private:
1117 const delay_import_directory_table_entry *Table;
1118 uint32_t Index;
1119 const COFFObjectFile *OwningObject = nullptr;
1120};
1121
1122// The iterator for the export directory table entry.
1123class ExportDirectoryEntryRef {
1124public:
1125 ExportDirectoryEntryRef() = default;
1126 ExportDirectoryEntryRef(const export_directory_table_entry *Table, uint32_t I,
1127 const COFFObjectFile *Owner)
1128 : ExportTable(Table), Index(I), OwningObject(Owner) {}
1129
1130 bool operator==(const ExportDirectoryEntryRef &Other) const;
1131 void moveNext();
1132
1133 std::error_code getDllName(StringRef &Result) const;
1134 std::error_code getOrdinalBase(uint32_t &Result) const;
1135 std::error_code getOrdinal(uint32_t &Result) const;
1136 std::error_code getExportRVA(uint32_t &Result) const;
1137 std::error_code getSymbolName(StringRef &Result) const;
1138
1139 std::error_code isForwarder(bool &Result) const;
1140 std::error_code getForwardTo(StringRef &Result) const;
1141
1142private:
1143 const export_directory_table_entry *ExportTable;
1144 uint32_t Index;
1145 const COFFObjectFile *OwningObject = nullptr;
1146};
1147
1148class ImportedSymbolRef {
1149public:
1150 ImportedSymbolRef() = default;
1151 ImportedSymbolRef(const import_lookup_table_entry32 *Entry, uint32_t I,
1152 const COFFObjectFile *Owner)
1153 : Entry32(Entry), Entry64(nullptr), Index(I), OwningObject(Owner) {}
1154 ImportedSymbolRef(const import_lookup_table_entry64 *Entry, uint32_t I,
1155 const COFFObjectFile *Owner)
1156 : Entry32(nullptr), Entry64(Entry), Index(I), OwningObject(Owner) {}
1157
1158 bool operator==(const ImportedSymbolRef &Other) const;
1159 void moveNext();
1160
1161 std::error_code getSymbolName(StringRef &Result) const;
1162 std::error_code isOrdinal(bool &Result) const;
1163 std::error_code getOrdinal(uint16_t &Result) const;
1164 std::error_code getHintNameRVA(uint32_t &Result) const;
1165
1166private:
1167 const import_lookup_table_entry32 *Entry32;
1168 const import_lookup_table_entry64 *Entry64;
1169 uint32_t Index;
1170 const COFFObjectFile *OwningObject = nullptr;
1171};
1172
1173class BaseRelocRef {
1174public:
1175 BaseRelocRef() = default;
1176 BaseRelocRef(const coff_base_reloc_block_header *Header,
1177 const COFFObjectFile *Owner)
1178 : Header(Header), Index(0) {}
1179
1180 bool operator==(const BaseRelocRef &Other) const;
1181 void moveNext();
1182
1183 std::error_code getType(uint8_t &Type) const;
1184 std::error_code getRVA(uint32_t &Result) const;
1185
1186private:
1187 const coff_base_reloc_block_header *Header;
1188 uint32_t Index;
1189};
1190
1191class ResourceSectionRef {
1192public:
1193 ResourceSectionRef() = default;
1194 explicit ResourceSectionRef(StringRef Ref) : BBS(Ref, support::little) {}
1195
1196 Expected<ArrayRef<UTF16>>
1197 getEntryNameString(const coff_resource_dir_entry &Entry);
1198 Expected<const coff_resource_dir_table &>
1199 getEntrySubDir(const coff_resource_dir_entry &Entry);
1200 Expected<const coff_resource_dir_table &> getBaseTable();
1201
1202private:
1203 BinaryByteStream BBS;
1204
1205 Expected<const coff_resource_dir_table &> getTableAtOffset(uint32_t Offset);
1206 Expected<ArrayRef<UTF16>> getDirStringAtOffset(uint32_t Offset);
1207};
1208
1209// Corresponds to `_FPO_DATA` structure in the PE/COFF spec.
1210struct FpoData {
1211 support::ulittle32_t Offset; // ulOffStart: Offset 1st byte of function code
1212 support::ulittle32_t Size; // cbProcSize: # bytes in function
1213 support::ulittle32_t NumLocals; // cdwLocals: # bytes in locals/4
1214 support::ulittle16_t NumParams; // cdwParams: # bytes in params/4
1215 support::ulittle16_t Attributes;
1216
1217 // cbProlog: # bytes in prolog
1218 int getPrologSize() const { return Attributes & 0xF; }
1219
1220 // cbRegs: # regs saved
1221 int getNumSavedRegs() const { return (Attributes >> 8) & 0x7; }
1222
1223 // fHasSEH: true if seh is func
1224 bool hasSEH() const { return (Attributes >> 9) & 1; }
1225
1226 // fUseBP: true if EBP has been allocated
1227 bool useBP() const { return (Attributes >> 10) & 1; }
1228
1229 // cbFrame: frame pointer
1230 int getFP() const { return Attributes >> 14; }
1231};
1232
1233} // end namespace object
1234
1235} // end namespace llvm
1236
1237#endif // LLVM_OBJECT_COFF_H