Bug Summary

File:include/llvm/Object/COFF.h
Warning:line 318, column 38
Called C++ object pointer is null

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 COFFObjectFile.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/lib/Object -I /build/llvm-toolchain-snapshot-7~svn338205/lib/Object -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/lib/Object -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/lib/Object/COFFObjectFile.cpp -faddrsig

/build/llvm-toolchain-snapshot-7~svn338205/lib/Object/COFFObjectFile.cpp

1//===- COFFObjectFile.cpp - COFF object file implementation ---------------===//
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#include "llvm/ADT/ArrayRef.h"
15#include "llvm/ADT/StringRef.h"
16#include "llvm/ADT/Triple.h"
17#include "llvm/ADT/iterator_range.h"
18#include "llvm/BinaryFormat/COFF.h"
19#include "llvm/Object/Binary.h"
20#include "llvm/Object/COFF.h"
21#include "llvm/Object/Error.h"
22#include "llvm/Object/ObjectFile.h"
23#include "llvm/Support/BinaryStreamReader.h"
24#include "llvm/Support/Endian.h"
25#include "llvm/Support/Error.h"
26#include "llvm/Support/ErrorHandling.h"
27#include "llvm/Support/MathExtras.h"
28#include "llvm/Support/MemoryBuffer.h"
29#include <algorithm>
30#include <cassert>
31#include <cstddef>
32#include <cstdint>
33#include <cstring>
34#include <limits>
35#include <memory>
36#include <system_error>
37
38using namespace llvm;
39using namespace object;
40
41using support::ulittle16_t;
42using support::ulittle32_t;
43using support::ulittle64_t;
44using support::little16_t;
45
46// Returns false if size is greater than the buffer size. And sets ec.
47static bool checkSize(MemoryBufferRef M, std::error_code &EC, uint64_t Size) {
48 if (M.getBufferSize() < Size) {
49 EC = object_error::unexpected_eof;
50 return false;
51 }
52 return true;
53}
54
55// Sets Obj unless any bytes in [addr, addr + size) fall outsize of m.
56// Returns unexpected_eof if error.
57template <typename T>
58static std::error_code getObject(const T *&Obj, MemoryBufferRef M,
59 const void *Ptr,
60 const uint64_t Size = sizeof(T)) {
61 uintptr_t Addr = uintptr_t(Ptr);
62 if (std::error_code EC = Binary::checkOffset(M, Addr, Size))
63 return EC;
64 Obj = reinterpret_cast<const T *>(Addr);
65 return std::error_code();
66}
67
68// Decode a string table entry in base 64 (//AAAAAA). Expects \arg Str without
69// prefixed slashes.
70static bool decodeBase64StringEntry(StringRef Str, uint32_t &Result) {
71 assert(Str.size() <= 6 && "String too long, possible overflow.")(static_cast <bool> (Str.size() <= 6 && "String too long, possible overflow."
) ? void (0) : __assert_fail ("Str.size() <= 6 && \"String too long, possible overflow.\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Object/COFFObjectFile.cpp"
, 71, __extension__ __PRETTY_FUNCTION__))
;
72 if (Str.size() > 6)
73 return true;
74
75 uint64_t Value = 0;
76 while (!Str.empty()) {
77 unsigned CharVal;
78 if (Str[0] >= 'A' && Str[0] <= 'Z') // 0..25
79 CharVal = Str[0] - 'A';
80 else if (Str[0] >= 'a' && Str[0] <= 'z') // 26..51
81 CharVal = Str[0] - 'a' + 26;
82 else if (Str[0] >= '0' && Str[0] <= '9') // 52..61
83 CharVal = Str[0] - '0' + 52;
84 else if (Str[0] == '+') // 62
85 CharVal = 62;
86 else if (Str[0] == '/') // 63
87 CharVal = 63;
88 else
89 return true;
90
91 Value = (Value * 64) + CharVal;
92 Str = Str.substr(1);
93 }
94
95 if (Value > std::numeric_limits<uint32_t>::max())
96 return true;
97
98 Result = static_cast<uint32_t>(Value);
99 return false;
100}
101
102template <typename coff_symbol_type>
103const coff_symbol_type *COFFObjectFile::toSymb(DataRefImpl Ref) const {
104 const coff_symbol_type *Addr =
105 reinterpret_cast<const coff_symbol_type *>(Ref.p);
106
107 assert(!checkOffset(Data, uintptr_t(Addr), sizeof(*Addr)))(static_cast <bool> (!checkOffset(Data, uintptr_t(Addr)
, sizeof(*Addr))) ? void (0) : __assert_fail ("!checkOffset(Data, uintptr_t(Addr), sizeof(*Addr))"
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Object/COFFObjectFile.cpp"
, 107, __extension__ __PRETTY_FUNCTION__))
;
108#ifndef NDEBUG
109 // Verify that the symbol points to a valid entry in the symbol table.
110 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(base());
111
112 assert((Offset - getPointerToSymbolTable()) % sizeof(coff_symbol_type) == 0 &&(static_cast <bool> ((Offset - getPointerToSymbolTable(
)) % sizeof(coff_symbol_type) == 0 && "Symbol did not point to the beginning of a symbol"
) ? void (0) : __assert_fail ("(Offset - getPointerToSymbolTable()) % sizeof(coff_symbol_type) == 0 && \"Symbol did not point to the beginning of a symbol\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Object/COFFObjectFile.cpp"
, 113, __extension__ __PRETTY_FUNCTION__))
113 "Symbol did not point to the beginning of a symbol")(static_cast <bool> ((Offset - getPointerToSymbolTable(
)) % sizeof(coff_symbol_type) == 0 && "Symbol did not point to the beginning of a symbol"
) ? void (0) : __assert_fail ("(Offset - getPointerToSymbolTable()) % sizeof(coff_symbol_type) == 0 && \"Symbol did not point to the beginning of a symbol\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Object/COFFObjectFile.cpp"
, 113, __extension__ __PRETTY_FUNCTION__))
;
114#endif
115
116 return Addr;
117}
118
119const coff_section *COFFObjectFile::toSec(DataRefImpl Ref) const {
120 const coff_section *Addr = reinterpret_cast<const coff_section*>(Ref.p);
121
122#ifndef NDEBUG
123 // Verify that the section points to a valid entry in the section table.
124 if (Addr < SectionTable || Addr >= (SectionTable + getNumberOfSections()))
125 report_fatal_error("Section was outside of section table.");
126
127 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(SectionTable);
128 assert(Offset % sizeof(coff_section) == 0 &&(static_cast <bool> (Offset % sizeof(coff_section) == 0
&& "Section did not point to the beginning of a section"
) ? void (0) : __assert_fail ("Offset % sizeof(coff_section) == 0 && \"Section did not point to the beginning of a section\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Object/COFFObjectFile.cpp"
, 129, __extension__ __PRETTY_FUNCTION__))
129 "Section did not point to the beginning of a section")(static_cast <bool> (Offset % sizeof(coff_section) == 0
&& "Section did not point to the beginning of a section"
) ? void (0) : __assert_fail ("Offset % sizeof(coff_section) == 0 && \"Section did not point to the beginning of a section\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Object/COFFObjectFile.cpp"
, 129, __extension__ __PRETTY_FUNCTION__))
;
130#endif
131
132 return Addr;
133}
134
135void COFFObjectFile::moveSymbolNext(DataRefImpl &Ref) const {
136 auto End = reinterpret_cast<uintptr_t>(StringTable);
137 if (SymbolTable16) {
138 const coff_symbol16 *Symb = toSymb<coff_symbol16>(Ref);
139 Symb += 1 + Symb->NumberOfAuxSymbols;
140 Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End);
141 } else if (SymbolTable32) {
142 const coff_symbol32 *Symb = toSymb<coff_symbol32>(Ref);
143 Symb += 1 + Symb->NumberOfAuxSymbols;
144 Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End);
145 } else {
146 llvm_unreachable("no symbol table pointer!")::llvm::llvm_unreachable_internal("no symbol table pointer!",
"/build/llvm-toolchain-snapshot-7~svn338205/lib/Object/COFFObjectFile.cpp"
, 146)
;
147 }
148}
149
150Expected<StringRef> COFFObjectFile::getSymbolName(DataRefImpl Ref) const {
151 COFFSymbolRef Symb = getCOFFSymbol(Ref);
152 StringRef Result;
153 if (std::error_code EC = getSymbolName(Symb, Result))
154 return errorCodeToError(EC);
155 return Result;
156}
157
158uint64_t COFFObjectFile::getSymbolValueImpl(DataRefImpl Ref) const {
159 return getCOFFSymbol(Ref).getValue();
160}
161
162uint32_t COFFObjectFile::getSymbolAlignment(DataRefImpl Ref) const {
163 // MSVC/link.exe seems to align symbols to the next-power-of-2
164 // up to 32 bytes.
165 COFFSymbolRef Symb = getCOFFSymbol(Ref);
166 return std::min(uint64_t(32), PowerOf2Ceil(Symb.getValue()));
167}
168
169Expected<uint64_t> COFFObjectFile::getSymbolAddress(DataRefImpl Ref) const {
170 uint64_t Result = getSymbolValue(Ref);
171 COFFSymbolRef Symb = getCOFFSymbol(Ref);
172 int32_t SectionNumber = Symb.getSectionNumber();
173
174 if (Symb.isAnyUndefined() || Symb.isCommon() ||
175 COFF::isReservedSectionNumber(SectionNumber))
176 return Result;
177
178 const coff_section *Section = nullptr;
179 if (std::error_code EC = getSection(SectionNumber, Section))
180 return errorCodeToError(EC);
181 Result += Section->VirtualAddress;
182
183 // The section VirtualAddress does not include ImageBase, and we want to
184 // return virtual addresses.
185 Result += getImageBase();
186
187 return Result;
188}
189
190Expected<SymbolRef::Type> COFFObjectFile::getSymbolType(DataRefImpl Ref) const {
191 COFFSymbolRef Symb = getCOFFSymbol(Ref);
192 int32_t SectionNumber = Symb.getSectionNumber();
193
194 if (Symb.getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION)
195 return SymbolRef::ST_Function;
196 if (Symb.isAnyUndefined())
197 return SymbolRef::ST_Unknown;
198 if (Symb.isCommon())
199 return SymbolRef::ST_Data;
200 if (Symb.isFileRecord())
201 return SymbolRef::ST_File;
202
203 // TODO: perhaps we need a new symbol type ST_Section.
204 if (SectionNumber == COFF::IMAGE_SYM_DEBUG || Symb.isSectionDefinition())
205 return SymbolRef::ST_Debug;
206
207 if (!COFF::isReservedSectionNumber(SectionNumber))
208 return SymbolRef::ST_Data;
209
210 return SymbolRef::ST_Other;
211}
212
213uint32_t COFFObjectFile::getSymbolFlags(DataRefImpl Ref) const {
214 COFFSymbolRef Symb = getCOFFSymbol(Ref);
215 uint32_t Result = SymbolRef::SF_None;
216
217 if (Symb.isExternal() || Symb.isWeakExternal())
218 Result |= SymbolRef::SF_Global;
219
220 if (const coff_aux_weak_external *AWE = Symb.getWeakExternal()) {
221 Result |= SymbolRef::SF_Weak;
222 if (AWE->Characteristics != COFF::IMAGE_WEAK_EXTERN_SEARCH_ALIAS)
223 Result |= SymbolRef::SF_Undefined;
224 }
225
226 if (Symb.getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE)
227 Result |= SymbolRef::SF_Absolute;
228
229 if (Symb.isFileRecord())
230 Result |= SymbolRef::SF_FormatSpecific;
231
232 if (Symb.isSectionDefinition())
233 Result |= SymbolRef::SF_FormatSpecific;
234
235 if (Symb.isCommon())
236 Result |= SymbolRef::SF_Common;
237
238 if (Symb.isUndefined())
239 Result |= SymbolRef::SF_Undefined;
240
241 return Result;
242}
243
244uint64_t COFFObjectFile::getCommonSymbolSizeImpl(DataRefImpl Ref) const {
245 COFFSymbolRef Symb = getCOFFSymbol(Ref);
246 return Symb.getValue();
1
Calling 'COFFSymbolRef::getValue'
247}
248
249Expected<section_iterator>
250COFFObjectFile::getSymbolSection(DataRefImpl Ref) const {
251 COFFSymbolRef Symb = getCOFFSymbol(Ref);
252 if (COFF::isReservedSectionNumber(Symb.getSectionNumber()))
253 return section_end();
254 const coff_section *Sec = nullptr;
255 if (std::error_code EC = getSection(Symb.getSectionNumber(), Sec))
256 return errorCodeToError(EC);
257 DataRefImpl Ret;
258 Ret.p = reinterpret_cast<uintptr_t>(Sec);
259 return section_iterator(SectionRef(Ret, this));
260}
261
262unsigned COFFObjectFile::getSymbolSectionID(SymbolRef Sym) const {
263 COFFSymbolRef Symb = getCOFFSymbol(Sym.getRawDataRefImpl());
264 return Symb.getSectionNumber();
265}
266
267void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
268 const coff_section *Sec = toSec(Ref);
269 Sec += 1;
270 Ref.p = reinterpret_cast<uintptr_t>(Sec);
271}
272
273std::error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
274 StringRef &Result) const {
275 const coff_section *Sec = toSec(Ref);
276 return getSectionName(Sec, Result);
277}
278
279uint64_t COFFObjectFile::getSectionAddress(DataRefImpl Ref) const {
280 const coff_section *Sec = toSec(Ref);
281 uint64_t Result = Sec->VirtualAddress;
282
283 // The section VirtualAddress does not include ImageBase, and we want to
284 // return virtual addresses.
285 Result += getImageBase();
286 return Result;
287}
288
289uint64_t COFFObjectFile::getSectionIndex(DataRefImpl Sec) const {
290 return toSec(Sec) - SectionTable;
291}
292
293uint64_t COFFObjectFile::getSectionSize(DataRefImpl Ref) const {
294 return getSectionSize(toSec(Ref));
295}
296
297std::error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
298 StringRef &Result) const {
299 const coff_section *Sec = toSec(Ref);
300 ArrayRef<uint8_t> Res;
301 std::error_code EC = getSectionContents(Sec, Res);
302 Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
303 return EC;
304}
305
306uint64_t COFFObjectFile::getSectionAlignment(DataRefImpl Ref) const {
307 const coff_section *Sec = toSec(Ref);
308 return Sec->getAlignment();
309}
310
311bool COFFObjectFile::isSectionCompressed(DataRefImpl Sec) const {
312 return false;
313}
314
315bool COFFObjectFile::isSectionText(DataRefImpl Ref) const {
316 const coff_section *Sec = toSec(Ref);
317 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
318}
319
320bool COFFObjectFile::isSectionData(DataRefImpl Ref) const {
321 const coff_section *Sec = toSec(Ref);
322 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
323}
324
325bool COFFObjectFile::isSectionBSS(DataRefImpl Ref) const {
326 const coff_section *Sec = toSec(Ref);
327 const uint32_t BssFlags = COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
328 COFF::IMAGE_SCN_MEM_READ |
329 COFF::IMAGE_SCN_MEM_WRITE;
330 return (Sec->Characteristics & BssFlags) == BssFlags;
331}
332
333unsigned COFFObjectFile::getSectionID(SectionRef Sec) const {
334 uintptr_t Offset =
335 uintptr_t(Sec.getRawDataRefImpl().p) - uintptr_t(SectionTable);
336 assert((Offset % sizeof(coff_section)) == 0)(static_cast <bool> ((Offset % sizeof(coff_section)) ==
0) ? void (0) : __assert_fail ("(Offset % sizeof(coff_section)) == 0"
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Object/COFFObjectFile.cpp"
, 336, __extension__ __PRETTY_FUNCTION__))
;
337 return (Offset / sizeof(coff_section)) + 1;
338}
339
340bool COFFObjectFile::isSectionVirtual(DataRefImpl Ref) const {
341 const coff_section *Sec = toSec(Ref);
342 // In COFF, a virtual section won't have any in-file
343 // content, so the file pointer to the content will be zero.
344 return Sec->PointerToRawData == 0;
345}
346
347static uint32_t getNumberOfRelocations(const coff_section *Sec,
348 MemoryBufferRef M, const uint8_t *base) {
349 // The field for the number of relocations in COFF section table is only
350 // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
351 // NumberOfRelocations field, and the actual relocation count is stored in the
352 // VirtualAddress field in the first relocation entry.
353 if (Sec->hasExtendedRelocations()) {
354 const coff_relocation *FirstReloc;
355 if (getObject(FirstReloc, M, reinterpret_cast<const coff_relocation*>(
356 base + Sec->PointerToRelocations)))
357 return 0;
358 // -1 to exclude this first relocation entry.
359 return FirstReloc->VirtualAddress - 1;
360 }
361 return Sec->NumberOfRelocations;
362}
363
364static const coff_relocation *
365getFirstReloc(const coff_section *Sec, MemoryBufferRef M, const uint8_t *Base) {
366 uint64_t NumRelocs = getNumberOfRelocations(Sec, M, Base);
367 if (!NumRelocs)
368 return nullptr;
369 auto begin = reinterpret_cast<const coff_relocation *>(
370 Base + Sec->PointerToRelocations);
371 if (Sec->hasExtendedRelocations()) {
372 // Skip the first relocation entry repurposed to store the number of
373 // relocations.
374 begin++;
375 }
376 if (Binary::checkOffset(M, uintptr_t(begin),
377 sizeof(coff_relocation) * NumRelocs))
378 return nullptr;
379 return begin;
380}
381
382relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
383 const coff_section *Sec = toSec(Ref);
384 const coff_relocation *begin = getFirstReloc(Sec, Data, base());
385 if (begin && Sec->VirtualAddress != 0)
386 report_fatal_error("Sections with relocations should have an address of 0");
387 DataRefImpl Ret;
388 Ret.p = reinterpret_cast<uintptr_t>(begin);
389 return relocation_iterator(RelocationRef(Ret, this));
390}
391
392relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
393 const coff_section *Sec = toSec(Ref);
394 const coff_relocation *I = getFirstReloc(Sec, Data, base());
395 if (I)
396 I += getNumberOfRelocations(Sec, Data, base());
397 DataRefImpl Ret;
398 Ret.p = reinterpret_cast<uintptr_t>(I);
399 return relocation_iterator(RelocationRef(Ret, this));
400}
401
402// Initialize the pointer to the symbol table.
403std::error_code COFFObjectFile::initSymbolTablePtr() {
404 if (COFFHeader)
405 if (std::error_code EC = getObject(
406 SymbolTable16, Data, base() + getPointerToSymbolTable(),
407 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
408 return EC;
409
410 if (COFFBigObjHeader)
411 if (std::error_code EC = getObject(
412 SymbolTable32, Data, base() + getPointerToSymbolTable(),
413 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
414 return EC;
415
416 // Find string table. The first four byte of the string table contains the
417 // total size of the string table, including the size field itself. If the
418 // string table is empty, the value of the first four byte would be 4.
419 uint32_t StringTableOffset = getPointerToSymbolTable() +
420 getNumberOfSymbols() * getSymbolTableEntrySize();
421 const uint8_t *StringTableAddr = base() + StringTableOffset;
422 const ulittle32_t *StringTableSizePtr;
423 if (std::error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
424 return EC;
425 StringTableSize = *StringTableSizePtr;
426 if (std::error_code EC =
427 getObject(StringTable, Data, StringTableAddr, StringTableSize))
428 return EC;
429
430 // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
431 // tools like cvtres write a size of 0 for an empty table instead of 4.
432 if (StringTableSize < 4)
433 StringTableSize = 4;
434
435 // Check that the string table is null terminated if has any in it.
436 if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
437 return object_error::parse_failed;
438 return std::error_code();
439}
440
441uint64_t COFFObjectFile::getImageBase() const {
442 if (PE32Header)
443 return PE32Header->ImageBase;
444 else if (PE32PlusHeader)
445 return PE32PlusHeader->ImageBase;
446 // This actually comes up in practice.
447 return 0;
448}
449
450// Returns the file offset for the given VA.
451std::error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
452 uint64_t ImageBase = getImageBase();
453 uint64_t Rva = Addr - ImageBase;
454 assert(Rva <= UINT32_MAX)(static_cast <bool> (Rva <= (4294967295U)) ? void (0
) : __assert_fail ("Rva <= UINT32_MAX", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Object/COFFObjectFile.cpp"
, 454, __extension__ __PRETTY_FUNCTION__))
;
455 return getRvaPtr((uint32_t)Rva, Res);
456}
457
458// Returns the file offset for the given RVA.
459std::error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
460 for (const SectionRef &S : sections()) {
461 const coff_section *Section = getCOFFSection(S);
462 uint32_t SectionStart = Section->VirtualAddress;
463 uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
464 if (SectionStart <= Addr && Addr < SectionEnd) {
465 uint32_t Offset = Addr - SectionStart;
466 Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
467 return std::error_code();
468 }
469 }
470 return object_error::parse_failed;
471}
472
473std::error_code
474COFFObjectFile::getRvaAndSizeAsBytes(uint32_t RVA, uint32_t Size,
475 ArrayRef<uint8_t> &Contents) const {
476 for (const SectionRef &S : sections()) {
477 const coff_section *Section = getCOFFSection(S);
478 uint32_t SectionStart = Section->VirtualAddress;
479 // Check if this RVA is within the section bounds. Be careful about integer
480 // overflow.
481 uint32_t OffsetIntoSection = RVA - SectionStart;
482 if (SectionStart <= RVA && OffsetIntoSection < Section->VirtualSize &&
483 Size <= Section->VirtualSize - OffsetIntoSection) {
484 uintptr_t Begin =
485 uintptr_t(base()) + Section->PointerToRawData + OffsetIntoSection;
486 Contents =
487 ArrayRef<uint8_t>(reinterpret_cast<const uint8_t *>(Begin), Size);
488 return std::error_code();
489 }
490 }
491 return object_error::parse_failed;
492}
493
494// Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
495// table entry.
496std::error_code COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint,
497 StringRef &Name) const {
498 uintptr_t IntPtr = 0;
499 if (std::error_code EC = getRvaPtr(Rva, IntPtr))
500 return EC;
501 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
502 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
503 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
504 return std::error_code();
505}
506
507std::error_code
508COFFObjectFile::getDebugPDBInfo(const debug_directory *DebugDir,
509 const codeview::DebugInfo *&PDBInfo,
510 StringRef &PDBFileName) const {
511 ArrayRef<uint8_t> InfoBytes;
512 if (std::error_code EC = getRvaAndSizeAsBytes(
513 DebugDir->AddressOfRawData, DebugDir->SizeOfData, InfoBytes))
514 return EC;
515 if (InfoBytes.size() < sizeof(*PDBInfo) + 1)
516 return object_error::parse_failed;
517 PDBInfo = reinterpret_cast<const codeview::DebugInfo *>(InfoBytes.data());
518 InfoBytes = InfoBytes.drop_front(sizeof(*PDBInfo));
519 PDBFileName = StringRef(reinterpret_cast<const char *>(InfoBytes.data()),
520 InfoBytes.size());
521 // Truncate the name at the first null byte. Ignore any padding.
522 PDBFileName = PDBFileName.split('\0').first;
523 return std::error_code();
524}
525
526std::error_code
527COFFObjectFile::getDebugPDBInfo(const codeview::DebugInfo *&PDBInfo,
528 StringRef &PDBFileName) const {
529 for (const debug_directory &D : debug_directories())
530 if (D.Type == COFF::IMAGE_DEBUG_TYPE_CODEVIEW)
531 return getDebugPDBInfo(&D, PDBInfo, PDBFileName);
532 // If we get here, there is no PDB info to return.
533 PDBInfo = nullptr;
534 PDBFileName = StringRef();
535 return std::error_code();
536}
537
538// Find the import table.
539std::error_code COFFObjectFile::initImportTablePtr() {
540 // First, we get the RVA of the import table. If the file lacks a pointer to
541 // the import table, do nothing.
542 const data_directory *DataEntry;
543 if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
544 return std::error_code();
545
546 // Do nothing if the pointer to import table is NULL.
547 if (DataEntry->RelativeVirtualAddress == 0)
548 return std::error_code();
549
550 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
551
552 // Find the section that contains the RVA. This is needed because the RVA is
553 // the import table's memory address which is different from its file offset.
554 uintptr_t IntPtr = 0;
555 if (std::error_code EC = getRvaPtr(ImportTableRva, IntPtr))
556 return EC;
557 if (std::error_code EC = checkOffset(Data, IntPtr, DataEntry->Size))
558 return EC;
559 ImportDirectory = reinterpret_cast<
560 const coff_import_directory_table_entry *>(IntPtr);
561 return std::error_code();
562}
563
564// Initializes DelayImportDirectory and NumberOfDelayImportDirectory.
565std::error_code COFFObjectFile::initDelayImportTablePtr() {
566 const data_directory *DataEntry;
567 if (getDataDirectory(COFF::DELAY_IMPORT_DESCRIPTOR, DataEntry))
568 return std::error_code();
569 if (DataEntry->RelativeVirtualAddress == 0)
570 return std::error_code();
571
572 uint32_t RVA = DataEntry->RelativeVirtualAddress;
573 NumberOfDelayImportDirectory = DataEntry->Size /
574 sizeof(delay_import_directory_table_entry) - 1;
575
576 uintptr_t IntPtr = 0;
577 if (std::error_code EC = getRvaPtr(RVA, IntPtr))
578 return EC;
579 DelayImportDirectory = reinterpret_cast<
580 const delay_import_directory_table_entry *>(IntPtr);
581 return std::error_code();
582}
583
584// Find the export table.
585std::error_code COFFObjectFile::initExportTablePtr() {
586 // First, we get the RVA of the export table. If the file lacks a pointer to
587 // the export table, do nothing.
588 const data_directory *DataEntry;
589 if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
590 return std::error_code();
591
592 // Do nothing if the pointer to export table is NULL.
593 if (DataEntry->RelativeVirtualAddress == 0)
594 return std::error_code();
595
596 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
597 uintptr_t IntPtr = 0;
598 if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr))
599 return EC;
600 ExportDirectory =
601 reinterpret_cast<const export_directory_table_entry *>(IntPtr);
602 return std::error_code();
603}
604
605std::error_code COFFObjectFile::initBaseRelocPtr() {
606 const data_directory *DataEntry;
607 if (getDataDirectory(COFF::BASE_RELOCATION_TABLE, DataEntry))
608 return std::error_code();
609 if (DataEntry->RelativeVirtualAddress == 0)
610 return std::error_code();
611
612 uintptr_t IntPtr = 0;
613 if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
614 return EC;
615 BaseRelocHeader = reinterpret_cast<const coff_base_reloc_block_header *>(
616 IntPtr);
617 BaseRelocEnd = reinterpret_cast<coff_base_reloc_block_header *>(
618 IntPtr + DataEntry->Size);
619 return std::error_code();
620}
621
622std::error_code COFFObjectFile::initDebugDirectoryPtr() {
623 // Get the RVA of the debug directory. Do nothing if it does not exist.
624 const data_directory *DataEntry;
625 if (getDataDirectory(COFF::DEBUG_DIRECTORY, DataEntry))
626 return std::error_code();
627
628 // Do nothing if the RVA is NULL.
629 if (DataEntry->RelativeVirtualAddress == 0)
630 return std::error_code();
631
632 // Check that the size is a multiple of the entry size.
633 if (DataEntry->Size % sizeof(debug_directory) != 0)
634 return object_error::parse_failed;
635
636 uintptr_t IntPtr = 0;
637 if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
638 return EC;
639 DebugDirectoryBegin = reinterpret_cast<const debug_directory *>(IntPtr);
640 if (std::error_code EC = getRvaPtr(
641 DataEntry->RelativeVirtualAddress + DataEntry->Size, IntPtr))
642 return EC;
643 DebugDirectoryEnd = reinterpret_cast<const debug_directory *>(IntPtr);
644 return std::error_code();
645}
646
647std::error_code COFFObjectFile::initLoadConfigPtr() {
648 // Get the RVA of the debug directory. Do nothing if it does not exist.
649 const data_directory *DataEntry;
650 if (getDataDirectory(COFF::LOAD_CONFIG_TABLE, DataEntry))
651 return std::error_code();
652
653 // Do nothing if the RVA is NULL.
654 if (DataEntry->RelativeVirtualAddress == 0)
655 return std::error_code();
656 uintptr_t IntPtr = 0;
657 if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
658 return EC;
659
660 LoadConfig = (const void *)IntPtr;
661 return std::error_code();
662}
663
664COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC)
665 : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
666 COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
667 DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
668 SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
669 ImportDirectory(nullptr),
670 DelayImportDirectory(nullptr), NumberOfDelayImportDirectory(0),
671 ExportDirectory(nullptr), BaseRelocHeader(nullptr), BaseRelocEnd(nullptr),
672 DebugDirectoryBegin(nullptr), DebugDirectoryEnd(nullptr) {
673 // Check that we at least have enough room for a header.
674 if (!checkSize(Data, EC, sizeof(coff_file_header)))
675 return;
676
677 // The current location in the file where we are looking at.
678 uint64_t CurPtr = 0;
679
680 // PE header is optional and is present only in executables. If it exists,
681 // it is placed right after COFF header.
682 bool HasPEHeader = false;
683
684 // Check if this is a PE/COFF file.
685 if (checkSize(Data, EC, sizeof(dos_header) + sizeof(COFF::PEMagic))) {
686 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
687 // PE signature to find 'normal' COFF header.
688 const auto *DH = reinterpret_cast<const dos_header *>(base());
689 if (DH->Magic[0] == 'M' && DH->Magic[1] == 'Z') {
690 CurPtr = DH->AddressOfNewExeHeader;
691 // Check the PE magic bytes. ("PE\0\0")
692 if (memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) != 0) {
693 EC = object_error::parse_failed;
694 return;
695 }
696 CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
697 HasPEHeader = true;
698 }
699 }
700
701 if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
702 return;
703
704 // It might be a bigobj file, let's check. Note that COFF bigobj and COFF
705 // import libraries share a common prefix but bigobj is more restrictive.
706 if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
707 COFFHeader->NumberOfSections == uint16_t(0xffff) &&
708 checkSize(Data, EC, sizeof(coff_bigobj_file_header))) {
709 if ((EC = getObject(COFFBigObjHeader, Data, base() + CurPtr)))
710 return;
711
712 // Verify that we are dealing with bigobj.
713 if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
714 std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic,
715 sizeof(COFF::BigObjMagic)) == 0) {
716 COFFHeader = nullptr;
717 CurPtr += sizeof(coff_bigobj_file_header);
718 } else {
719 // It's not a bigobj.
720 COFFBigObjHeader = nullptr;
721 }
722 }
723 if (COFFHeader) {
724 // The prior checkSize call may have failed. This isn't a hard error
725 // because we were just trying to sniff out bigobj.
726 EC = std::error_code();
727 CurPtr += sizeof(coff_file_header);
728
729 if (COFFHeader->isImportLibrary())
730 return;
731 }
732
733 if (HasPEHeader) {
734 const pe32_header *Header;
735 if ((EC = getObject(Header, Data, base() + CurPtr)))
736 return;
737
738 const uint8_t *DataDirAddr;
739 uint64_t DataDirSize;
740 if (Header->Magic == COFF::PE32Header::PE32) {
741 PE32Header = Header;
742 DataDirAddr = base() + CurPtr + sizeof(pe32_header);
743 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
744 } else if (Header->Magic == COFF::PE32Header::PE32_PLUS) {
745 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
746 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
747 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
748 } else {
749 // It's neither PE32 nor PE32+.
750 EC = object_error::parse_failed;
751 return;
752 }
753 if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
754 return;
755 }
756
757 if (COFFHeader)
758 CurPtr += COFFHeader->SizeOfOptionalHeader;
759
760 if ((EC = getObject(SectionTable, Data, base() + CurPtr,
761 (uint64_t)getNumberOfSections() * sizeof(coff_section))))
762 return;
763
764 // Initialize the pointer to the symbol table.
765 if (getPointerToSymbolTable() != 0) {
766 if ((EC = initSymbolTablePtr())) {
767 SymbolTable16 = nullptr;
768 SymbolTable32 = nullptr;
769 StringTable = nullptr;
770 StringTableSize = 0;
771 }
772 } else {
773 // We had better not have any symbols if we don't have a symbol table.
774 if (getNumberOfSymbols() != 0) {
775 EC = object_error::parse_failed;
776 return;
777 }
778 }
779
780 // Initialize the pointer to the beginning of the import table.
781 if ((EC = initImportTablePtr()))
782 return;
783 if ((EC = initDelayImportTablePtr()))
784 return;
785
786 // Initialize the pointer to the export table.
787 if ((EC = initExportTablePtr()))
788 return;
789
790 // Initialize the pointer to the base relocation table.
791 if ((EC = initBaseRelocPtr()))
792 return;
793
794 // Initialize the pointer to the export table.
795 if ((EC = initDebugDirectoryPtr()))
796 return;
797
798 if ((EC = initLoadConfigPtr()))
799 return;
800
801 EC = std::error_code();
802}
803
804basic_symbol_iterator COFFObjectFile::symbol_begin() const {
805 DataRefImpl Ret;
806 Ret.p = getSymbolTable();
807 return basic_symbol_iterator(SymbolRef(Ret, this));
808}
809
810basic_symbol_iterator COFFObjectFile::symbol_end() const {
811 // The symbol table ends where the string table begins.
812 DataRefImpl Ret;
813 Ret.p = reinterpret_cast<uintptr_t>(StringTable);
814 return basic_symbol_iterator(SymbolRef(Ret, this));
815}
816
817import_directory_iterator COFFObjectFile::import_directory_begin() const {
818 if (!ImportDirectory)
819 return import_directory_end();
820 if (ImportDirectory->isNull())
821 return import_directory_end();
822 return import_directory_iterator(
823 ImportDirectoryEntryRef(ImportDirectory, 0, this));
824}
825
826import_directory_iterator COFFObjectFile::import_directory_end() const {
827 return import_directory_iterator(
828 ImportDirectoryEntryRef(nullptr, -1, this));
829}
830
831delay_import_directory_iterator
832COFFObjectFile::delay_import_directory_begin() const {
833 return delay_import_directory_iterator(
834 DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this));
835}
836
837delay_import_directory_iterator
838COFFObjectFile::delay_import_directory_end() const {
839 return delay_import_directory_iterator(
840 DelayImportDirectoryEntryRef(
841 DelayImportDirectory, NumberOfDelayImportDirectory, this));
842}
843
844export_directory_iterator COFFObjectFile::export_directory_begin() const {
845 return export_directory_iterator(
846 ExportDirectoryEntryRef(ExportDirectory, 0, this));
847}
848
849export_directory_iterator COFFObjectFile::export_directory_end() const {
850 if (!ExportDirectory)
851 return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
852 ExportDirectoryEntryRef Ref(ExportDirectory,
853 ExportDirectory->AddressTableEntries, this);
854 return export_directory_iterator(Ref);
855}
856
857section_iterator COFFObjectFile::section_begin() const {
858 DataRefImpl Ret;
859 Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
860 return section_iterator(SectionRef(Ret, this));
861}
862
863section_iterator COFFObjectFile::section_end() const {
864 DataRefImpl Ret;
865 int NumSections =
866 COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
867 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
868 return section_iterator(SectionRef(Ret, this));
869}
870
871base_reloc_iterator COFFObjectFile::base_reloc_begin() const {
872 return base_reloc_iterator(BaseRelocRef(BaseRelocHeader, this));
873}
874
875base_reloc_iterator COFFObjectFile::base_reloc_end() const {
876 return base_reloc_iterator(BaseRelocRef(BaseRelocEnd, this));
877}
878
879uint8_t COFFObjectFile::getBytesInAddress() const {
880 return getArch() == Triple::x86_64 || getArch() == Triple::aarch64 ? 8 : 4;
881}
882
883StringRef COFFObjectFile::getFileFormatName() const {
884 switch(getMachine()) {
885 case COFF::IMAGE_FILE_MACHINE_I386:
886 return "COFF-i386";
887 case COFF::IMAGE_FILE_MACHINE_AMD64:
888 return "COFF-x86-64";
889 case COFF::IMAGE_FILE_MACHINE_ARMNT:
890 return "COFF-ARM";
891 case COFF::IMAGE_FILE_MACHINE_ARM64:
892 return "COFF-ARM64";
893 default:
894 return "COFF-<unknown arch>";
895 }
896}
897
898Triple::ArchType COFFObjectFile::getArch() const {
899 switch (getMachine()) {
900 case COFF::IMAGE_FILE_MACHINE_I386:
901 return Triple::x86;
902 case COFF::IMAGE_FILE_MACHINE_AMD64:
903 return Triple::x86_64;
904 case COFF::IMAGE_FILE_MACHINE_ARMNT:
905 return Triple::thumb;
906 case COFF::IMAGE_FILE_MACHINE_ARM64:
907 return Triple::aarch64;
908 default:
909 return Triple::UnknownArch;
910 }
911}
912
913Expected<uint64_t> COFFObjectFile::getStartAddress() const {
914 if (PE32Header)
915 return PE32Header->AddressOfEntryPoint;
916 return 0;
917}
918
919iterator_range<import_directory_iterator>
920COFFObjectFile::import_directories() const {
921 return make_range(import_directory_begin(), import_directory_end());
922}
923
924iterator_range<delay_import_directory_iterator>
925COFFObjectFile::delay_import_directories() const {
926 return make_range(delay_import_directory_begin(),
927 delay_import_directory_end());
928}
929
930iterator_range<export_directory_iterator>
931COFFObjectFile::export_directories() const {
932 return make_range(export_directory_begin(), export_directory_end());
933}
934
935iterator_range<base_reloc_iterator> COFFObjectFile::base_relocs() const {
936 return make_range(base_reloc_begin(), base_reloc_end());
937}
938
939std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
940 Res = PE32Header;
941 return std::error_code();
942}
943
944std::error_code
945COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
946 Res = PE32PlusHeader;
947 return std::error_code();
948}
949
950std::error_code
951COFFObjectFile::getDataDirectory(uint32_t Index,
952 const data_directory *&Res) const {
953 // Error if there's no data directory or the index is out of range.
954 if (!DataDirectory) {
955 Res = nullptr;
956 return object_error::parse_failed;
957 }
958 assert(PE32Header || PE32PlusHeader)(static_cast <bool> (PE32Header || PE32PlusHeader) ? void
(0) : __assert_fail ("PE32Header || PE32PlusHeader", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Object/COFFObjectFile.cpp"
, 958, __extension__ __PRETTY_FUNCTION__))
;
959 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
960 : PE32PlusHeader->NumberOfRvaAndSize;
961 if (Index >= NumEnt) {
962 Res = nullptr;
963 return object_error::parse_failed;
964 }
965 Res = &DataDirectory[Index];
966 return std::error_code();
967}
968
969std::error_code COFFObjectFile::getSection(int32_t Index,
970 const coff_section *&Result) const {
971 Result = nullptr;
972 if (COFF::isReservedSectionNumber(Index))
973 return std::error_code();
974 if (static_cast<uint32_t>(Index) <= getNumberOfSections()) {
975 // We already verified the section table data, so no need to check again.
976 Result = SectionTable + (Index - 1);
977 return std::error_code();
978 }
979 return object_error::parse_failed;
980}
981
982std::error_code COFFObjectFile::getSection(StringRef SectionName,
983 const coff_section *&Result) const {
984 Result = nullptr;
985 StringRef SecName;
986 for (const SectionRef &Section : sections()) {
987 if (std::error_code E = Section.getName(SecName))
988 return E;
989 if (SecName == SectionName) {
990 Result = getCOFFSection(Section);
991 return std::error_code();
992 }
993 }
994 return object_error::parse_failed;
995}
996
997std::error_code COFFObjectFile::getString(uint32_t Offset,
998 StringRef &Result) const {
999 if (StringTableSize <= 4)
1000 // Tried to get a string from an empty string table.
1001 return object_error::parse_failed;
1002 if (Offset >= StringTableSize)
1003 return object_error::unexpected_eof;
1004 Result = StringRef(StringTable + Offset);
1005 return std::error_code();
1006}
1007
1008std::error_code COFFObjectFile::getSymbolName(COFFSymbolRef Symbol,
1009 StringRef &Res) const {
1010 return getSymbolName(Symbol.getGeneric(), Res);
1011}
1012
1013std::error_code COFFObjectFile::getSymbolName(const coff_symbol_generic *Symbol,
1014 StringRef &Res) const {
1015 // Check for string table entry. First 4 bytes are 0.
1016 if (Symbol->Name.Offset.Zeroes == 0) {
1017 if (std::error_code EC = getString(Symbol->Name.Offset.Offset, Res))
1018 return EC;
1019 return std::error_code();
1020 }
1021
1022 if (Symbol->Name.ShortName[COFF::NameSize - 1] == 0)
1023 // Null terminated, let ::strlen figure out the length.
1024 Res = StringRef(Symbol->Name.ShortName);
1025 else
1026 // Not null terminated, use all 8 bytes.
1027 Res = StringRef(Symbol->Name.ShortName, COFF::NameSize);
1028 return std::error_code();
1029}
1030
1031ArrayRef<uint8_t>
1032COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
1033 const uint8_t *Aux = nullptr;
1034
1035 size_t SymbolSize = getSymbolTableEntrySize();
1036 if (Symbol.getNumberOfAuxSymbols() > 0) {
1037 // AUX data comes immediately after the symbol in COFF
1038 Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
1039#ifndef NDEBUG
1040 // Verify that the Aux symbol points to a valid entry in the symbol table.
1041 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
1042 if (Offset < getPointerToSymbolTable() ||
1043 Offset >=
1044 getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
1045 report_fatal_error("Aux Symbol data was outside of symbol table.");
1046
1047 assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&(static_cast <bool> ((Offset - getPointerToSymbolTable(
)) % SymbolSize == 0 && "Aux Symbol data did not point to the beginning of a symbol"
) ? void (0) : __assert_fail ("(Offset - getPointerToSymbolTable()) % SymbolSize == 0 && \"Aux Symbol data did not point to the beginning of a symbol\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Object/COFFObjectFile.cpp"
, 1048, __extension__ __PRETTY_FUNCTION__))
1048 "Aux Symbol data did not point to the beginning of a symbol")(static_cast <bool> ((Offset - getPointerToSymbolTable(
)) % SymbolSize == 0 && "Aux Symbol data did not point to the beginning of a symbol"
) ? void (0) : __assert_fail ("(Offset - getPointerToSymbolTable()) % SymbolSize == 0 && \"Aux Symbol data did not point to the beginning of a symbol\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/Object/COFFObjectFile.cpp"
, 1048, __extension__ __PRETTY_FUNCTION__))
;
1049#endif
1050 }
1051 return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
1052}
1053
1054std::error_code COFFObjectFile::getSectionName(const coff_section *Sec,
1055 StringRef &Res) const {
1056 StringRef Name;
1057 if (Sec->Name[COFF::NameSize - 1] == 0)
1058 // Null terminated, let ::strlen figure out the length.
1059 Name = Sec->Name;
1060 else
1061 // Not null terminated, use all 8 bytes.
1062 Name = StringRef(Sec->Name, COFF::NameSize);
1063
1064 // Check for string table entry. First byte is '/'.
1065 if (Name.startswith("/")) {
1066 uint32_t Offset;
1067 if (Name.startswith("//")) {
1068 if (decodeBase64StringEntry(Name.substr(2), Offset))
1069 return object_error::parse_failed;
1070 } else {
1071 if (Name.substr(1).getAsInteger(10, Offset))
1072 return object_error::parse_failed;
1073 }
1074 if (std::error_code EC = getString(Offset, Name))
1075 return EC;
1076 }
1077
1078 Res = Name;
1079 return std::error_code();
1080}
1081
1082uint64_t COFFObjectFile::getSectionSize(const coff_section *Sec) const {
1083 // SizeOfRawData and VirtualSize change what they represent depending on
1084 // whether or not we have an executable image.
1085 //
1086 // For object files, SizeOfRawData contains the size of section's data;
1087 // VirtualSize should be zero but isn't due to buggy COFF writers.
1088 //
1089 // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the
1090 // actual section size is in VirtualSize. It is possible for VirtualSize to
1091 // be greater than SizeOfRawData; the contents past that point should be
1092 // considered to be zero.
1093 if (getDOSHeader())
1094 return std::min(Sec->VirtualSize, Sec->SizeOfRawData);
1095 return Sec->SizeOfRawData;
1096}
1097
1098std::error_code
1099COFFObjectFile::getSectionContents(const coff_section *Sec,
1100 ArrayRef<uint8_t> &Res) const {
1101 // In COFF, a virtual section won't have any in-file
1102 // content, so the file pointer to the content will be zero.
1103 if (Sec->PointerToRawData == 0)
1104 return std::error_code();
1105 // The only thing that we need to verify is that the contents is contained
1106 // within the file bounds. We don't need to make sure it doesn't cover other
1107 // data, as there's nothing that says that is not allowed.
1108 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
1109 uint32_t SectionSize = getSectionSize(Sec);
1110 if (checkOffset(Data, ConStart, SectionSize))
1111 return object_error::parse_failed;
1112 Res = makeArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize);
1113 return std::error_code();
1114}
1115
1116const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
1117 return reinterpret_cast<const coff_relocation*>(Rel.p);
1118}
1119
1120void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
1121 Rel.p = reinterpret_cast<uintptr_t>(
1122 reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
1123}
1124
1125uint64_t COFFObjectFile::getRelocationOffset(DataRefImpl Rel) const {
1126 const coff_relocation *R = toRel(Rel);
1127 return R->VirtualAddress;
1128}
1129
1130symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
1131 const coff_relocation *R = toRel(Rel);
1132 DataRefImpl Ref;
1133 if (R->SymbolTableIndex >= getNumberOfSymbols())
1134 return symbol_end();
1135 if (SymbolTable16)
1136 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
1137 else if (SymbolTable32)
1138 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
1139 else
1140 llvm_unreachable("no symbol table pointer!")::llvm::llvm_unreachable_internal("no symbol table pointer!",
"/build/llvm-toolchain-snapshot-7~svn338205/lib/Object/COFFObjectFile.cpp"
, 1140)
;
1141 return symbol_iterator(SymbolRef(Ref, this));
1142}
1143
1144uint64_t COFFObjectFile::getRelocationType(DataRefImpl Rel) const {
1145 const coff_relocation* R = toRel(Rel);
1146 return R->Type;
1147}
1148
1149const coff_section *
1150COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
1151 return toSec(Section.getRawDataRefImpl());
1152}
1153
1154COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
1155 if (SymbolTable16)
1156 return toSymb<coff_symbol16>(Ref);
1157 if (SymbolTable32)
1158 return toSymb<coff_symbol32>(Ref);
1159 llvm_unreachable("no symbol table pointer!")::llvm::llvm_unreachable_internal("no symbol table pointer!",
"/build/llvm-toolchain-snapshot-7~svn338205/lib/Object/COFFObjectFile.cpp"
, 1159)
;
1160}
1161
1162COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
1163 return getCOFFSymbol(Symbol.getRawDataRefImpl());
1164}
1165
1166const coff_relocation *
1167COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
1168 return toRel(Reloc.getRawDataRefImpl());
1169}
1170
1171ArrayRef<coff_relocation>
1172COFFObjectFile::getRelocations(const coff_section *Sec) const {
1173 return {getFirstReloc(Sec, Data, base()),
1174 getNumberOfRelocations(Sec, Data, base())};
1175}
1176
1177#define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \
1178 case COFF::reloc_type: \
1179 Res = #reloc_type; \
1180 break;
1181
1182void COFFObjectFile::getRelocationTypeName(
1183 DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
1184 const coff_relocation *Reloc = toRel(Rel);
1185 StringRef Res;
1186 switch (getMachine()) {
1187 case COFF::IMAGE_FILE_MACHINE_AMD64:
1188 switch (Reloc->Type) {
1189 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
1190 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
1191 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
1192 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
1193 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
1194 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
1195 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
1196 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
1197 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
1198 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
1199 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
1200 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
1201 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
1202 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
1203 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
1204 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
1205 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
1206 default:
1207 Res = "Unknown";
1208 }
1209 break;
1210 case COFF::IMAGE_FILE_MACHINE_ARMNT:
1211 switch (Reloc->Type) {
1212 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
1213 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
1214 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
1215 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
1216 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
1217 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
1218 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
1219 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
1220 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
1221 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
1222 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
1223 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
1224 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
1225 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
1226 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
1227 default:
1228 Res = "Unknown";
1229 }
1230 break;
1231 case COFF::IMAGE_FILE_MACHINE_ARM64:
1232 switch (Reloc->Type) {
1233 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ABSOLUTE);
1234 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ADDR32);
1235 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ADDR32NB);
1236 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_BRANCH26);
1237 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_PAGEBASE_REL21);
1238 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_REL21);
1239 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_PAGEOFFSET_12A);
1240 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_PAGEOFFSET_12L);
1241 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL);
1242 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL_LOW12A);
1243 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL_HIGH12A);
1244 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL_LOW12L);
1245 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_TOKEN);
1246 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECTION);
1247 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ADDR64);
1248 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_BRANCH19);
1249 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_BRANCH14);
1250 default:
1251 Res = "Unknown";
1252 }
1253 break;
1254 case COFF::IMAGE_FILE_MACHINE_I386:
1255 switch (Reloc->Type) {
1256 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
1257 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
1258 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
1259 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
1260 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
1261 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
1262 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
1263 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
1264 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
1265 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
1266 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
1267 default:
1268 Res = "Unknown";
1269 }
1270 break;
1271 default:
1272 Res = "Unknown";
1273 }
1274 Result.append(Res.begin(), Res.end());
1275}
1276
1277#undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1278
1279bool COFFObjectFile::isRelocatableObject() const {
1280 return !DataDirectory;
1281}
1282
1283bool ImportDirectoryEntryRef::
1284operator==(const ImportDirectoryEntryRef &Other) const {
1285 return ImportTable == Other.ImportTable && Index == Other.Index;
1286}
1287
1288void ImportDirectoryEntryRef::moveNext() {
1289 ++Index;
1290 if (ImportTable[Index].isNull()) {
1291 Index = -1;
1292 ImportTable = nullptr;
1293 }
1294}
1295
1296std::error_code ImportDirectoryEntryRef::getImportTableEntry(
1297 const coff_import_directory_table_entry *&Result) const {
1298 return getObject(Result, OwningObject->Data, ImportTable + Index);
1299}
1300
1301static imported_symbol_iterator
1302makeImportedSymbolIterator(const COFFObjectFile *Object,
1303 uintptr_t Ptr, int Index) {
1304 if (Object->getBytesInAddress() == 4) {
1305 auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr);
1306 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1307 }
1308 auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr);
1309 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1310}
1311
1312static imported_symbol_iterator
1313importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) {
1314 uintptr_t IntPtr = 0;
1315 Object->getRvaPtr(RVA, IntPtr);
1316 return makeImportedSymbolIterator(Object, IntPtr, 0);
1317}
1318
1319static imported_symbol_iterator
1320importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) {
1321 uintptr_t IntPtr = 0;
1322 Object->getRvaPtr(RVA, IntPtr);
1323 // Forward the pointer to the last entry which is null.
1324 int Index = 0;
1325 if (Object->getBytesInAddress() == 4) {
1326 auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr);
1327 while (*Entry++)
1328 ++Index;
1329 } else {
1330 auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr);
1331 while (*Entry++)
1332 ++Index;
1333 }
1334 return makeImportedSymbolIterator(Object, IntPtr, Index);
1335}
1336
1337imported_symbol_iterator
1338ImportDirectoryEntryRef::imported_symbol_begin() const {
1339 return importedSymbolBegin(ImportTable[Index].ImportAddressTableRVA,
1340 OwningObject);
1341}
1342
1343imported_symbol_iterator
1344ImportDirectoryEntryRef::imported_symbol_end() const {
1345 return importedSymbolEnd(ImportTable[Index].ImportAddressTableRVA,
1346 OwningObject);
1347}
1348
1349iterator_range<imported_symbol_iterator>
1350ImportDirectoryEntryRef::imported_symbols() const {
1351 return make_range(imported_symbol_begin(), imported_symbol_end());
1352}
1353
1354imported_symbol_iterator ImportDirectoryEntryRef::lookup_table_begin() const {
1355 return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA,
1356 OwningObject);
1357}
1358
1359imported_symbol_iterator ImportDirectoryEntryRef::lookup_table_end() const {
1360 return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA,
1361 OwningObject);
1362}
1363
1364iterator_range<imported_symbol_iterator>
1365ImportDirectoryEntryRef::lookup_table_symbols() const {
1366 return make_range(lookup_table_begin(), lookup_table_end());
1367}
1368
1369std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1370 uintptr_t IntPtr = 0;
1371 if (std::error_code EC =
1372 OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr))
1373 return EC;
1374 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1375 return std::error_code();
1376}
1377
1378std::error_code
1379ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t &Result) const {
1380 Result = ImportTable[Index].ImportLookupTableRVA;
1381 return std::error_code();
1382}
1383
1384std::error_code
1385ImportDirectoryEntryRef::getImportAddressTableRVA(uint32_t &Result) const {
1386 Result = ImportTable[Index].ImportAddressTableRVA;
1387 return std::error_code();
1388}
1389
1390bool DelayImportDirectoryEntryRef::
1391operator==(const DelayImportDirectoryEntryRef &Other) const {
1392 return Table == Other.Table && Index == Other.Index;
1393}
1394
1395void DelayImportDirectoryEntryRef::moveNext() {
1396 ++Index;
1397}
1398
1399imported_symbol_iterator
1400DelayImportDirectoryEntryRef::imported_symbol_begin() const {
1401 return importedSymbolBegin(Table[Index].DelayImportNameTable,
1402 OwningObject);
1403}
1404
1405imported_symbol_iterator
1406DelayImportDirectoryEntryRef::imported_symbol_end() const {
1407 return importedSymbolEnd(Table[Index].DelayImportNameTable,
1408 OwningObject);
1409}
1410
1411iterator_range<imported_symbol_iterator>
1412DelayImportDirectoryEntryRef::imported_symbols() const {
1413 return make_range(imported_symbol_begin(), imported_symbol_end());
1414}
1415
1416std::error_code DelayImportDirectoryEntryRef::getName(StringRef &Result) const {
1417 uintptr_t IntPtr = 0;
1418 if (std::error_code EC = OwningObject->getRvaPtr(Table[Index].Name, IntPtr))
1419 return EC;
1420 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1421 return std::error_code();
1422}
1423
1424std::error_code DelayImportDirectoryEntryRef::
1425getDelayImportTable(const delay_import_directory_table_entry *&Result) const {
1426 Result = Table;
1427 return std::error_code();
1428}
1429
1430std::error_code DelayImportDirectoryEntryRef::
1431getImportAddress(int AddrIndex, uint64_t &Result) const {
1432 uint32_t RVA = Table[Index].DelayImportAddressTable +
1433 AddrIndex * (OwningObject->is64() ? 8 : 4);
1434 uintptr_t IntPtr = 0;
1435 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1436 return EC;
1437 if (OwningObject->is64())
1438 Result = *reinterpret_cast<const ulittle64_t *>(IntPtr);
1439 else
1440 Result = *reinterpret_cast<const ulittle32_t *>(IntPtr);
1441 return std::error_code();
1442}
1443
1444bool ExportDirectoryEntryRef::
1445operator==(const ExportDirectoryEntryRef &Other) const {
1446 return ExportTable == Other.ExportTable && Index == Other.Index;
1447}
1448
1449void ExportDirectoryEntryRef::moveNext() {
1450 ++Index;
1451}
1452
1453// Returns the name of the current export symbol. If the symbol is exported only
1454// by ordinal, the empty string is set as a result.
1455std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1456 uintptr_t IntPtr = 0;
1457 if (std::error_code EC =
1458 OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1459 return EC;
1460 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1461 return std::error_code();
1462}
1463
1464// Returns the starting ordinal number.
1465std::error_code
1466ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1467 Result = ExportTable->OrdinalBase;
1468 return std::error_code();
1469}
1470
1471// Returns the export ordinal of the current export symbol.
1472std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1473 Result = ExportTable->OrdinalBase + Index;
1474 return std::error_code();
1475}
1476
1477// Returns the address of the current export symbol.
1478std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1479 uintptr_t IntPtr = 0;
1480 if (std::error_code EC =
1481 OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1482 return EC;
1483 const export_address_table_entry *entry =
1484 reinterpret_cast<const export_address_table_entry *>(IntPtr);
1485 Result = entry[Index].ExportRVA;
1486 return std::error_code();
1487}
1488
1489// Returns the name of the current export symbol. If the symbol is exported only
1490// by ordinal, the empty string is set as a result.
1491std::error_code
1492ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1493 uintptr_t IntPtr = 0;
1494 if (std::error_code EC =
1495 OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1496 return EC;
1497 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1498
1499 uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1500 int Offset = 0;
1501 for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1502 I < E; ++I, ++Offset) {
1503 if (*I != Index)
1504 continue;
1505 if (std::error_code EC =
1506 OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1507 return EC;
1508 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1509 if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1510 return EC;
1511 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1512 return std::error_code();
1513 }
1514 Result = "";
1515 return std::error_code();
1516}
1517
1518std::error_code ExportDirectoryEntryRef::isForwarder(bool &Result) const {
1519 const data_directory *DataEntry;
1520 if (auto EC = OwningObject->getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
1521 return EC;
1522 uint32_t RVA;
1523 if (auto EC = getExportRVA(RVA))
1524 return EC;
1525 uint32_t Begin = DataEntry->RelativeVirtualAddress;
1526 uint32_t End = DataEntry->RelativeVirtualAddress + DataEntry->Size;
1527 Result = (Begin <= RVA && RVA < End);
1528 return std::error_code();
1529}
1530
1531std::error_code ExportDirectoryEntryRef::getForwardTo(StringRef &Result) const {
1532 uint32_t RVA;
1533 if (auto EC = getExportRVA(RVA))
1534 return EC;
1535 uintptr_t IntPtr = 0;
1536 if (auto EC = OwningObject->getRvaPtr(RVA, IntPtr))
1537 return EC;
1538 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1539 return std::error_code();
1540}
1541
1542bool ImportedSymbolRef::
1543operator==(const ImportedSymbolRef &Other) const {
1544 return Entry32 == Other.Entry32 && Entry64 == Other.Entry64
1545 && Index == Other.Index;
1546}
1547
1548void ImportedSymbolRef::moveNext() {
1549 ++Index;
1550}
1551
1552std::error_code
1553ImportedSymbolRef::getSymbolName(StringRef &Result) const {
1554 uint32_t RVA;
1555 if (Entry32) {
1556 // If a symbol is imported only by ordinal, it has no name.
1557 if (Entry32[Index].isOrdinal())
1558 return std::error_code();
1559 RVA = Entry32[Index].getHintNameRVA();
1560 } else {
1561 if (Entry64[Index].isOrdinal())
1562 return std::error_code();
1563 RVA = Entry64[Index].getHintNameRVA();
1564 }
1565 uintptr_t IntPtr = 0;
1566 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1567 return EC;
1568 // +2 because the first two bytes is hint.
1569 Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2));
1570 return std::error_code();
1571}
1572
1573std::error_code ImportedSymbolRef::isOrdinal(bool &Result) const {
1574 if (Entry32)
1575 Result = Entry32[Index].isOrdinal();
1576 else
1577 Result = Entry64[Index].isOrdinal();
1578 return std::error_code();
1579}
1580
1581std::error_code ImportedSymbolRef::getHintNameRVA(uint32_t &Result) const {
1582 if (Entry32)
1583 Result = Entry32[Index].getHintNameRVA();
1584 else
1585 Result = Entry64[Index].getHintNameRVA();
1586 return std::error_code();
1587}
1588
1589std::error_code ImportedSymbolRef::getOrdinal(uint16_t &Result) const {
1590 uint32_t RVA;
1591 if (Entry32) {
1592 if (Entry32[Index].isOrdinal()) {
1593 Result = Entry32[Index].getOrdinal();
1594 return std::error_code();
1595 }
1596 RVA = Entry32[Index].getHintNameRVA();
1597 } else {
1598 if (Entry64[Index].isOrdinal()) {
1599 Result = Entry64[Index].getOrdinal();
1600 return std::error_code();
1601 }
1602 RVA = Entry64[Index].getHintNameRVA();
1603 }
1604 uintptr_t IntPtr = 0;
1605 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1606 return EC;
1607 Result = *reinterpret_cast<const ulittle16_t *>(IntPtr);
1608 return std::error_code();
1609}
1610
1611Expected<std::unique_ptr<COFFObjectFile>>
1612ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1613 std::error_code EC;
1614 std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1615 if (EC)
1616 return errorCodeToError(EC);
1617 return std::move(Ret);
1618}
1619
1620bool BaseRelocRef::operator==(const BaseRelocRef &Other) const {
1621 return Header == Other.Header && Index == Other.Index;
1622}
1623
1624void BaseRelocRef::moveNext() {
1625 // Header->BlockSize is the size of the current block, including the
1626 // size of the header itself.
1627 uint32_t Size = sizeof(*Header) +
1628 sizeof(coff_base_reloc_block_entry) * (Index + 1);
1629 if (Size == Header->BlockSize) {
1630 // .reloc contains a list of base relocation blocks. Each block
1631 // consists of the header followed by entries. The header contains
1632 // how many entories will follow. When we reach the end of the
1633 // current block, proceed to the next block.
1634 Header = reinterpret_cast<const coff_base_reloc_block_header *>(
1635 reinterpret_cast<const uint8_t *>(Header) + Size);
1636 Index = 0;
1637 } else {
1638 ++Index;
1639 }
1640}
1641
1642std::error_code BaseRelocRef::getType(uint8_t &Type) const {
1643 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1644 Type = Entry[Index].getType();
1645 return std::error_code();
1646}
1647
1648std::error_code BaseRelocRef::getRVA(uint32_t &Result) const {
1649 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1650 Result = Header->PageRVA + Entry[Index].getOffset();
1651 return std::error_code();
1652}
1653
1654#define RETURN_IF_ERROR(E)if (E) return E; \
1655 if (E) \
1656 return E;
1657
1658Expected<ArrayRef<UTF16>>
1659ResourceSectionRef::getDirStringAtOffset(uint32_t Offset) {
1660 BinaryStreamReader Reader = BinaryStreamReader(BBS);
1661 Reader.setOffset(Offset);
1662 uint16_t Length;
1663 RETURN_IF_ERROR(Reader.readInteger(Length))if (Reader.readInteger(Length)) return Reader.readInteger(Length
);
;
1664 ArrayRef<UTF16> RawDirString;
1665 RETURN_IF_ERROR(Reader.readArray(RawDirString, Length))if (Reader.readArray(RawDirString, Length)) return Reader.readArray
(RawDirString, Length);
;
1666 return RawDirString;
1667}
1668
1669Expected<ArrayRef<UTF16>>
1670ResourceSectionRef::getEntryNameString(const coff_resource_dir_entry &Entry) {
1671 return getDirStringAtOffset(Entry.Identifier.getNameOffset());
1672}
1673
1674Expected<const coff_resource_dir_table &>
1675ResourceSectionRef::getTableAtOffset(uint32_t Offset) {
1676 const coff_resource_dir_table *Table = nullptr;
1677
1678 BinaryStreamReader Reader(BBS);
1679 Reader.setOffset(Offset);
1680 RETURN_IF_ERROR(Reader.readObject(Table))if (Reader.readObject(Table)) return Reader.readObject(Table)
;
;
1681 assert(Table != nullptr)(static_cast <bool> (Table != nullptr) ? void (0) : __assert_fail
("Table != nullptr", "/build/llvm-toolchain-snapshot-7~svn338205/lib/Object/COFFObjectFile.cpp"
, 1681, __extension__ __PRETTY_FUNCTION__))
;
1682 return *Table;
1683}
1684
1685Expected<const coff_resource_dir_table &>
1686ResourceSectionRef::getEntrySubDir(const coff_resource_dir_entry &Entry) {
1687 return getTableAtOffset(Entry.Offset.value());
1688}
1689
1690Expected<const coff_resource_dir_table &> ResourceSectionRef::getBaseTable() {
1691 return getTableAtOffset(0);
1692}

/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; }
2
Assuming the condition is false
3
'?' condition is false
4
Called C++ object pointer is null
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())
1008 return errorToErrorCode(std::move(E));
1009 Res = reinterpret_cast<const T *>(S->getRawPtr());
1010 return std::error_code();
1011 }
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