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-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 -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-8/lib/clang/8.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-8~svn350071/build-llvm/lib/Object -I /build/llvm-toolchain-snapshot-8~svn350071/lib/Object -I /build/llvm-toolchain-snapshot-8~svn350071/build-llvm/include -I /build/llvm-toolchain-snapshot-8~svn350071/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/8.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-8/lib/clang/8.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-8~svn350071/build-llvm/lib/Object -fdebug-prefix-map=/build/llvm-toolchain-snapshot-8~svn350071=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-12-27-042839-1215-1 -x c++ /build/llvm-toolchain-snapshot-8~svn350071/lib/Object/COFFObjectFile.cpp -faddrsig

/build/llvm-toolchain-snapshot-8~svn350071/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.")((Str.size() <= 6 && "String too long, possible overflow."
) ? static_cast<void> (0) : __assert_fail ("Str.size() <= 6 && \"String too long, possible overflow.\""
, "/build/llvm-toolchain-snapshot-8~svn350071/lib/Object/COFFObjectFile.cpp"
, 71, __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)))((!checkOffset(Data, uintptr_t(Addr), sizeof(*Addr))) ? static_cast
<void> (0) : __assert_fail ("!checkOffset(Data, uintptr_t(Addr), sizeof(*Addr))"
, "/build/llvm-toolchain-snapshot-8~svn350071/lib/Object/COFFObjectFile.cpp"
, 107, __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 &&(((Offset - getPointerToSymbolTable()) % sizeof(coff_symbol_type
) == 0 && "Symbol did not point to the beginning of a symbol"
) ? static_cast<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-8~svn350071/lib/Object/COFFObjectFile.cpp"
, 113, __PRETTY_FUNCTION__))
113 "Symbol did not point to the beginning of a symbol")(((Offset - getPointerToSymbolTable()) % sizeof(coff_symbol_type
) == 0 && "Symbol did not point to the beginning of a symbol"
) ? static_cast<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-8~svn350071/lib/Object/COFFObjectFile.cpp"
, 113, __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 &&((Offset % sizeof(coff_section) == 0 && "Section did not point to the beginning of a section"
) ? static_cast<void> (0) : __assert_fail ("Offset % sizeof(coff_section) == 0 && \"Section did not point to the beginning of a section\""
, "/build/llvm-toolchain-snapshot-8~svn350071/lib/Object/COFFObjectFile.cpp"
, 129, __PRETTY_FUNCTION__))
129 "Section did not point to the beginning of a section")((Offset % sizeof(coff_section) == 0 && "Section did not point to the beginning of a section"
) ? static_cast<void> (0) : __assert_fail ("Offset % sizeof(coff_section) == 0 && \"Section did not point to the beginning of a section\""
, "/build/llvm-toolchain-snapshot-8~svn350071/lib/Object/COFFObjectFile.cpp"
, 129, __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-8~svn350071/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)(((Offset % sizeof(coff_section)) == 0) ? static_cast<void
> (0) : __assert_fail ("(Offset % sizeof(coff_section)) == 0"
, "/build/llvm-toolchain-snapshot-8~svn350071/lib/Object/COFFObjectFile.cpp"
, 336, __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)((Rva <= (4294967295U)) ? static_cast<void> (0) : __assert_fail
("Rva <= UINT32_MAX", "/build/llvm-toolchain-snapshot-8~svn350071/lib/Object/COFFObjectFile.cpp"
, 454, __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 // FIXME: Verify the section containing BaseRelocHeader has at least
620 // DataEntry->Size bytes after DataEntry->RelativeVirtualAddress.
621 return std::error_code();
622}
623
624std::error_code COFFObjectFile::initDebugDirectoryPtr() {
625 // Get the RVA of the debug directory. Do nothing if it does not exist.
626 const data_directory *DataEntry;
627 if (getDataDirectory(COFF::DEBUG_DIRECTORY, DataEntry))
628 return std::error_code();
629
630 // Do nothing if the RVA is NULL.
631 if (DataEntry->RelativeVirtualAddress == 0)
632 return std::error_code();
633
634 // Check that the size is a multiple of the entry size.
635 if (DataEntry->Size % sizeof(debug_directory) != 0)
636 return object_error::parse_failed;
637
638 uintptr_t IntPtr = 0;
639 if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
640 return EC;
641 DebugDirectoryBegin = reinterpret_cast<const debug_directory *>(IntPtr);
642 DebugDirectoryEnd = reinterpret_cast<const debug_directory *>(
643 IntPtr + DataEntry->Size);
644 // FIXME: Verify the section containing DebugDirectoryBegin has at least
645 // DataEntry->Size bytes after DataEntry->RelativeVirtualAddress.
646 return std::error_code();
647}
648
649std::error_code COFFObjectFile::initLoadConfigPtr() {
650 // Get the RVA of the debug directory. Do nothing if it does not exist.
651 const data_directory *DataEntry;
652 if (getDataDirectory(COFF::LOAD_CONFIG_TABLE, DataEntry))
653 return std::error_code();
654
655 // Do nothing if the RVA is NULL.
656 if (DataEntry->RelativeVirtualAddress == 0)
657 return std::error_code();
658 uintptr_t IntPtr = 0;
659 if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
660 return EC;
661
662 LoadConfig = (const void *)IntPtr;
663 return std::error_code();
664}
665
666COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC)
667 : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
668 COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
669 DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
670 SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
671 ImportDirectory(nullptr),
672 DelayImportDirectory(nullptr), NumberOfDelayImportDirectory(0),
673 ExportDirectory(nullptr), BaseRelocHeader(nullptr), BaseRelocEnd(nullptr),
674 DebugDirectoryBegin(nullptr), DebugDirectoryEnd(nullptr) {
675 // Check that we at least have enough room for a header.
676 if (!checkSize(Data, EC, sizeof(coff_file_header)))
677 return;
678
679 // The current location in the file where we are looking at.
680 uint64_t CurPtr = 0;
681
682 // PE header is optional and is present only in executables. If it exists,
683 // it is placed right after COFF header.
684 bool HasPEHeader = false;
685
686 // Check if this is a PE/COFF file.
687 if (checkSize(Data, EC, sizeof(dos_header) + sizeof(COFF::PEMagic))) {
688 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
689 // PE signature to find 'normal' COFF header.
690 const auto *DH = reinterpret_cast<const dos_header *>(base());
691 if (DH->Magic[0] == 'M' && DH->Magic[1] == 'Z') {
692 CurPtr = DH->AddressOfNewExeHeader;
693 // Check the PE magic bytes. ("PE\0\0")
694 if (memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) != 0) {
695 EC = object_error::parse_failed;
696 return;
697 }
698 CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
699 HasPEHeader = true;
700 }
701 }
702
703 if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
704 return;
705
706 // It might be a bigobj file, let's check. Note that COFF bigobj and COFF
707 // import libraries share a common prefix but bigobj is more restrictive.
708 if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
709 COFFHeader->NumberOfSections == uint16_t(0xffff) &&
710 checkSize(Data, EC, sizeof(coff_bigobj_file_header))) {
711 if ((EC = getObject(COFFBigObjHeader, Data, base() + CurPtr)))
712 return;
713
714 // Verify that we are dealing with bigobj.
715 if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
716 std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic,
717 sizeof(COFF::BigObjMagic)) == 0) {
718 COFFHeader = nullptr;
719 CurPtr += sizeof(coff_bigobj_file_header);
720 } else {
721 // It's not a bigobj.
722 COFFBigObjHeader = nullptr;
723 }
724 }
725 if (COFFHeader) {
726 // The prior checkSize call may have failed. This isn't a hard error
727 // because we were just trying to sniff out bigobj.
728 EC = std::error_code();
729 CurPtr += sizeof(coff_file_header);
730
731 if (COFFHeader->isImportLibrary())
732 return;
733 }
734
735 if (HasPEHeader) {
736 const pe32_header *Header;
737 if ((EC = getObject(Header, Data, base() + CurPtr)))
738 return;
739
740 const uint8_t *DataDirAddr;
741 uint64_t DataDirSize;
742 if (Header->Magic == COFF::PE32Header::PE32) {
743 PE32Header = Header;
744 DataDirAddr = base() + CurPtr + sizeof(pe32_header);
745 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
746 } else if (Header->Magic == COFF::PE32Header::PE32_PLUS) {
747 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
748 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
749 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
750 } else {
751 // It's neither PE32 nor PE32+.
752 EC = object_error::parse_failed;
753 return;
754 }
755 if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
756 return;
757 }
758
759 if (COFFHeader)
760 CurPtr += COFFHeader->SizeOfOptionalHeader;
761
762 if ((EC = getObject(SectionTable, Data, base() + CurPtr,
763 (uint64_t)getNumberOfSections() * sizeof(coff_section))))
764 return;
765
766 // Initialize the pointer to the symbol table.
767 if (getPointerToSymbolTable() != 0) {
768 if ((EC = initSymbolTablePtr())) {
769 SymbolTable16 = nullptr;
770 SymbolTable32 = nullptr;
771 StringTable = nullptr;
772 StringTableSize = 0;
773 }
774 } else {
775 // We had better not have any symbols if we don't have a symbol table.
776 if (getNumberOfSymbols() != 0) {
777 EC = object_error::parse_failed;
778 return;
779 }
780 }
781
782 // Initialize the pointer to the beginning of the import table.
783 if ((EC = initImportTablePtr()))
784 return;
785 if ((EC = initDelayImportTablePtr()))
786 return;
787
788 // Initialize the pointer to the export table.
789 if ((EC = initExportTablePtr()))
790 return;
791
792 // Initialize the pointer to the base relocation table.
793 if ((EC = initBaseRelocPtr()))
794 return;
795
796 // Initialize the pointer to the export table.
797 if ((EC = initDebugDirectoryPtr()))
798 return;
799
800 if ((EC = initLoadConfigPtr()))
801 return;
802
803 EC = std::error_code();
804}
805
806basic_symbol_iterator COFFObjectFile::symbol_begin() const {
807 DataRefImpl Ret;
808 Ret.p = getSymbolTable();
809 return basic_symbol_iterator(SymbolRef(Ret, this));
810}
811
812basic_symbol_iterator COFFObjectFile::symbol_end() const {
813 // The symbol table ends where the string table begins.
814 DataRefImpl Ret;
815 Ret.p = reinterpret_cast<uintptr_t>(StringTable);
816 return basic_symbol_iterator(SymbolRef(Ret, this));
817}
818
819import_directory_iterator COFFObjectFile::import_directory_begin() const {
820 if (!ImportDirectory)
821 return import_directory_end();
822 if (ImportDirectory->isNull())
823 return import_directory_end();
824 return import_directory_iterator(
825 ImportDirectoryEntryRef(ImportDirectory, 0, this));
826}
827
828import_directory_iterator COFFObjectFile::import_directory_end() const {
829 return import_directory_iterator(
830 ImportDirectoryEntryRef(nullptr, -1, this));
831}
832
833delay_import_directory_iterator
834COFFObjectFile::delay_import_directory_begin() const {
835 return delay_import_directory_iterator(
836 DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this));
837}
838
839delay_import_directory_iterator
840COFFObjectFile::delay_import_directory_end() const {
841 return delay_import_directory_iterator(
842 DelayImportDirectoryEntryRef(
843 DelayImportDirectory, NumberOfDelayImportDirectory, this));
844}
845
846export_directory_iterator COFFObjectFile::export_directory_begin() const {
847 return export_directory_iterator(
848 ExportDirectoryEntryRef(ExportDirectory, 0, this));
849}
850
851export_directory_iterator COFFObjectFile::export_directory_end() const {
852 if (!ExportDirectory)
853 return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
854 ExportDirectoryEntryRef Ref(ExportDirectory,
855 ExportDirectory->AddressTableEntries, this);
856 return export_directory_iterator(Ref);
857}
858
859section_iterator COFFObjectFile::section_begin() const {
860 DataRefImpl Ret;
861 Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
862 return section_iterator(SectionRef(Ret, this));
863}
864
865section_iterator COFFObjectFile::section_end() const {
866 DataRefImpl Ret;
867 int NumSections =
868 COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
869 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
870 return section_iterator(SectionRef(Ret, this));
871}
872
873base_reloc_iterator COFFObjectFile::base_reloc_begin() const {
874 return base_reloc_iterator(BaseRelocRef(BaseRelocHeader, this));
875}
876
877base_reloc_iterator COFFObjectFile::base_reloc_end() const {
878 return base_reloc_iterator(BaseRelocRef(BaseRelocEnd, this));
879}
880
881uint8_t COFFObjectFile::getBytesInAddress() const {
882 return getArch() == Triple::x86_64 || getArch() == Triple::aarch64 ? 8 : 4;
883}
884
885StringRef COFFObjectFile::getFileFormatName() const {
886 switch(getMachine()) {
887 case COFF::IMAGE_FILE_MACHINE_I386:
888 return "COFF-i386";
889 case COFF::IMAGE_FILE_MACHINE_AMD64:
890 return "COFF-x86-64";
891 case COFF::IMAGE_FILE_MACHINE_ARMNT:
892 return "COFF-ARM";
893 case COFF::IMAGE_FILE_MACHINE_ARM64:
894 return "COFF-ARM64";
895 default:
896 return "COFF-<unknown arch>";
897 }
898}
899
900Triple::ArchType COFFObjectFile::getArch() const {
901 switch (getMachine()) {
902 case COFF::IMAGE_FILE_MACHINE_I386:
903 return Triple::x86;
904 case COFF::IMAGE_FILE_MACHINE_AMD64:
905 return Triple::x86_64;
906 case COFF::IMAGE_FILE_MACHINE_ARMNT:
907 return Triple::thumb;
908 case COFF::IMAGE_FILE_MACHINE_ARM64:
909 return Triple::aarch64;
910 default:
911 return Triple::UnknownArch;
912 }
913}
914
915Expected<uint64_t> COFFObjectFile::getStartAddress() const {
916 if (PE32Header)
917 return PE32Header->AddressOfEntryPoint;
918 return 0;
919}
920
921iterator_range<import_directory_iterator>
922COFFObjectFile::import_directories() const {
923 return make_range(import_directory_begin(), import_directory_end());
924}
925
926iterator_range<delay_import_directory_iterator>
927COFFObjectFile::delay_import_directories() const {
928 return make_range(delay_import_directory_begin(),
929 delay_import_directory_end());
930}
931
932iterator_range<export_directory_iterator>
933COFFObjectFile::export_directories() const {
934 return make_range(export_directory_begin(), export_directory_end());
935}
936
937iterator_range<base_reloc_iterator> COFFObjectFile::base_relocs() const {
938 return make_range(base_reloc_begin(), base_reloc_end());
939}
940
941std::error_code
942COFFObjectFile::getCOFFHeader(const coff_file_header *&Res) const {
943 Res = COFFHeader;
944 return std::error_code();
945}
946
947std::error_code
948COFFObjectFile::getCOFFBigObjHeader(const coff_bigobj_file_header *&Res) const {
949 Res = COFFBigObjHeader;
950 return std::error_code();
951}
952
953std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
954 Res = PE32Header;
955 return std::error_code();
956}
957
958std::error_code
959COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
960 Res = PE32PlusHeader;
961 return std::error_code();
962}
963
964std::error_code
965COFFObjectFile::getDataDirectory(uint32_t Index,
966 const data_directory *&Res) const {
967 // Error if there's no data directory or the index is out of range.
968 if (!DataDirectory) {
969 Res = nullptr;
970 return object_error::parse_failed;
971 }
972 assert(PE32Header || PE32PlusHeader)((PE32Header || PE32PlusHeader) ? static_cast<void> (0)
: __assert_fail ("PE32Header || PE32PlusHeader", "/build/llvm-toolchain-snapshot-8~svn350071/lib/Object/COFFObjectFile.cpp"
, 972, __PRETTY_FUNCTION__))
;
973 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
974 : PE32PlusHeader->NumberOfRvaAndSize;
975 if (Index >= NumEnt) {
976 Res = nullptr;
977 return object_error::parse_failed;
978 }
979 Res = &DataDirectory[Index];
980 return std::error_code();
981}
982
983std::error_code COFFObjectFile::getSection(int32_t Index,
984 const coff_section *&Result) const {
985 Result = nullptr;
986 if (COFF::isReservedSectionNumber(Index))
987 return std::error_code();
988 if (static_cast<uint32_t>(Index) <= getNumberOfSections()) {
989 // We already verified the section table data, so no need to check again.
990 Result = SectionTable + (Index - 1);
991 return std::error_code();
992 }
993 return object_error::parse_failed;
994}
995
996std::error_code COFFObjectFile::getSection(StringRef SectionName,
997 const coff_section *&Result) const {
998 Result = nullptr;
999 StringRef SecName;
1000 for (const SectionRef &Section : sections()) {
1001 if (std::error_code E = Section.getName(SecName))
1002 return E;
1003 if (SecName == SectionName) {
1004 Result = getCOFFSection(Section);
1005 return std::error_code();
1006 }
1007 }
1008 return object_error::parse_failed;
1009}
1010
1011std::error_code COFFObjectFile::getString(uint32_t Offset,
1012 StringRef &Result) const {
1013 if (StringTableSize <= 4)
1014 // Tried to get a string from an empty string table.
1015 return object_error::parse_failed;
1016 if (Offset >= StringTableSize)
1017 return object_error::unexpected_eof;
1018 Result = StringRef(StringTable + Offset);
1019 return std::error_code();
1020}
1021
1022std::error_code COFFObjectFile::getSymbolName(COFFSymbolRef Symbol,
1023 StringRef &Res) const {
1024 return getSymbolName(Symbol.getGeneric(), Res);
1025}
1026
1027std::error_code COFFObjectFile::getSymbolName(const coff_symbol_generic *Symbol,
1028 StringRef &Res) const {
1029 // Check for string table entry. First 4 bytes are 0.
1030 if (Symbol->Name.Offset.Zeroes == 0) {
1031 if (std::error_code EC = getString(Symbol->Name.Offset.Offset, Res))
1032 return EC;
1033 return std::error_code();
1034 }
1035
1036 if (Symbol->Name.ShortName[COFF::NameSize - 1] == 0)
1037 // Null terminated, let ::strlen figure out the length.
1038 Res = StringRef(Symbol->Name.ShortName);
1039 else
1040 // Not null terminated, use all 8 bytes.
1041 Res = StringRef(Symbol->Name.ShortName, COFF::NameSize);
1042 return std::error_code();
1043}
1044
1045ArrayRef<uint8_t>
1046COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
1047 const uint8_t *Aux = nullptr;
1048
1049 size_t SymbolSize = getSymbolTableEntrySize();
1050 if (Symbol.getNumberOfAuxSymbols() > 0) {
1051 // AUX data comes immediately after the symbol in COFF
1052 Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
1053#ifndef NDEBUG
1054 // Verify that the Aux symbol points to a valid entry in the symbol table.
1055 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
1056 if (Offset < getPointerToSymbolTable() ||
1057 Offset >=
1058 getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
1059 report_fatal_error("Aux Symbol data was outside of symbol table.");
1060
1061 assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&(((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
"Aux Symbol data did not point to the beginning of a symbol"
) ? static_cast<void> (0) : __assert_fail ("(Offset - getPointerToSymbolTable()) % SymbolSize == 0 && \"Aux Symbol data did not point to the beginning of a symbol\""
, "/build/llvm-toolchain-snapshot-8~svn350071/lib/Object/COFFObjectFile.cpp"
, 1062, __PRETTY_FUNCTION__))
1062 "Aux Symbol data did not point to the beginning of a symbol")(((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
"Aux Symbol data did not point to the beginning of a symbol"
) ? static_cast<void> (0) : __assert_fail ("(Offset - getPointerToSymbolTable()) % SymbolSize == 0 && \"Aux Symbol data did not point to the beginning of a symbol\""
, "/build/llvm-toolchain-snapshot-8~svn350071/lib/Object/COFFObjectFile.cpp"
, 1062, __PRETTY_FUNCTION__))
;
1063#endif
1064 }
1065 return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
1066}
1067
1068std::error_code COFFObjectFile::getSectionName(const coff_section *Sec,
1069 StringRef &Res) const {
1070 StringRef Name;
1071 if (Sec->Name[COFF::NameSize - 1] == 0)
1072 // Null terminated, let ::strlen figure out the length.
1073 Name = Sec->Name;
1074 else
1075 // Not null terminated, use all 8 bytes.
1076 Name = StringRef(Sec->Name, COFF::NameSize);
1077
1078 // Check for string table entry. First byte is '/'.
1079 if (Name.startswith("/")) {
1080 uint32_t Offset;
1081 if (Name.startswith("//")) {
1082 if (decodeBase64StringEntry(Name.substr(2), Offset))
1083 return object_error::parse_failed;
1084 } else {
1085 if (Name.substr(1).getAsInteger(10, Offset))
1086 return object_error::parse_failed;
1087 }
1088 if (std::error_code EC = getString(Offset, Name))
1089 return EC;
1090 }
1091
1092 Res = Name;
1093 return std::error_code();
1094}
1095
1096uint64_t COFFObjectFile::getSectionSize(const coff_section *Sec) const {
1097 // SizeOfRawData and VirtualSize change what they represent depending on
1098 // whether or not we have an executable image.
1099 //
1100 // For object files, SizeOfRawData contains the size of section's data;
1101 // VirtualSize should be zero but isn't due to buggy COFF writers.
1102 //
1103 // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the
1104 // actual section size is in VirtualSize. It is possible for VirtualSize to
1105 // be greater than SizeOfRawData; the contents past that point should be
1106 // considered to be zero.
1107 if (getDOSHeader())
1108 return std::min(Sec->VirtualSize, Sec->SizeOfRawData);
1109 return Sec->SizeOfRawData;
1110}
1111
1112std::error_code
1113COFFObjectFile::getSectionContents(const coff_section *Sec,
1114 ArrayRef<uint8_t> &Res) const {
1115 // In COFF, a virtual section won't have any in-file
1116 // content, so the file pointer to the content will be zero.
1117 if (Sec->PointerToRawData == 0)
1118 return std::error_code();
1119 // The only thing that we need to verify is that the contents is contained
1120 // within the file bounds. We don't need to make sure it doesn't cover other
1121 // data, as there's nothing that says that is not allowed.
1122 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
1123 uint32_t SectionSize = getSectionSize(Sec);
1124 if (checkOffset(Data, ConStart, SectionSize))
1125 return object_error::parse_failed;
1126 Res = makeArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize);
1127 return std::error_code();
1128}
1129
1130const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
1131 return reinterpret_cast<const coff_relocation*>(Rel.p);
1132}
1133
1134void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
1135 Rel.p = reinterpret_cast<uintptr_t>(
1136 reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
1137}
1138
1139uint64_t COFFObjectFile::getRelocationOffset(DataRefImpl Rel) const {
1140 const coff_relocation *R = toRel(Rel);
1141 return R->VirtualAddress;
1142}
1143
1144symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
1145 const coff_relocation *R = toRel(Rel);
1146 DataRefImpl Ref;
1147 if (R->SymbolTableIndex >= getNumberOfSymbols())
1148 return symbol_end();
1149 if (SymbolTable16)
1150 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
1151 else if (SymbolTable32)
1152 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
1153 else
1154 llvm_unreachable("no symbol table pointer!")::llvm::llvm_unreachable_internal("no symbol table pointer!",
"/build/llvm-toolchain-snapshot-8~svn350071/lib/Object/COFFObjectFile.cpp"
, 1154)
;
1155 return symbol_iterator(SymbolRef(Ref, this));
1156}
1157
1158uint64_t COFFObjectFile::getRelocationType(DataRefImpl Rel) const {
1159 const coff_relocation* R = toRel(Rel);
1160 return R->Type;
1161}
1162
1163const coff_section *
1164COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
1165 return toSec(Section.getRawDataRefImpl());
1166}
1167
1168COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
1169 if (SymbolTable16)
1170 return toSymb<coff_symbol16>(Ref);
1171 if (SymbolTable32)
1172 return toSymb<coff_symbol32>(Ref);
1173 llvm_unreachable("no symbol table pointer!")::llvm::llvm_unreachable_internal("no symbol table pointer!",
"/build/llvm-toolchain-snapshot-8~svn350071/lib/Object/COFFObjectFile.cpp"
, 1173)
;
1174}
1175
1176COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
1177 return getCOFFSymbol(Symbol.getRawDataRefImpl());
1178}
1179
1180const coff_relocation *
1181COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
1182 return toRel(Reloc.getRawDataRefImpl());
1183}
1184
1185ArrayRef<coff_relocation>
1186COFFObjectFile::getRelocations(const coff_section *Sec) const {
1187 return {getFirstReloc(Sec, Data, base()),
1188 getNumberOfRelocations(Sec, Data, base())};
1189}
1190
1191#define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \
1192 case COFF::reloc_type: \
1193 return #reloc_type;
1194
1195StringRef COFFObjectFile::getRelocationTypeName(uint16_t Type) const {
1196 switch (getMachine()) {
1197 case COFF::IMAGE_FILE_MACHINE_AMD64:
1198 switch (Type) {
1199 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
1200 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
1201 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
1202 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
1203 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
1204 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
1205 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
1206 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
1207 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
1208 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
1209 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
1210 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
1211 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
1212 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
1213 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
1214 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
1215 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
1216 default:
1217 return "Unknown";
1218 }
1219 break;
1220 case COFF::IMAGE_FILE_MACHINE_ARMNT:
1221 switch (Type) {
1222 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
1223 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
1224 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
1225 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
1226 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
1227 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
1228 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
1229 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
1230 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
1231 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
1232 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
1233 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
1234 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
1235 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
1236 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
1237 default:
1238 return "Unknown";
1239 }
1240 break;
1241 case COFF::IMAGE_FILE_MACHINE_ARM64:
1242 switch (Type) {
1243 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ABSOLUTE);
1244 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ADDR32);
1245 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ADDR32NB);
1246 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_BRANCH26);
1247 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_PAGEBASE_REL21);
1248 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_REL21);
1249 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_PAGEOFFSET_12A);
1250 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_PAGEOFFSET_12L);
1251 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL);
1252 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL_LOW12A);
1253 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL_HIGH12A);
1254 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL_LOW12L);
1255 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_TOKEN);
1256 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECTION);
1257 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ADDR64);
1258 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_BRANCH19);
1259 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_BRANCH14);
1260 default:
1261 return "Unknown";
1262 }
1263 break;
1264 case COFF::IMAGE_FILE_MACHINE_I386:
1265 switch (Type) {
1266 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
1267 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
1268 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
1269 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
1270 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
1271 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
1272 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
1273 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
1274 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
1275 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
1276 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
1277 default:
1278 return "Unknown";
1279 }
1280 break;
1281 default:
1282 return "Unknown";
1283 }
1284}
1285
1286#undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1287
1288void COFFObjectFile::getRelocationTypeName(
1289 DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
1290 const coff_relocation *Reloc = toRel(Rel);
1291 StringRef Res = getRelocationTypeName(Reloc->Type);
1292 Result.append(Res.begin(), Res.end());
1293}
1294
1295bool COFFObjectFile::isRelocatableObject() const {
1296 return !DataDirectory;
1297}
1298
1299StringRef COFFObjectFile::mapDebugSectionName(StringRef Name) const {
1300 return StringSwitch<StringRef>(Name)
1301 .Case("eh_fram", "eh_frame")
1302 .Default(Name);
1303}
1304
1305bool ImportDirectoryEntryRef::
1306operator==(const ImportDirectoryEntryRef &Other) const {
1307 return ImportTable == Other.ImportTable && Index == Other.Index;
1308}
1309
1310void ImportDirectoryEntryRef::moveNext() {
1311 ++Index;
1312 if (ImportTable[Index].isNull()) {
1313 Index = -1;
1314 ImportTable = nullptr;
1315 }
1316}
1317
1318std::error_code ImportDirectoryEntryRef::getImportTableEntry(
1319 const coff_import_directory_table_entry *&Result) const {
1320 return getObject(Result, OwningObject->Data, ImportTable + Index);
1321}
1322
1323static imported_symbol_iterator
1324makeImportedSymbolIterator(const COFFObjectFile *Object,
1325 uintptr_t Ptr, int Index) {
1326 if (Object->getBytesInAddress() == 4) {
1327 auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr);
1328 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1329 }
1330 auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr);
1331 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1332}
1333
1334static imported_symbol_iterator
1335importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) {
1336 uintptr_t IntPtr = 0;
1337 Object->getRvaPtr(RVA, IntPtr);
1338 return makeImportedSymbolIterator(Object, IntPtr, 0);
1339}
1340
1341static imported_symbol_iterator
1342importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) {
1343 uintptr_t IntPtr = 0;
1344 Object->getRvaPtr(RVA, IntPtr);
1345 // Forward the pointer to the last entry which is null.
1346 int Index = 0;
1347 if (Object->getBytesInAddress() == 4) {
1348 auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr);
1349 while (*Entry++)
1350 ++Index;
1351 } else {
1352 auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr);
1353 while (*Entry++)
1354 ++Index;
1355 }
1356 return makeImportedSymbolIterator(Object, IntPtr, Index);
1357}
1358
1359imported_symbol_iterator
1360ImportDirectoryEntryRef::imported_symbol_begin() const {
1361 return importedSymbolBegin(ImportTable[Index].ImportAddressTableRVA,
1362 OwningObject);
1363}
1364
1365imported_symbol_iterator
1366ImportDirectoryEntryRef::imported_symbol_end() const {
1367 return importedSymbolEnd(ImportTable[Index].ImportAddressTableRVA,
1368 OwningObject);
1369}
1370
1371iterator_range<imported_symbol_iterator>
1372ImportDirectoryEntryRef::imported_symbols() const {
1373 return make_range(imported_symbol_begin(), imported_symbol_end());
1374}
1375
1376imported_symbol_iterator ImportDirectoryEntryRef::lookup_table_begin() const {
1377 return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA,
1378 OwningObject);
1379}
1380
1381imported_symbol_iterator ImportDirectoryEntryRef::lookup_table_end() const {
1382 return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA,
1383 OwningObject);
1384}
1385
1386iterator_range<imported_symbol_iterator>
1387ImportDirectoryEntryRef::lookup_table_symbols() const {
1388 return make_range(lookup_table_begin(), lookup_table_end());
1389}
1390
1391std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1392 uintptr_t IntPtr = 0;
1393 if (std::error_code EC =
1394 OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr))
1395 return EC;
1396 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1397 return std::error_code();
1398}
1399
1400std::error_code
1401ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t &Result) const {
1402 Result = ImportTable[Index].ImportLookupTableRVA;
1403 return std::error_code();
1404}
1405
1406std::error_code
1407ImportDirectoryEntryRef::getImportAddressTableRVA(uint32_t &Result) const {
1408 Result = ImportTable[Index].ImportAddressTableRVA;
1409 return std::error_code();
1410}
1411
1412bool DelayImportDirectoryEntryRef::
1413operator==(const DelayImportDirectoryEntryRef &Other) const {
1414 return Table == Other.Table && Index == Other.Index;
1415}
1416
1417void DelayImportDirectoryEntryRef::moveNext() {
1418 ++Index;
1419}
1420
1421imported_symbol_iterator
1422DelayImportDirectoryEntryRef::imported_symbol_begin() const {
1423 return importedSymbolBegin(Table[Index].DelayImportNameTable,
1424 OwningObject);
1425}
1426
1427imported_symbol_iterator
1428DelayImportDirectoryEntryRef::imported_symbol_end() const {
1429 return importedSymbolEnd(Table[Index].DelayImportNameTable,
1430 OwningObject);
1431}
1432
1433iterator_range<imported_symbol_iterator>
1434DelayImportDirectoryEntryRef::imported_symbols() const {
1435 return make_range(imported_symbol_begin(), imported_symbol_end());
1436}
1437
1438std::error_code DelayImportDirectoryEntryRef::getName(StringRef &Result) const {
1439 uintptr_t IntPtr = 0;
1440 if (std::error_code EC = OwningObject->getRvaPtr(Table[Index].Name, IntPtr))
1441 return EC;
1442 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1443 return std::error_code();
1444}
1445
1446std::error_code DelayImportDirectoryEntryRef::
1447getDelayImportTable(const delay_import_directory_table_entry *&Result) const {
1448 Result = Table;
1449 return std::error_code();
1450}
1451
1452std::error_code DelayImportDirectoryEntryRef::
1453getImportAddress(int AddrIndex, uint64_t &Result) const {
1454 uint32_t RVA = Table[Index].DelayImportAddressTable +
1455 AddrIndex * (OwningObject->is64() ? 8 : 4);
1456 uintptr_t IntPtr = 0;
1457 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1458 return EC;
1459 if (OwningObject->is64())
1460 Result = *reinterpret_cast<const ulittle64_t *>(IntPtr);
1461 else
1462 Result = *reinterpret_cast<const ulittle32_t *>(IntPtr);
1463 return std::error_code();
1464}
1465
1466bool ExportDirectoryEntryRef::
1467operator==(const ExportDirectoryEntryRef &Other) const {
1468 return ExportTable == Other.ExportTable && Index == Other.Index;
1469}
1470
1471void ExportDirectoryEntryRef::moveNext() {
1472 ++Index;
1473}
1474
1475// Returns the name of the current export symbol. If the symbol is exported only
1476// by ordinal, the empty string is set as a result.
1477std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1478 uintptr_t IntPtr = 0;
1479 if (std::error_code EC =
1480 OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1481 return EC;
1482 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1483 return std::error_code();
1484}
1485
1486// Returns the starting ordinal number.
1487std::error_code
1488ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1489 Result = ExportTable->OrdinalBase;
1490 return std::error_code();
1491}
1492
1493// Returns the export ordinal of the current export symbol.
1494std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1495 Result = ExportTable->OrdinalBase + Index;
1496 return std::error_code();
1497}
1498
1499// Returns the address of the current export symbol.
1500std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1501 uintptr_t IntPtr = 0;
1502 if (std::error_code EC =
1503 OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1504 return EC;
1505 const export_address_table_entry *entry =
1506 reinterpret_cast<const export_address_table_entry *>(IntPtr);
1507 Result = entry[Index].ExportRVA;
1508 return std::error_code();
1509}
1510
1511// Returns the name of the current export symbol. If the symbol is exported only
1512// by ordinal, the empty string is set as a result.
1513std::error_code
1514ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1515 uintptr_t IntPtr = 0;
1516 if (std::error_code EC =
1517 OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1518 return EC;
1519 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1520
1521 uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1522 int Offset = 0;
1523 for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1524 I < E; ++I, ++Offset) {
1525 if (*I != Index)
1526 continue;
1527 if (std::error_code EC =
1528 OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1529 return EC;
1530 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1531 if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1532 return EC;
1533 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1534 return std::error_code();
1535 }
1536 Result = "";
1537 return std::error_code();
1538}
1539
1540std::error_code ExportDirectoryEntryRef::isForwarder(bool &Result) const {
1541 const data_directory *DataEntry;
1542 if (auto EC = OwningObject->getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
1543 return EC;
1544 uint32_t RVA;
1545 if (auto EC = getExportRVA(RVA))
1546 return EC;
1547 uint32_t Begin = DataEntry->RelativeVirtualAddress;
1548 uint32_t End = DataEntry->RelativeVirtualAddress + DataEntry->Size;
1549 Result = (Begin <= RVA && RVA < End);
1550 return std::error_code();
1551}
1552
1553std::error_code ExportDirectoryEntryRef::getForwardTo(StringRef &Result) const {
1554 uint32_t RVA;
1555 if (auto EC = getExportRVA(RVA))
1556 return EC;
1557 uintptr_t IntPtr = 0;
1558 if (auto EC = OwningObject->getRvaPtr(RVA, IntPtr))
1559 return EC;
1560 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1561 return std::error_code();
1562}
1563
1564bool ImportedSymbolRef::
1565operator==(const ImportedSymbolRef &Other) const {
1566 return Entry32 == Other.Entry32 && Entry64 == Other.Entry64
1567 && Index == Other.Index;
1568}
1569
1570void ImportedSymbolRef::moveNext() {
1571 ++Index;
1572}
1573
1574std::error_code
1575ImportedSymbolRef::getSymbolName(StringRef &Result) const {
1576 uint32_t RVA;
1577 if (Entry32) {
1578 // If a symbol is imported only by ordinal, it has no name.
1579 if (Entry32[Index].isOrdinal())
1580 return std::error_code();
1581 RVA = Entry32[Index].getHintNameRVA();
1582 } else {
1583 if (Entry64[Index].isOrdinal())
1584 return std::error_code();
1585 RVA = Entry64[Index].getHintNameRVA();
1586 }
1587 uintptr_t IntPtr = 0;
1588 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1589 return EC;
1590 // +2 because the first two bytes is hint.
1591 Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2));
1592 return std::error_code();
1593}
1594
1595std::error_code ImportedSymbolRef::isOrdinal(bool &Result) const {
1596 if (Entry32)
1597 Result = Entry32[Index].isOrdinal();
1598 else
1599 Result = Entry64[Index].isOrdinal();
1600 return std::error_code();
1601}
1602
1603std::error_code ImportedSymbolRef::getHintNameRVA(uint32_t &Result) const {
1604 if (Entry32)
1605 Result = Entry32[Index].getHintNameRVA();
1606 else
1607 Result = Entry64[Index].getHintNameRVA();
1608 return std::error_code();
1609}
1610
1611std::error_code ImportedSymbolRef::getOrdinal(uint16_t &Result) const {
1612 uint32_t RVA;
1613 if (Entry32) {
1614 if (Entry32[Index].isOrdinal()) {
1615 Result = Entry32[Index].getOrdinal();
1616 return std::error_code();
1617 }
1618 RVA = Entry32[Index].getHintNameRVA();
1619 } else {
1620 if (Entry64[Index].isOrdinal()) {
1621 Result = Entry64[Index].getOrdinal();
1622 return std::error_code();
1623 }
1624 RVA = Entry64[Index].getHintNameRVA();
1625 }
1626 uintptr_t IntPtr = 0;
1627 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1628 return EC;
1629 Result = *reinterpret_cast<const ulittle16_t *>(IntPtr);
1630 return std::error_code();
1631}
1632
1633Expected<std::unique_ptr<COFFObjectFile>>
1634ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1635 std::error_code EC;
1636 std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1637 if (EC)
1638 return errorCodeToError(EC);
1639 return std::move(Ret);
1640}
1641
1642bool BaseRelocRef::operator==(const BaseRelocRef &Other) const {
1643 return Header == Other.Header && Index == Other.Index;
1644}
1645
1646void BaseRelocRef::moveNext() {
1647 // Header->BlockSize is the size of the current block, including the
1648 // size of the header itself.
1649 uint32_t Size = sizeof(*Header) +
1650 sizeof(coff_base_reloc_block_entry) * (Index + 1);
1651 if (Size == Header->BlockSize) {
1652 // .reloc contains a list of base relocation blocks. Each block
1653 // consists of the header followed by entries. The header contains
1654 // how many entories will follow. When we reach the end of the
1655 // current block, proceed to the next block.
1656 Header = reinterpret_cast<const coff_base_reloc_block_header *>(
1657 reinterpret_cast<const uint8_t *>(Header) + Size);
1658 Index = 0;
1659 } else {
1660 ++Index;
1661 }
1662}
1663
1664std::error_code BaseRelocRef::getType(uint8_t &Type) const {
1665 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1666 Type = Entry[Index].getType();
1667 return std::error_code();
1668}
1669
1670std::error_code BaseRelocRef::getRVA(uint32_t &Result) const {
1671 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1672 Result = Header->PageRVA + Entry[Index].getOffset();
1673 return std::error_code();
1674}
1675
1676#define RETURN_IF_ERROR(E)if (E) return E; \
1677 if (E) \
1678 return E;
1679
1680Expected<ArrayRef<UTF16>>
1681ResourceSectionRef::getDirStringAtOffset(uint32_t Offset) {
1682 BinaryStreamReader Reader = BinaryStreamReader(BBS);
1683 Reader.setOffset(Offset);
1684 uint16_t Length;
1685 RETURN_IF_ERROR(Reader.readInteger(Length))if (Reader.readInteger(Length)) return Reader.readInteger(Length
);
;
1686 ArrayRef<UTF16> RawDirString;
1687 RETURN_IF_ERROR(Reader.readArray(RawDirString, Length))if (Reader.readArray(RawDirString, Length)) return Reader.readArray
(RawDirString, Length);
;
1688 return RawDirString;
1689}
1690
1691Expected<ArrayRef<UTF16>>
1692ResourceSectionRef::getEntryNameString(const coff_resource_dir_entry &Entry) {
1693 return getDirStringAtOffset(Entry.Identifier.getNameOffset());
1694}
1695
1696Expected<const coff_resource_dir_table &>
1697ResourceSectionRef::getTableAtOffset(uint32_t Offset) {
1698 const coff_resource_dir_table *Table = nullptr;
1699
1700 BinaryStreamReader Reader(BBS);
1701 Reader.setOffset(Offset);
1702 RETURN_IF_ERROR(Reader.readObject(Table))if (Reader.readObject(Table)) return Reader.readObject(Table)
;
;
1703 assert(Table != nullptr)((Table != nullptr) ? static_cast<void> (0) : __assert_fail
("Table != nullptr", "/build/llvm-toolchain-snapshot-8~svn350071/lib/Object/COFFObjectFile.cpp"
, 1703, __PRETTY_FUNCTION__))
;
1704 return *Table;
1705}
1706
1707Expected<const coff_resource_dir_table &>
1708ResourceSectionRef::getEntrySubDir(const coff_resource_dir_entry &Entry) {
1709 return getTableAtOffset(Entry.Offset.value());
1710}
1711
1712Expected<const coff_resource_dir_table &> ResourceSectionRef::getBaseTable() {
1713 return getTableAtOffset(0);
1714}

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

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