Bug Summary

File:llvm/lib/Object/COFFObjectFile.cpp
Warning:line 1602, 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 -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~++20200926111128+c6c5629f2fb/build-llvm/lib/Object -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/llvm/lib/Object -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/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~++20200926111128+c6c5629f2fb/build-llvm/lib/Object -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb=. -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-2020-09-26-161721-17566-1 -x c++ /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/llvm/lib/Object/COFFObjectFile.cpp

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

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