Bug Summary

File:llvm/lib/Object/COFFObjectFile.cpp
Warning:line 1700, column 3
2nd function call argument is an uninitialized value

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name COFFObjectFile.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -fhalf-no-semantic-interposition -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210525111110+78eaff2ef8a9/build-llvm/lib/Object -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210525111110+78eaff2ef8a9/build-llvm/lib/Object -I /build/llvm-toolchain-snapshot-13~++20210525111110+78eaff2ef8a9/llvm/lib/Object -I /build/llvm-toolchain-snapshot-13~++20210525111110+78eaff2ef8a9/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210525111110+78eaff2ef8a9/llvm/include -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-13/lib/clang/13.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210525111110+78eaff2ef8a9/build-llvm/lib/Object -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210525111110+78eaff2ef8a9=. -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 -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-05-25-184031-10426-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210525111110+78eaff2ef8a9/llvm/lib/Object/COFFObjectFile.cpp

/build/llvm-toolchain-snapshot-13~++20210525111110+78eaff2ef8a9/llvm/lib/Object/COFFObjectFile.cpp

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

/build/llvm-toolchain-snapshot-13~++20210525111110+78eaff2ef8a9/llvm/include/llvm/Support/BinaryStreamReader.h

1//===- BinaryStreamReader.h - Reads objects from a binary stream *- 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#ifndef LLVM_SUPPORT_BINARYSTREAMREADER_H
10#define LLVM_SUPPORT_BINARYSTREAMREADER_H
11
12#include "llvm/ADT/ArrayRef.h"
13#include "llvm/ADT/STLExtras.h"
14#include "llvm/ADT/StringRef.h"
15#include "llvm/Support/Alignment.h"
16#include "llvm/Support/BinaryStreamArray.h"
17#include "llvm/Support/BinaryStreamRef.h"
18#include "llvm/Support/ConvertUTF.h"
19#include "llvm/Support/Endian.h"
20#include "llvm/Support/Error.h"
21#include "llvm/Support/type_traits.h"
22#include <type_traits>
23
24namespace llvm {
25
26/// Provides read only access to a subclass of `BinaryStream`. Provides
27/// bounds checking and helpers for writing certain common data types such as
28/// null-terminated strings, integers in various flavors of endianness, etc.
29/// Can be subclassed to provide reading of custom datatypes, although no
30/// are overridable.
31class BinaryStreamReader {
32public:
33 BinaryStreamReader() = default;
34 explicit BinaryStreamReader(BinaryStreamRef Ref);
35 explicit BinaryStreamReader(BinaryStream &Stream);
36 explicit BinaryStreamReader(ArrayRef<uint8_t> Data,
37 llvm::support::endianness Endian);
38 explicit BinaryStreamReader(StringRef Data, llvm::support::endianness Endian);
39
40 BinaryStreamReader(const BinaryStreamReader &Other)
41 : Stream(Other.Stream), Offset(Other.Offset) {}
42
43 BinaryStreamReader &operator=(const BinaryStreamReader &Other) {
44 Stream = Other.Stream;
45 Offset = Other.Offset;
46 return *this;
47 }
48
49 virtual ~BinaryStreamReader() {}
50
51 /// Read as much as possible from the underlying string at the current offset
52 /// without invoking a copy, and set \p Buffer to the resulting data slice.
53 /// Updates the stream's offset to point after the newly read data.
54 ///
55 /// \returns a success error code if the data was successfully read, otherwise
56 /// returns an appropriate error code.
57 Error readLongestContiguousChunk(ArrayRef<uint8_t> &Buffer);
58
59 /// Read \p Size bytes from the underlying stream at the current offset and
60 /// and set \p Buffer to the resulting data slice. Whether a copy occurs
61 /// depends on the implementation of the underlying stream. Updates the
62 /// stream's offset to point after the newly read data.
63 ///
64 /// \returns a success error code if the data was successfully read, otherwise
65 /// returns an appropriate error code.
66 Error readBytes(ArrayRef<uint8_t> &Buffer, uint32_t Size);
67
68 /// Read an integer of the specified endianness into \p Dest and update the
69 /// stream's offset. The data is always copied from the stream's underlying
70 /// buffer into \p Dest. Updates the stream's offset to point after the newly
71 /// read data.
72 ///
73 /// \returns a success error code if the data was successfully read, otherwise
74 /// returns an appropriate error code.
75 template <typename T> Error readInteger(T &Dest) {
76 static_assert(std::is_integral<T>::value,
77 "Cannot call readInteger with non-integral value!");
78
79 ArrayRef<uint8_t> Bytes;
80 if (auto EC = readBytes(Bytes, sizeof(T)))
4
Assuming the condition is true
5
Taking true branch
81 return EC;
6
Returning without writing to 'Dest'
82
83 Dest = llvm::support::endian::read<T, llvm::support::unaligned>(
84 Bytes.data(), Stream.getEndian());
85 return Error::success();
86 }
87
88 /// Similar to readInteger.
89 template <typename T> Error readEnum(T &Dest) {
90 static_assert(std::is_enum<T>::value,
91 "Cannot call readEnum with non-enum value!");
92 std::underlying_type_t<T> N;
93 if (auto EC = readInteger(N))
94 return EC;
95 Dest = static_cast<T>(N);
96 return Error::success();
97 }
98
99 /// Read an unsigned LEB128 encoded value.
100 ///
101 /// \returns a success error code if the data was successfully read, otherwise
102 /// returns an appropriate error code.
103 Error readULEB128(uint64_t &Dest);
104
105 /// Read a signed LEB128 encoded value.
106 ///
107 /// \returns a success error code if the data was successfully read, otherwise
108 /// returns an appropriate error code.
109 Error readSLEB128(int64_t &Dest);
110
111 /// Read a null terminated string from \p Dest. Whether a copy occurs depends
112 /// on the implementation of the underlying stream. Updates the stream's
113 /// offset to point after the newly read data.
114 ///
115 /// \returns a success error code if the data was successfully read, otherwise
116 /// returns an appropriate error code.
117 Error readCString(StringRef &Dest);
118
119 /// Similar to readCString, however read a null-terminated UTF16 string
120 /// instead.
121 ///
122 /// \returns a success error code if the data was successfully read, otherwise
123 /// returns an appropriate error code.
124 Error readWideString(ArrayRef<UTF16> &Dest);
125
126 /// Read a \p Length byte string into \p Dest. Whether a copy occurs depends
127 /// on the implementation of the underlying stream. Updates the stream's
128 /// offset to point after the newly read data.
129 ///
130 /// \returns a success error code if the data was successfully read, otherwise
131 /// returns an appropriate error code.
132 Error readFixedString(StringRef &Dest, uint32_t Length);
133
134 /// Read the entire remainder of the underlying stream into \p Ref. This is
135 /// equivalent to calling getUnderlyingStream().slice(Offset). Updates the
136 /// stream's offset to point to the end of the stream. Never causes a copy.
137 ///
138 /// \returns a success error code if the data was successfully read, otherwise
139 /// returns an appropriate error code.
140 Error readStreamRef(BinaryStreamRef &Ref);
141
142 /// Read \p Length bytes from the underlying stream into \p Ref. This is
143 /// equivalent to calling getUnderlyingStream().slice(Offset, Length).
144 /// Updates the stream's offset to point after the newly read object. Never
145 /// causes a copy.
146 ///
147 /// \returns a success error code if the data was successfully read, otherwise
148 /// returns an appropriate error code.
149 Error readStreamRef(BinaryStreamRef &Ref, uint32_t Length);
150
151 /// Read \p Length bytes from the underlying stream into \p Ref. This is
152 /// equivalent to calling getUnderlyingStream().slice(Offset, Length).
153 /// Updates the stream's offset to point after the newly read object. Never
154 /// causes a copy.
155 ///
156 /// \returns a success error code if the data was successfully read, otherwise
157 /// returns an appropriate error code.
158 Error readSubstream(BinarySubstreamRef &Ref, uint32_t Length);
159
160 /// Get a pointer to an object of type T from the underlying stream, as if by
161 /// memcpy, and store the result into \p Dest. It is up to the caller to
162 /// ensure that objects of type T can be safely treated in this manner.
163 /// Updates the stream's offset to point after the newly read object. Whether
164 /// a copy occurs depends upon the implementation of the underlying
165 /// stream.
166 ///
167 /// \returns a success error code if the data was successfully read, otherwise
168 /// returns an appropriate error code.
169 template <typename T> Error readObject(const T *&Dest) {
170 ArrayRef<uint8_t> Buffer;
171 if (auto EC = readBytes(Buffer, sizeof(T)))
172 return EC;
173 Dest = reinterpret_cast<const T *>(Buffer.data());
174 return Error::success();
175 }
176
177 /// Get a reference to a \p NumElements element array of objects of type T
178 /// from the underlying stream as if by memcpy, and store the resulting array
179 /// slice into \p array. It is up to the caller to ensure that objects of
180 /// type T can be safely treated in this manner. Updates the stream's offset
181 /// to point after the newly read object. Whether a copy occurs depends upon
182 /// the implementation of the underlying stream.
183 ///
184 /// \returns a success error code if the data was successfully read, otherwise
185 /// returns an appropriate error code.
186 template <typename T>
187 Error readArray(ArrayRef<T> &Array, uint32_t NumElements) {
188 ArrayRef<uint8_t> Bytes;
189 if (NumElements == 0) {
190 Array = ArrayRef<T>();
191 return Error::success();
192 }
193
194 if (NumElements > UINT32_MAX(4294967295U) / sizeof(T))
195 return make_error<BinaryStreamError>(
196 stream_error_code::invalid_array_size);
197
198 if (auto EC = readBytes(Bytes, NumElements * sizeof(T)))
199 return EC;
200
201 assert(isAddrAligned(Align::Of<T>(), Bytes.data()) &&(static_cast <bool> (isAddrAligned(Align::Of<T>()
, Bytes.data()) && "Reading at invalid alignment!") ?
void (0) : __assert_fail ("isAddrAligned(Align::Of<T>(), Bytes.data()) && \"Reading at invalid alignment!\""
, "/build/llvm-toolchain-snapshot-13~++20210525111110+78eaff2ef8a9/llvm/include/llvm/Support/BinaryStreamReader.h"
, 202, __extension__ __PRETTY_FUNCTION__))
202 "Reading at invalid alignment!")(static_cast <bool> (isAddrAligned(Align::Of<T>()
, Bytes.data()) && "Reading at invalid alignment!") ?
void (0) : __assert_fail ("isAddrAligned(Align::Of<T>(), Bytes.data()) && \"Reading at invalid alignment!\""
, "/build/llvm-toolchain-snapshot-13~++20210525111110+78eaff2ef8a9/llvm/include/llvm/Support/BinaryStreamReader.h"
, 202, __extension__ __PRETTY_FUNCTION__))
;
203
204 Array = ArrayRef<T>(reinterpret_cast<const T *>(Bytes.data()), NumElements);
205 return Error::success();
206 }
207
208 /// Read a VarStreamArray of size \p Size bytes and store the result into
209 /// \p Array. Updates the stream's offset to point after the newly read
210 /// array. Never causes a copy (although iterating the elements of the
211 /// VarStreamArray may, depending upon the implementation of the underlying
212 /// stream).
213 ///
214 /// \returns a success error code if the data was successfully read, otherwise
215 /// returns an appropriate error code.
216 template <typename T, typename U>
217 Error readArray(VarStreamArray<T, U> &Array, uint32_t Size,
218 uint32_t Skew = 0) {
219 BinaryStreamRef S;
220 if (auto EC = readStreamRef(S, Size))
221 return EC;
222 Array.setUnderlyingStream(S, Skew);
223 return Error::success();
224 }
225
226 /// Read a FixedStreamArray of \p NumItems elements and store the result into
227 /// \p Array. Updates the stream's offset to point after the newly read
228 /// array. Never causes a copy (although iterating the elements of the
229 /// FixedStreamArray may, depending upon the implementation of the underlying
230 /// stream).
231 ///
232 /// \returns a success error code if the data was successfully read, otherwise
233 /// returns an appropriate error code.
234 template <typename T>
235 Error readArray(FixedStreamArray<T> &Array, uint32_t NumItems) {
236 if (NumItems == 0) {
237 Array = FixedStreamArray<T>();
238 return Error::success();
239 }
240
241 if (NumItems > UINT32_MAX(4294967295U) / sizeof(T))
242 return make_error<BinaryStreamError>(
243 stream_error_code::invalid_array_size);
244
245 BinaryStreamRef View;
246 if (auto EC = readStreamRef(View, NumItems * sizeof(T)))
247 return EC;
248
249 Array = FixedStreamArray<T>(View);
250 return Error::success();
251 }
252
253 bool empty() const { return bytesRemaining() == 0; }
254 void setOffset(uint32_t Off) { Offset = Off; }
255 uint32_t getOffset() const { return Offset; }
256 uint32_t getLength() const { return Stream.getLength(); }
257 uint32_t bytesRemaining() const { return getLength() - getOffset(); }
258
259 /// Advance the stream's offset by \p Amount bytes.
260 ///
261 /// \returns a success error code if at least \p Amount bytes remain in the
262 /// stream, otherwise returns an appropriate error code.
263 Error skip(uint32_t Amount);
264
265 /// Examine the next byte of the underlying stream without advancing the
266 /// stream's offset. If the stream is empty the behavior is undefined.
267 ///
268 /// \returns the next byte in the stream.
269 uint8_t peek() const;
270
271 Error padToAlignment(uint32_t Align);
272
273 std::pair<BinaryStreamReader, BinaryStreamReader>
274 split(uint32_t Offset) const;
275
276private:
277 BinaryStreamRef Stream;
278 uint32_t Offset = 0;
279};
280} // namespace llvm
281
282#endif // LLVM_SUPPORT_BINARYSTREAMREADER_H