Bug Summary

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

Annotated Source Code

/build/llvm-toolchain-snapshot-6.0~svn318801/lib/Object/COFFObjectFile.cpp

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

/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/Support/BinaryStreamReader.h

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

/build/llvm-toolchain-snapshot-6.0~svn318801/include/llvm/Support/Error.h

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