Bug Summary

File:src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Object/COFFObjectFile.cpp
Warning:line 1650, column 12
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple amd64-unknown-openbsd7.0 -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 -mrelocation-model pic -pic-level 1 -fhalf-no-semantic-interposition -mframe-pointer=all -relaxed-aliasing -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fcoverage-compilation-dir=/usr/src/gnu/usr.bin/clang/libLLVM/obj -resource-dir /usr/local/lib/clang/13.0.0 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Analysis -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ASMParser -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/BinaryFormat -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Bitcode -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Bitcode -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Bitstream -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /include/llvm/CodeGen -I /include/llvm/CodeGen/PBQP -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/IR -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/IR -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/Coroutines -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ProfileData/Coverage -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/CodeView -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/DWARF -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/MSF -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/PDB -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Demangle -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ExecutionEngine -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ExecutionEngine/JITLink -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ExecutionEngine/Orc -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Frontend -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Frontend/OpenACC -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Frontend -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Frontend/OpenMP -I /include/llvm/CodeGen/GlobalISel -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/IRReader -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/InstCombine -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/Transforms/InstCombine -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/LTO -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Linker -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/MC -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/MC/MCParser -I /include/llvm/CodeGen/MIRParser -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Object -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Option -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Passes -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ProfileData -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/Scalar -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ADT -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Support -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/Symbolize -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Target -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/Utils -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/Vectorize -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/IPO -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include -I /usr/src/gnu/usr.bin/clang/libLLVM/../include -I /usr/src/gnu/usr.bin/clang/libLLVM/obj -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include -D NDEBUG -D __STDC_LIMIT_MACROS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D LLVM_PREFIX="/usr" -D PIC -internal-isystem /usr/include/c++/v1 -internal-isystem /usr/local/lib/clang/13.0.0/include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/usr/src/gnu/usr.bin/clang/libLLVM/obj -ferror-limit 19 -fvisibility-inlines-hidden -fwrapv -D_RET_PROTECTOR -ret-protector -fno-rtti -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -fno-builtin-malloc -fno-builtin-calloc -fno-builtin-realloc -fno-builtin-valloc -fno-builtin-free -fno-builtin-strdup -fno-builtin-strndup -analyzer-output=html -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /home/ben/Projects/vmm/scan-build/2022-01-12-194120-40624-1 -x c++ /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Object/COFFObjectFile.cpp

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

/usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Object/COFF.h

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

/usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Support/Error.h

1//===- llvm/Support/Error.h - Recoverable error handling --------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines an API used to report recoverable errors.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_SUPPORT_ERROR_H
14#define LLVM_SUPPORT_ERROR_H
15
16#include "llvm-c/Error.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/StringExtras.h"
20#include "llvm/ADT/Twine.h"
21#include "llvm/Config/abi-breaking.h"
22#include "llvm/Support/AlignOf.h"
23#include "llvm/Support/Compiler.h"
24#include "llvm/Support/Debug.h"
25#include "llvm/Support/ErrorHandling.h"
26#include "llvm/Support/ErrorOr.h"
27#include "llvm/Support/Format.h"
28#include "llvm/Support/raw_ostream.h"
29#include <algorithm>
30#include <cassert>
31#include <cstdint>
32#include <cstdlib>
33#include <functional>
34#include <memory>
35#include <new>
36#include <string>
37#include <system_error>
38#include <type_traits>
39#include <utility>
40#include <vector>
41
42namespace llvm {
43
44class ErrorSuccess;
45
46/// Base class for error info classes. Do not extend this directly: Extend
47/// the ErrorInfo template subclass instead.
48class ErrorInfoBase {
49public:
50 virtual ~ErrorInfoBase() = default;
51
52 /// Print an error message to an output stream.
53 virtual void log(raw_ostream &OS) const = 0;
54
55 /// Return the error message as a string.
56 virtual std::string message() const {
57 std::string Msg;
58 raw_string_ostream OS(Msg);
59 log(OS);
60 return OS.str();
61 }
62
63 /// Convert this error to a std::error_code.
64 ///
65 /// This is a temporary crutch to enable interaction with code still
66 /// using std::error_code. It will be removed in the future.
67 virtual std::error_code convertToErrorCode() const = 0;
68
69 // Returns the class ID for this type.
70 static const void *classID() { return &ID; }
71
72 // Returns the class ID for the dynamic type of this ErrorInfoBase instance.
73 virtual const void *dynamicClassID() const = 0;
74
75 // Check whether this instance is a subclass of the class identified by
76 // ClassID.
77 virtual bool isA(const void *const ClassID) const {
78 return ClassID == classID();
79 }
80
81 // Check whether this instance is a subclass of ErrorInfoT.
82 template <typename ErrorInfoT> bool isA() const {
83 return isA(ErrorInfoT::classID());
84 }
85
86private:
87 virtual void anchor();
88
89 static char ID;
90};
91
92/// Lightweight error class with error context and mandatory checking.
93///
94/// Instances of this class wrap a ErrorInfoBase pointer. Failure states
95/// are represented by setting the pointer to a ErrorInfoBase subclass
96/// instance containing information describing the failure. Success is
97/// represented by a null pointer value.
98///
99/// Instances of Error also contains a 'Checked' flag, which must be set
100/// before the destructor is called, otherwise the destructor will trigger a
101/// runtime error. This enforces at runtime the requirement that all Error
102/// instances be checked or returned to the caller.
103///
104/// There are two ways to set the checked flag, depending on what state the
105/// Error instance is in. For Error instances indicating success, it
106/// is sufficient to invoke the boolean conversion operator. E.g.:
107///
108/// @code{.cpp}
109/// Error foo(<...>);
110///
111/// if (auto E = foo(<...>))
112/// return E; // <- Return E if it is in the error state.
113/// // We have verified that E was in the success state. It can now be safely
114/// // destroyed.
115/// @endcode
116///
117/// A success value *can not* be dropped. For example, just calling 'foo(<...>)'
118/// without testing the return value will raise a runtime error, even if foo
119/// returns success.
120///
121/// For Error instances representing failure, you must use either the
122/// handleErrors or handleAllErrors function with a typed handler. E.g.:
123///
124/// @code{.cpp}
125/// class MyErrorInfo : public ErrorInfo<MyErrorInfo> {
126/// // Custom error info.
127/// };
128///
129/// Error foo(<...>) { return make_error<MyErrorInfo>(...); }
130///
131/// auto E = foo(<...>); // <- foo returns failure with MyErrorInfo.
132/// auto NewE =
133/// handleErrors(E,
134/// [](const MyErrorInfo &M) {
135/// // Deal with the error.
136/// },
137/// [](std::unique_ptr<OtherError> M) -> Error {
138/// if (canHandle(*M)) {
139/// // handle error.
140/// return Error::success();
141/// }
142/// // Couldn't handle this error instance. Pass it up the stack.
143/// return Error(std::move(M));
144/// );
145/// // Note - we must check or return NewE in case any of the handlers
146/// // returned a new error.
147/// @endcode
148///
149/// The handleAllErrors function is identical to handleErrors, except
150/// that it has a void return type, and requires all errors to be handled and
151/// no new errors be returned. It prevents errors (assuming they can all be
152/// handled) from having to be bubbled all the way to the top-level.
153///
154/// *All* Error instances must be checked before destruction, even if
155/// they're moved-assigned or constructed from Success values that have already
156/// been checked. This enforces checking through all levels of the call stack.
157class LLVM_NODISCARD[[clang::warn_unused_result]] Error {
158 // ErrorList needs to be able to yank ErrorInfoBase pointers out of Errors
159 // to add to the error list. It can't rely on handleErrors for this, since
160 // handleErrors does not support ErrorList handlers.
161 friend class ErrorList;
162
163 // handleErrors needs to be able to set the Checked flag.
164 template <typename... HandlerTs>
165 friend Error handleErrors(Error E, HandlerTs &&... Handlers);
166
167 // Expected<T> needs to be able to steal the payload when constructed from an
168 // error.
169 template <typename T> friend class Expected;
170
171 // wrap needs to be able to steal the payload.
172 friend LLVMErrorRef wrap(Error);
173
174protected:
175 /// Create a success value. Prefer using 'Error::success()' for readability
176 Error() {
177 setPtr(nullptr);
178 setChecked(false);
179 }
180
181public:
182 /// Create a success value.
183 static ErrorSuccess success();
184
185 // Errors are not copy-constructable.
186 Error(const Error &Other) = delete;
187
188 /// Move-construct an error value. The newly constructed error is considered
189 /// unchecked, even if the source error had been checked. The original error
190 /// becomes a checked Success value, regardless of its original state.
191 Error(Error &&Other) {
192 setChecked(true);
193 *this = std::move(Other);
194 }
195
196 /// Create an error value. Prefer using the 'make_error' function, but
197 /// this constructor can be useful when "re-throwing" errors from handlers.
198 Error(std::unique_ptr<ErrorInfoBase> Payload) {
199 setPtr(Payload.release());
200 setChecked(false);
201 }
202
203 // Errors are not copy-assignable.
204 Error &operator=(const Error &Other) = delete;
205
206 /// Move-assign an error value. The current error must represent success, you
207 /// you cannot overwrite an unhandled error. The current error is then
208 /// considered unchecked. The source error becomes a checked success value,
209 /// regardless of its original state.
210 Error &operator=(Error &&Other) {
211 // Don't allow overwriting of unchecked values.
212 assertIsChecked();
213 setPtr(Other.getPtr());
214
215 // This Error is unchecked, even if the source error was checked.
216 setChecked(false);
217
218 // Null out Other's payload and set its checked bit.
219 Other.setPtr(nullptr);
220 Other.setChecked(true);
221
222 return *this;
223 }
224
225 /// Destroy a Error. Fails with a call to abort() if the error is
226 /// unchecked.
227 ~Error() {
228 assertIsChecked();
229 delete getPtr();
230 }
231
232 /// Bool conversion. Returns true if this Error is in a failure state,
233 /// and false if it is in an accept state. If the error is in a Success state
234 /// it will be considered checked.
235 explicit operator bool() {
236 setChecked(getPtr() == nullptr);
13
Assuming the condition is true
237 return getPtr() != nullptr;
14
Returning zero, which participates in a condition later
238 }
239
240 /// Check whether one error is a subclass of another.
241 template <typename ErrT> bool isA() const {
242 return getPtr() && getPtr()->isA(ErrT::classID());
243 }
244
245 /// Returns the dynamic class id of this error, or null if this is a success
246 /// value.
247 const void* dynamicClassID() const {
248 if (!getPtr())
249 return nullptr;
250 return getPtr()->dynamicClassID();
251 }
252
253private:
254#if LLVM_ENABLE_ABI_BREAKING_CHECKS0
255 // assertIsChecked() happens very frequently, but under normal circumstances
256 // is supposed to be a no-op. So we want it to be inlined, but having a bunch
257 // of debug prints can cause the function to be too large for inlining. So
258 // it's important that we define this function out of line so that it can't be
259 // inlined.
260 LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn))
261 void fatalUncheckedError() const;
262#endif
263
264 void assertIsChecked() {
265#if LLVM_ENABLE_ABI_BREAKING_CHECKS0
266 if (LLVM_UNLIKELY(!getChecked() || getPtr())__builtin_expect((bool)(!getChecked() || getPtr()), false))
267 fatalUncheckedError();
268#endif
269 }
270
271 ErrorInfoBase *getPtr() const {
272#if LLVM_ENABLE_ABI_BREAKING_CHECKS0
273 return reinterpret_cast<ErrorInfoBase*>(
274 reinterpret_cast<uintptr_t>(Payload) &
275 ~static_cast<uintptr_t>(0x1));
276#else
277 return Payload;
278#endif
279 }
280
281 void setPtr(ErrorInfoBase *EI) {
282#if LLVM_ENABLE_ABI_BREAKING_CHECKS0
283 Payload = reinterpret_cast<ErrorInfoBase*>(
284 (reinterpret_cast<uintptr_t>(EI) &
285 ~static_cast<uintptr_t>(0x1)) |
286 (reinterpret_cast<uintptr_t>(Payload) & 0x1));
287#else
288 Payload = EI;
289#endif
290 }
291
292 bool getChecked() const {
293#if LLVM_ENABLE_ABI_BREAKING_CHECKS0
294 return (reinterpret_cast<uintptr_t>(Payload) & 0x1) == 0;
295#else
296 return true;
297#endif
298 }
299
300 void setChecked(bool V) {
301#if LLVM_ENABLE_ABI_BREAKING_CHECKS0
302 Payload = reinterpret_cast<ErrorInfoBase*>(
303 (reinterpret_cast<uintptr_t>(Payload) &
304 ~static_cast<uintptr_t>(0x1)) |
305 (V ? 0 : 1));
306#endif
307 }
308
309 std::unique_ptr<ErrorInfoBase> takePayload() {
310 std::unique_ptr<ErrorInfoBase> Tmp(getPtr());
311 setPtr(nullptr);
312 setChecked(true);
313 return Tmp;
314 }
315
316 friend raw_ostream &operator<<(raw_ostream &OS, const Error &E) {
317 if (auto P = E.getPtr())
318 P->log(OS);
319 else
320 OS << "success";
321 return OS;
322 }
323
324 ErrorInfoBase *Payload = nullptr;
325};
326
327/// Subclass of Error for the sole purpose of identifying the success path in
328/// the type system. This allows to catch invalid conversion to Expected<T> at
329/// compile time.
330class ErrorSuccess final : public Error {};
331
332inline ErrorSuccess Error::success() { return ErrorSuccess(); }
333
334/// Make a Error instance representing failure using the given error info
335/// type.
336template <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) {
337 return Error(std::make_unique<ErrT>(std::forward<ArgTs>(Args)...));
338}
339
340/// Base class for user error types. Users should declare their error types
341/// like:
342///
343/// class MyError : public ErrorInfo<MyError> {
344/// ....
345/// };
346///
347/// This class provides an implementation of the ErrorInfoBase::kind
348/// method, which is used by the Error RTTI system.
349template <typename ThisErrT, typename ParentErrT = ErrorInfoBase>
350class ErrorInfo : public ParentErrT {
351public:
352 using ParentErrT::ParentErrT; // inherit constructors
353
354 static const void *classID() { return &ThisErrT::ID; }
355
356 const void *dynamicClassID() const override { return &ThisErrT::ID; }
357
358 bool isA(const void *const ClassID) const override {
359 return ClassID == classID() || ParentErrT::isA(ClassID);
360 }
361};
362
363/// Special ErrorInfo subclass representing a list of ErrorInfos.
364/// Instances of this class are constructed by joinError.
365class ErrorList final : public ErrorInfo<ErrorList> {
366 // handleErrors needs to be able to iterate the payload list of an
367 // ErrorList.
368 template <typename... HandlerTs>
369 friend Error handleErrors(Error E, HandlerTs &&... Handlers);
370
371 // joinErrors is implemented in terms of join.
372 friend Error joinErrors(Error, Error);
373
374public:
375 void log(raw_ostream &OS) const override {
376 OS << "Multiple errors:\n";
377 for (auto &ErrPayload : Payloads) {
378 ErrPayload->log(OS);
379 OS << "\n";
380 }
381 }
382
383 std::error_code convertToErrorCode() const override;
384
385 // Used by ErrorInfo::classID.
386 static char ID;
387
388private:
389 ErrorList(std::unique_ptr<ErrorInfoBase> Payload1,
390 std::unique_ptr<ErrorInfoBase> Payload2) {
391 assert(!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() &&((void)0)
392 "ErrorList constructor payloads should be singleton errors")((void)0);
393 Payloads.push_back(std::move(Payload1));
394 Payloads.push_back(std::move(Payload2));
395 }
396
397 static Error join(Error E1, Error E2) {
398 if (!E1)
399 return E2;
400 if (!E2)
401 return E1;
402 if (E1.isA<ErrorList>()) {
403 auto &E1List = static_cast<ErrorList &>(*E1.getPtr());
404 if (E2.isA<ErrorList>()) {
405 auto E2Payload = E2.takePayload();
406 auto &E2List = static_cast<ErrorList &>(*E2Payload);
407 for (auto &Payload : E2List.Payloads)
408 E1List.Payloads.push_back(std::move(Payload));
409 } else
410 E1List.Payloads.push_back(E2.takePayload());
411
412 return E1;
413 }
414 if (E2.isA<ErrorList>()) {
415 auto &E2List = static_cast<ErrorList &>(*E2.getPtr());
416 E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload());
417 return E2;
418 }
419 return Error(std::unique_ptr<ErrorList>(
420 new ErrorList(E1.takePayload(), E2.takePayload())));
421 }
422
423 std::vector<std::unique_ptr<ErrorInfoBase>> Payloads;
424};
425
426/// Concatenate errors. The resulting Error is unchecked, and contains the
427/// ErrorInfo(s), if any, contained in E1, followed by the
428/// ErrorInfo(s), if any, contained in E2.
429inline Error joinErrors(Error E1, Error E2) {
430 return ErrorList::join(std::move(E1), std::move(E2));
431}
432
433/// Tagged union holding either a T or a Error.
434///
435/// This class parallels ErrorOr, but replaces error_code with Error. Since
436/// Error cannot be copied, this class replaces getError() with
437/// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the
438/// error class type.
439///
440/// Example usage of 'Expected<T>' as a function return type:
441///
442/// @code{.cpp}
443/// Expected<int> myDivide(int A, int B) {
444/// if (B == 0) {
445/// // return an Error
446/// return createStringError(inconvertibleErrorCode(),
447/// "B must not be zero!");
448/// }
449/// // return an integer
450/// return A / B;
451/// }
452/// @endcode
453///
454/// Checking the results of to a function returning 'Expected<T>':
455/// @code{.cpp}
456/// if (auto E = Result.takeError()) {
457/// // We must consume the error. Typically one of:
458/// // - return the error to our caller
459/// // - toString(), when logging
460/// // - consumeError(), to silently swallow the error
461/// // - handleErrors(), to distinguish error types
462/// errs() << "Problem with division " << toString(std::move(E)) << "\n";
463/// return;
464/// }
465/// // use the result
466/// outs() << "The answer is " << *Result << "\n";
467/// @endcode
468///
469/// For unit-testing a function returning an 'Expceted<T>', see the
470/// 'EXPECT_THAT_EXPECTED' macros in llvm/Testing/Support/Error.h
471
472template <class T> class LLVM_NODISCARD[[clang::warn_unused_result]] Expected {
473 template <class T1> friend class ExpectedAsOutParameter;
474 template <class OtherT> friend class Expected;
475
476 static constexpr bool isRef = std::is_reference<T>::value;
477
478 using wrap = std::reference_wrapper<std::remove_reference_t<T>>;
479
480 using error_type = std::unique_ptr<ErrorInfoBase>;
481
482public:
483 using storage_type = std::conditional_t<isRef, wrap, T>;
484 using value_type = T;
485
486private:
487 using reference = std::remove_reference_t<T> &;
488 using const_reference = const std::remove_reference_t<T> &;
489 using pointer = std::remove_reference_t<T> *;
490 using const_pointer = const std::remove_reference_t<T> *;
491
492public:
493 /// Create an Expected<T> error value from the given Error.
494 Expected(Error Err)
495 : HasError(true)
496#if LLVM_ENABLE_ABI_BREAKING_CHECKS0
497 // Expected is unchecked upon construction in Debug builds.
498 , Unchecked(true)
499#endif
500 {
501 assert(Err && "Cannot create Expected<T> from Error success value.")((void)0);
502 new (getErrorStorage()) error_type(Err.takePayload());
503 }
504
505 /// Forbid to convert from Error::success() implicitly, this avoids having
506 /// Expected<T> foo() { return Error::success(); } which compiles otherwise
507 /// but triggers the assertion above.
508 Expected(ErrorSuccess) = delete;
509
510 /// Create an Expected<T> success value from the given OtherT value, which
511 /// must be convertible to T.
512 template <typename OtherT>
513 Expected(OtherT &&Val,
514 std::enable_if_t<std::is_convertible<OtherT, T>::value> * = nullptr)
515 : HasError(false)
516#if LLVM_ENABLE_ABI_BREAKING_CHECKS0
517 // Expected is unchecked upon construction in Debug builds.
518 ,
519 Unchecked(true)
520#endif
521 {
522 new (getStorage()) storage_type(std::forward<OtherT>(Val));
523 }
524
525 /// Move construct an Expected<T> value.
526 Expected(Expected &&Other) { moveConstruct(std::move(Other)); }
527
528 /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
529 /// must be convertible to T.
530 template <class OtherT>
531 Expected(
532 Expected<OtherT> &&Other,
533 std::enable_if_t<std::is_convertible<OtherT, T>::value> * = nullptr) {
534 moveConstruct(std::move(Other));
535 }
536
537 /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
538 /// isn't convertible to T.
539 template <class OtherT>
540 explicit Expected(
541 Expected<OtherT> &&Other,
542 std::enable_if_t<!std::is_convertible<OtherT, T>::value> * = nullptr) {
543 moveConstruct(std::move(Other));
544 }
545
546 /// Move-assign from another Expected<T>.
547 Expected &operator=(Expected &&Other) {
548 moveAssign(std::move(Other));
549 return *this;
550 }
551
552 /// Destroy an Expected<T>.
553 ~Expected() {
554 assertIsChecked();
555 if (!HasError)
556 getStorage()->~storage_type();
557 else
558 getErrorStorage()->~error_type();
559 }
560
561 /// Return false if there is an error.
562 explicit operator bool() {
563#if LLVM_ENABLE_ABI_BREAKING_CHECKS0
564 Unchecked = HasError;
565#endif
566 return !HasError;
567 }
568
569 /// Returns a reference to the stored T value.
570 reference get() {
571 assertIsChecked();
572 return *getStorage();
573 }
574
575 /// Returns a const reference to the stored T value.
576 const_reference get() const {
577 assertIsChecked();
578 return const_cast<Expected<T> *>(this)->get();
579 }
580
581 /// Check that this Expected<T> is an error of type ErrT.
582 template <typename ErrT> bool errorIsA() const {
583 return HasError && (*getErrorStorage())->template isA<ErrT>();
584 }
585
586 /// Take ownership of the stored error.
587 /// After calling this the Expected<T> is in an indeterminate state that can
588 /// only be safely destructed. No further calls (beside the destructor) should
589 /// be made on the Expected<T> value.
590 Error takeError() {
591#if LLVM_ENABLE_ABI_BREAKING_CHECKS0
592 Unchecked = false;
593#endif
594 return HasError ? Error(std::move(*getErrorStorage())) : Error::success();
595 }
596
597 /// Returns a pointer to the stored T value.
598 pointer operator->() {
599 assertIsChecked();
600 return toPointer(getStorage());
601 }
602
603 /// Returns a const pointer to the stored T value.
604 const_pointer operator->() const {
605 assertIsChecked();
606 return toPointer(getStorage());
607 }
608
609 /// Returns a reference to the stored T value.
610 reference operator*() {
611 assertIsChecked();
612 return *getStorage();
613 }
614
615 /// Returns a const reference to the stored T value.
616 const_reference operator*() const {
617 assertIsChecked();
618 return *getStorage();
619 }
620
621private:
622 template <class T1>
623 static bool compareThisIfSameType(const T1 &a, const T1 &b) {
624 return &a == &b;
625 }
626
627 template <class T1, class T2>
628 static bool compareThisIfSameType(const T1 &, const T2 &) {
629 return false;
630 }
631
632 template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) {
633 HasError = Other.HasError;
634#if LLVM_ENABLE_ABI_BREAKING_CHECKS0
635 Unchecked = true;
636 Other.Unchecked = false;
637#endif
638
639 if (!HasError)
640 new (getStorage()) storage_type(std::move(*Other.getStorage()));
641 else
642 new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage()));
643 }
644
645 template <class OtherT> void moveAssign(Expected<OtherT> &&Other) {
646 assertIsChecked();
647
648 if (compareThisIfSameType(*this, Other))
649 return;
650
651 this->~Expected();
652 new (this) Expected(std::move(Other));
653 }
654
655 pointer toPointer(pointer Val) { return Val; }
656
657 const_pointer toPointer(const_pointer Val) const { return Val; }
658
659 pointer toPointer(wrap *Val) { return &Val->get(); }
660
661 const_pointer toPointer(const wrap *Val) const { return &Val->get(); }
662
663 storage_type *getStorage() {
664 assert(!HasError && "Cannot get value when an error exists!")((void)0);
665 return reinterpret_cast<storage_type *>(&TStorage);
666 }
667
668 const storage_type *getStorage() const {
669 assert(!HasError && "Cannot get value when an error exists!")((void)0);
670 return reinterpret_cast<const storage_type *>(&TStorage);
671 }
672
673 error_type *getErrorStorage() {
674 assert(HasError && "Cannot get error when a value exists!")((void)0);
675 return reinterpret_cast<error_type *>(&ErrorStorage);
676 }
677
678 const error_type *getErrorStorage() const {
679 assert(HasError && "Cannot get error when a value exists!")((void)0);
680 return reinterpret_cast<const error_type *>(&ErrorStorage);
681 }
682
683 // Used by ExpectedAsOutParameter to reset the checked flag.
684 void setUnchecked() {
685#if LLVM_ENABLE_ABI_BREAKING_CHECKS0
686 Unchecked = true;
687#endif
688 }
689
690#if LLVM_ENABLE_ABI_BREAKING_CHECKS0
691 LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn))
692 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline))
693 void fatalUncheckedExpected() const {
694 dbgs() << "Expected<T> must be checked before access or destruction.\n";
695 if (HasError) {
696 dbgs() << "Unchecked Expected<T> contained error:\n";
697 (*getErrorStorage())->log(dbgs());
698 } else
699 dbgs() << "Expected<T> value was in success state. (Note: Expected<T> "
700 "values in success mode must still be checked prior to being "
701 "destroyed).\n";
702 abort();
703 }
704#endif
705
706 void assertIsChecked() const {
707#if LLVM_ENABLE_ABI_BREAKING_CHECKS0
708 if (LLVM_UNLIKELY(Unchecked)__builtin_expect((bool)(Unchecked), false))
709 fatalUncheckedExpected();
710#endif
711 }
712
713 union {
714 AlignedCharArrayUnion<storage_type> TStorage;
715 AlignedCharArrayUnion<error_type> ErrorStorage;
716 };
717 bool HasError : 1;
718#if LLVM_ENABLE_ABI_BREAKING_CHECKS0
719 bool Unchecked : 1;
720#endif
721};
722
723/// Report a serious error, calling any installed error handler. See
724/// ErrorHandling.h.
725LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) void report_fatal_error(Error Err,
726 bool gen_crash_diag = true);
727
728/// Report a fatal error if Err is a failure value.
729///
730/// This function can be used to wrap calls to fallible functions ONLY when it
731/// is known that the Error will always be a success value. E.g.
732///
733/// @code{.cpp}
734/// // foo only attempts the fallible operation if DoFallibleOperation is
735/// // true. If DoFallibleOperation is false then foo always returns
736/// // Error::success().
737/// Error foo(bool DoFallibleOperation);
738///
739/// cantFail(foo(false));
740/// @endcode
741inline void cantFail(Error Err, const char *Msg = nullptr) {
742 if (Err) {
743 if (!Msg)
744 Msg = "Failure value returned from cantFail wrapped call";
745#ifndef NDEBUG1
746 std::string Str;
747 raw_string_ostream OS(Str);
748 OS << Msg << "\n" << Err;
749 Msg = OS.str().c_str();
750#endif
751 llvm_unreachable(Msg)__builtin_unreachable();
752 }
753}
754
755/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
756/// returns the contained value.
757///
758/// This function can be used to wrap calls to fallible functions ONLY when it
759/// is known that the Error will always be a success value. E.g.
760///
761/// @code{.cpp}
762/// // foo only attempts the fallible operation if DoFallibleOperation is
763/// // true. If DoFallibleOperation is false then foo always returns an int.
764/// Expected<int> foo(bool DoFallibleOperation);
765///
766/// int X = cantFail(foo(false));
767/// @endcode
768template <typename T>
769T cantFail(Expected<T> ValOrErr, const char *Msg = nullptr) {
770 if (ValOrErr)
771 return std::move(*ValOrErr);
772 else {
773 if (!Msg)
774 Msg = "Failure value returned from cantFail wrapped call";
775#ifndef NDEBUG1
776 std::string Str;
777 raw_string_ostream OS(Str);
778 auto E = ValOrErr.takeError();
779 OS << Msg << "\n" << E;
780 Msg = OS.str().c_str();
781#endif
782 llvm_unreachable(Msg)__builtin_unreachable();
783 }
784}
785
786/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
787/// returns the contained reference.
788///
789/// This function can be used to wrap calls to fallible functions ONLY when it
790/// is known that the Error will always be a success value. E.g.
791///
792/// @code{.cpp}
793/// // foo only attempts the fallible operation if DoFallibleOperation is
794/// // true. If DoFallibleOperation is false then foo always returns a Bar&.
795/// Expected<Bar&> foo(bool DoFallibleOperation);
796///
797/// Bar &X = cantFail(foo(false));
798/// @endcode
799template <typename T>
800T& cantFail(Expected<T&> ValOrErr, const char *Msg = nullptr) {
801 if (ValOrErr)
802 return *ValOrErr;
803 else {
804 if (!Msg)
805 Msg = "Failure value returned from cantFail wrapped call";
806#ifndef NDEBUG1
807 std::string Str;
808 raw_string_ostream OS(Str);
809 auto E = ValOrErr.takeError();
810 OS << Msg << "\n" << E;
811 Msg = OS.str().c_str();
812#endif
813 llvm_unreachable(Msg)__builtin_unreachable();
814 }
815}
816
817/// Helper for testing applicability of, and applying, handlers for
818/// ErrorInfo types.
819template <typename HandlerT>
820class ErrorHandlerTraits
821 : public ErrorHandlerTraits<decltype(
822 &std::remove_reference<HandlerT>::type::operator())> {};
823
824// Specialization functions of the form 'Error (const ErrT&)'.
825template <typename ErrT> class ErrorHandlerTraits<Error (&)(ErrT &)> {
826public:
827 static bool appliesTo(const ErrorInfoBase &E) {
828 return E.template isA<ErrT>();
829 }
830
831 template <typename HandlerT>
832 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
833 assert(appliesTo(*E) && "Applying incorrect handler")((void)0);
834 return H(static_cast<ErrT &>(*E));
835 }
836};
837
838// Specialization functions of the form 'void (const ErrT&)'.
839template <typename ErrT> class ErrorHandlerTraits<void (&)(ErrT &)> {
840public:
841 static bool appliesTo(const ErrorInfoBase &E) {
842 return E.template isA<ErrT>();
843 }
844
845 template <typename HandlerT>
846 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
847 assert(appliesTo(*E) && "Applying incorrect handler")((void)0);
848 H(static_cast<ErrT &>(*E));
849 return Error::success();
850 }
851};
852
853/// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'.
854template <typename ErrT>
855class ErrorHandlerTraits<Error (&)(std::unique_ptr<ErrT>)> {
856public:
857 static bool appliesTo(const ErrorInfoBase &E) {
858 return E.template isA<ErrT>();
859 }
860
861 template <typename HandlerT>
862 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
863 assert(appliesTo(*E) && "Applying incorrect handler")((void)0);
864 std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
865 return H(std::move(SubE));
866 }
867};
868
869/// Specialization for functions of the form 'void (std::unique_ptr<ErrT>)'.
870template <typename ErrT>
871class ErrorHandlerTraits<void (&)(std::unique_ptr<ErrT>)> {
872public:
873 static bool appliesTo(const ErrorInfoBase &E) {
874 return E.template isA<ErrT>();
875 }
876
877 template <typename HandlerT>
878 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
879 assert(appliesTo(*E) && "Applying incorrect handler")((void)0);
880 std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
881 H(std::move(SubE));
882 return Error::success();
883 }
884};
885
886// Specialization for member functions of the form 'RetT (const ErrT&)'.
887template <typename C, typename RetT, typename ErrT>
888class ErrorHandlerTraits<RetT (C::*)(ErrT &)>
889 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
890
891// Specialization for member functions of the form 'RetT (const ErrT&) const'.
892template <typename C, typename RetT, typename ErrT>
893class ErrorHandlerTraits<RetT (C::*)(ErrT &) const>
894 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
895
896// Specialization for member functions of the form 'RetT (const ErrT&)'.
897template <typename C, typename RetT, typename ErrT>
898class ErrorHandlerTraits<RetT (C::*)(const ErrT &)>
899 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
900
901// Specialization for member functions of the form 'RetT (const ErrT&) const'.
902template <typename C, typename RetT, typename ErrT>
903class ErrorHandlerTraits<RetT (C::*)(const ErrT &) const>
904 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
905
906/// Specialization for member functions of the form
907/// 'RetT (std::unique_ptr<ErrT>)'.
908template <typename C, typename RetT, typename ErrT>
909class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>)>
910 : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
911
912/// Specialization for member functions of the form
913/// 'RetT (std::unique_ptr<ErrT>) const'.
914template <typename C, typename RetT, typename ErrT>
915class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>) const>
916 : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
917
918inline Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload) {
919 return Error(std::move(Payload));
920}
921
922template <typename HandlerT, typename... HandlerTs>
923Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload,
924 HandlerT &&Handler, HandlerTs &&... Handlers) {
925 if (ErrorHandlerTraits<HandlerT>::appliesTo(*Payload))
926 return ErrorHandlerTraits<HandlerT>::apply(std::forward<HandlerT>(Handler),
927 std::move(Payload));
928 return handleErrorImpl(std::move(Payload),
929 std::forward<HandlerTs>(Handlers)...);
930}
931
932/// Pass the ErrorInfo(s) contained in E to their respective handlers. Any
933/// unhandled errors (or Errors returned by handlers) are re-concatenated and
934/// returned.
935/// Because this function returns an error, its result must also be checked
936/// or returned. If you intend to handle all errors use handleAllErrors
937/// (which returns void, and will abort() on unhandled errors) instead.
938template <typename... HandlerTs>
939Error handleErrors(Error E, HandlerTs &&... Hs) {
940 if (!E)
941 return Error::success();
942
943 std::unique_ptr<ErrorInfoBase> Payload = E.takePayload();
944
945 if (Payload->isA<ErrorList>()) {
946 ErrorList &List = static_cast<ErrorList &>(*Payload);
947 Error R;
948 for (auto &P : List.Payloads)
949 R = ErrorList::join(
950 std::move(R),
951 handleErrorImpl(std::move(P), std::forward<HandlerTs>(Hs)...));
952 return R;
953 }
954
955 return handleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...);
956}
957
958/// Behaves the same as handleErrors, except that by contract all errors
959/// *must* be handled by the given handlers (i.e. there must be no remaining
960/// errors after running the handlers, or llvm_unreachable is called).
961template <typename... HandlerTs>
962void handleAllErrors(Error E, HandlerTs &&... Handlers) {
963 cantFail(handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...));
964}
965
966/// Check that E is a non-error, then drop it.
967/// If E is an error, llvm_unreachable will be called.
968inline void handleAllErrors(Error E) {
969 cantFail(std::move(E));
970}
971
972/// Handle any errors (if present) in an Expected<T>, then try a recovery path.
973///
974/// If the incoming value is a success value it is returned unmodified. If it
975/// is a failure value then it the contained error is passed to handleErrors.
976/// If handleErrors is able to handle the error then the RecoveryPath functor
977/// is called to supply the final result. If handleErrors is not able to
978/// handle all errors then the unhandled errors are returned.
979///
980/// This utility enables the follow pattern:
981///
982/// @code{.cpp}
983/// enum FooStrategy { Aggressive, Conservative };
984/// Expected<Foo> foo(FooStrategy S);
985///
986/// auto ResultOrErr =
987/// handleExpected(
988/// foo(Aggressive),
989/// []() { return foo(Conservative); },
990/// [](AggressiveStrategyError&) {
991/// // Implicitly conusme this - we'll recover by using a conservative
992/// // strategy.
993/// });
994///
995/// @endcode
996template <typename T, typename RecoveryFtor, typename... HandlerTs>
997Expected<T> handleExpected(Expected<T> ValOrErr, RecoveryFtor &&RecoveryPath,
998 HandlerTs &&... Handlers) {
999 if (ValOrErr)
1000 return ValOrErr;
1001
1002 if (auto Err = handleErrors(ValOrErr.takeError(),
1003 std::forward<HandlerTs>(Handlers)...))
1004 return std::move(Err);
1005
1006 return RecoveryPath();
1007}
1008
1009/// Log all errors (if any) in E to OS. If there are any errors, ErrorBanner
1010/// will be printed before the first one is logged. A newline will be printed
1011/// after each error.
1012///
1013/// This function is compatible with the helpers from Support/WithColor.h. You
1014/// can pass any of them as the OS. Please consider using them instead of
1015/// including 'error: ' in the ErrorBanner.
1016///
1017/// This is useful in the base level of your program to allow clean termination
1018/// (allowing clean deallocation of resources, etc.), while reporting error
1019/// information to the user.
1020void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner = {});
1021
1022/// Write all error messages (if any) in E to a string. The newline character
1023/// is used to separate error messages.
1024inline std::string toString(Error E) {
1025 SmallVector<std::string, 2> Errors;
1026 handleAllErrors(std::move(E), [&Errors](const ErrorInfoBase &EI) {
1027 Errors.push_back(EI.message());
1028 });
1029 return join(Errors.begin(), Errors.end(), "\n");
1030}
1031
1032/// Consume a Error without doing anything. This method should be used
1033/// only where an error can be considered a reasonable and expected return
1034/// value.
1035///
1036/// Uses of this method are potentially indicative of design problems: If it's
1037/// legitimate to do nothing while processing an "error", the error-producer
1038/// might be more clearly refactored to return an Optional<T>.
1039inline void consumeError(Error Err) {
1040 handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {});
1041}
1042
1043/// Convert an Expected to an Optional without doing anything. This method
1044/// should be used only where an error can be considered a reasonable and
1045/// expected return value.
1046///
1047/// Uses of this method are potentially indicative of problems: perhaps the
1048/// error should be propagated further, or the error-producer should just
1049/// return an Optional in the first place.
1050template <typename T> Optional<T> expectedToOptional(Expected<T> &&E) {
1051 if (E)
1052 return std::move(*E);
1053 consumeError(E.takeError());
1054 return None;
1055}
1056
1057/// Helper for converting an Error to a bool.
1058///
1059/// This method returns true if Err is in an error state, or false if it is
1060/// in a success state. Puts Err in a checked state in both cases (unlike
1061/// Error::operator bool(), which only does this for success states).
1062inline bool errorToBool(Error Err) {
1063 bool IsError = static_cast<bool>(Err);
1064 if (IsError)
1065 consumeError(std::move(Err));
1066 return IsError;
1067}
1068
1069/// Helper for Errors used as out-parameters.
1070///
1071/// This helper is for use with the Error-as-out-parameter idiom, where an error
1072/// is passed to a function or method by reference, rather than being returned.
1073/// In such cases it is helpful to set the checked bit on entry to the function
1074/// so that the error can be written to (unchecked Errors abort on assignment)
1075/// and clear the checked bit on exit so that clients cannot accidentally forget
1076/// to check the result. This helper performs these actions automatically using
1077/// RAII:
1078///
1079/// @code{.cpp}
1080/// Result foo(Error &Err) {
1081/// ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set
1082/// // <body of foo>
1083/// // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed.
1084/// }
1085/// @endcode
1086///
1087/// ErrorAsOutParameter takes an Error* rather than Error& so that it can be
1088/// used with optional Errors (Error pointers that are allowed to be null). If
1089/// ErrorAsOutParameter took an Error reference, an instance would have to be
1090/// created inside every condition that verified that Error was non-null. By
1091/// taking an Error pointer we can just create one instance at the top of the
1092/// function.
1093class ErrorAsOutParameter {
1094public:
1095 ErrorAsOutParameter(Error *Err) : Err(Err) {
1096 // Raise the checked bit if Err is success.
1097 if (Err)
1098 (void)!!*Err;
1099 }
1100
1101 ~ErrorAsOutParameter() {
1102 // Clear the checked bit.
1103 if (Err && !*Err)
1104 *Err = Error::success();
1105 }
1106
1107private:
1108 Error *Err;
1109};
1110
1111/// Helper for Expected<T>s used as out-parameters.
1112///
1113/// See ErrorAsOutParameter.
1114template <typename T>
1115class ExpectedAsOutParameter {
1116public:
1117 ExpectedAsOutParameter(Expected<T> *ValOrErr)
1118 : ValOrErr(ValOrErr) {
1119 if (ValOrErr)
1120 (void)!!*ValOrErr;
1121 }
1122
1123 ~ExpectedAsOutParameter() {
1124 if (ValOrErr)
1125 ValOrErr->setUnchecked();
1126 }
1127
1128private:
1129 Expected<T> *ValOrErr;
1130};
1131
1132/// This class wraps a std::error_code in a Error.
1133///
1134/// This is useful if you're writing an interface that returns a Error
1135/// (or Expected) and you want to call code that still returns
1136/// std::error_codes.
1137class ECError : public ErrorInfo<ECError> {
1138 friend Error errorCodeToError(std::error_code);
1139
1140 virtual void anchor() override;
1141
1142public:
1143 void setErrorCode(std::error_code EC) { this->EC = EC; }
1144 std::error_code convertToErrorCode() const override { return EC; }
1145 void log(raw_ostream &OS) const override { OS << EC.message(); }
1146
1147 // Used by ErrorInfo::classID.
1148 static char ID;
1149
1150protected:
1151 ECError() = default;
1152 ECError(std::error_code EC) : EC(EC) {}
1153
1154 std::error_code EC;
1155};
1156
1157/// The value returned by this function can be returned from convertToErrorCode
1158/// for Error values where no sensible translation to std::error_code exists.
1159/// It should only be used in this situation, and should never be used where a
1160/// sensible conversion to std::error_code is available, as attempts to convert
1161/// to/from this error will result in a fatal error. (i.e. it is a programmatic
1162///error to try to convert such a value).
1163std::error_code inconvertibleErrorCode();
1164
1165/// Helper for converting an std::error_code to a Error.
1166Error errorCodeToError(std::error_code EC);
1167
1168/// Helper for converting an ECError to a std::error_code.
1169///
1170/// This method requires that Err be Error() or an ECError, otherwise it
1171/// will trigger a call to abort().
1172std::error_code errorToErrorCode(Error Err);
1173
1174/// Convert an ErrorOr<T> to an Expected<T>.
1175template <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) {
1176 if (auto EC = EO.getError())
1177 return errorCodeToError(EC);
1178 return std::move(*EO);
1179}
1180
1181/// Convert an Expected<T> to an ErrorOr<T>.
1182template <typename T> ErrorOr<T> expectedToErrorOr(Expected<T> &&E) {
1183 if (auto Err = E.takeError())
1184 return errorToErrorCode(std::move(Err));
1185 return std::move(*E);
1186}
1187
1188/// This class wraps a string in an Error.
1189///
1190/// StringError is useful in cases where the client is not expected to be able
1191/// to consume the specific error message programmatically (for example, if the
1192/// error message is to be presented to the user).
1193///
1194/// StringError can also be used when additional information is to be printed
1195/// along with a error_code message. Depending on the constructor called, this
1196/// class can either display:
1197/// 1. the error_code message (ECError behavior)
1198/// 2. a string
1199/// 3. the error_code message and a string
1200///
1201/// These behaviors are useful when subtyping is required; for example, when a
1202/// specific library needs an explicit error type. In the example below,
1203/// PDBError is derived from StringError:
1204///
1205/// @code{.cpp}
1206/// Expected<int> foo() {
1207/// return llvm::make_error<PDBError>(pdb_error_code::dia_failed_loading,
1208/// "Additional information");
1209/// }
1210/// @endcode
1211///
1212class StringError : public ErrorInfo<StringError> {
1213public:
1214 static char ID;
1215
1216 // Prints EC + S and converts to EC
1217 StringError(std::error_code EC, const Twine &S = Twine());
1218
1219 // Prints S and converts to EC
1220 StringError(const Twine &S, std::error_code EC);
1221
1222 void log(raw_ostream &OS) const override;
1223 std::error_code convertToErrorCode() const override;
1224
1225 const std::string &getMessage() const { return Msg; }
1226
1227private:
1228 std::string Msg;
1229 std::error_code EC;
1230 const bool PrintMsgOnly = false;
1231};
1232
1233/// Create formatted StringError object.
1234template <typename... Ts>
1235inline Error createStringError(std::error_code EC, char const *Fmt,
1236 const Ts &... Vals) {
1237 std::string Buffer;
1238 raw_string_ostream Stream(Buffer);
1239 Stream << format(Fmt, Vals...);
1240 return make_error<StringError>(Stream.str(), EC);
1241}
1242
1243Error createStringError(std::error_code EC, char const *Msg);
1244
1245inline Error createStringError(std::error_code EC, const Twine &S) {
1246 return createStringError(EC, S.str().c_str());
1247}
1248
1249template <typename... Ts>
1250inline Error createStringError(std::errc EC, char const *Fmt,
1251 const Ts &... Vals) {
1252 return createStringError(std::make_error_code(EC), Fmt, Vals...);
1253}
1254
1255/// This class wraps a filename and another Error.
1256///
1257/// In some cases, an error needs to live along a 'source' name, in order to
1258/// show more detailed information to the user.
1259class FileError final : public ErrorInfo<FileError> {
1260
1261 friend Error createFileError(const Twine &, Error);
1262 friend Error createFileError(const Twine &, size_t, Error);
1263
1264public:
1265 void log(raw_ostream &OS) const override {
1266 assert(Err && !FileName.empty() && "Trying to log after takeError().")((void)0);
1267 OS << "'" << FileName << "': ";
1268 if (Line.hasValue())
1269 OS << "line " << Line.getValue() << ": ";
1270 Err->log(OS);
1271 }
1272
1273 StringRef getFileName() { return FileName; }
1274
1275 Error takeError() { return Error(std::move(Err)); }
1276
1277 std::error_code convertToErrorCode() const override;
1278
1279 // Used by ErrorInfo::classID.
1280 static char ID;
1281
1282private:
1283 FileError(const Twine &F, Optional<size_t> LineNum,
1284 std::unique_ptr<ErrorInfoBase> E) {
1285 assert(E && "Cannot create FileError from Error success value.")((void)0);
1286 assert(!F.isTriviallyEmpty() &&((void)0)
1287 "The file name provided to FileError must not be empty.")((void)0);
1288 FileName = F.str();
1289 Err = std::move(E);
1290 Line = std::move(LineNum);
1291 }
1292
1293 static Error build(const Twine &F, Optional<size_t> Line, Error E) {
1294 std::unique_ptr<ErrorInfoBase> Payload;
1295 handleAllErrors(std::move(E),
1296 [&](std::unique_ptr<ErrorInfoBase> EIB) -> Error {
1297 Payload = std::move(EIB);
1298 return Error::success();
1299 });
1300 return Error(
1301 std::unique_ptr<FileError>(new FileError(F, Line, std::move(Payload))));
1302 }
1303
1304 std::string FileName;
1305 Optional<size_t> Line;
1306 std::unique_ptr<ErrorInfoBase> Err;
1307};
1308
1309/// Concatenate a source file path and/or name with an Error. The resulting
1310/// Error is unchecked.
1311inline Error createFileError(const Twine &F, Error E) {
1312 return FileError::build(F, Optional<size_t>(), std::move(E));
1313}
1314
1315/// Concatenate a source file path and/or name with line number and an Error.
1316/// The resulting Error is unchecked.
1317inline Error createFileError(const Twine &F, size_t Line, Error E) {
1318 return FileError::build(F, Optional<size_t>(Line), std::move(E));
1319}
1320
1321/// Concatenate a source file path and/or name with a std::error_code
1322/// to form an Error object.
1323inline Error createFileError(const Twine &F, std::error_code EC) {
1324 return createFileError(F, errorCodeToError(EC));
1325}
1326
1327/// Concatenate a source file path and/or name with line number and
1328/// std::error_code to form an Error object.
1329inline Error createFileError(const Twine &F, size_t Line, std::error_code EC) {
1330 return createFileError(F, Line, errorCodeToError(EC));
1331}
1332
1333Error createFileError(const Twine &F, ErrorSuccess) = delete;
1334
1335/// Helper for check-and-exit error handling.
1336///
1337/// For tool use only. NOT FOR USE IN LIBRARY CODE.
1338///
1339class ExitOnError {
1340public:
1341 /// Create an error on exit helper.
1342 ExitOnError(std::string Banner = "", int DefaultErrorExitCode = 1)
1343 : Banner(std::move(Banner)),
1344 GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {}
1345
1346 /// Set the banner string for any errors caught by operator().
1347 void setBanner(std::string Banner) { this->Banner = std::move(Banner); }
1348
1349 /// Set the exit-code mapper function.
1350 void setExitCodeMapper(std::function<int(const Error &)> GetExitCode) {
1351 this->GetExitCode = std::move(GetExitCode);
1352 }
1353
1354 /// Check Err. If it's in a failure state log the error(s) and exit.
1355 void operator()(Error Err) const { checkError(std::move(Err)); }
1356
1357 /// Check E. If it's in a success state then return the contained value. If
1358 /// it's in a failure state log the error(s) and exit.
1359 template <typename T> T operator()(Expected<T> &&E) const {
1360 checkError(E.takeError());
1361 return std::move(*E);
1362 }
1363
1364 /// Check E. If it's in a success state then return the contained reference. If
1365 /// it's in a failure state log the error(s) and exit.
1366 template <typename T> T& operator()(Expected<T&> &&E) const {
1367 checkError(E.takeError());
1368 return *E;
1369 }
1370
1371private:
1372 void checkError(Error Err) const {
1373 if (Err) {
1374 int ExitCode = GetExitCode(Err);
1375 logAllUnhandledErrors(std::move(Err), errs(), Banner);
1376 exit(ExitCode);
1377 }
1378 }
1379
1380 std::string Banner;
1381 std::function<int(const Error &)> GetExitCode;
1382};
1383
1384/// Conversion from Error to LLVMErrorRef for C error bindings.
1385inline LLVMErrorRef wrap(Error Err) {
1386 return reinterpret_cast<LLVMErrorRef>(Err.takePayload().release());
1387}
1388
1389/// Conversion from LLVMErrorRef to Error for C error bindings.
1390inline Error unwrap(LLVMErrorRef ErrRef) {
1391 return Error(std::unique_ptr<ErrorInfoBase>(
1392 reinterpret_cast<ErrorInfoBase *>(ErrRef)));
1393}
1394
1395} // end namespace llvm
1396
1397#endif // LLVM_SUPPORT_ERROR_H