Bug Summary

File:llvm/lib/Object/COFFObjectFile.cpp
Warning:line 1643, column 12
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -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 -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -fhalf-no-semantic-interposition -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/build-llvm/lib/Object -I /build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/lib/Object -I /build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/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/local/include -internal-isystem /usr/lib/llvm-12/lib/clang/12.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++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/build-llvm/lib/Object -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2021-01-24-223304-31662-1 -x c++ /build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/lib/Object/COFFObjectFile.cpp

/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/lib/Object/COFFObjectFile.cpp

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

/build/llvm-toolchain-snapshot-12~++20210124100612+2afaf072f5c1/llvm/include/llvm/Object/COFF.h

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