File: | llvm/lib/Object/COFFObjectFile.cpp |
Warning: | line 1103, column 7 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===- COFFObjectFile.cpp - COFF object file implementation ---------------===// | |||
2 | // | |||
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | |||
4 | // See https://llvm.org/LICENSE.txt for license information. | |||
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | |||
6 | // | |||
7 | //===----------------------------------------------------------------------===// | |||
8 | // | |||
9 | // This file declares the COFFObjectFile class. | |||
10 | // | |||
11 | //===----------------------------------------------------------------------===// | |||
12 | ||||
13 | #include "llvm/ADT/ArrayRef.h" | |||
14 | #include "llvm/ADT/StringRef.h" | |||
15 | #include "llvm/ADT/Triple.h" | |||
16 | #include "llvm/ADT/iterator_range.h" | |||
17 | #include "llvm/BinaryFormat/COFF.h" | |||
18 | #include "llvm/Object/Binary.h" | |||
19 | #include "llvm/Object/COFF.h" | |||
20 | #include "llvm/Object/Error.h" | |||
21 | #include "llvm/Object/ObjectFile.h" | |||
22 | #include "llvm/Support/BinaryStreamReader.h" | |||
23 | #include "llvm/Support/Endian.h" | |||
24 | #include "llvm/Support/Error.h" | |||
25 | #include "llvm/Support/ErrorHandling.h" | |||
26 | #include "llvm/Support/MathExtras.h" | |||
27 | #include "llvm/Support/MemoryBuffer.h" | |||
28 | #include <algorithm> | |||
29 | #include <cassert> | |||
30 | #include <cstddef> | |||
31 | #include <cstdint> | |||
32 | #include <cstring> | |||
33 | #include <limits> | |||
34 | #include <memory> | |||
35 | #include <system_error> | |||
36 | ||||
37 | using namespace llvm; | |||
38 | using namespace object; | |||
39 | ||||
40 | using support::ulittle16_t; | |||
41 | using support::ulittle32_t; | |||
42 | using support::ulittle64_t; | |||
43 | using support::little16_t; | |||
44 | ||||
45 | // Returns false if size is greater than the buffer size. And sets ec. | |||
46 | static bool checkSize(MemoryBufferRef M, std::error_code &EC, uint64_t Size) { | |||
47 | if (M.getBufferSize() < Size) { | |||
48 | EC = object_error::unexpected_eof; | |||
49 | return false; | |||
50 | } | |||
51 | return true; | |||
52 | } | |||
53 | ||||
54 | // Sets Obj unless any bytes in [addr, addr + size) fall outsize of m. | |||
55 | // Returns unexpected_eof if error. | |||
56 | template <typename T> | |||
57 | static std::error_code getObject(const T *&Obj, MemoryBufferRef M, | |||
58 | const void *Ptr, | |||
59 | const uint64_t Size = sizeof(T)) { | |||
60 | uintptr_t Addr = uintptr_t(Ptr); | |||
61 | if (std::error_code EC = Binary::checkOffset(M, Addr, Size)) | |||
62 | return EC; | |||
63 | Obj = reinterpret_cast<const T *>(Addr); | |||
64 | return std::error_code(); | |||
65 | } | |||
66 | ||||
67 | // Decode a string table entry in base 64 (//AAAAAA). Expects \arg Str without | |||
68 | // prefixed slashes. | |||
69 | static bool decodeBase64StringEntry(StringRef Str, uint32_t &Result) { | |||
70 | assert(Str.size() <= 6 && "String too long, possible overflow.")((Str.size() <= 6 && "String too long, possible overflow." ) ? static_cast<void> (0) : __assert_fail ("Str.size() <= 6 && \"String too long, possible overflow.\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Object/COFFObjectFile.cpp" , 70, __PRETTY_FUNCTION__)); | |||
71 | if (Str.size() > 6) | |||
72 | return true; | |||
73 | ||||
74 | uint64_t Value = 0; | |||
75 | while (!Str.empty()) { | |||
76 | unsigned CharVal; | |||
77 | if (Str[0] >= 'A' && Str[0] <= 'Z') // 0..25 | |||
78 | CharVal = Str[0] - 'A'; | |||
79 | else if (Str[0] >= 'a' && Str[0] <= 'z') // 26..51 | |||
80 | CharVal = Str[0] - 'a' + 26; | |||
81 | else if (Str[0] >= '0' && Str[0] <= '9') // 52..61 | |||
82 | CharVal = Str[0] - '0' + 52; | |||
83 | else if (Str[0] == '+') // 62 | |||
84 | CharVal = 62; | |||
85 | else if (Str[0] == '/') // 63 | |||
86 | CharVal = 63; | |||
87 | else | |||
88 | return true; | |||
89 | ||||
90 | Value = (Value * 64) + CharVal; | |||
91 | Str = Str.substr(1); | |||
92 | } | |||
93 | ||||
94 | if (Value > std::numeric_limits<uint32_t>::max()) | |||
95 | return true; | |||
96 | ||||
97 | Result = static_cast<uint32_t>(Value); | |||
98 | return false; | |||
99 | } | |||
100 | ||||
101 | template <typename coff_symbol_type> | |||
102 | const coff_symbol_type *COFFObjectFile::toSymb(DataRefImpl Ref) const { | |||
103 | const coff_symbol_type *Addr = | |||
104 | reinterpret_cast<const coff_symbol_type *>(Ref.p); | |||
105 | ||||
106 | assert(!checkOffset(Data, uintptr_t(Addr), sizeof(*Addr)))((!checkOffset(Data, uintptr_t(Addr), sizeof(*Addr))) ? static_cast <void> (0) : __assert_fail ("!checkOffset(Data, uintptr_t(Addr), sizeof(*Addr))" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Object/COFFObjectFile.cpp" , 106, __PRETTY_FUNCTION__)); | |||
107 | #ifndef NDEBUG | |||
108 | // Verify that the symbol points to a valid entry in the symbol table. | |||
109 | uintptr_t Offset = uintptr_t(Addr) - uintptr_t(base()); | |||
110 | ||||
111 | assert((Offset - getPointerToSymbolTable()) % sizeof(coff_symbol_type) == 0 &&(((Offset - getPointerToSymbolTable()) % sizeof(coff_symbol_type ) == 0 && "Symbol did not point to the beginning of a symbol" ) ? static_cast<void> (0) : __assert_fail ("(Offset - getPointerToSymbolTable()) % sizeof(coff_symbol_type) == 0 && \"Symbol did not point to the beginning of a symbol\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Object/COFFObjectFile.cpp" , 112, __PRETTY_FUNCTION__)) | |||
112 | "Symbol did not point to the beginning of a symbol")(((Offset - getPointerToSymbolTable()) % sizeof(coff_symbol_type ) == 0 && "Symbol did not point to the beginning of a symbol" ) ? static_cast<void> (0) : __assert_fail ("(Offset - getPointerToSymbolTable()) % sizeof(coff_symbol_type) == 0 && \"Symbol did not point to the beginning of a symbol\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Object/COFFObjectFile.cpp" , 112, __PRETTY_FUNCTION__)); | |||
113 | #endif | |||
114 | ||||
115 | return Addr; | |||
116 | } | |||
117 | ||||
118 | const coff_section *COFFObjectFile::toSec(DataRefImpl Ref) const { | |||
119 | const coff_section *Addr = reinterpret_cast<const coff_section*>(Ref.p); | |||
120 | ||||
121 | #ifndef NDEBUG | |||
122 | // Verify that the section points to a valid entry in the section table. | |||
123 | if (Addr < SectionTable || Addr >= (SectionTable + getNumberOfSections())) | |||
124 | report_fatal_error("Section was outside of section table."); | |||
125 | ||||
126 | uintptr_t Offset = uintptr_t(Addr) - uintptr_t(SectionTable); | |||
127 | assert(Offset % sizeof(coff_section) == 0 &&((Offset % sizeof(coff_section) == 0 && "Section did not point to the beginning of a section" ) ? static_cast<void> (0) : __assert_fail ("Offset % sizeof(coff_section) == 0 && \"Section did not point to the beginning of a section\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Object/COFFObjectFile.cpp" , 128, __PRETTY_FUNCTION__)) | |||
128 | "Section did not point to the beginning of a section")((Offset % sizeof(coff_section) == 0 && "Section did not point to the beginning of a section" ) ? static_cast<void> (0) : __assert_fail ("Offset % sizeof(coff_section) == 0 && \"Section did not point to the beginning of a section\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Object/COFFObjectFile.cpp" , 128, __PRETTY_FUNCTION__)); | |||
129 | #endif | |||
130 | ||||
131 | return Addr; | |||
132 | } | |||
133 | ||||
134 | void COFFObjectFile::moveSymbolNext(DataRefImpl &Ref) const { | |||
135 | auto End = reinterpret_cast<uintptr_t>(StringTable); | |||
136 | if (SymbolTable16) { | |||
137 | const coff_symbol16 *Symb = toSymb<coff_symbol16>(Ref); | |||
138 | Symb += 1 + Symb->NumberOfAuxSymbols; | |||
139 | Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End); | |||
140 | } else if (SymbolTable32) { | |||
141 | const coff_symbol32 *Symb = toSymb<coff_symbol32>(Ref); | |||
142 | Symb += 1 + Symb->NumberOfAuxSymbols; | |||
143 | Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End); | |||
144 | } else { | |||
145 | llvm_unreachable("no symbol table pointer!")::llvm::llvm_unreachable_internal("no symbol table pointer!", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Object/COFFObjectFile.cpp" , 145); | |||
146 | } | |||
147 | } | |||
148 | ||||
149 | Expected<StringRef> COFFObjectFile::getSymbolName(DataRefImpl Ref) const { | |||
150 | COFFSymbolRef Symb = getCOFFSymbol(Ref); | |||
151 | StringRef Result; | |||
152 | if (std::error_code EC = getSymbolName(Symb, Result)) | |||
153 | return errorCodeToError(EC); | |||
154 | return Result; | |||
155 | } | |||
156 | ||||
157 | uint64_t COFFObjectFile::getSymbolValueImpl(DataRefImpl Ref) const { | |||
158 | return getCOFFSymbol(Ref).getValue(); | |||
159 | } | |||
160 | ||||
161 | uint32_t COFFObjectFile::getSymbolAlignment(DataRefImpl Ref) const { | |||
162 | // MSVC/link.exe seems to align symbols to the next-power-of-2 | |||
163 | // up to 32 bytes. | |||
164 | COFFSymbolRef Symb = getCOFFSymbol(Ref); | |||
165 | return std::min(uint64_t(32), PowerOf2Ceil(Symb.getValue())); | |||
166 | } | |||
167 | ||||
168 | Expected<uint64_t> COFFObjectFile::getSymbolAddress(DataRefImpl Ref) const { | |||
169 | uint64_t Result = getSymbolValue(Ref); | |||
170 | COFFSymbolRef Symb = getCOFFSymbol(Ref); | |||
171 | int32_t SectionNumber = Symb.getSectionNumber(); | |||
172 | ||||
173 | if (Symb.isAnyUndefined() || Symb.isCommon() || | |||
174 | COFF::isReservedSectionNumber(SectionNumber)) | |||
175 | return Result; | |||
176 | ||||
177 | const coff_section *Section = nullptr; | |||
178 | if (std::error_code EC = getSection(SectionNumber, Section)) | |||
179 | return errorCodeToError(EC); | |||
180 | Result += Section->VirtualAddress; | |||
181 | ||||
182 | // The section VirtualAddress does not include ImageBase, and we want to | |||
183 | // return virtual addresses. | |||
184 | Result += getImageBase(); | |||
185 | ||||
186 | return Result; | |||
187 | } | |||
188 | ||||
189 | Expected<SymbolRef::Type> COFFObjectFile::getSymbolType(DataRefImpl Ref) const { | |||
190 | COFFSymbolRef Symb = getCOFFSymbol(Ref); | |||
191 | int32_t SectionNumber = Symb.getSectionNumber(); | |||
192 | ||||
193 | if (Symb.getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION) | |||
194 | return SymbolRef::ST_Function; | |||
195 | if (Symb.isAnyUndefined()) | |||
196 | return SymbolRef::ST_Unknown; | |||
197 | if (Symb.isCommon()) | |||
198 | return SymbolRef::ST_Data; | |||
199 | if (Symb.isFileRecord()) | |||
200 | return SymbolRef::ST_File; | |||
201 | ||||
202 | // TODO: perhaps we need a new symbol type ST_Section. | |||
203 | if (SectionNumber == COFF::IMAGE_SYM_DEBUG || Symb.isSectionDefinition()) | |||
204 | return SymbolRef::ST_Debug; | |||
205 | ||||
206 | if (!COFF::isReservedSectionNumber(SectionNumber)) | |||
207 | return SymbolRef::ST_Data; | |||
208 | ||||
209 | return SymbolRef::ST_Other; | |||
210 | } | |||
211 | ||||
212 | uint32_t COFFObjectFile::getSymbolFlags(DataRefImpl Ref) const { | |||
213 | COFFSymbolRef Symb = getCOFFSymbol(Ref); | |||
214 | uint32_t Result = SymbolRef::SF_None; | |||
215 | ||||
216 | if (Symb.isExternal() || Symb.isWeakExternal()) | |||
217 | Result |= SymbolRef::SF_Global; | |||
218 | ||||
219 | if (const coff_aux_weak_external *AWE = Symb.getWeakExternal()) { | |||
220 | Result |= SymbolRef::SF_Weak; | |||
221 | if (AWE->Characteristics != COFF::IMAGE_WEAK_EXTERN_SEARCH_ALIAS) | |||
222 | Result |= SymbolRef::SF_Undefined; | |||
223 | } | |||
224 | ||||
225 | if (Symb.getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE) | |||
226 | Result |= SymbolRef::SF_Absolute; | |||
227 | ||||
228 | if (Symb.isFileRecord()) | |||
229 | Result |= SymbolRef::SF_FormatSpecific; | |||
230 | ||||
231 | if (Symb.isSectionDefinition()) | |||
232 | Result |= SymbolRef::SF_FormatSpecific; | |||
233 | ||||
234 | if (Symb.isCommon()) | |||
235 | Result |= SymbolRef::SF_Common; | |||
236 | ||||
237 | if (Symb.isUndefined()) | |||
238 | Result |= SymbolRef::SF_Undefined; | |||
239 | ||||
240 | return Result; | |||
241 | } | |||
242 | ||||
243 | uint64_t COFFObjectFile::getCommonSymbolSizeImpl(DataRefImpl Ref) const { | |||
244 | COFFSymbolRef Symb = getCOFFSymbol(Ref); | |||
245 | return Symb.getValue(); | |||
246 | } | |||
247 | ||||
248 | Expected<section_iterator> | |||
249 | COFFObjectFile::getSymbolSection(DataRefImpl Ref) const { | |||
250 | COFFSymbolRef Symb = getCOFFSymbol(Ref); | |||
251 | if (COFF::isReservedSectionNumber(Symb.getSectionNumber())) | |||
252 | return section_end(); | |||
253 | const coff_section *Sec = nullptr; | |||
254 | if (std::error_code EC = getSection(Symb.getSectionNumber(), Sec)) | |||
255 | return errorCodeToError(EC); | |||
256 | DataRefImpl Ret; | |||
257 | Ret.p = reinterpret_cast<uintptr_t>(Sec); | |||
258 | return section_iterator(SectionRef(Ret, this)); | |||
259 | } | |||
260 | ||||
261 | unsigned COFFObjectFile::getSymbolSectionID(SymbolRef Sym) const { | |||
262 | COFFSymbolRef Symb = getCOFFSymbol(Sym.getRawDataRefImpl()); | |||
263 | return Symb.getSectionNumber(); | |||
264 | } | |||
265 | ||||
266 | void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const { | |||
267 | const coff_section *Sec = toSec(Ref); | |||
268 | Sec += 1; | |||
269 | Ref.p = reinterpret_cast<uintptr_t>(Sec); | |||
270 | } | |||
271 | ||||
272 | Expected<StringRef> COFFObjectFile::getSectionName(DataRefImpl Ref) const { | |||
273 | const coff_section *Sec = toSec(Ref); | |||
274 | return getSectionName(Sec); | |||
275 | } | |||
276 | ||||
277 | uint64_t COFFObjectFile::getSectionAddress(DataRefImpl Ref) const { | |||
278 | const coff_section *Sec = toSec(Ref); | |||
279 | uint64_t Result = Sec->VirtualAddress; | |||
280 | ||||
281 | // The section VirtualAddress does not include ImageBase, and we want to | |||
282 | // return virtual addresses. | |||
283 | Result += getImageBase(); | |||
284 | return Result; | |||
285 | } | |||
286 | ||||
287 | uint64_t COFFObjectFile::getSectionIndex(DataRefImpl Sec) const { | |||
288 | return toSec(Sec) - SectionTable; | |||
289 | } | |||
290 | ||||
291 | uint64_t COFFObjectFile::getSectionSize(DataRefImpl Ref) const { | |||
292 | return getSectionSize(toSec(Ref)); | |||
293 | } | |||
294 | ||||
295 | Expected<ArrayRef<uint8_t>> | |||
296 | COFFObjectFile::getSectionContents(DataRefImpl Ref) const { | |||
297 | const coff_section *Sec = toSec(Ref); | |||
298 | ArrayRef<uint8_t> Res; | |||
299 | if (Error E = getSectionContents(Sec, Res)) | |||
300 | return std::move(E); | |||
301 | return Res; | |||
302 | } | |||
303 | ||||
304 | uint64_t COFFObjectFile::getSectionAlignment(DataRefImpl Ref) const { | |||
305 | const coff_section *Sec = toSec(Ref); | |||
306 | return Sec->getAlignment(); | |||
307 | } | |||
308 | ||||
309 | bool COFFObjectFile::isSectionCompressed(DataRefImpl Sec) const { | |||
310 | return false; | |||
311 | } | |||
312 | ||||
313 | bool COFFObjectFile::isSectionText(DataRefImpl Ref) const { | |||
314 | const coff_section *Sec = toSec(Ref); | |||
315 | return Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE; | |||
316 | } | |||
317 | ||||
318 | bool COFFObjectFile::isSectionData(DataRefImpl Ref) const { | |||
319 | const coff_section *Sec = toSec(Ref); | |||
320 | return Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA; | |||
321 | } | |||
322 | ||||
323 | bool COFFObjectFile::isSectionBSS(DataRefImpl Ref) const { | |||
324 | const coff_section *Sec = toSec(Ref); | |||
325 | const uint32_t BssFlags = COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA | | |||
326 | COFF::IMAGE_SCN_MEM_READ | | |||
327 | COFF::IMAGE_SCN_MEM_WRITE; | |||
328 | return (Sec->Characteristics & BssFlags) == BssFlags; | |||
329 | } | |||
330 | ||||
331 | unsigned COFFObjectFile::getSectionID(SectionRef Sec) const { | |||
332 | uintptr_t Offset = | |||
333 | uintptr_t(Sec.getRawDataRefImpl().p) - uintptr_t(SectionTable); | |||
334 | assert((Offset % sizeof(coff_section)) == 0)(((Offset % sizeof(coff_section)) == 0) ? static_cast<void > (0) : __assert_fail ("(Offset % sizeof(coff_section)) == 0" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Object/COFFObjectFile.cpp" , 334, __PRETTY_FUNCTION__)); | |||
335 | return (Offset / sizeof(coff_section)) + 1; | |||
336 | } | |||
337 | ||||
338 | bool COFFObjectFile::isSectionVirtual(DataRefImpl Ref) const { | |||
339 | const coff_section *Sec = toSec(Ref); | |||
340 | // In COFF, a virtual section won't have any in-file | |||
341 | // content, so the file pointer to the content will be zero. | |||
342 | return Sec->PointerToRawData == 0; | |||
343 | } | |||
344 | ||||
345 | static uint32_t getNumberOfRelocations(const coff_section *Sec, | |||
346 | MemoryBufferRef M, const uint8_t *base) { | |||
347 | // The field for the number of relocations in COFF section table is only | |||
348 | // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to | |||
349 | // NumberOfRelocations field, and the actual relocation count is stored in the | |||
350 | // VirtualAddress field in the first relocation entry. | |||
351 | if (Sec->hasExtendedRelocations()) { | |||
352 | const coff_relocation *FirstReloc; | |||
353 | if (getObject(FirstReloc, M, reinterpret_cast<const coff_relocation*>( | |||
354 | base + Sec->PointerToRelocations))) | |||
355 | return 0; | |||
356 | // -1 to exclude this first relocation entry. | |||
357 | return FirstReloc->VirtualAddress - 1; | |||
358 | } | |||
359 | return Sec->NumberOfRelocations; | |||
360 | } | |||
361 | ||||
362 | static const coff_relocation * | |||
363 | getFirstReloc(const coff_section *Sec, MemoryBufferRef M, const uint8_t *Base) { | |||
364 | uint64_t NumRelocs = getNumberOfRelocations(Sec, M, Base); | |||
365 | if (!NumRelocs) | |||
366 | return nullptr; | |||
367 | auto begin = reinterpret_cast<const coff_relocation *>( | |||
368 | Base + Sec->PointerToRelocations); | |||
369 | if (Sec->hasExtendedRelocations()) { | |||
370 | // Skip the first relocation entry repurposed to store the number of | |||
371 | // relocations. | |||
372 | begin++; | |||
373 | } | |||
374 | if (Binary::checkOffset(M, uintptr_t(begin), | |||
375 | sizeof(coff_relocation) * NumRelocs)) | |||
376 | return nullptr; | |||
377 | return begin; | |||
378 | } | |||
379 | ||||
380 | relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const { | |||
381 | const coff_section *Sec = toSec(Ref); | |||
382 | const coff_relocation *begin = getFirstReloc(Sec, Data, base()); | |||
383 | if (begin && Sec->VirtualAddress != 0) | |||
384 | report_fatal_error("Sections with relocations should have an address of 0"); | |||
385 | DataRefImpl Ret; | |||
386 | Ret.p = reinterpret_cast<uintptr_t>(begin); | |||
387 | return relocation_iterator(RelocationRef(Ret, this)); | |||
388 | } | |||
389 | ||||
390 | relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const { | |||
391 | const coff_section *Sec = toSec(Ref); | |||
392 | const coff_relocation *I = getFirstReloc(Sec, Data, base()); | |||
393 | if (I) | |||
394 | I += getNumberOfRelocations(Sec, Data, base()); | |||
395 | DataRefImpl Ret; | |||
396 | Ret.p = reinterpret_cast<uintptr_t>(I); | |||
397 | return relocation_iterator(RelocationRef(Ret, this)); | |||
398 | } | |||
399 | ||||
400 | // Initialize the pointer to the symbol table. | |||
401 | std::error_code COFFObjectFile::initSymbolTablePtr() { | |||
402 | if (COFFHeader) | |||
403 | if (std::error_code EC = getObject( | |||
404 | SymbolTable16, Data, base() + getPointerToSymbolTable(), | |||
405 | (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize())) | |||
406 | return EC; | |||
407 | ||||
408 | if (COFFBigObjHeader) | |||
409 | if (std::error_code EC = getObject( | |||
410 | SymbolTable32, Data, base() + getPointerToSymbolTable(), | |||
411 | (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize())) | |||
412 | return EC; | |||
413 | ||||
414 | // Find string table. The first four byte of the string table contains the | |||
415 | // total size of the string table, including the size field itself. If the | |||
416 | // string table is empty, the value of the first four byte would be 4. | |||
417 | uint32_t StringTableOffset = getPointerToSymbolTable() + | |||
418 | getNumberOfSymbols() * getSymbolTableEntrySize(); | |||
419 | const uint8_t *StringTableAddr = base() + StringTableOffset; | |||
420 | const ulittle32_t *StringTableSizePtr; | |||
421 | if (std::error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr)) | |||
422 | return EC; | |||
423 | StringTableSize = *StringTableSizePtr; | |||
424 | if (std::error_code EC = | |||
425 | getObject(StringTable, Data, StringTableAddr, StringTableSize)) | |||
426 | return EC; | |||
427 | ||||
428 | // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some | |||
429 | // tools like cvtres write a size of 0 for an empty table instead of 4. | |||
430 | if (StringTableSize < 4) | |||
431 | StringTableSize = 4; | |||
432 | ||||
433 | // Check that the string table is null terminated if has any in it. | |||
434 | if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0) | |||
435 | return object_error::parse_failed; | |||
436 | return std::error_code(); | |||
437 | } | |||
438 | ||||
439 | uint64_t COFFObjectFile::getImageBase() const { | |||
440 | if (PE32Header) | |||
441 | return PE32Header->ImageBase; | |||
442 | else if (PE32PlusHeader) | |||
443 | return PE32PlusHeader->ImageBase; | |||
444 | // This actually comes up in practice. | |||
445 | return 0; | |||
446 | } | |||
447 | ||||
448 | // Returns the file offset for the given VA. | |||
449 | std::error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const { | |||
450 | uint64_t ImageBase = getImageBase(); | |||
451 | uint64_t Rva = Addr - ImageBase; | |||
452 | assert(Rva <= UINT32_MAX)((Rva <= (4294967295U)) ? static_cast<void> (0) : __assert_fail ("Rva <= UINT32_MAX", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Object/COFFObjectFile.cpp" , 452, __PRETTY_FUNCTION__)); | |||
453 | return getRvaPtr((uint32_t)Rva, Res); | |||
454 | } | |||
455 | ||||
456 | // Returns the file offset for the given RVA. | |||
457 | std::error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const { | |||
458 | for (const SectionRef &S : sections()) { | |||
459 | const coff_section *Section = getCOFFSection(S); | |||
460 | uint32_t SectionStart = Section->VirtualAddress; | |||
461 | uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize; | |||
462 | if (SectionStart <= Addr && Addr < SectionEnd) { | |||
463 | uint32_t Offset = Addr - SectionStart; | |||
464 | Res = uintptr_t(base()) + Section->PointerToRawData + Offset; | |||
465 | return std::error_code(); | |||
466 | } | |||
467 | } | |||
468 | return object_error::parse_failed; | |||
469 | } | |||
470 | ||||
471 | std::error_code | |||
472 | COFFObjectFile::getRvaAndSizeAsBytes(uint32_t RVA, uint32_t Size, | |||
473 | ArrayRef<uint8_t> &Contents) const { | |||
474 | for (const SectionRef &S : sections()) { | |||
475 | const coff_section *Section = getCOFFSection(S); | |||
476 | uint32_t SectionStart = Section->VirtualAddress; | |||
477 | // Check if this RVA is within the section bounds. Be careful about integer | |||
478 | // overflow. | |||
479 | uint32_t OffsetIntoSection = RVA - SectionStart; | |||
480 | if (SectionStart <= RVA && OffsetIntoSection < Section->VirtualSize && | |||
481 | Size <= Section->VirtualSize - OffsetIntoSection) { | |||
482 | uintptr_t Begin = | |||
483 | uintptr_t(base()) + Section->PointerToRawData + OffsetIntoSection; | |||
484 | Contents = | |||
485 | ArrayRef<uint8_t>(reinterpret_cast<const uint8_t *>(Begin), Size); | |||
486 | return std::error_code(); | |||
487 | } | |||
488 | } | |||
489 | return object_error::parse_failed; | |||
490 | } | |||
491 | ||||
492 | // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name | |||
493 | // table entry. | |||
494 | std::error_code COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint, | |||
495 | StringRef &Name) const { | |||
496 | uintptr_t IntPtr = 0; | |||
497 | if (std::error_code EC = getRvaPtr(Rva, IntPtr)) | |||
498 | return EC; | |||
499 | const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr); | |||
500 | Hint = *reinterpret_cast<const ulittle16_t *>(Ptr); | |||
501 | Name = StringRef(reinterpret_cast<const char *>(Ptr + 2)); | |||
502 | return std::error_code(); | |||
503 | } | |||
504 | ||||
505 | std::error_code | |||
506 | COFFObjectFile::getDebugPDBInfo(const debug_directory *DebugDir, | |||
507 | const codeview::DebugInfo *&PDBInfo, | |||
508 | StringRef &PDBFileName) const { | |||
509 | ArrayRef<uint8_t> InfoBytes; | |||
510 | if (std::error_code EC = getRvaAndSizeAsBytes( | |||
511 | DebugDir->AddressOfRawData, DebugDir->SizeOfData, InfoBytes)) | |||
512 | return EC; | |||
513 | if (InfoBytes.size() < sizeof(*PDBInfo) + 1) | |||
514 | return object_error::parse_failed; | |||
515 | PDBInfo = reinterpret_cast<const codeview::DebugInfo *>(InfoBytes.data()); | |||
516 | InfoBytes = InfoBytes.drop_front(sizeof(*PDBInfo)); | |||
517 | PDBFileName = StringRef(reinterpret_cast<const char *>(InfoBytes.data()), | |||
518 | InfoBytes.size()); | |||
519 | // Truncate the name at the first null byte. Ignore any padding. | |||
520 | PDBFileName = PDBFileName.split('\0').first; | |||
521 | return std::error_code(); | |||
522 | } | |||
523 | ||||
524 | std::error_code | |||
525 | COFFObjectFile::getDebugPDBInfo(const codeview::DebugInfo *&PDBInfo, | |||
526 | StringRef &PDBFileName) const { | |||
527 | for (const debug_directory &D : debug_directories()) | |||
528 | if (D.Type == COFF::IMAGE_DEBUG_TYPE_CODEVIEW) | |||
529 | return getDebugPDBInfo(&D, PDBInfo, PDBFileName); | |||
530 | // If we get here, there is no PDB info to return. | |||
531 | PDBInfo = nullptr; | |||
532 | PDBFileName = StringRef(); | |||
533 | return std::error_code(); | |||
534 | } | |||
535 | ||||
536 | // Find the import table. | |||
537 | std::error_code COFFObjectFile::initImportTablePtr() { | |||
538 | // First, we get the RVA of the import table. If the file lacks a pointer to | |||
539 | // the import table, do nothing. | |||
540 | const data_directory *DataEntry; | |||
541 | if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry)) | |||
542 | return std::error_code(); | |||
543 | ||||
544 | // Do nothing if the pointer to import table is NULL. | |||
545 | if (DataEntry->RelativeVirtualAddress == 0) | |||
546 | return std::error_code(); | |||
547 | ||||
548 | uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress; | |||
549 | ||||
550 | // Find the section that contains the RVA. This is needed because the RVA is | |||
551 | // the import table's memory address which is different from its file offset. | |||
552 | uintptr_t IntPtr = 0; | |||
553 | if (std::error_code EC = getRvaPtr(ImportTableRva, IntPtr)) | |||
554 | return EC; | |||
555 | if (std::error_code EC = checkOffset(Data, IntPtr, DataEntry->Size)) | |||
556 | return EC; | |||
557 | ImportDirectory = reinterpret_cast< | |||
558 | const coff_import_directory_table_entry *>(IntPtr); | |||
559 | return std::error_code(); | |||
560 | } | |||
561 | ||||
562 | // Initializes DelayImportDirectory and NumberOfDelayImportDirectory. | |||
563 | std::error_code COFFObjectFile::initDelayImportTablePtr() { | |||
564 | const data_directory *DataEntry; | |||
565 | if (getDataDirectory(COFF::DELAY_IMPORT_DESCRIPTOR, DataEntry)) | |||
566 | return std::error_code(); | |||
567 | if (DataEntry->RelativeVirtualAddress == 0) | |||
568 | return std::error_code(); | |||
569 | ||||
570 | uint32_t RVA = DataEntry->RelativeVirtualAddress; | |||
571 | NumberOfDelayImportDirectory = DataEntry->Size / | |||
572 | sizeof(delay_import_directory_table_entry) - 1; | |||
573 | ||||
574 | uintptr_t IntPtr = 0; | |||
575 | if (std::error_code EC = getRvaPtr(RVA, IntPtr)) | |||
576 | return EC; | |||
577 | DelayImportDirectory = reinterpret_cast< | |||
578 | const delay_import_directory_table_entry *>(IntPtr); | |||
579 | return std::error_code(); | |||
580 | } | |||
581 | ||||
582 | // Find the export table. | |||
583 | std::error_code COFFObjectFile::initExportTablePtr() { | |||
584 | // First, we get the RVA of the export table. If the file lacks a pointer to | |||
585 | // the export table, do nothing. | |||
586 | const data_directory *DataEntry; | |||
587 | if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry)) | |||
588 | return std::error_code(); | |||
589 | ||||
590 | // Do nothing if the pointer to export table is NULL. | |||
591 | if (DataEntry->RelativeVirtualAddress == 0) | |||
592 | return std::error_code(); | |||
593 | ||||
594 | uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress; | |||
595 | uintptr_t IntPtr = 0; | |||
596 | if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr)) | |||
597 | return EC; | |||
598 | ExportDirectory = | |||
599 | reinterpret_cast<const export_directory_table_entry *>(IntPtr); | |||
600 | return std::error_code(); | |||
601 | } | |||
602 | ||||
603 | std::error_code COFFObjectFile::initBaseRelocPtr() { | |||
604 | const data_directory *DataEntry; | |||
605 | if (getDataDirectory(COFF::BASE_RELOCATION_TABLE, DataEntry)) | |||
606 | return std::error_code(); | |||
607 | if (DataEntry->RelativeVirtualAddress == 0) | |||
608 | return std::error_code(); | |||
609 | ||||
610 | uintptr_t IntPtr = 0; | |||
611 | if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr)) | |||
612 | return EC; | |||
613 | BaseRelocHeader = reinterpret_cast<const coff_base_reloc_block_header *>( | |||
614 | IntPtr); | |||
615 | BaseRelocEnd = reinterpret_cast<coff_base_reloc_block_header *>( | |||
616 | IntPtr + DataEntry->Size); | |||
617 | // FIXME: Verify the section containing BaseRelocHeader has at least | |||
618 | // DataEntry->Size bytes after DataEntry->RelativeVirtualAddress. | |||
619 | return std::error_code(); | |||
620 | } | |||
621 | ||||
622 | std::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 | DebugDirectoryEnd = reinterpret_cast<const debug_directory *>( | |||
641 | IntPtr + DataEntry->Size); | |||
642 | // FIXME: Verify the section containing DebugDirectoryBegin has at least | |||
643 | // DataEntry->Size bytes after DataEntry->RelativeVirtualAddress. | |||
644 | return std::error_code(); | |||
645 | } | |||
646 | ||||
647 | std::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 | ||||
664 | COFFObjectFile::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 | ||||
804 | basic_symbol_iterator COFFObjectFile::symbol_begin() const { | |||
805 | DataRefImpl Ret; | |||
806 | Ret.p = getSymbolTable(); | |||
807 | return basic_symbol_iterator(SymbolRef(Ret, this)); | |||
808 | } | |||
809 | ||||
810 | basic_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 | ||||
817 | import_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 | ||||
826 | import_directory_iterator COFFObjectFile::import_directory_end() const { | |||
827 | return import_directory_iterator( | |||
828 | ImportDirectoryEntryRef(nullptr, -1, this)); | |||
829 | } | |||
830 | ||||
831 | delay_import_directory_iterator | |||
832 | COFFObjectFile::delay_import_directory_begin() const { | |||
833 | return delay_import_directory_iterator( | |||
834 | DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this)); | |||
835 | } | |||
836 | ||||
837 | delay_import_directory_iterator | |||
838 | COFFObjectFile::delay_import_directory_end() const { | |||
839 | return delay_import_directory_iterator( | |||
840 | DelayImportDirectoryEntryRef( | |||
841 | DelayImportDirectory, NumberOfDelayImportDirectory, this)); | |||
842 | } | |||
843 | ||||
844 | export_directory_iterator COFFObjectFile::export_directory_begin() const { | |||
845 | return export_directory_iterator( | |||
846 | ExportDirectoryEntryRef(ExportDirectory, 0, this)); | |||
847 | } | |||
848 | ||||
849 | export_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 | ||||
857 | section_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 | ||||
863 | section_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 | ||||
871 | base_reloc_iterator COFFObjectFile::base_reloc_begin() const { | |||
872 | return base_reloc_iterator(BaseRelocRef(BaseRelocHeader, this)); | |||
873 | } | |||
874 | ||||
875 | base_reloc_iterator COFFObjectFile::base_reloc_end() const { | |||
876 | return base_reloc_iterator(BaseRelocRef(BaseRelocEnd, this)); | |||
877 | } | |||
878 | ||||
879 | uint8_t COFFObjectFile::getBytesInAddress() const { | |||
880 | return getArch() == Triple::x86_64 || getArch() == Triple::aarch64 ? 8 : 4; | |||
881 | } | |||
882 | ||||
883 | StringRef 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 | ||||
898 | Triple::ArchType 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 | ||||
913 | Expected<uint64_t> COFFObjectFile::getStartAddress() const { | |||
914 | if (PE32Header) | |||
915 | return PE32Header->AddressOfEntryPoint; | |||
916 | return 0; | |||
917 | } | |||
918 | ||||
919 | iterator_range<import_directory_iterator> | |||
920 | COFFObjectFile::import_directories() const { | |||
921 | return make_range(import_directory_begin(), import_directory_end()); | |||
922 | } | |||
923 | ||||
924 | iterator_range<delay_import_directory_iterator> | |||
925 | COFFObjectFile::delay_import_directories() const { | |||
926 | return make_range(delay_import_directory_begin(), | |||
927 | delay_import_directory_end()); | |||
928 | } | |||
929 | ||||
930 | iterator_range<export_directory_iterator> | |||
931 | COFFObjectFile::export_directories() const { | |||
932 | return make_range(export_directory_begin(), export_directory_end()); | |||
933 | } | |||
934 | ||||
935 | iterator_range<base_reloc_iterator> COFFObjectFile::base_relocs() const { | |||
936 | return make_range(base_reloc_begin(), base_reloc_end()); | |||
937 | } | |||
938 | ||||
939 | std::error_code | |||
940 | COFFObjectFile::getDataDirectory(uint32_t Index, | |||
941 | const data_directory *&Res) const { | |||
942 | // Error if there's no data directory or the index is out of range. | |||
943 | if (!DataDirectory) { | |||
944 | Res = nullptr; | |||
945 | return object_error::parse_failed; | |||
946 | } | |||
947 | assert(PE32Header || PE32PlusHeader)((PE32Header || PE32PlusHeader) ? static_cast<void> (0) : __assert_fail ("PE32Header || PE32PlusHeader", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Object/COFFObjectFile.cpp" , 947, __PRETTY_FUNCTION__)); | |||
948 | uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize | |||
949 | : PE32PlusHeader->NumberOfRvaAndSize; | |||
950 | if (Index >= NumEnt) { | |||
951 | Res = nullptr; | |||
952 | return object_error::parse_failed; | |||
953 | } | |||
954 | Res = &DataDirectory[Index]; | |||
955 | return std::error_code(); | |||
956 | } | |||
957 | ||||
958 | std::error_code COFFObjectFile::getSection(int32_t Index, | |||
959 | const coff_section *&Result) const { | |||
960 | Result = nullptr; | |||
961 | if (COFF::isReservedSectionNumber(Index)) | |||
962 | return std::error_code(); | |||
963 | if (static_cast<uint32_t>(Index) <= getNumberOfSections()) { | |||
964 | // We already verified the section table data, so no need to check again. | |||
965 | Result = SectionTable + (Index - 1); | |||
966 | return std::error_code(); | |||
967 | } | |||
968 | return object_error::parse_failed; | |||
969 | } | |||
970 | ||||
971 | std::error_code COFFObjectFile::getSection(StringRef SectionName, | |||
972 | const coff_section *&Result) const { | |||
973 | Result = nullptr; | |||
974 | for (const SectionRef &Section : sections()) { | |||
975 | auto NameOrErr = Section.getName(); | |||
976 | if (!NameOrErr) | |||
977 | return errorToErrorCode(NameOrErr.takeError()); | |||
978 | ||||
979 | if (*NameOrErr == SectionName) { | |||
980 | Result = getCOFFSection(Section); | |||
981 | return std::error_code(); | |||
982 | } | |||
983 | } | |||
984 | return object_error::parse_failed; | |||
985 | } | |||
986 | ||||
987 | std::error_code COFFObjectFile::getString(uint32_t Offset, | |||
988 | StringRef &Result) const { | |||
989 | if (StringTableSize <= 4) | |||
990 | // Tried to get a string from an empty string table. | |||
991 | return object_error::parse_failed; | |||
992 | if (Offset >= StringTableSize) | |||
993 | return object_error::unexpected_eof; | |||
994 | Result = StringRef(StringTable + Offset); | |||
995 | return std::error_code(); | |||
996 | } | |||
997 | ||||
998 | std::error_code COFFObjectFile::getSymbolName(COFFSymbolRef Symbol, | |||
999 | StringRef &Res) const { | |||
1000 | return getSymbolName(Symbol.getGeneric(), Res); | |||
1001 | } | |||
1002 | ||||
1003 | std::error_code COFFObjectFile::getSymbolName(const coff_symbol_generic *Symbol, | |||
1004 | StringRef &Res) const { | |||
1005 | // Check for string table entry. First 4 bytes are 0. | |||
1006 | if (Symbol->Name.Offset.Zeroes == 0) { | |||
1007 | if (std::error_code EC = getString(Symbol->Name.Offset.Offset, Res)) | |||
1008 | return EC; | |||
1009 | return std::error_code(); | |||
1010 | } | |||
1011 | ||||
1012 | if (Symbol->Name.ShortName[COFF::NameSize - 1] == 0) | |||
1013 | // Null terminated, let ::strlen figure out the length. | |||
1014 | Res = StringRef(Symbol->Name.ShortName); | |||
1015 | else | |||
1016 | // Not null terminated, use all 8 bytes. | |||
1017 | Res = StringRef(Symbol->Name.ShortName, COFF::NameSize); | |||
1018 | return std::error_code(); | |||
1019 | } | |||
1020 | ||||
1021 | ArrayRef<uint8_t> | |||
1022 | COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const { | |||
1023 | const uint8_t *Aux = nullptr; | |||
1024 | ||||
1025 | size_t SymbolSize = getSymbolTableEntrySize(); | |||
1026 | if (Symbol.getNumberOfAuxSymbols() > 0) { | |||
1027 | // AUX data comes immediately after the symbol in COFF | |||
1028 | Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize; | |||
1029 | #ifndef NDEBUG | |||
1030 | // Verify that the Aux symbol points to a valid entry in the symbol table. | |||
1031 | uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base()); | |||
1032 | if (Offset < getPointerToSymbolTable() || | |||
1033 | Offset >= | |||
1034 | getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize)) | |||
1035 | report_fatal_error("Aux Symbol data was outside of symbol table."); | |||
1036 | ||||
1037 | assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&(((Offset - getPointerToSymbolTable()) % SymbolSize == 0 && "Aux Symbol data did not point to the beginning of a symbol" ) ? static_cast<void> (0) : __assert_fail ("(Offset - getPointerToSymbolTable()) % SymbolSize == 0 && \"Aux Symbol data did not point to the beginning of a symbol\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Object/COFFObjectFile.cpp" , 1038, __PRETTY_FUNCTION__)) | |||
1038 | "Aux Symbol data did not point to the beginning of a symbol")(((Offset - getPointerToSymbolTable()) % SymbolSize == 0 && "Aux Symbol data did not point to the beginning of a symbol" ) ? static_cast<void> (0) : __assert_fail ("(Offset - getPointerToSymbolTable()) % SymbolSize == 0 && \"Aux Symbol data did not point to the beginning of a symbol\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Object/COFFObjectFile.cpp" , 1038, __PRETTY_FUNCTION__)); | |||
1039 | #endif | |||
1040 | } | |||
1041 | return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize); | |||
1042 | } | |||
1043 | ||||
1044 | uint32_t COFFObjectFile::getSymbolIndex(COFFSymbolRef Symbol) const { | |||
1045 | uintptr_t Offset = | |||
1046 | reinterpret_cast<uintptr_t>(Symbol.getRawPtr()) - getSymbolTable(); | |||
1047 | assert(Offset % getSymbolTableEntrySize() == 0 &&((Offset % getSymbolTableEntrySize() == 0 && "Symbol did not point to the beginning of a symbol" ) ? static_cast<void> (0) : __assert_fail ("Offset % getSymbolTableEntrySize() == 0 && \"Symbol did not point to the beginning of a symbol\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Object/COFFObjectFile.cpp" , 1048, __PRETTY_FUNCTION__)) | |||
1048 | "Symbol did not point to the beginning of a symbol")((Offset % getSymbolTableEntrySize() == 0 && "Symbol did not point to the beginning of a symbol" ) ? static_cast<void> (0) : __assert_fail ("Offset % getSymbolTableEntrySize() == 0 && \"Symbol did not point to the beginning of a symbol\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Object/COFFObjectFile.cpp" , 1048, __PRETTY_FUNCTION__)); | |||
1049 | size_t Index = Offset / getSymbolTableEntrySize(); | |||
1050 | assert(Index < getNumberOfSymbols())((Index < getNumberOfSymbols()) ? static_cast<void> ( 0) : __assert_fail ("Index < getNumberOfSymbols()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Object/COFFObjectFile.cpp" , 1050, __PRETTY_FUNCTION__)); | |||
1051 | return Index; | |||
1052 | } | |||
1053 | ||||
1054 | Expected<StringRef> | |||
1055 | COFFObjectFile::getSectionName(const coff_section *Sec) const { | |||
1056 | StringRef Name; | |||
1057 | if (Sec->Name[COFF::NameSize - 1] == 0) | |||
1058 | // Null terminated, let ::strlen figure out the length. | |||
1059 | Name = Sec->Name; | |||
1060 | else | |||
1061 | // Not null terminated, use all 8 bytes. | |||
1062 | Name = StringRef(Sec->Name, COFF::NameSize); | |||
1063 | ||||
1064 | // Check for string table entry. First byte is '/'. | |||
1065 | if (Name.startswith("/")) { | |||
1066 | uint32_t Offset; | |||
1067 | if (Name.startswith("//")) { | |||
1068 | if (decodeBase64StringEntry(Name.substr(2), Offset)) | |||
1069 | return createStringError(object_error::parse_failed, | |||
1070 | "invalid section name"); | |||
1071 | } else { | |||
1072 | if (Name.substr(1).getAsInteger(10, Offset)) | |||
1073 | return createStringError(object_error::parse_failed, | |||
1074 | "invalid section name"); | |||
1075 | } | |||
1076 | if (std::error_code EC = getString(Offset, Name)) | |||
1077 | return errorCodeToError(EC); | |||
1078 | } | |||
1079 | ||||
1080 | return Name; | |||
1081 | } | |||
1082 | ||||
1083 | uint64_t COFFObjectFile::getSectionSize(const coff_section *Sec) const { | |||
1084 | // SizeOfRawData and VirtualSize change what they represent depending on | |||
1085 | // whether or not we have an executable image. | |||
1086 | // | |||
1087 | // For object files, SizeOfRawData contains the size of section's data; | |||
1088 | // VirtualSize should be zero but isn't due to buggy COFF writers. | |||
1089 | // | |||
1090 | // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the | |||
1091 | // actual section size is in VirtualSize. It is possible for VirtualSize to | |||
1092 | // be greater than SizeOfRawData; the contents past that point should be | |||
1093 | // considered to be zero. | |||
1094 | if (getDOSHeader()) | |||
1095 | return std::min(Sec->VirtualSize, Sec->SizeOfRawData); | |||
1096 | return Sec->SizeOfRawData; | |||
1097 | } | |||
1098 | ||||
1099 | Error COFFObjectFile::getSectionContents(const coff_section *Sec, | |||
1100 | ArrayRef<uint8_t> &Res) const { | |||
1101 | // In COFF, a virtual section won't have any in-file | |||
1102 | // content, so the file pointer to the content will be zero. | |||
1103 | if (Sec->PointerToRawData == 0) | |||
| ||||
1104 | return Error::success(); | |||
1105 | // The only thing that we need to verify is that the contents is contained | |||
1106 | // within the file bounds. We don't need to make sure it doesn't cover other | |||
1107 | // data, as there's nothing that says that is not allowed. | |||
1108 | uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData; | |||
1109 | uint32_t SectionSize = getSectionSize(Sec); | |||
1110 | if (checkOffset(Data, ConStart, SectionSize)) | |||
1111 | return make_error<BinaryError>(); | |||
1112 | Res = makeArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize); | |||
1113 | return Error::success(); | |||
1114 | } | |||
1115 | ||||
1116 | const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const { | |||
1117 | return reinterpret_cast<const coff_relocation*>(Rel.p); | |||
1118 | } | |||
1119 | ||||
1120 | void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const { | |||
1121 | Rel.p = reinterpret_cast<uintptr_t>( | |||
1122 | reinterpret_cast<const coff_relocation*>(Rel.p) + 1); | |||
1123 | } | |||
1124 | ||||
1125 | uint64_t COFFObjectFile::getRelocationOffset(DataRefImpl Rel) const { | |||
1126 | const coff_relocation *R = toRel(Rel); | |||
1127 | return R->VirtualAddress; | |||
1128 | } | |||
1129 | ||||
1130 | symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const { | |||
1131 | const coff_relocation *R = toRel(Rel); | |||
1132 | DataRefImpl Ref; | |||
1133 | if (R->SymbolTableIndex >= getNumberOfSymbols()) | |||
1134 | return symbol_end(); | |||
1135 | if (SymbolTable16) | |||
1136 | Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex); | |||
1137 | else if (SymbolTable32) | |||
1138 | Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex); | |||
1139 | else | |||
1140 | llvm_unreachable("no symbol table pointer!")::llvm::llvm_unreachable_internal("no symbol table pointer!", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Object/COFFObjectFile.cpp" , 1140); | |||
1141 | return symbol_iterator(SymbolRef(Ref, this)); | |||
1142 | } | |||
1143 | ||||
1144 | uint64_t COFFObjectFile::getRelocationType(DataRefImpl Rel) const { | |||
1145 | const coff_relocation* R = toRel(Rel); | |||
1146 | return R->Type; | |||
1147 | } | |||
1148 | ||||
1149 | const coff_section * | |||
1150 | COFFObjectFile::getCOFFSection(const SectionRef &Section) const { | |||
1151 | return toSec(Section.getRawDataRefImpl()); | |||
1152 | } | |||
1153 | ||||
1154 | COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const { | |||
1155 | if (SymbolTable16) | |||
1156 | return toSymb<coff_symbol16>(Ref); | |||
1157 | if (SymbolTable32) | |||
1158 | return toSymb<coff_symbol32>(Ref); | |||
1159 | llvm_unreachable("no symbol table pointer!")::llvm::llvm_unreachable_internal("no symbol table pointer!", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Object/COFFObjectFile.cpp" , 1159); | |||
1160 | } | |||
1161 | ||||
1162 | COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const { | |||
1163 | return getCOFFSymbol(Symbol.getRawDataRefImpl()); | |||
1164 | } | |||
1165 | ||||
1166 | const coff_relocation * | |||
1167 | COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const { | |||
1168 | return toRel(Reloc.getRawDataRefImpl()); | |||
1169 | } | |||
1170 | ||||
1171 | ArrayRef<coff_relocation> | |||
1172 | COFFObjectFile::getRelocations(const coff_section *Sec) const { | |||
1173 | return {getFirstReloc(Sec, Data, base()), | |||
1174 | getNumberOfRelocations(Sec, Data, base())}; | |||
1175 | } | |||
1176 | ||||
1177 | #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \ | |||
1178 | case COFF::reloc_type: \ | |||
1179 | return #reloc_type; | |||
1180 | ||||
1181 | StringRef COFFObjectFile::getRelocationTypeName(uint16_t Type) const { | |||
1182 | switch (getMachine()) { | |||
1183 | case COFF::IMAGE_FILE_MACHINE_AMD64: | |||
1184 | switch (Type) { | |||
1185 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE); | |||
1186 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64); | |||
1187 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32); | |||
1188 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB); | |||
1189 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32); | |||
1190 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1); | |||
1191 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2); | |||
1192 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3); | |||
1193 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4); | |||
1194 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5); | |||
1195 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION); | |||
1196 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL); | |||
1197 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7); | |||
1198 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN); | |||
1199 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32); | |||
1200 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR); | |||
1201 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32); | |||
1202 | default: | |||
1203 | return "Unknown"; | |||
1204 | } | |||
1205 | break; | |||
1206 | case COFF::IMAGE_FILE_MACHINE_ARMNT: | |||
1207 | switch (Type) { | |||
1208 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE); | |||
1209 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32); | |||
1210 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB); | |||
1211 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24); | |||
1212 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11); | |||
1213 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN); | |||
1214 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24); | |||
1215 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11); | |||
1216 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_REL32); | |||
1217 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION); | |||
1218 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL); | |||
1219 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A); | |||
1220 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T); | |||
1221 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T); | |||
1222 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T); | |||
1223 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T); | |||
1224 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_PAIR); | |||
1225 | default: | |||
1226 | return "Unknown"; | |||
1227 | } | |||
1228 | break; | |||
1229 | case COFF::IMAGE_FILE_MACHINE_ARM64: | |||
1230 | switch (Type) { | |||
1231 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ABSOLUTE); | |||
1232 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ADDR32); | |||
1233 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ADDR32NB); | |||
1234 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_BRANCH26); | |||
1235 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_PAGEBASE_REL21); | |||
1236 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_REL21); | |||
1237 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_PAGEOFFSET_12A); | |||
1238 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_PAGEOFFSET_12L); | |||
1239 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL); | |||
1240 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL_LOW12A); | |||
1241 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL_HIGH12A); | |||
1242 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL_LOW12L); | |||
1243 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_TOKEN); | |||
1244 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECTION); | |||
1245 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ADDR64); | |||
1246 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_BRANCH19); | |||
1247 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_BRANCH14); | |||
1248 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_REL32); | |||
1249 | default: | |||
1250 | return "Unknown"; | |||
1251 | } | |||
1252 | break; | |||
1253 | case COFF::IMAGE_FILE_MACHINE_I386: | |||
1254 | switch (Type) { | |||
1255 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE); | |||
1256 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16); | |||
1257 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16); | |||
1258 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32); | |||
1259 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB); | |||
1260 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12); | |||
1261 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION); | |||
1262 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL); | |||
1263 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN); | |||
1264 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7); | |||
1265 | LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32); | |||
1266 | default: | |||
1267 | return "Unknown"; | |||
1268 | } | |||
1269 | break; | |||
1270 | default: | |||
1271 | return "Unknown"; | |||
1272 | } | |||
1273 | } | |||
1274 | ||||
1275 | #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME | |||
1276 | ||||
1277 | void COFFObjectFile::getRelocationTypeName( | |||
1278 | DataRefImpl Rel, SmallVectorImpl<char> &Result) const { | |||
1279 | const coff_relocation *Reloc = toRel(Rel); | |||
1280 | StringRef Res = getRelocationTypeName(Reloc->Type); | |||
1281 | Result.append(Res.begin(), Res.end()); | |||
1282 | } | |||
1283 | ||||
1284 | bool COFFObjectFile::isRelocatableObject() const { | |||
1285 | return !DataDirectory; | |||
1286 | } | |||
1287 | ||||
1288 | StringRef COFFObjectFile::mapDebugSectionName(StringRef Name) const { | |||
1289 | return StringSwitch<StringRef>(Name) | |||
1290 | .Case("eh_fram", "eh_frame") | |||
1291 | .Default(Name); | |||
1292 | } | |||
1293 | ||||
1294 | bool ImportDirectoryEntryRef:: | |||
1295 | operator==(const ImportDirectoryEntryRef &Other) const { | |||
1296 | return ImportTable == Other.ImportTable && Index == Other.Index; | |||
1297 | } | |||
1298 | ||||
1299 | void ImportDirectoryEntryRef::moveNext() { | |||
1300 | ++Index; | |||
1301 | if (ImportTable[Index].isNull()) { | |||
1302 | Index = -1; | |||
1303 | ImportTable = nullptr; | |||
1304 | } | |||
1305 | } | |||
1306 | ||||
1307 | std::error_code ImportDirectoryEntryRef::getImportTableEntry( | |||
1308 | const coff_import_directory_table_entry *&Result) const { | |||
1309 | return getObject(Result, OwningObject->Data, ImportTable + Index); | |||
1310 | } | |||
1311 | ||||
1312 | static imported_symbol_iterator | |||
1313 | makeImportedSymbolIterator(const COFFObjectFile *Object, | |||
1314 | uintptr_t Ptr, int Index) { | |||
1315 | if (Object->getBytesInAddress() == 4) { | |||
1316 | auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr); | |||
1317 | return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object)); | |||
1318 | } | |||
1319 | auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr); | |||
1320 | return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object)); | |||
1321 | } | |||
1322 | ||||
1323 | static imported_symbol_iterator | |||
1324 | importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) { | |||
1325 | uintptr_t IntPtr = 0; | |||
1326 | Object->getRvaPtr(RVA, IntPtr); | |||
1327 | return makeImportedSymbolIterator(Object, IntPtr, 0); | |||
1328 | } | |||
1329 | ||||
1330 | static imported_symbol_iterator | |||
1331 | importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) { | |||
1332 | uintptr_t IntPtr = 0; | |||
1333 | Object->getRvaPtr(RVA, IntPtr); | |||
1334 | // Forward the pointer to the last entry which is null. | |||
1335 | int Index = 0; | |||
1336 | if (Object->getBytesInAddress() == 4) { | |||
1337 | auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr); | |||
1338 | while (*Entry++) | |||
1339 | ++Index; | |||
1340 | } else { | |||
1341 | auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr); | |||
1342 | while (*Entry++) | |||
1343 | ++Index; | |||
1344 | } | |||
1345 | return makeImportedSymbolIterator(Object, IntPtr, Index); | |||
1346 | } | |||
1347 | ||||
1348 | imported_symbol_iterator | |||
1349 | ImportDirectoryEntryRef::imported_symbol_begin() const { | |||
1350 | return importedSymbolBegin(ImportTable[Index].ImportAddressTableRVA, | |||
1351 | OwningObject); | |||
1352 | } | |||
1353 | ||||
1354 | imported_symbol_iterator | |||
1355 | ImportDirectoryEntryRef::imported_symbol_end() const { | |||
1356 | return importedSymbolEnd(ImportTable[Index].ImportAddressTableRVA, | |||
1357 | OwningObject); | |||
1358 | } | |||
1359 | ||||
1360 | iterator_range<imported_symbol_iterator> | |||
1361 | ImportDirectoryEntryRef::imported_symbols() const { | |||
1362 | return make_range(imported_symbol_begin(), imported_symbol_end()); | |||
1363 | } | |||
1364 | ||||
1365 | imported_symbol_iterator ImportDirectoryEntryRef::lookup_table_begin() const { | |||
1366 | return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA, | |||
1367 | OwningObject); | |||
1368 | } | |||
1369 | ||||
1370 | imported_symbol_iterator ImportDirectoryEntryRef::lookup_table_end() const { | |||
1371 | return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA, | |||
1372 | OwningObject); | |||
1373 | } | |||
1374 | ||||
1375 | iterator_range<imported_symbol_iterator> | |||
1376 | ImportDirectoryEntryRef::lookup_table_symbols() const { | |||
1377 | return make_range(lookup_table_begin(), lookup_table_end()); | |||
1378 | } | |||
1379 | ||||
1380 | std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const { | |||
1381 | uintptr_t IntPtr = 0; | |||
1382 | if (std::error_code EC = | |||
1383 | OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr)) | |||
1384 | return EC; | |||
1385 | Result = StringRef(reinterpret_cast<const char *>(IntPtr)); | |||
1386 | return std::error_code(); | |||
1387 | } | |||
1388 | ||||
1389 | std::error_code | |||
1390 | ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t &Result) const { | |||
1391 | Result = ImportTable[Index].ImportLookupTableRVA; | |||
1392 | return std::error_code(); | |||
1393 | } | |||
1394 | ||||
1395 | std::error_code | |||
1396 | ImportDirectoryEntryRef::getImportAddressTableRVA(uint32_t &Result) const { | |||
1397 | Result = ImportTable[Index].ImportAddressTableRVA; | |||
1398 | return std::error_code(); | |||
1399 | } | |||
1400 | ||||
1401 | bool DelayImportDirectoryEntryRef:: | |||
1402 | operator==(const DelayImportDirectoryEntryRef &Other) const { | |||
1403 | return Table == Other.Table && Index == Other.Index; | |||
1404 | } | |||
1405 | ||||
1406 | void DelayImportDirectoryEntryRef::moveNext() { | |||
1407 | ++Index; | |||
1408 | } | |||
1409 | ||||
1410 | imported_symbol_iterator | |||
1411 | DelayImportDirectoryEntryRef::imported_symbol_begin() const { | |||
1412 | return importedSymbolBegin(Table[Index].DelayImportNameTable, | |||
1413 | OwningObject); | |||
1414 | } | |||
1415 | ||||
1416 | imported_symbol_iterator | |||
1417 | DelayImportDirectoryEntryRef::imported_symbol_end() const { | |||
1418 | return importedSymbolEnd(Table[Index].DelayImportNameTable, | |||
1419 | OwningObject); | |||
1420 | } | |||
1421 | ||||
1422 | iterator_range<imported_symbol_iterator> | |||
1423 | DelayImportDirectoryEntryRef::imported_symbols() const { | |||
1424 | return make_range(imported_symbol_begin(), imported_symbol_end()); | |||
1425 | } | |||
1426 | ||||
1427 | std::error_code DelayImportDirectoryEntryRef::getName(StringRef &Result) const { | |||
1428 | uintptr_t IntPtr = 0; | |||
1429 | if (std::error_code EC = OwningObject->getRvaPtr(Table[Index].Name, IntPtr)) | |||
1430 | return EC; | |||
1431 | Result = StringRef(reinterpret_cast<const char *>(IntPtr)); | |||
1432 | return std::error_code(); | |||
1433 | } | |||
1434 | ||||
1435 | std::error_code DelayImportDirectoryEntryRef:: | |||
1436 | getDelayImportTable(const delay_import_directory_table_entry *&Result) const { | |||
1437 | Result = &Table[Index]; | |||
1438 | return std::error_code(); | |||
1439 | } | |||
1440 | ||||
1441 | std::error_code DelayImportDirectoryEntryRef:: | |||
1442 | getImportAddress(int AddrIndex, uint64_t &Result) const { | |||
1443 | uint32_t RVA = Table[Index].DelayImportAddressTable + | |||
1444 | AddrIndex * (OwningObject->is64() ? 8 : 4); | |||
1445 | uintptr_t IntPtr = 0; | |||
1446 | if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr)) | |||
1447 | return EC; | |||
1448 | if (OwningObject->is64()) | |||
1449 | Result = *reinterpret_cast<const ulittle64_t *>(IntPtr); | |||
1450 | else | |||
1451 | Result = *reinterpret_cast<const ulittle32_t *>(IntPtr); | |||
1452 | return std::error_code(); | |||
1453 | } | |||
1454 | ||||
1455 | bool ExportDirectoryEntryRef:: | |||
1456 | operator==(const ExportDirectoryEntryRef &Other) const { | |||
1457 | return ExportTable == Other.ExportTable && Index == Other.Index; | |||
1458 | } | |||
1459 | ||||
1460 | void ExportDirectoryEntryRef::moveNext() { | |||
1461 | ++Index; | |||
1462 | } | |||
1463 | ||||
1464 | // Returns the name of the current export symbol. If the symbol is exported only | |||
1465 | // by ordinal, the empty string is set as a result. | |||
1466 | std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const { | |||
1467 | uintptr_t IntPtr = 0; | |||
1468 | if (std::error_code EC = | |||
1469 | OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr)) | |||
1470 | return EC; | |||
1471 | Result = StringRef(reinterpret_cast<const char *>(IntPtr)); | |||
1472 | return std::error_code(); | |||
1473 | } | |||
1474 | ||||
1475 | // Returns the starting ordinal number. | |||
1476 | std::error_code | |||
1477 | ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const { | |||
1478 | Result = ExportTable->OrdinalBase; | |||
1479 | return std::error_code(); | |||
1480 | } | |||
1481 | ||||
1482 | // Returns the export ordinal of the current export symbol. | |||
1483 | std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const { | |||
1484 | Result = ExportTable->OrdinalBase + Index; | |||
1485 | return std::error_code(); | |||
1486 | } | |||
1487 | ||||
1488 | // Returns the address of the current export symbol. | |||
1489 | std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const { | |||
1490 | uintptr_t IntPtr = 0; | |||
1491 | if (std::error_code EC = | |||
1492 | OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr)) | |||
1493 | return EC; | |||
1494 | const export_address_table_entry *entry = | |||
1495 | reinterpret_cast<const export_address_table_entry *>(IntPtr); | |||
1496 | Result = entry[Index].ExportRVA; | |||
1497 | return std::error_code(); | |||
1498 | } | |||
1499 | ||||
1500 | // Returns the name of the current export symbol. If the symbol is exported only | |||
1501 | // by ordinal, the empty string is set as a result. | |||
1502 | std::error_code | |||
1503 | ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const { | |||
1504 | uintptr_t IntPtr = 0; | |||
1505 | if (std::error_code EC = | |||
1506 | OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr)) | |||
1507 | return EC; | |||
1508 | const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr); | |||
1509 | ||||
1510 | uint32_t NumEntries = ExportTable->NumberOfNamePointers; | |||
1511 | int Offset = 0; | |||
1512 | for (const ulittle16_t *I = Start, *E = Start + NumEntries; | |||
1513 | I < E; ++I, ++Offset) { | |||
1514 | if (*I != Index) | |||
1515 | continue; | |||
1516 | if (std::error_code EC = | |||
1517 | OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr)) | |||
1518 | return EC; | |||
1519 | const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr); | |||
1520 | if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr)) | |||
1521 | return EC; | |||
1522 | Result = StringRef(reinterpret_cast<const char *>(IntPtr)); | |||
1523 | return std::error_code(); | |||
1524 | } | |||
1525 | Result = ""; | |||
1526 | return std::error_code(); | |||
1527 | } | |||
1528 | ||||
1529 | std::error_code ExportDirectoryEntryRef::isForwarder(bool &Result) const { | |||
1530 | const data_directory *DataEntry; | |||
1531 | if (auto EC = OwningObject->getDataDirectory(COFF::EXPORT_TABLE, DataEntry)) | |||
1532 | return EC; | |||
1533 | uint32_t RVA; | |||
1534 | if (auto EC = getExportRVA(RVA)) | |||
1535 | return EC; | |||
1536 | uint32_t Begin = DataEntry->RelativeVirtualAddress; | |||
1537 | uint32_t End = DataEntry->RelativeVirtualAddress + DataEntry->Size; | |||
1538 | Result = (Begin <= RVA && RVA < End); | |||
1539 | return std::error_code(); | |||
1540 | } | |||
1541 | ||||
1542 | std::error_code ExportDirectoryEntryRef::getForwardTo(StringRef &Result) const { | |||
1543 | uint32_t RVA; | |||
1544 | if (auto EC = getExportRVA(RVA)) | |||
1545 | return EC; | |||
1546 | uintptr_t IntPtr = 0; | |||
1547 | if (auto EC = OwningObject->getRvaPtr(RVA, IntPtr)) | |||
1548 | return EC; | |||
1549 | Result = StringRef(reinterpret_cast<const char *>(IntPtr)); | |||
1550 | return std::error_code(); | |||
1551 | } | |||
1552 | ||||
1553 | bool ImportedSymbolRef:: | |||
1554 | operator==(const ImportedSymbolRef &Other) const { | |||
1555 | return Entry32 == Other.Entry32 && Entry64 == Other.Entry64 | |||
1556 | && Index == Other.Index; | |||
1557 | } | |||
1558 | ||||
1559 | void ImportedSymbolRef::moveNext() { | |||
1560 | ++Index; | |||
1561 | } | |||
1562 | ||||
1563 | std::error_code | |||
1564 | ImportedSymbolRef::getSymbolName(StringRef &Result) const { | |||
1565 | uint32_t RVA; | |||
1566 | if (Entry32) { | |||
1567 | // If a symbol is imported only by ordinal, it has no name. | |||
1568 | if (Entry32[Index].isOrdinal()) | |||
1569 | return std::error_code(); | |||
1570 | RVA = Entry32[Index].getHintNameRVA(); | |||
1571 | } else { | |||
1572 | if (Entry64[Index].isOrdinal()) | |||
1573 | return std::error_code(); | |||
1574 | RVA = Entry64[Index].getHintNameRVA(); | |||
1575 | } | |||
1576 | uintptr_t IntPtr = 0; | |||
1577 | if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr)) | |||
1578 | return EC; | |||
1579 | // +2 because the first two bytes is hint. | |||
1580 | Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2)); | |||
1581 | return std::error_code(); | |||
1582 | } | |||
1583 | ||||
1584 | std::error_code ImportedSymbolRef::isOrdinal(bool &Result) const { | |||
1585 | if (Entry32) | |||
1586 | Result = Entry32[Index].isOrdinal(); | |||
1587 | else | |||
1588 | Result = Entry64[Index].isOrdinal(); | |||
1589 | return std::error_code(); | |||
1590 | } | |||
1591 | ||||
1592 | std::error_code ImportedSymbolRef::getHintNameRVA(uint32_t &Result) const { | |||
1593 | if (Entry32) | |||
1594 | Result = Entry32[Index].getHintNameRVA(); | |||
1595 | else | |||
1596 | Result = Entry64[Index].getHintNameRVA(); | |||
1597 | return std::error_code(); | |||
1598 | } | |||
1599 | ||||
1600 | std::error_code ImportedSymbolRef::getOrdinal(uint16_t &Result) const { | |||
1601 | uint32_t RVA; | |||
1602 | if (Entry32) { | |||
1603 | if (Entry32[Index].isOrdinal()) { | |||
1604 | Result = Entry32[Index].getOrdinal(); | |||
1605 | return std::error_code(); | |||
1606 | } | |||
1607 | RVA = Entry32[Index].getHintNameRVA(); | |||
1608 | } else { | |||
1609 | if (Entry64[Index].isOrdinal()) { | |||
1610 | Result = Entry64[Index].getOrdinal(); | |||
1611 | return std::error_code(); | |||
1612 | } | |||
1613 | RVA = Entry64[Index].getHintNameRVA(); | |||
1614 | } | |||
1615 | uintptr_t IntPtr = 0; | |||
1616 | if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr)) | |||
1617 | return EC; | |||
1618 | Result = *reinterpret_cast<const ulittle16_t *>(IntPtr); | |||
1619 | return std::error_code(); | |||
1620 | } | |||
1621 | ||||
1622 | Expected<std::unique_ptr<COFFObjectFile>> | |||
1623 | ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) { | |||
1624 | std::error_code EC; | |||
1625 | std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC)); | |||
1626 | if (EC) | |||
1627 | return errorCodeToError(EC); | |||
1628 | return std::move(Ret); | |||
1629 | } | |||
1630 | ||||
1631 | bool BaseRelocRef::operator==(const BaseRelocRef &Other) const { | |||
1632 | return Header == Other.Header && Index == Other.Index; | |||
1633 | } | |||
1634 | ||||
1635 | void BaseRelocRef::moveNext() { | |||
1636 | // Header->BlockSize is the size of the current block, including the | |||
1637 | // size of the header itself. | |||
1638 | uint32_t Size = sizeof(*Header) + | |||
1639 | sizeof(coff_base_reloc_block_entry) * (Index + 1); | |||
1640 | if (Size == Header->BlockSize) { | |||
1641 | // .reloc contains a list of base relocation blocks. Each block | |||
1642 | // consists of the header followed by entries. The header contains | |||
1643 | // how many entories will follow. When we reach the end of the | |||
1644 | // current block, proceed to the next block. | |||
1645 | Header = reinterpret_cast<const coff_base_reloc_block_header *>( | |||
1646 | reinterpret_cast<const uint8_t *>(Header) + Size); | |||
1647 | Index = 0; | |||
1648 | } else { | |||
1649 | ++Index; | |||
1650 | } | |||
1651 | } | |||
1652 | ||||
1653 | std::error_code BaseRelocRef::getType(uint8_t &Type) const { | |||
1654 | auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1); | |||
1655 | Type = Entry[Index].getType(); | |||
1656 | return std::error_code(); | |||
1657 | } | |||
1658 | ||||
1659 | std::error_code BaseRelocRef::getRVA(uint32_t &Result) const { | |||
1660 | auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1); | |||
1661 | Result = Header->PageRVA + Entry[Index].getOffset(); | |||
1662 | return std::error_code(); | |||
1663 | } | |||
1664 | ||||
1665 | #define RETURN_IF_ERROR(Expr)do { Error E = (Expr); if (E) return std::move(E); } while (0 ) \ | |||
1666 | do { \ | |||
1667 | Error E = (Expr); \ | |||
1668 | if (E) \ | |||
1669 | return std::move(E); \ | |||
1670 | } while (0) | |||
1671 | ||||
1672 | Expected<ArrayRef<UTF16>> | |||
1673 | ResourceSectionRef::getDirStringAtOffset(uint32_t Offset) { | |||
1674 | BinaryStreamReader Reader = BinaryStreamReader(BBS); | |||
1675 | Reader.setOffset(Offset); | |||
1676 | uint16_t Length; | |||
1677 | RETURN_IF_ERROR(Reader.readInteger(Length))do { Error E = (Reader.readInteger(Length)); if (E) return std ::move(E); } while (0); | |||
1678 | ArrayRef<UTF16> RawDirString; | |||
1679 | RETURN_IF_ERROR(Reader.readArray(RawDirString, Length))do { Error E = (Reader.readArray(RawDirString, Length)); if ( E) return std::move(E); } while (0); | |||
1680 | return RawDirString; | |||
1681 | } | |||
1682 | ||||
1683 | Expected<ArrayRef<UTF16>> | |||
1684 | ResourceSectionRef::getEntryNameString(const coff_resource_dir_entry &Entry) { | |||
1685 | return getDirStringAtOffset(Entry.Identifier.getNameOffset()); | |||
1686 | } | |||
1687 | ||||
1688 | Expected<const coff_resource_dir_table &> | |||
1689 | ResourceSectionRef::getTableAtOffset(uint32_t Offset) { | |||
1690 | const coff_resource_dir_table *Table = nullptr; | |||
1691 | ||||
1692 | BinaryStreamReader Reader(BBS); | |||
1693 | Reader.setOffset(Offset); | |||
1694 | RETURN_IF_ERROR(Reader.readObject(Table))do { Error E = (Reader.readObject(Table)); if (E) return std:: move(E); } while (0); | |||
1695 | assert(Table != nullptr)((Table != nullptr) ? static_cast<void> (0) : __assert_fail ("Table != nullptr", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Object/COFFObjectFile.cpp" , 1695, __PRETTY_FUNCTION__)); | |||
1696 | return *Table; | |||
1697 | } | |||
1698 | ||||
1699 | Expected<const coff_resource_dir_entry &> | |||
1700 | ResourceSectionRef::getTableEntryAtOffset(uint32_t Offset) { | |||
1701 | const coff_resource_dir_entry *Entry = nullptr; | |||
1702 | ||||
1703 | BinaryStreamReader Reader(BBS); | |||
1704 | Reader.setOffset(Offset); | |||
1705 | RETURN_IF_ERROR(Reader.readObject(Entry))do { Error E = (Reader.readObject(Entry)); if (E) return std:: move(E); } while (0); | |||
1706 | assert(Entry != nullptr)((Entry != nullptr) ? static_cast<void> (0) : __assert_fail ("Entry != nullptr", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Object/COFFObjectFile.cpp" , 1706, __PRETTY_FUNCTION__)); | |||
1707 | return *Entry; | |||
1708 | } | |||
1709 | ||||
1710 | Expected<const coff_resource_data_entry &> | |||
1711 | ResourceSectionRef::getDataEntryAtOffset(uint32_t Offset) { | |||
1712 | const coff_resource_data_entry *Entry = nullptr; | |||
1713 | ||||
1714 | BinaryStreamReader Reader(BBS); | |||
1715 | Reader.setOffset(Offset); | |||
1716 | RETURN_IF_ERROR(Reader.readObject(Entry))do { Error E = (Reader.readObject(Entry)); if (E) return std:: move(E); } while (0); | |||
1717 | assert(Entry != nullptr)((Entry != nullptr) ? static_cast<void> (0) : __assert_fail ("Entry != nullptr", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Object/COFFObjectFile.cpp" , 1717, __PRETTY_FUNCTION__)); | |||
1718 | return *Entry; | |||
1719 | } | |||
1720 | ||||
1721 | Expected<const coff_resource_dir_table &> | |||
1722 | ResourceSectionRef::getEntrySubDir(const coff_resource_dir_entry &Entry) { | |||
1723 | assert(Entry.Offset.isSubDir())((Entry.Offset.isSubDir()) ? static_cast<void> (0) : __assert_fail ("Entry.Offset.isSubDir()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Object/COFFObjectFile.cpp" , 1723, __PRETTY_FUNCTION__)); | |||
1724 | return getTableAtOffset(Entry.Offset.value()); | |||
1725 | } | |||
1726 | ||||
1727 | Expected<const coff_resource_data_entry &> | |||
1728 | ResourceSectionRef::getEntryData(const coff_resource_dir_entry &Entry) { | |||
1729 | assert(!Entry.Offset.isSubDir())((!Entry.Offset.isSubDir()) ? static_cast<void> (0) : __assert_fail ("!Entry.Offset.isSubDir()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Object/COFFObjectFile.cpp" , 1729, __PRETTY_FUNCTION__)); | |||
1730 | return getDataEntryAtOffset(Entry.Offset.value()); | |||
1731 | } | |||
1732 | ||||
1733 | Expected<const coff_resource_dir_table &> ResourceSectionRef::getBaseTable() { | |||
1734 | return getTableAtOffset(0); | |||
1735 | } | |||
1736 | ||||
1737 | Expected<const coff_resource_dir_entry &> | |||
1738 | ResourceSectionRef::getTableEntry(const coff_resource_dir_table &Table, | |||
1739 | uint32_t Index) { | |||
1740 | if (Index >= (uint32_t)(Table.NumberOfNameEntries + Table.NumberOfIDEntries)) | |||
1741 | return createStringError(object_error::parse_failed, "index out of range"); | |||
1742 | const uint8_t *TablePtr = reinterpret_cast<const uint8_t *>(&Table); | |||
1743 | ptrdiff_t TableOffset = TablePtr - BBS.data().data(); | |||
1744 | return getTableEntryAtOffset(TableOffset + sizeof(Table) + | |||
1745 | Index * sizeof(coff_resource_dir_entry)); | |||
1746 | } | |||
1747 | ||||
1748 | Error ResourceSectionRef::load(const COFFObjectFile *O) { | |||
1749 | for (const SectionRef &S : O->sections()) { | |||
1750 | Expected<StringRef> Name = S.getName(); | |||
1751 | if (!Name) | |||
1752 | return Name.takeError(); | |||
1753 | ||||
1754 | if (*Name == ".rsrc" || *Name == ".rsrc$01") | |||
1755 | return load(O, S); | |||
1756 | } | |||
1757 | return createStringError(object_error::parse_failed, | |||
1758 | "no resource section found"); | |||
1759 | } | |||
1760 | ||||
1761 | Error ResourceSectionRef::load(const COFFObjectFile *O, const SectionRef &S) { | |||
1762 | Obj = O; | |||
1763 | Section = S; | |||
1764 | Expected<StringRef> Contents = Section.getContents(); | |||
1765 | if (!Contents) | |||
1766 | return Contents.takeError(); | |||
1767 | BBS = BinaryByteStream(*Contents, support::little); | |||
1768 | const coff_section *COFFSect = Obj->getCOFFSection(Section); | |||
1769 | ArrayRef<coff_relocation> OrigRelocs = Obj->getRelocations(COFFSect); | |||
1770 | Relocs.reserve(OrigRelocs.size()); | |||
1771 | for (const coff_relocation &R : OrigRelocs) | |||
1772 | Relocs.push_back(&R); | |||
1773 | std::sort(Relocs.begin(), Relocs.end(), | |||
1774 | [](const coff_relocation *A, const coff_relocation *B) { | |||
1775 | return A->VirtualAddress < B->VirtualAddress; | |||
1776 | }); | |||
1777 | return Error::success(); | |||
1778 | } | |||
1779 | ||||
1780 | Expected<StringRef> | |||
1781 | ResourceSectionRef::getContents(const coff_resource_data_entry &Entry) { | |||
1782 | if (!Obj) | |||
| ||||
1783 | return createStringError(object_error::parse_failed, "no object provided"); | |||
1784 | ||||
1785 | // Find a potential relocation at the DataRVA field (first member of | |||
1786 | // the coff_resource_data_entry struct). | |||
1787 | const uint8_t *EntryPtr = reinterpret_cast<const uint8_t *>(&Entry); | |||
1788 | ptrdiff_t EntryOffset = EntryPtr - BBS.data().data(); | |||
1789 | coff_relocation RelocTarget{ulittle32_t(EntryOffset), ulittle32_t(0), | |||
1790 | ulittle16_t(0)}; | |||
1791 | auto RelocsForOffset = | |||
1792 | std::equal_range(Relocs.begin(), Relocs.end(), &RelocTarget, | |||
1793 | [](const coff_relocation *A, const coff_relocation *B) { | |||
1794 | return A->VirtualAddress < B->VirtualAddress; | |||
1795 | }); | |||
1796 | ||||
1797 | if (RelocsForOffset.first != RelocsForOffset.second) { | |||
1798 | // We found a relocation with the right offset. Check that it does have | |||
1799 | // the expected type. | |||
1800 | const coff_relocation &R = **RelocsForOffset.first; | |||
1801 | uint16_t RVAReloc; | |||
1802 | switch (Obj->getMachine()) { | |||
1803 | case COFF::IMAGE_FILE_MACHINE_I386: | |||
1804 | RVAReloc = COFF::IMAGE_REL_I386_DIR32NB; | |||
1805 | break; | |||
1806 | case COFF::IMAGE_FILE_MACHINE_AMD64: | |||
1807 | RVAReloc = COFF::IMAGE_REL_AMD64_ADDR32NB; | |||
1808 | break; | |||
1809 | case COFF::IMAGE_FILE_MACHINE_ARMNT: | |||
1810 | RVAReloc = COFF::IMAGE_REL_ARM_ADDR32NB; | |||
1811 | break; | |||
1812 | case COFF::IMAGE_FILE_MACHINE_ARM64: | |||
1813 | RVAReloc = COFF::IMAGE_REL_ARM64_ADDR32NB; | |||
1814 | break; | |||
1815 | default: | |||
1816 | return createStringError(object_error::parse_failed, | |||
1817 | "unsupported architecture"); | |||
1818 | } | |||
1819 | if (R.Type != RVAReloc) | |||
1820 | return createStringError(object_error::parse_failed, | |||
1821 | "unexpected relocation type"); | |||
1822 | // Get the relocation's symbol | |||
1823 | Expected<COFFSymbolRef> Sym = Obj->getSymbol(R.SymbolTableIndex); | |||
1824 | if (!Sym) | |||
1825 | return Sym.takeError(); | |||
1826 | const coff_section *Section = nullptr; | |||
1827 | // And the symbol's section | |||
1828 | if (std::error_code EC = Obj->getSection(Sym->getSectionNumber(), Section)) | |||
1829 | return errorCodeToError(EC); | |||
1830 | // Add the initial value of DataRVA to the symbol's offset to find the | |||
1831 | // data it points at. | |||
1832 | uint64_t Offset = Entry.DataRVA + Sym->getValue(); | |||
1833 | ArrayRef<uint8_t> Contents; | |||
1834 | if (Error E = Obj->getSectionContents(Section, Contents)) | |||
1835 | return std::move(E); | |||
1836 | if (Offset + Entry.DataSize > Contents.size()) | |||
1837 | return createStringError(object_error::parse_failed, | |||
1838 | "data outside of section"); | |||
1839 | // Return a reference to the data inside the section. | |||
1840 | return StringRef(reinterpret_cast<const char *>(Contents.data()) + Offset, | |||
1841 | Entry.DataSize); | |||
1842 | } else { | |||
1843 | // Relocatable objects need a relocation for the DataRVA field. | |||
1844 | if (Obj->isRelocatableObject()) | |||
1845 | return createStringError(object_error::parse_failed, | |||
1846 | "no relocation found for DataRVA"); | |||
1847 | ||||
1848 | // Locate the section that contains the address that DataRVA points at. | |||
1849 | uint64_t VA = Entry.DataRVA + Obj->getImageBase(); | |||
1850 | for (const SectionRef &S : Obj->sections()) { | |||
1851 | if (VA >= S.getAddress() && | |||
1852 | VA + Entry.DataSize <= S.getAddress() + S.getSize()) { | |||
1853 | uint64_t Offset = VA - S.getAddress(); | |||
1854 | Expected<StringRef> Contents = S.getContents(); | |||
1855 | if (!Contents) | |||
1856 | return Contents.takeError(); | |||
1857 | return Contents->slice(Offset, Offset + Entry.DataSize); | |||
1858 | } | |||
1859 | } | |||
1860 | return createStringError(object_error::parse_failed, | |||
1861 | "address not found in image"); | |||
1862 | } | |||
1863 | } |
1 | // Iterators -*- C++ -*- |
2 | |
3 | // Copyright (C) 2001-2016 Free Software Foundation, Inc. |
4 | // |
5 | // This file is part of the GNU ISO C++ Library. This library is free |
6 | // software; you can redistribute it and/or modify it under the |
7 | // terms of the GNU General Public License as published by the |
8 | // Free Software Foundation; either version 3, or (at your option) |
9 | // any later version. |
10 | |
11 | // This library is distributed in the hope that it will be useful, |
12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of |
13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
14 | // GNU General Public License for more details. |
15 | |
16 | // Under Section 7 of GPL version 3, you are granted additional |
17 | // permissions described in the GCC Runtime Library Exception, version |
18 | // 3.1, as published by the Free Software Foundation. |
19 | |
20 | // You should have received a copy of the GNU General Public License and |
21 | // a copy of the GCC Runtime Library Exception along with this program; |
22 | // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see |
23 | // <http://www.gnu.org/licenses/>. |
24 | |
25 | /* |
26 | * |
27 | * Copyright (c) 1994 |
28 | * Hewlett-Packard Company |
29 | * |
30 | * Permission to use, copy, modify, distribute and sell this software |
31 | * and its documentation for any purpose is hereby granted without fee, |
32 | * provided that the above copyright notice appear in all copies and |
33 | * that both that copyright notice and this permission notice appear |
34 | * in supporting documentation. Hewlett-Packard Company makes no |
35 | * representations about the suitability of this software for any |
36 | * purpose. It is provided "as is" without express or implied warranty. |
37 | * |
38 | * |
39 | * Copyright (c) 1996-1998 |
40 | * Silicon Graphics Computer Systems, Inc. |
41 | * |
42 | * Permission to use, copy, modify, distribute and sell this software |
43 | * and its documentation for any purpose is hereby granted without fee, |
44 | * provided that the above copyright notice appear in all copies and |
45 | * that both that copyright notice and this permission notice appear |
46 | * in supporting documentation. Silicon Graphics makes no |
47 | * representations about the suitability of this software for any |
48 | * purpose. It is provided "as is" without express or implied warranty. |
49 | */ |
50 | |
51 | /** @file bits/stl_iterator.h |
52 | * This is an internal header file, included by other library headers. |
53 | * Do not attempt to use it directly. @headername{iterator} |
54 | * |
55 | * This file implements reverse_iterator, back_insert_iterator, |
56 | * front_insert_iterator, insert_iterator, __normal_iterator, and their |
57 | * supporting functions and overloaded operators. |
58 | */ |
59 | |
60 | #ifndef _STL_ITERATOR_H1 |
61 | #define _STL_ITERATOR_H1 1 |
62 | |
63 | #include <bits/cpp_type_traits.h> |
64 | #include <ext/type_traits.h> |
65 | #include <bits/move.h> |
66 | #include <bits/ptr_traits.h> |
67 | |
68 | namespace std _GLIBCXX_VISIBILITY(default)__attribute__ ((__visibility__ ("default"))) |
69 | { |
70 | _GLIBCXX_BEGIN_NAMESPACE_VERSION |
71 | |
72 | /** |
73 | * @addtogroup iterators |
74 | * @{ |
75 | */ |
76 | |
77 | // 24.4.1 Reverse iterators |
78 | /** |
79 | * Bidirectional and random access iterators have corresponding reverse |
80 | * %iterator adaptors that iterate through the data structure in the |
81 | * opposite direction. They have the same signatures as the corresponding |
82 | * iterators. The fundamental relation between a reverse %iterator and its |
83 | * corresponding %iterator @c i is established by the identity: |
84 | * @code |
85 | * &*(reverse_iterator(i)) == &*(i - 1) |
86 | * @endcode |
87 | * |
88 | * <em>This mapping is dictated by the fact that while there is always a |
89 | * pointer past the end of an array, there might not be a valid pointer |
90 | * before the beginning of an array.</em> [24.4.1]/1,2 |
91 | * |
92 | * Reverse iterators can be tricky and surprising at first. Their |
93 | * semantics make sense, however, and the trickiness is a side effect of |
94 | * the requirement that the iterators must be safe. |
95 | */ |
96 | template<typename _Iterator> |
97 | class reverse_iterator |
98 | : public iterator<typename iterator_traits<_Iterator>::iterator_category, |
99 | typename iterator_traits<_Iterator>::value_type, |
100 | typename iterator_traits<_Iterator>::difference_type, |
101 | typename iterator_traits<_Iterator>::pointer, |
102 | typename iterator_traits<_Iterator>::reference> |
103 | { |
104 | protected: |
105 | _Iterator current; |
106 | |
107 | typedef iterator_traits<_Iterator> __traits_type; |
108 | |
109 | public: |
110 | typedef _Iterator iterator_type; |
111 | typedef typename __traits_type::difference_type difference_type; |
112 | typedef typename __traits_type::pointer pointer; |
113 | typedef typename __traits_type::reference reference; |
114 | |
115 | /** |
116 | * The default constructor value-initializes member @p current. |
117 | * If it is a pointer, that means it is zero-initialized. |
118 | */ |
119 | // _GLIBCXX_RESOLVE_LIB_DEFECTS |
120 | // 235 No specification of default ctor for reverse_iterator |
121 | reverse_iterator() : current() { } |
122 | |
123 | /** |
124 | * This %iterator will move in the opposite direction that @p x does. |
125 | */ |
126 | explicit |
127 | reverse_iterator(iterator_type __x) : current(__x) { } |
128 | |
129 | /** |
130 | * The copy constructor is normal. |
131 | */ |
132 | reverse_iterator(const reverse_iterator& __x) |
133 | : current(__x.current) { } |
134 | |
135 | /** |
136 | * A %reverse_iterator across other types can be copied if the |
137 | * underlying %iterator can be converted to the type of @c current. |
138 | */ |
139 | template<typename _Iter> |
140 | reverse_iterator(const reverse_iterator<_Iter>& __x) |
141 | : current(__x.base()) { } |
142 | |
143 | /** |
144 | * @return @c current, the %iterator used for underlying work. |
145 | */ |
146 | iterator_type |
147 | base() const |
148 | { return current; } |
149 | |
150 | /** |
151 | * @return A reference to the value at @c --current |
152 | * |
153 | * This requires that @c --current is dereferenceable. |
154 | * |
155 | * @warning This implementation requires that for an iterator of the |
156 | * underlying iterator type, @c x, a reference obtained by |
157 | * @c *x remains valid after @c x has been modified or |
158 | * destroyed. This is a bug: http://gcc.gnu.org/PR51823 |
159 | */ |
160 | reference |
161 | operator*() const |
162 | { |
163 | _Iterator __tmp = current; |
164 | return *--__tmp; |
165 | } |
166 | |
167 | /** |
168 | * @return A pointer to the value at @c --current |
169 | * |
170 | * This requires that @c --current is dereferenceable. |
171 | */ |
172 | pointer |
173 | operator->() const |
174 | { return &(operator*()); } |
175 | |
176 | /** |
177 | * @return @c *this |
178 | * |
179 | * Decrements the underlying iterator. |
180 | */ |
181 | reverse_iterator& |
182 | operator++() |
183 | { |
184 | --current; |
185 | return *this; |
186 | } |
187 | |
188 | /** |
189 | * @return The original value of @c *this |
190 | * |
191 | * Decrements the underlying iterator. |
192 | */ |
193 | reverse_iterator |
194 | operator++(int) |
195 | { |
196 | reverse_iterator __tmp = *this; |
197 | --current; |
198 | return __tmp; |
199 | } |
200 | |
201 | /** |
202 | * @return @c *this |
203 | * |
204 | * Increments the underlying iterator. |
205 | */ |
206 | reverse_iterator& |
207 | operator--() |
208 | { |
209 | ++current; |
210 | return *this; |
211 | } |
212 | |
213 | /** |
214 | * @return A reverse_iterator with the previous value of @c *this |
215 | * |
216 | * Increments the underlying iterator. |
217 | */ |
218 | reverse_iterator |
219 | operator--(int) |
220 | { |
221 | reverse_iterator __tmp = *this; |
222 | ++current; |
223 | return __tmp; |
224 | } |
225 | |
226 | /** |
227 | * @return A reverse_iterator that refers to @c current - @a __n |
228 | * |
229 | * The underlying iterator must be a Random Access Iterator. |
230 | */ |
231 | reverse_iterator |
232 | operator+(difference_type __n) const |
233 | { return reverse_iterator(current - __n); } |
234 | |
235 | /** |
236 | * @return *this |
237 | * |
238 | * Moves the underlying iterator backwards @a __n steps. |
239 | * The underlying iterator must be a Random Access Iterator. |
240 | */ |
241 | reverse_iterator& |
242 | operator+=(difference_type __n) |
243 | { |
244 | current -= __n; |
245 | return *this; |
246 | } |
247 | |
248 | /** |
249 | * @return A reverse_iterator that refers to @c current - @a __n |
250 | * |
251 | * The underlying iterator must be a Random Access Iterator. |
252 | */ |
253 | reverse_iterator |
254 | operator-(difference_type __n) const |
255 | { return reverse_iterator(current + __n); } |
256 | |
257 | /** |
258 | * @return *this |
259 | * |
260 | * Moves the underlying iterator forwards @a __n steps. |
261 | * The underlying iterator must be a Random Access Iterator. |
262 | */ |
263 | reverse_iterator& |
264 | operator-=(difference_type __n) |
265 | { |
266 | current += __n; |
267 | return *this; |
268 | } |
269 | |
270 | /** |
271 | * @return The value at @c current - @a __n - 1 |
272 | * |
273 | * The underlying iterator must be a Random Access Iterator. |
274 | */ |
275 | reference |
276 | operator[](difference_type __n) const |
277 | { return *(*this + __n); } |
278 | }; |
279 | |
280 | //@{ |
281 | /** |
282 | * @param __x A %reverse_iterator. |
283 | * @param __y A %reverse_iterator. |
284 | * @return A simple bool. |
285 | * |
286 | * Reverse iterators forward many operations to their underlying base() |
287 | * iterators. Others are implemented in terms of one another. |
288 | * |
289 | */ |
290 | template<typename _Iterator> |
291 | inline bool |
292 | operator==(const reverse_iterator<_Iterator>& __x, |
293 | const reverse_iterator<_Iterator>& __y) |
294 | { return __x.base() == __y.base(); } |
295 | |
296 | template<typename _Iterator> |
297 | inline bool |
298 | operator<(const reverse_iterator<_Iterator>& __x, |
299 | const reverse_iterator<_Iterator>& __y) |
300 | { return __y.base() < __x.base(); } |
301 | |
302 | template<typename _Iterator> |
303 | inline bool |
304 | operator!=(const reverse_iterator<_Iterator>& __x, |
305 | const reverse_iterator<_Iterator>& __y) |
306 | { return !(__x == __y); } |
307 | |
308 | template<typename _Iterator> |
309 | inline bool |
310 | operator>(const reverse_iterator<_Iterator>& __x, |
311 | const reverse_iterator<_Iterator>& __y) |
312 | { return __y < __x; } |
313 | |
314 | template<typename _Iterator> |
315 | inline bool |
316 | operator<=(const reverse_iterator<_Iterator>& __x, |
317 | const reverse_iterator<_Iterator>& __y) |
318 | { return !(__y < __x); } |
319 | |
320 | template<typename _Iterator> |
321 | inline bool |
322 | operator>=(const reverse_iterator<_Iterator>& __x, |
323 | const reverse_iterator<_Iterator>& __y) |
324 | { return !(__x < __y); } |
325 | |
326 | template<typename _Iterator> |
327 | #if __cplusplus201402L < 201103L |
328 | inline typename reverse_iterator<_Iterator>::difference_type |
329 | operator-(const reverse_iterator<_Iterator>& __x, |
330 | const reverse_iterator<_Iterator>& __y) |
331 | #else |
332 | inline auto |
333 | operator-(const reverse_iterator<_Iterator>& __x, |
334 | const reverse_iterator<_Iterator>& __y) |
335 | -> decltype(__x.base() - __y.base()) |
336 | #endif |
337 | { return __y.base() - __x.base(); } |
338 | |
339 | template<typename _Iterator> |
340 | inline reverse_iterator<_Iterator> |
341 | operator+(typename reverse_iterator<_Iterator>::difference_type __n, |
342 | const reverse_iterator<_Iterator>& __x) |
343 | { return reverse_iterator<_Iterator>(__x.base() - __n); } |
344 | |
345 | // _GLIBCXX_RESOLVE_LIB_DEFECTS |
346 | // DR 280. Comparison of reverse_iterator to const reverse_iterator. |
347 | template<typename _IteratorL, typename _IteratorR> |
348 | inline bool |
349 | operator==(const reverse_iterator<_IteratorL>& __x, |
350 | const reverse_iterator<_IteratorR>& __y) |
351 | { return __x.base() == __y.base(); } |
352 | |
353 | template<typename _IteratorL, typename _IteratorR> |
354 | inline bool |
355 | operator<(const reverse_iterator<_IteratorL>& __x, |
356 | const reverse_iterator<_IteratorR>& __y) |
357 | { return __y.base() < __x.base(); } |
358 | |
359 | template<typename _IteratorL, typename _IteratorR> |
360 | inline bool |
361 | operator!=(const reverse_iterator<_IteratorL>& __x, |
362 | const reverse_iterator<_IteratorR>& __y) |
363 | { return !(__x == __y); } |
364 | |
365 | template<typename _IteratorL, typename _IteratorR> |
366 | inline bool |
367 | operator>(const reverse_iterator<_IteratorL>& __x, |
368 | const reverse_iterator<_IteratorR>& __y) |
369 | { return __y < __x; } |
370 | |
371 | template<typename _IteratorL, typename _IteratorR> |
372 | inline bool |
373 | operator<=(const reverse_iterator<_IteratorL>& __x, |
374 | const reverse_iterator<_IteratorR>& __y) |
375 | { return !(__y < __x); } |
376 | |
377 | template<typename _IteratorL, typename _IteratorR> |
378 | inline bool |
379 | operator>=(const reverse_iterator<_IteratorL>& __x, |
380 | const reverse_iterator<_IteratorR>& __y) |
381 | { return !(__x < __y); } |
382 | |
383 | template<typename _IteratorL, typename _IteratorR> |
384 | #if __cplusplus201402L >= 201103L |
385 | // DR 685. |
386 | inline auto |
387 | operator-(const reverse_iterator<_IteratorL>& __x, |
388 | const reverse_iterator<_IteratorR>& __y) |
389 | -> decltype(__y.base() - __x.base()) |
390 | #else |
391 | inline typename reverse_iterator<_IteratorL>::difference_type |
392 | operator-(const reverse_iterator<_IteratorL>& __x, |
393 | const reverse_iterator<_IteratorR>& __y) |
394 | #endif |
395 | { return __y.base() - __x.base(); } |
396 | //@} |
397 | |
398 | #if __cplusplus201402L >= 201103L |
399 | // Same as C++14 make_reverse_iterator but used in C++03 mode too. |
400 | template<typename _Iterator> |
401 | inline reverse_iterator<_Iterator> |
402 | __make_reverse_iterator(_Iterator __i) |
403 | { return reverse_iterator<_Iterator>(__i); } |
404 | |
405 | # if __cplusplus201402L > 201103L |
406 | # define __cpp_lib_make_reverse_iterator201402 201402 |
407 | |
408 | // _GLIBCXX_RESOLVE_LIB_DEFECTS |
409 | // DR 2285. make_reverse_iterator |
410 | /// Generator function for reverse_iterator. |
411 | template<typename _Iterator> |
412 | inline reverse_iterator<_Iterator> |
413 | make_reverse_iterator(_Iterator __i) |
414 | { return reverse_iterator<_Iterator>(__i); } |
415 | # endif |
416 | #endif |
417 | |
418 | #if __cplusplus201402L >= 201103L |
419 | template<typename _Iterator> |
420 | auto |
421 | __niter_base(reverse_iterator<_Iterator> __it) |
422 | -> decltype(__make_reverse_iterator(__niter_base(__it.base()))) |
423 | { return __make_reverse_iterator(__niter_base(__it.base())); } |
424 | |
425 | template<typename _Iterator> |
426 | struct __is_move_iterator<reverse_iterator<_Iterator> > |
427 | : __is_move_iterator<_Iterator> |
428 | { }; |
429 | |
430 | template<typename _Iterator> |
431 | auto |
432 | __miter_base(reverse_iterator<_Iterator> __it) |
433 | -> decltype(__make_reverse_iterator(__miter_base(__it.base()))) |
434 | { return __make_reverse_iterator(__miter_base(__it.base())); } |
435 | #endif |
436 | |
437 | // 24.4.2.2.1 back_insert_iterator |
438 | /** |
439 | * @brief Turns assignment into insertion. |
440 | * |
441 | * These are output iterators, constructed from a container-of-T. |
442 | * Assigning a T to the iterator appends it to the container using |
443 | * push_back. |
444 | * |
445 | * Tip: Using the back_inserter function to create these iterators can |
446 | * save typing. |
447 | */ |
448 | template<typename _Container> |
449 | class back_insert_iterator |
450 | : public iterator<output_iterator_tag, void, void, void, void> |
451 | { |
452 | protected: |
453 | _Container* container; |
454 | |
455 | public: |
456 | /// A nested typedef for the type of whatever container you used. |
457 | typedef _Container container_type; |
458 | |
459 | /// The only way to create this %iterator is with a container. |
460 | explicit |
461 | back_insert_iterator(_Container& __x) |
462 | : container(std::__addressof(__x)) { } |
463 | |
464 | /** |
465 | * @param __value An instance of whatever type |
466 | * container_type::const_reference is; presumably a |
467 | * reference-to-const T for container<T>. |
468 | * @return This %iterator, for chained operations. |
469 | * |
470 | * This kind of %iterator doesn't really have a @a position in the |
471 | * container (you can think of the position as being permanently at |
472 | * the end, if you like). Assigning a value to the %iterator will |
473 | * always append the value to the end of the container. |
474 | */ |
475 | #if __cplusplus201402L < 201103L |
476 | back_insert_iterator& |
477 | operator=(typename _Container::const_reference __value) |
478 | { |
479 | container->push_back(__value); |
480 | return *this; |
481 | } |
482 | #else |
483 | back_insert_iterator& |
484 | operator=(const typename _Container::value_type& __value) |
485 | { |
486 | container->push_back(__value); |
487 | return *this; |
488 | } |
489 | |
490 | back_insert_iterator& |
491 | operator=(typename _Container::value_type&& __value) |
492 | { |
493 | container->push_back(std::move(__value)); |
494 | return *this; |
495 | } |
496 | #endif |
497 | |
498 | /// Simply returns *this. |
499 | back_insert_iterator& |
500 | operator*() |
501 | { return *this; } |
502 | |
503 | /// Simply returns *this. (This %iterator does not @a move.) |
504 | back_insert_iterator& |
505 | operator++() |
506 | { return *this; } |
507 | |
508 | /// Simply returns *this. (This %iterator does not @a move.) |
509 | back_insert_iterator |
510 | operator++(int) |
511 | { return *this; } |
512 | }; |
513 | |
514 | /** |
515 | * @param __x A container of arbitrary type. |
516 | * @return An instance of back_insert_iterator working on @p __x. |
517 | * |
518 | * This wrapper function helps in creating back_insert_iterator instances. |
519 | * Typing the name of the %iterator requires knowing the precise full |
520 | * type of the container, which can be tedious and impedes generic |
521 | * programming. Using this function lets you take advantage of automatic |
522 | * template parameter deduction, making the compiler match the correct |
523 | * types for you. |
524 | */ |
525 | template<typename _Container> |
526 | inline back_insert_iterator<_Container> |
527 | back_inserter(_Container& __x) |
528 | { return back_insert_iterator<_Container>(__x); } |
529 | |
530 | /** |
531 | * @brief Turns assignment into insertion. |
532 | * |
533 | * These are output iterators, constructed from a container-of-T. |
534 | * Assigning a T to the iterator prepends it to the container using |
535 | * push_front. |
536 | * |
537 | * Tip: Using the front_inserter function to create these iterators can |
538 | * save typing. |
539 | */ |
540 | template<typename _Container> |
541 | class front_insert_iterator |
542 | : public iterator<output_iterator_tag, void, void, void, void> |
543 | { |
544 | protected: |
545 | _Container* container; |
546 | |
547 | public: |
548 | /// A nested typedef for the type of whatever container you used. |
549 | typedef _Container container_type; |
550 | |
551 | /// The only way to create this %iterator is with a container. |
552 | explicit front_insert_iterator(_Container& __x) |
553 | : container(std::__addressof(__x)) { } |
554 | |
555 | /** |
556 | * @param __value An instance of whatever type |
557 | * container_type::const_reference is; presumably a |
558 | * reference-to-const T for container<T>. |
559 | * @return This %iterator, for chained operations. |
560 | * |
561 | * This kind of %iterator doesn't really have a @a position in the |
562 | * container (you can think of the position as being permanently at |
563 | * the front, if you like). Assigning a value to the %iterator will |
564 | * always prepend the value to the front of the container. |
565 | */ |
566 | #if __cplusplus201402L < 201103L |
567 | front_insert_iterator& |
568 | operator=(typename _Container::const_reference __value) |
569 | { |
570 | container->push_front(__value); |
571 | return *this; |
572 | } |
573 | #else |
574 | front_insert_iterator& |
575 | operator=(const typename _Container::value_type& __value) |
576 | { |
577 | container->push_front(__value); |
578 | return *this; |
579 | } |
580 | |
581 | front_insert_iterator& |
582 | operator=(typename _Container::value_type&& __value) |
583 | { |
584 | container->push_front(std::move(__value)); |
585 | return *this; |
586 | } |
587 | #endif |
588 | |
589 | /// Simply returns *this. |
590 | front_insert_iterator& |
591 | operator*() |
592 | { return *this; } |
593 | |
594 | /// Simply returns *this. (This %iterator does not @a move.) |
595 | front_insert_iterator& |
596 | operator++() |
597 | { return *this; } |
598 | |
599 | /// Simply returns *this. (This %iterator does not @a move.) |
600 | front_insert_iterator |
601 | operator++(int) |
602 | { return *this; } |
603 | }; |
604 | |
605 | /** |
606 | * @param __x A container of arbitrary type. |
607 | * @return An instance of front_insert_iterator working on @p x. |
608 | * |
609 | * This wrapper function helps in creating front_insert_iterator instances. |
610 | * Typing the name of the %iterator requires knowing the precise full |
611 | * type of the container, which can be tedious and impedes generic |
612 | * programming. Using this function lets you take advantage of automatic |
613 | * template parameter deduction, making the compiler match the correct |
614 | * types for you. |
615 | */ |
616 | template<typename _Container> |
617 | inline front_insert_iterator<_Container> |
618 | front_inserter(_Container& __x) |
619 | { return front_insert_iterator<_Container>(__x); } |
620 | |
621 | /** |
622 | * @brief Turns assignment into insertion. |
623 | * |
624 | * These are output iterators, constructed from a container-of-T. |
625 | * Assigning a T to the iterator inserts it in the container at the |
626 | * %iterator's position, rather than overwriting the value at that |
627 | * position. |
628 | * |
629 | * (Sequences will actually insert a @e copy of the value before the |
630 | * %iterator's position.) |
631 | * |
632 | * Tip: Using the inserter function to create these iterators can |
633 | * save typing. |
634 | */ |
635 | template<typename _Container> |
636 | class insert_iterator |
637 | : public iterator<output_iterator_tag, void, void, void, void> |
638 | { |
639 | protected: |
640 | _Container* container; |
641 | typename _Container::iterator iter; |
642 | |
643 | public: |
644 | /// A nested typedef for the type of whatever container you used. |
645 | typedef _Container container_type; |
646 | |
647 | /** |
648 | * The only way to create this %iterator is with a container and an |
649 | * initial position (a normal %iterator into the container). |
650 | */ |
651 | insert_iterator(_Container& __x, typename _Container::iterator __i) |
652 | : container(std::__addressof(__x)), iter(__i) {} |
653 | |
654 | /** |
655 | * @param __value An instance of whatever type |
656 | * container_type::const_reference is; presumably a |
657 | * reference-to-const T for container<T>. |
658 | * @return This %iterator, for chained operations. |
659 | * |
660 | * This kind of %iterator maintains its own position in the |
661 | * container. Assigning a value to the %iterator will insert the |
662 | * value into the container at the place before the %iterator. |
663 | * |
664 | * The position is maintained such that subsequent assignments will |
665 | * insert values immediately after one another. For example, |
666 | * @code |
667 | * // vector v contains A and Z |
668 | * |
669 | * insert_iterator i (v, ++v.begin()); |
670 | * i = 1; |
671 | * i = 2; |
672 | * i = 3; |
673 | * |
674 | * // vector v contains A, 1, 2, 3, and Z |
675 | * @endcode |
676 | */ |
677 | #if __cplusplus201402L < 201103L |
678 | insert_iterator& |
679 | operator=(typename _Container::const_reference __value) |
680 | { |
681 | iter = container->insert(iter, __value); |
682 | ++iter; |
683 | return *this; |
684 | } |
685 | #else |
686 | insert_iterator& |
687 | operator=(const typename _Container::value_type& __value) |
688 | { |
689 | iter = container->insert(iter, __value); |
690 | ++iter; |
691 | return *this; |
692 | } |
693 | |
694 | insert_iterator& |
695 | operator=(typename _Container::value_type&& __value) |
696 | { |
697 | iter = container->insert(iter, std::move(__value)); |
698 | ++iter; |
699 | return *this; |
700 | } |
701 | #endif |
702 | |
703 | /// Simply returns *this. |
704 | insert_iterator& |
705 | operator*() |
706 | { return *this; } |
707 | |
708 | /// Simply returns *this. (This %iterator does not @a move.) |
709 | insert_iterator& |
710 | operator++() |
711 | { return *this; } |
712 | |
713 | /// Simply returns *this. (This %iterator does not @a move.) |
714 | insert_iterator& |
715 | operator++(int) |
716 | { return *this; } |
717 | }; |
718 | |
719 | /** |
720 | * @param __x A container of arbitrary type. |
721 | * @return An instance of insert_iterator working on @p __x. |
722 | * |
723 | * This wrapper function helps in creating insert_iterator instances. |
724 | * Typing the name of the %iterator requires knowing the precise full |
725 | * type of the container, which can be tedious and impedes generic |
726 | * programming. Using this function lets you take advantage of automatic |
727 | * template parameter deduction, making the compiler match the correct |
728 | * types for you. |
729 | */ |
730 | template<typename _Container, typename _Iterator> |
731 | inline insert_iterator<_Container> |
732 | inserter(_Container& __x, _Iterator __i) |
733 | { |
734 | return insert_iterator<_Container>(__x, |
735 | typename _Container::iterator(__i)); |
736 | } |
737 | |
738 | // @} group iterators |
739 | |
740 | _GLIBCXX_END_NAMESPACE_VERSION |
741 | } // namespace |
742 | |
743 | namespace __gnu_cxx _GLIBCXX_VISIBILITY(default)__attribute__ ((__visibility__ ("default"))) |
744 | { |
745 | _GLIBCXX_BEGIN_NAMESPACE_VERSION |
746 | |
747 | // This iterator adapter is @a normal in the sense that it does not |
748 | // change the semantics of any of the operators of its iterator |
749 | // parameter. Its primary purpose is to convert an iterator that is |
750 | // not a class, e.g. a pointer, into an iterator that is a class. |
751 | // The _Container parameter exists solely so that different containers |
752 | // using this template can instantiate different types, even if the |
753 | // _Iterator parameter is the same. |
754 | using std::iterator_traits; |
755 | using std::iterator; |
756 | template<typename _Iterator, typename _Container> |
757 | class __normal_iterator |
758 | { |
759 | protected: |
760 | _Iterator _M_current; |
761 | |
762 | typedef iterator_traits<_Iterator> __traits_type; |
763 | |
764 | public: |
765 | typedef _Iterator iterator_type; |
766 | typedef typename __traits_type::iterator_category iterator_category; |
767 | typedef typename __traits_type::value_type value_type; |
768 | typedef typename __traits_type::difference_type difference_type; |
769 | typedef typename __traits_type::reference reference; |
770 | typedef typename __traits_type::pointer pointer; |
771 | |
772 | _GLIBCXX_CONSTEXPRconstexpr __normal_iterator() _GLIBCXX_NOEXCEPTnoexcept |
773 | : _M_current(_Iterator()) { } |
774 | |
775 | explicit |
776 | __normal_iterator(const _Iterator& __i) _GLIBCXX_NOEXCEPTnoexcept |
777 | : _M_current(__i) { } |
778 | |
779 | // Allow iterator to const_iterator conversion |
780 | template<typename _Iter> |
781 | __normal_iterator(const __normal_iterator<_Iter, |
782 | typename __enable_if< |
783 | (std::__are_same<_Iter, typename _Container::pointer>::__value), |
784 | _Container>::__type>& __i) _GLIBCXX_NOEXCEPTnoexcept |
785 | : _M_current(__i.base()) { } |
786 | |
787 | // Forward iterator requirements |
788 | reference |
789 | operator*() const _GLIBCXX_NOEXCEPTnoexcept |
790 | { return *_M_current; } |
791 | |
792 | pointer |
793 | operator->() const _GLIBCXX_NOEXCEPTnoexcept |
794 | { return _M_current; } |
795 | |
796 | __normal_iterator& |
797 | operator++() _GLIBCXX_NOEXCEPTnoexcept |
798 | { |
799 | ++_M_current; |
800 | return *this; |
801 | } |
802 | |
803 | __normal_iterator |
804 | operator++(int) _GLIBCXX_NOEXCEPTnoexcept |
805 | { return __normal_iterator(_M_current++); } |
806 | |
807 | // Bidirectional iterator requirements |
808 | __normal_iterator& |
809 | operator--() _GLIBCXX_NOEXCEPTnoexcept |
810 | { |
811 | --_M_current; |
812 | return *this; |
813 | } |
814 | |
815 | __normal_iterator |
816 | operator--(int) _GLIBCXX_NOEXCEPTnoexcept |
817 | { return __normal_iterator(_M_current--); } |
818 | |
819 | // Random access iterator requirements |
820 | reference |
821 | operator[](difference_type __n) const _GLIBCXX_NOEXCEPTnoexcept |
822 | { return _M_current[__n]; } |
823 | |
824 | __normal_iterator& |
825 | operator+=(difference_type __n) _GLIBCXX_NOEXCEPTnoexcept |
826 | { _M_current += __n; return *this; } |
827 | |
828 | __normal_iterator |
829 | operator+(difference_type __n) const _GLIBCXX_NOEXCEPTnoexcept |
830 | { return __normal_iterator(_M_current + __n); } |
831 | |
832 | __normal_iterator& |
833 | operator-=(difference_type __n) _GLIBCXX_NOEXCEPTnoexcept |
834 | { _M_current -= __n; return *this; } |
835 | |
836 | __normal_iterator |
837 | operator-(difference_type __n) const _GLIBCXX_NOEXCEPTnoexcept |
838 | { return __normal_iterator(_M_current - __n); } |
839 | |
840 | const _Iterator& |
841 | base() const _GLIBCXX_NOEXCEPTnoexcept |
842 | { return _M_current; } |
843 | }; |
844 | |
845 | // Note: In what follows, the left- and right-hand-side iterators are |
846 | // allowed to vary in types (conceptually in cv-qualification) so that |
847 | // comparison between cv-qualified and non-cv-qualified iterators be |
848 | // valid. However, the greedy and unfriendly operators in std::rel_ops |
849 | // will make overload resolution ambiguous (when in scope) if we don't |
850 | // provide overloads whose operands are of the same type. Can someone |
851 | // remind me what generic programming is about? -- Gaby |
852 | |
853 | // Forward iterator requirements |
854 | template<typename _IteratorL, typename _IteratorR, typename _Container> |
855 | inline bool |
856 | operator==(const __normal_iterator<_IteratorL, _Container>& __lhs, |
857 | const __normal_iterator<_IteratorR, _Container>& __rhs) |
858 | _GLIBCXX_NOEXCEPTnoexcept |
859 | { return __lhs.base() == __rhs.base(); } |
860 | |
861 | template<typename _Iterator, typename _Container> |
862 | inline bool |
863 | operator==(const __normal_iterator<_Iterator, _Container>& __lhs, |
864 | const __normal_iterator<_Iterator, _Container>& __rhs) |
865 | _GLIBCXX_NOEXCEPTnoexcept |
866 | { return __lhs.base() == __rhs.base(); } |
867 | |
868 | template<typename _IteratorL, typename _IteratorR, typename _Container> |
869 | inline bool |
870 | operator!=(const __normal_iterator<_IteratorL, _Container>& __lhs, |
871 | const __normal_iterator<_IteratorR, _Container>& __rhs) |
872 | _GLIBCXX_NOEXCEPTnoexcept |
873 | { return __lhs.base() != __rhs.base(); } |
874 | |
875 | template<typename _Iterator, typename _Container> |
876 | inline bool |
877 | operator!=(const __normal_iterator<_Iterator, _Container>& __lhs, |
878 | const __normal_iterator<_Iterator, _Container>& __rhs) |
879 | _GLIBCXX_NOEXCEPTnoexcept |
880 | { return __lhs.base() != __rhs.base(); } |
881 | |
882 | // Random access iterator requirements |
883 | template<typename _IteratorL, typename _IteratorR, typename _Container> |
884 | inline bool |
885 | operator<(const __normal_iterator<_IteratorL, _Container>& __lhs, |
886 | const __normal_iterator<_IteratorR, _Container>& __rhs) |
887 | _GLIBCXX_NOEXCEPTnoexcept |
888 | { return __lhs.base() < __rhs.base(); } |
889 | |
890 | template<typename _Iterator, typename _Container> |
891 | inline bool |
892 | operator<(const __normal_iterator<_Iterator, _Container>& __lhs, |
893 | const __normal_iterator<_Iterator, _Container>& __rhs) |
894 | _GLIBCXX_NOEXCEPTnoexcept |
895 | { return __lhs.base() < __rhs.base(); } |
896 | |
897 | template<typename _IteratorL, typename _IteratorR, typename _Container> |
898 | inline bool |
899 | operator>(const __normal_iterator<_IteratorL, _Container>& __lhs, |
900 | const __normal_iterator<_IteratorR, _Container>& __rhs) |
901 | _GLIBCXX_NOEXCEPTnoexcept |
902 | { return __lhs.base() > __rhs.base(); } |
903 | |
904 | template<typename _Iterator, typename _Container> |
905 | inline bool |
906 | operator>(const __normal_iterator<_Iterator, _Container>& __lhs, |
907 | const __normal_iterator<_Iterator, _Container>& __rhs) |
908 | _GLIBCXX_NOEXCEPTnoexcept |
909 | { return __lhs.base() > __rhs.base(); } |
910 | |
911 | template<typename _IteratorL, typename _IteratorR, typename _Container> |
912 | inline bool |
913 | operator<=(const __normal_iterator<_IteratorL, _Container>& __lhs, |
914 | const __normal_iterator<_IteratorR, _Container>& __rhs) |
915 | _GLIBCXX_NOEXCEPTnoexcept |
916 | { return __lhs.base() <= __rhs.base(); } |
917 | |
918 | template<typename _Iterator, typename _Container> |
919 | inline bool |
920 | operator<=(const __normal_iterator<_Iterator, _Container>& __lhs, |
921 | const __normal_iterator<_Iterator, _Container>& __rhs) |
922 | _GLIBCXX_NOEXCEPTnoexcept |
923 | { return __lhs.base() <= __rhs.base(); } |
924 | |
925 | template<typename _IteratorL, typename _IteratorR, typename _Container> |
926 | inline bool |
927 | operator>=(const __normal_iterator<_IteratorL, _Container>& __lhs, |
928 | const __normal_iterator<_IteratorR, _Container>& __rhs) |
929 | _GLIBCXX_NOEXCEPTnoexcept |
930 | { return __lhs.base() >= __rhs.base(); } |
931 | |
932 | template<typename _Iterator, typename _Container> |
933 | inline bool |
934 | operator>=(const __normal_iterator<_Iterator, _Container>& __lhs, |
935 | const __normal_iterator<_Iterator, _Container>& __rhs) |
936 | _GLIBCXX_NOEXCEPTnoexcept |
937 | { return __lhs.base() >= __rhs.base(); } |
938 | |
939 | // _GLIBCXX_RESOLVE_LIB_DEFECTS |
940 | // According to the resolution of DR179 not only the various comparison |
941 | // operators but also operator- must accept mixed iterator/const_iterator |
942 | // parameters. |
943 | template<typename _IteratorL, typename _IteratorR, typename _Container> |
944 | #if __cplusplus201402L >= 201103L |
945 | // DR 685. |
946 | inline auto |
947 | operator-(const __normal_iterator<_IteratorL, _Container>& __lhs, |
948 | const __normal_iterator<_IteratorR, _Container>& __rhs) noexcept |
949 | -> decltype(__lhs.base() - __rhs.base()) |
950 | #else |
951 | inline typename __normal_iterator<_IteratorL, _Container>::difference_type |
952 | operator-(const __normal_iterator<_IteratorL, _Container>& __lhs, |
953 | const __normal_iterator<_IteratorR, _Container>& __rhs) |
954 | #endif |
955 | { return __lhs.base() - __rhs.base(); } |
956 | |
957 | template<typename _Iterator, typename _Container> |
958 | inline typename __normal_iterator<_Iterator, _Container>::difference_type |
959 | operator-(const __normal_iterator<_Iterator, _Container>& __lhs, |
960 | const __normal_iterator<_Iterator, _Container>& __rhs) |
961 | _GLIBCXX_NOEXCEPTnoexcept |
962 | { return __lhs.base() - __rhs.base(); } |
963 | |
964 | template<typename _Iterator, typename _Container> |
965 | inline __normal_iterator<_Iterator, _Container> |
966 | operator+(typename __normal_iterator<_Iterator, _Container>::difference_type |
967 | __n, const __normal_iterator<_Iterator, _Container>& __i) |
968 | _GLIBCXX_NOEXCEPTnoexcept |
969 | { return __normal_iterator<_Iterator, _Container>(__i.base() + __n); } |
970 | |
971 | _GLIBCXX_END_NAMESPACE_VERSION |
972 | } // namespace |
973 | |
974 | namespace std _GLIBCXX_VISIBILITY(default)__attribute__ ((__visibility__ ("default"))) |
975 | { |
976 | _GLIBCXX_BEGIN_NAMESPACE_VERSION |
977 | |
978 | template<typename _Iterator, typename _Container> |
979 | _Iterator |
980 | __niter_base(__gnu_cxx::__normal_iterator<_Iterator, _Container> __it) |
981 | { return __it.base(); } |
982 | |
983 | _GLIBCXX_END_NAMESPACE_VERSION |
984 | } // namespace |
985 | |
986 | #if __cplusplus201402L >= 201103L |
987 | |
988 | namespace std _GLIBCXX_VISIBILITY(default)__attribute__ ((__visibility__ ("default"))) |
989 | { |
990 | _GLIBCXX_BEGIN_NAMESPACE_VERSION |
991 | |
992 | /** |
993 | * @addtogroup iterators |
994 | * @{ |
995 | */ |
996 | |
997 | // 24.4.3 Move iterators |
998 | /** |
999 | * Class template move_iterator is an iterator adapter with the same |
1000 | * behavior as the underlying iterator except that its dereference |
1001 | * operator implicitly converts the value returned by the underlying |
1002 | * iterator's dereference operator to an rvalue reference. Some |
1003 | * generic algorithms can be called with move iterators to replace |
1004 | * copying with moving. |
1005 | */ |
1006 | template<typename _Iterator> |
1007 | class move_iterator |
1008 | { |
1009 | protected: |
1010 | _Iterator _M_current; |
1011 | |
1012 | typedef iterator_traits<_Iterator> __traits_type; |
1013 | typedef typename __traits_type::reference __base_ref; |
1014 | |
1015 | public: |
1016 | typedef _Iterator iterator_type; |
1017 | typedef typename __traits_type::iterator_category iterator_category; |
1018 | typedef typename __traits_type::value_type value_type; |
1019 | typedef typename __traits_type::difference_type difference_type; |
1020 | // NB: DR 680. |
1021 | typedef _Iterator pointer; |
1022 | // _GLIBCXX_RESOLVE_LIB_DEFECTS |
1023 | // 2106. move_iterator wrapping iterators returning prvalues |
1024 | typedef typename conditional<is_reference<__base_ref>::value, |
1025 | typename remove_reference<__base_ref>::type&&, |
1026 | __base_ref>::type reference; |
1027 | |
1028 | move_iterator() |
1029 | : _M_current() { } |
1030 | |
1031 | explicit |
1032 | move_iterator(iterator_type __i) |
1033 | : _M_current(__i) { } |
1034 | |
1035 | template<typename _Iter> |
1036 | move_iterator(const move_iterator<_Iter>& __i) |
1037 | : _M_current(__i.base()) { } |
1038 | |
1039 | iterator_type |
1040 | base() const |
1041 | { return _M_current; } |
1042 | |
1043 | reference |
1044 | operator*() const |
1045 | { return static_cast<reference>(*_M_current); } |
1046 | |
1047 | pointer |
1048 | operator->() const |
1049 | { return _M_current; } |
1050 | |
1051 | move_iterator& |
1052 | operator++() |
1053 | { |
1054 | ++_M_current; |
1055 | return *this; |
1056 | } |
1057 | |
1058 | move_iterator |
1059 | operator++(int) |
1060 | { |
1061 | move_iterator __tmp = *this; |
1062 | ++_M_current; |
1063 | return __tmp; |
1064 | } |
1065 | |
1066 | move_iterator& |
1067 | operator--() |
1068 | { |
1069 | --_M_current; |
1070 | return *this; |
1071 | } |
1072 | |
1073 | move_iterator |
1074 | operator--(int) |
1075 | { |
1076 | move_iterator __tmp = *this; |
1077 | --_M_current; |
1078 | return __tmp; |
1079 | } |
1080 | |
1081 | move_iterator |
1082 | operator+(difference_type __n) const |
1083 | { return move_iterator(_M_current + __n); } |
1084 | |
1085 | move_iterator& |
1086 | operator+=(difference_type __n) |
1087 | { |
1088 | _M_current += __n; |
1089 | return *this; |
1090 | } |
1091 | |
1092 | move_iterator |
1093 | operator-(difference_type __n) const |
1094 | { return move_iterator(_M_current - __n); } |
1095 | |
1096 | move_iterator& |
1097 | operator-=(difference_type __n) |
1098 | { |
1099 | _M_current -= __n; |
1100 | return *this; |
1101 | } |
1102 | |
1103 | reference |
1104 | operator[](difference_type __n) const |
1105 | { return std::move(_M_current[__n]); } |
1106 | }; |
1107 | |
1108 | // Note: See __normal_iterator operators note from Gaby to understand |
1109 | // why there are always 2 versions for most of the move_iterator |
1110 | // operators. |
1111 | template<typename _IteratorL, typename _IteratorR> |
1112 | inline bool |
1113 | operator==(const move_iterator<_IteratorL>& __x, |
1114 | const move_iterator<_IteratorR>& __y) |
1115 | { return __x.base() == __y.base(); } |
1116 | |
1117 | template<typename _Iterator> |
1118 | inline bool |
1119 | operator==(const move_iterator<_Iterator>& __x, |
1120 | const move_iterator<_Iterator>& __y) |
1121 | { return __x.base() == __y.base(); } |
1122 | |
1123 | template<typename _IteratorL, typename _IteratorR> |
1124 | inline bool |
1125 | operator!=(const move_iterator<_IteratorL>& __x, |
1126 | const move_iterator<_IteratorR>& __y) |
1127 | { return !(__x == __y); } |
1128 | |
1129 | template<typename _Iterator> |
1130 | inline bool |
1131 | operator!=(const move_iterator<_Iterator>& __x, |
1132 | const move_iterator<_Iterator>& __y) |
1133 | { return !(__x == __y); } |
1134 | |
1135 | template<typename _IteratorL, typename _IteratorR> |
1136 | inline bool |
1137 | operator<(const move_iterator<_IteratorL>& __x, |
1138 | const move_iterator<_IteratorR>& __y) |
1139 | { return __x.base() < __y.base(); } |
1140 | |
1141 | template<typename _Iterator> |
1142 | inline bool |
1143 | operator<(const move_iterator<_Iterator>& __x, |
1144 | const move_iterator<_Iterator>& __y) |
1145 | { return __x.base() < __y.base(); } |
1146 | |
1147 | template<typename _IteratorL, typename _IteratorR> |
1148 | inline bool |
1149 | operator<=(const move_iterator<_IteratorL>& __x, |
1150 | const move_iterator<_IteratorR>& __y) |
1151 | { return !(__y < __x); } |
1152 | |
1153 | template<typename _Iterator> |
1154 | inline bool |
1155 | operator<=(const move_iterator<_Iterator>& __x, |
1156 | const move_iterator<_Iterator>& __y) |
1157 | { return !(__y < __x); } |
1158 | |
1159 | template<typename _IteratorL, typename _IteratorR> |
1160 | inline bool |
1161 | operator>(const move_iterator<_IteratorL>& __x, |
1162 | const move_iterator<_IteratorR>& __y) |
1163 | { return __y < __x; } |
1164 | |
1165 | template<typename _Iterator> |
1166 | inline bool |
1167 | operator>(const move_iterator<_Iterator>& __x, |
1168 | const move_iterator<_Iterator>& __y) |
1169 | { return __y < __x; } |
1170 | |
1171 | template<typename _IteratorL, typename _IteratorR> |
1172 | inline bool |
1173 | operator>=(const move_iterator<_IteratorL>& __x, |
1174 | const move_iterator<_IteratorR>& __y) |
1175 | { return !(__x < __y); } |
1176 | |
1177 | template<typename _Iterator> |
1178 | inline bool |
1179 | operator>=(const move_iterator<_Iterator>& __x, |
1180 | const move_iterator<_Iterator>& __y) |
1181 | { return !(__x < __y); } |
1182 | |
1183 | // DR 685. |
1184 | template<typename _IteratorL, typename _IteratorR> |
1185 | inline auto |
1186 | operator-(const move_iterator<_IteratorL>& __x, |
1187 | const move_iterator<_IteratorR>& __y) |
1188 | -> decltype(__x.base() - __y.base()) |
1189 | { return __x.base() - __y.base(); } |
1190 | |
1191 | template<typename _Iterator> |
1192 | inline auto |
1193 | operator-(const move_iterator<_Iterator>& __x, |
1194 | const move_iterator<_Iterator>& __y) |
1195 | -> decltype(__x.base() - __y.base()) |
1196 | { return __x.base() - __y.base(); } |
1197 | |
1198 | template<typename _Iterator> |
1199 | inline move_iterator<_Iterator> |
1200 | operator+(typename move_iterator<_Iterator>::difference_type __n, |
1201 | const move_iterator<_Iterator>& __x) |
1202 | { return __x + __n; } |
1203 | |
1204 | template<typename _Iterator> |
1205 | inline move_iterator<_Iterator> |
1206 | make_move_iterator(_Iterator __i) |
1207 | { return move_iterator<_Iterator>(__i); } |
1208 | |
1209 | template<typename _Iterator, typename _ReturnType |
1210 | = typename conditional<__move_if_noexcept_cond |
1211 | <typename iterator_traits<_Iterator>::value_type>::value, |
1212 | _Iterator, move_iterator<_Iterator>>::type> |
1213 | inline _ReturnType |
1214 | __make_move_if_noexcept_iterator(_Iterator __i) |
1215 | { return _ReturnType(__i); } |
1216 | |
1217 | // Overload for pointers that matches std::move_if_noexcept more closely, |
1218 | // returning a constant iterator when we don't want to move. |
1219 | template<typename _Tp, typename _ReturnType |
1220 | = typename conditional<__move_if_noexcept_cond<_Tp>::value, |
1221 | const _Tp*, move_iterator<_Tp*>>::type> |
1222 | inline _ReturnType |
1223 | __make_move_if_noexcept_iterator(_Tp* __i) |
1224 | { return _ReturnType(__i); } |
1225 | |
1226 | // @} group iterators |
1227 | |
1228 | template<typename _Iterator> |
1229 | auto |
1230 | __niter_base(move_iterator<_Iterator> __it) |
1231 | -> decltype(make_move_iterator(__niter_base(__it.base()))) |
1232 | { return make_move_iterator(__niter_base(__it.base())); } |
1233 | |
1234 | template<typename _Iterator> |
1235 | struct __is_move_iterator<move_iterator<_Iterator> > |
1236 | { |
1237 | enum { __value = 1 }; |
1238 | typedef __true_type __type; |
1239 | }; |
1240 | |
1241 | template<typename _Iterator> |
1242 | auto |
1243 | __miter_base(move_iterator<_Iterator> __it) |
1244 | -> decltype(__miter_base(__it.base())) |
1245 | { return __miter_base(__it.base()); } |
1246 | |
1247 | _GLIBCXX_END_NAMESPACE_VERSION |
1248 | } // namespace |
1249 | |
1250 | #define _GLIBCXX_MAKE_MOVE_ITERATOR(_Iter)std::make_move_iterator(_Iter) std::make_move_iterator(_Iter) |
1251 | #define _GLIBCXX_MAKE_MOVE_IF_NOEXCEPT_ITERATOR(_Iter)std::__make_move_if_noexcept_iterator(_Iter) \ |
1252 | std::__make_move_if_noexcept_iterator(_Iter) |
1253 | #else |
1254 | #define _GLIBCXX_MAKE_MOVE_ITERATOR(_Iter)std::make_move_iterator(_Iter) (_Iter) |
1255 | #define _GLIBCXX_MAKE_MOVE_IF_NOEXCEPT_ITERATOR(_Iter)std::__make_move_if_noexcept_iterator(_Iter) (_Iter) |
1256 | #endif // C++11 |
1257 | |
1258 | #ifdef _GLIBCXX_DEBUG |
1259 | # include <debug/stl_iterator.h> |
1260 | #endif |
1261 | |
1262 | #endif |
1 | //===- COFF.h - COFF object file implementation -----------------*- C++ -*-===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // |
9 | // This file declares the COFFObjectFile class. |
10 | // |
11 | //===----------------------------------------------------------------------===// |
12 | |
13 | #ifndef LLVM_OBJECT_COFF_H |
14 | #define LLVM_OBJECT_COFF_H |
15 | |
16 | #include "llvm/ADT/iterator_range.h" |
17 | #include "llvm/BinaryFormat/COFF.h" |
18 | #include "llvm/MC/SubtargetFeature.h" |
19 | #include "llvm/Object/Binary.h" |
20 | #include "llvm/Object/CVDebugRecord.h" |
21 | #include "llvm/Object/Error.h" |
22 | #include "llvm/Object/ObjectFile.h" |
23 | #include "llvm/Support/BinaryByteStream.h" |
24 | #include "llvm/Support/ConvertUTF.h" |
25 | #include "llvm/Support/Endian.h" |
26 | #include "llvm/Support/ErrorHandling.h" |
27 | #include <cassert> |
28 | #include <cstddef> |
29 | #include <cstdint> |
30 | #include <system_error> |
31 | |
32 | namespace llvm { |
33 | |
34 | template <typename T> class ArrayRef; |
35 | |
36 | namespace object { |
37 | |
38 | class BaseRelocRef; |
39 | class DelayImportDirectoryEntryRef; |
40 | class ExportDirectoryEntryRef; |
41 | class ImportDirectoryEntryRef; |
42 | class ImportedSymbolRef; |
43 | class ResourceSectionRef; |
44 | |
45 | using import_directory_iterator = content_iterator<ImportDirectoryEntryRef>; |
46 | using delay_import_directory_iterator = |
47 | content_iterator<DelayImportDirectoryEntryRef>; |
48 | using export_directory_iterator = content_iterator<ExportDirectoryEntryRef>; |
49 | using imported_symbol_iterator = content_iterator<ImportedSymbolRef>; |
50 | using base_reloc_iterator = content_iterator<BaseRelocRef>; |
51 | |
52 | /// The DOS compatible header at the front of all PE/COFF executables. |
53 | struct dos_header { |
54 | char Magic[2]; |
55 | support::ulittle16_t UsedBytesInTheLastPage; |
56 | support::ulittle16_t FileSizeInPages; |
57 | support::ulittle16_t NumberOfRelocationItems; |
58 | support::ulittle16_t HeaderSizeInParagraphs; |
59 | support::ulittle16_t MinimumExtraParagraphs; |
60 | support::ulittle16_t MaximumExtraParagraphs; |
61 | support::ulittle16_t InitialRelativeSS; |
62 | support::ulittle16_t InitialSP; |
63 | support::ulittle16_t Checksum; |
64 | support::ulittle16_t InitialIP; |
65 | support::ulittle16_t InitialRelativeCS; |
66 | support::ulittle16_t AddressOfRelocationTable; |
67 | support::ulittle16_t OverlayNumber; |
68 | support::ulittle16_t Reserved[4]; |
69 | support::ulittle16_t OEMid; |
70 | support::ulittle16_t OEMinfo; |
71 | support::ulittle16_t Reserved2[10]; |
72 | support::ulittle32_t AddressOfNewExeHeader; |
73 | }; |
74 | |
75 | struct coff_file_header { |
76 | support::ulittle16_t Machine; |
77 | support::ulittle16_t NumberOfSections; |
78 | support::ulittle32_t TimeDateStamp; |
79 | support::ulittle32_t PointerToSymbolTable; |
80 | support::ulittle32_t NumberOfSymbols; |
81 | support::ulittle16_t SizeOfOptionalHeader; |
82 | support::ulittle16_t Characteristics; |
83 | |
84 | bool isImportLibrary() const { return NumberOfSections == 0xffff; } |
85 | }; |
86 | |
87 | struct coff_bigobj_file_header { |
88 | support::ulittle16_t Sig1; |
89 | support::ulittle16_t Sig2; |
90 | support::ulittle16_t Version; |
91 | support::ulittle16_t Machine; |
92 | support::ulittle32_t TimeDateStamp; |
93 | uint8_t UUID[16]; |
94 | support::ulittle32_t unused1; |
95 | support::ulittle32_t unused2; |
96 | support::ulittle32_t unused3; |
97 | support::ulittle32_t unused4; |
98 | support::ulittle32_t NumberOfSections; |
99 | support::ulittle32_t PointerToSymbolTable; |
100 | support::ulittle32_t NumberOfSymbols; |
101 | }; |
102 | |
103 | /// The 32-bit PE header that follows the COFF header. |
104 | struct pe32_header { |
105 | support::ulittle16_t Magic; |
106 | uint8_t MajorLinkerVersion; |
107 | uint8_t MinorLinkerVersion; |
108 | support::ulittle32_t SizeOfCode; |
109 | support::ulittle32_t SizeOfInitializedData; |
110 | support::ulittle32_t SizeOfUninitializedData; |
111 | support::ulittle32_t AddressOfEntryPoint; |
112 | support::ulittle32_t BaseOfCode; |
113 | support::ulittle32_t BaseOfData; |
114 | support::ulittle32_t ImageBase; |
115 | support::ulittle32_t SectionAlignment; |
116 | support::ulittle32_t FileAlignment; |
117 | support::ulittle16_t MajorOperatingSystemVersion; |
118 | support::ulittle16_t MinorOperatingSystemVersion; |
119 | support::ulittle16_t MajorImageVersion; |
120 | support::ulittle16_t MinorImageVersion; |
121 | support::ulittle16_t MajorSubsystemVersion; |
122 | support::ulittle16_t MinorSubsystemVersion; |
123 | support::ulittle32_t Win32VersionValue; |
124 | support::ulittle32_t SizeOfImage; |
125 | support::ulittle32_t SizeOfHeaders; |
126 | support::ulittle32_t CheckSum; |
127 | support::ulittle16_t Subsystem; |
128 | // FIXME: This should be DllCharacteristics. |
129 | support::ulittle16_t DLLCharacteristics; |
130 | support::ulittle32_t SizeOfStackReserve; |
131 | support::ulittle32_t SizeOfStackCommit; |
132 | support::ulittle32_t SizeOfHeapReserve; |
133 | support::ulittle32_t SizeOfHeapCommit; |
134 | support::ulittle32_t LoaderFlags; |
135 | // FIXME: This should be NumberOfRvaAndSizes. |
136 | support::ulittle32_t NumberOfRvaAndSize; |
137 | }; |
138 | |
139 | /// The 64-bit PE header that follows the COFF header. |
140 | struct pe32plus_header { |
141 | support::ulittle16_t Magic; |
142 | uint8_t MajorLinkerVersion; |
143 | uint8_t MinorLinkerVersion; |
144 | support::ulittle32_t SizeOfCode; |
145 | support::ulittle32_t SizeOfInitializedData; |
146 | support::ulittle32_t SizeOfUninitializedData; |
147 | support::ulittle32_t AddressOfEntryPoint; |
148 | support::ulittle32_t BaseOfCode; |
149 | support::ulittle64_t ImageBase; |
150 | support::ulittle32_t SectionAlignment; |
151 | support::ulittle32_t FileAlignment; |
152 | support::ulittle16_t MajorOperatingSystemVersion; |
153 | support::ulittle16_t MinorOperatingSystemVersion; |
154 | support::ulittle16_t MajorImageVersion; |
155 | support::ulittle16_t MinorImageVersion; |
156 | support::ulittle16_t MajorSubsystemVersion; |
157 | support::ulittle16_t MinorSubsystemVersion; |
158 | support::ulittle32_t Win32VersionValue; |
159 | support::ulittle32_t SizeOfImage; |
160 | support::ulittle32_t SizeOfHeaders; |
161 | support::ulittle32_t CheckSum; |
162 | support::ulittle16_t Subsystem; |
163 | support::ulittle16_t DLLCharacteristics; |
164 | support::ulittle64_t SizeOfStackReserve; |
165 | support::ulittle64_t SizeOfStackCommit; |
166 | support::ulittle64_t SizeOfHeapReserve; |
167 | support::ulittle64_t SizeOfHeapCommit; |
168 | support::ulittle32_t LoaderFlags; |
169 | support::ulittle32_t NumberOfRvaAndSize; |
170 | }; |
171 | |
172 | struct data_directory { |
173 | support::ulittle32_t RelativeVirtualAddress; |
174 | support::ulittle32_t Size; |
175 | }; |
176 | |
177 | struct debug_directory { |
178 | support::ulittle32_t Characteristics; |
179 | support::ulittle32_t TimeDateStamp; |
180 | support::ulittle16_t MajorVersion; |
181 | support::ulittle16_t MinorVersion; |
182 | support::ulittle32_t Type; |
183 | support::ulittle32_t SizeOfData; |
184 | support::ulittle32_t AddressOfRawData; |
185 | support::ulittle32_t PointerToRawData; |
186 | }; |
187 | |
188 | template <typename IntTy> |
189 | struct import_lookup_table_entry { |
190 | IntTy Data; |
191 | |
192 | bool isOrdinal() const { return Data < 0; } |
193 | |
194 | uint16_t getOrdinal() const { |
195 | assert(isOrdinal() && "ILT entry is not an ordinal!")((isOrdinal() && "ILT entry is not an ordinal!") ? static_cast <void> (0) : __assert_fail ("isOrdinal() && \"ILT entry is not an ordinal!\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Object/COFF.h" , 195, __PRETTY_FUNCTION__)); |
196 | return Data & 0xFFFF; |
197 | } |
198 | |
199 | uint32_t getHintNameRVA() const { |
200 | assert(!isOrdinal() && "ILT entry is not a Hint/Name RVA!")((!isOrdinal() && "ILT entry is not a Hint/Name RVA!" ) ? static_cast<void> (0) : __assert_fail ("!isOrdinal() && \"ILT entry is not a Hint/Name RVA!\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Object/COFF.h" , 200, __PRETTY_FUNCTION__)); |
201 | return Data & 0xFFFFFFFF; |
202 | } |
203 | }; |
204 | |
205 | using import_lookup_table_entry32 = |
206 | import_lookup_table_entry<support::little32_t>; |
207 | using import_lookup_table_entry64 = |
208 | import_lookup_table_entry<support::little64_t>; |
209 | |
210 | struct delay_import_directory_table_entry { |
211 | // dumpbin reports this field as "Characteristics" instead of "Attributes". |
212 | support::ulittle32_t Attributes; |
213 | support::ulittle32_t Name; |
214 | support::ulittle32_t ModuleHandle; |
215 | support::ulittle32_t DelayImportAddressTable; |
216 | support::ulittle32_t DelayImportNameTable; |
217 | support::ulittle32_t BoundDelayImportTable; |
218 | support::ulittle32_t UnloadDelayImportTable; |
219 | support::ulittle32_t TimeStamp; |
220 | }; |
221 | |
222 | struct export_directory_table_entry { |
223 | support::ulittle32_t ExportFlags; |
224 | support::ulittle32_t TimeDateStamp; |
225 | support::ulittle16_t MajorVersion; |
226 | support::ulittle16_t MinorVersion; |
227 | support::ulittle32_t NameRVA; |
228 | support::ulittle32_t OrdinalBase; |
229 | support::ulittle32_t AddressTableEntries; |
230 | support::ulittle32_t NumberOfNamePointers; |
231 | support::ulittle32_t ExportAddressTableRVA; |
232 | support::ulittle32_t NamePointerRVA; |
233 | support::ulittle32_t OrdinalTableRVA; |
234 | }; |
235 | |
236 | union export_address_table_entry { |
237 | support::ulittle32_t ExportRVA; |
238 | support::ulittle32_t ForwarderRVA; |
239 | }; |
240 | |
241 | using export_name_pointer_table_entry = support::ulittle32_t; |
242 | using export_ordinal_table_entry = support::ulittle16_t; |
243 | |
244 | struct StringTableOffset { |
245 | support::ulittle32_t Zeroes; |
246 | support::ulittle32_t Offset; |
247 | }; |
248 | |
249 | template <typename SectionNumberType> |
250 | struct coff_symbol { |
251 | union { |
252 | char ShortName[COFF::NameSize]; |
253 | StringTableOffset Offset; |
254 | } Name; |
255 | |
256 | support::ulittle32_t Value; |
257 | SectionNumberType SectionNumber; |
258 | |
259 | support::ulittle16_t Type; |
260 | |
261 | uint8_t StorageClass; |
262 | uint8_t NumberOfAuxSymbols; |
263 | }; |
264 | |
265 | using coff_symbol16 = coff_symbol<support::ulittle16_t>; |
266 | using coff_symbol32 = coff_symbol<support::ulittle32_t>; |
267 | |
268 | // Contains only common parts of coff_symbol16 and coff_symbol32. |
269 | struct coff_symbol_generic { |
270 | union { |
271 | char ShortName[COFF::NameSize]; |
272 | StringTableOffset Offset; |
273 | } Name; |
274 | support::ulittle32_t Value; |
275 | }; |
276 | |
277 | struct coff_aux_section_definition; |
278 | struct coff_aux_weak_external; |
279 | |
280 | class COFFSymbolRef { |
281 | public: |
282 | COFFSymbolRef() = default; |
283 | COFFSymbolRef(const coff_symbol16 *CS) : CS16(CS) {} |
284 | COFFSymbolRef(const coff_symbol32 *CS) : CS32(CS) {} |
285 | |
286 | const void *getRawPtr() const { |
287 | return CS16 ? static_cast<const void *>(CS16) : CS32; |
288 | } |
289 | |
290 | const coff_symbol_generic *getGeneric() const { |
291 | if (CS16) |
292 | return reinterpret_cast<const coff_symbol_generic *>(CS16); |
293 | return reinterpret_cast<const coff_symbol_generic *>(CS32); |
294 | } |
295 | |
296 | friend bool operator<(COFFSymbolRef A, COFFSymbolRef B) { |
297 | return A.getRawPtr() < B.getRawPtr(); |
298 | } |
299 | |
300 | bool isBigObj() const { |
301 | if (CS16) |
302 | return false; |
303 | if (CS32) |
304 | return true; |
305 | llvm_unreachable("COFFSymbolRef points to nothing!")::llvm::llvm_unreachable_internal("COFFSymbolRef points to nothing!" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Object/COFF.h" , 305); |
306 | } |
307 | |
308 | const char *getShortName() const { |
309 | return CS16 ? CS16->Name.ShortName : CS32->Name.ShortName; |
310 | } |
311 | |
312 | const StringTableOffset &getStringTableOffset() const { |
313 | assert(isSet() && "COFFSymbolRef points to nothing!")((isSet() && "COFFSymbolRef points to nothing!") ? static_cast <void> (0) : __assert_fail ("isSet() && \"COFFSymbolRef points to nothing!\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Object/COFF.h" , 313, __PRETTY_FUNCTION__)); |
314 | return CS16 ? CS16->Name.Offset : CS32->Name.Offset; |
315 | } |
316 | |
317 | uint32_t getValue() const { |
318 | assert(isSet() && "COFFSymbolRef points to nothing!")((isSet() && "COFFSymbolRef points to nothing!") ? static_cast <void> (0) : __assert_fail ("isSet() && \"COFFSymbolRef points to nothing!\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Object/COFF.h" , 318, __PRETTY_FUNCTION__)); |
319 | return CS16 ? CS16->Value : CS32->Value; |
320 | } |
321 | |
322 | int32_t getSectionNumber() const { |
323 | assert(isSet() && "COFFSymbolRef points to nothing!")((isSet() && "COFFSymbolRef points to nothing!") ? static_cast <void> (0) : __assert_fail ("isSet() && \"COFFSymbolRef points to nothing!\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Object/COFF.h" , 323, __PRETTY_FUNCTION__)); |
324 | if (CS16) { |
325 | // Reserved sections are returned as negative numbers. |
326 | if (CS16->SectionNumber <= COFF::MaxNumberOfSections16) |
327 | return CS16->SectionNumber; |
328 | return static_cast<int16_t>(CS16->SectionNumber); |
329 | } |
330 | return static_cast<int32_t>(CS32->SectionNumber); |
331 | } |
332 | |
333 | uint16_t getType() const { |
334 | assert(isSet() && "COFFSymbolRef points to nothing!")((isSet() && "COFFSymbolRef points to nothing!") ? static_cast <void> (0) : __assert_fail ("isSet() && \"COFFSymbolRef points to nothing!\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Object/COFF.h" , 334, __PRETTY_FUNCTION__)); |
335 | return CS16 ? CS16->Type : CS32->Type; |
336 | } |
337 | |
338 | uint8_t getStorageClass() const { |
339 | assert(isSet() && "COFFSymbolRef points to nothing!")((isSet() && "COFFSymbolRef points to nothing!") ? static_cast <void> (0) : __assert_fail ("isSet() && \"COFFSymbolRef points to nothing!\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Object/COFF.h" , 339, __PRETTY_FUNCTION__)); |
340 | return CS16 ? CS16->StorageClass : CS32->StorageClass; |
341 | } |
342 | |
343 | uint8_t getNumberOfAuxSymbols() const { |
344 | assert(isSet() && "COFFSymbolRef points to nothing!")((isSet() && "COFFSymbolRef points to nothing!") ? static_cast <void> (0) : __assert_fail ("isSet() && \"COFFSymbolRef points to nothing!\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Object/COFF.h" , 344, __PRETTY_FUNCTION__)); |
345 | return CS16 ? CS16->NumberOfAuxSymbols : CS32->NumberOfAuxSymbols; |
346 | } |
347 | |
348 | uint8_t getBaseType() const { return getType() & 0x0F; } |
349 | |
350 | uint8_t getComplexType() const { |
351 | return (getType() & 0xF0) >> COFF::SCT_COMPLEX_TYPE_SHIFT; |
352 | } |
353 | |
354 | template <typename T> const T *getAux() const { |
355 | return CS16 ? reinterpret_cast<const T *>(CS16 + 1) |
356 | : reinterpret_cast<const T *>(CS32 + 1); |
357 | } |
358 | |
359 | const coff_aux_section_definition *getSectionDefinition() const { |
360 | if (!getNumberOfAuxSymbols() || |
361 | getStorageClass() != COFF::IMAGE_SYM_CLASS_STATIC) |
362 | return nullptr; |
363 | return getAux<coff_aux_section_definition>(); |
364 | } |
365 | |
366 | const coff_aux_weak_external *getWeakExternal() const { |
367 | if (!getNumberOfAuxSymbols() || |
368 | getStorageClass() != COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL) |
369 | return nullptr; |
370 | return getAux<coff_aux_weak_external>(); |
371 | } |
372 | |
373 | bool isAbsolute() const { |
374 | return getSectionNumber() == -1; |
375 | } |
376 | |
377 | bool isExternal() const { |
378 | return getStorageClass() == COFF::IMAGE_SYM_CLASS_EXTERNAL; |
379 | } |
380 | |
381 | bool isCommon() const { |
382 | return isExternal() && getSectionNumber() == COFF::IMAGE_SYM_UNDEFINED && |
383 | getValue() != 0; |
384 | } |
385 | |
386 | bool isUndefined() const { |
387 | return isExternal() && getSectionNumber() == COFF::IMAGE_SYM_UNDEFINED && |
388 | getValue() == 0; |
389 | } |
390 | |
391 | bool isWeakExternal() const { |
392 | return getStorageClass() == COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL; |
393 | } |
394 | |
395 | bool isFunctionDefinition() const { |
396 | return isExternal() && getBaseType() == COFF::IMAGE_SYM_TYPE_NULL && |
397 | getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION && |
398 | !COFF::isReservedSectionNumber(getSectionNumber()); |
399 | } |
400 | |
401 | bool isFunctionLineInfo() const { |
402 | return getStorageClass() == COFF::IMAGE_SYM_CLASS_FUNCTION; |
403 | } |
404 | |
405 | bool isAnyUndefined() const { |
406 | return isUndefined() || isWeakExternal(); |
407 | } |
408 | |
409 | bool isFileRecord() const { |
410 | return getStorageClass() == COFF::IMAGE_SYM_CLASS_FILE; |
411 | } |
412 | |
413 | bool isSection() const { |
414 | return getStorageClass() == COFF::IMAGE_SYM_CLASS_SECTION; |
415 | } |
416 | |
417 | bool isSectionDefinition() const { |
418 | // C++/CLI creates external ABS symbols for non-const appdomain globals. |
419 | // These are also followed by an auxiliary section definition. |
420 | bool isAppdomainGlobal = |
421 | getStorageClass() == COFF::IMAGE_SYM_CLASS_EXTERNAL && |
422 | getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE; |
423 | bool isOrdinarySection = getStorageClass() == COFF::IMAGE_SYM_CLASS_STATIC; |
424 | if (!getNumberOfAuxSymbols()) |
425 | return false; |
426 | return isAppdomainGlobal || isOrdinarySection; |
427 | } |
428 | |
429 | bool isCLRToken() const { |
430 | return getStorageClass() == COFF::IMAGE_SYM_CLASS_CLR_TOKEN; |
431 | } |
432 | |
433 | private: |
434 | bool isSet() const { return CS16 || CS32; } |
435 | |
436 | const coff_symbol16 *CS16 = nullptr; |
437 | const coff_symbol32 *CS32 = nullptr; |
438 | }; |
439 | |
440 | struct coff_section { |
441 | char Name[COFF::NameSize]; |
442 | support::ulittle32_t VirtualSize; |
443 | support::ulittle32_t VirtualAddress; |
444 | support::ulittle32_t SizeOfRawData; |
445 | support::ulittle32_t PointerToRawData; |
446 | support::ulittle32_t PointerToRelocations; |
447 | support::ulittle32_t PointerToLinenumbers; |
448 | support::ulittle16_t NumberOfRelocations; |
449 | support::ulittle16_t NumberOfLinenumbers; |
450 | support::ulittle32_t Characteristics; |
451 | |
452 | // Returns true if the actual number of relocations is stored in |
453 | // VirtualAddress field of the first relocation table entry. |
454 | bool hasExtendedRelocations() const { |
455 | return (Characteristics & COFF::IMAGE_SCN_LNK_NRELOC_OVFL) && |
456 | NumberOfRelocations == UINT16_MAX(65535); |
457 | } |
458 | |
459 | uint32_t getAlignment() const { |
460 | // The IMAGE_SCN_TYPE_NO_PAD bit is a legacy way of getting to |
461 | // IMAGE_SCN_ALIGN_1BYTES. |
462 | if (Characteristics & COFF::IMAGE_SCN_TYPE_NO_PAD) |
463 | return 1; |
464 | |
465 | // Bit [20:24] contains section alignment. 0 means use a default alignment |
466 | // of 16. |
467 | uint32_t Shift = (Characteristics >> 20) & 0xF; |
468 | if (Shift > 0) |
469 | return 1U << (Shift - 1); |
470 | return 16; |
471 | } |
472 | }; |
473 | |
474 | struct coff_relocation { |
475 | support::ulittle32_t VirtualAddress; |
476 | support::ulittle32_t SymbolTableIndex; |
477 | support::ulittle16_t Type; |
478 | }; |
479 | |
480 | struct coff_aux_function_definition { |
481 | support::ulittle32_t TagIndex; |
482 | support::ulittle32_t TotalSize; |
483 | support::ulittle32_t PointerToLinenumber; |
484 | support::ulittle32_t PointerToNextFunction; |
485 | char Unused1[2]; |
486 | }; |
487 | |
488 | static_assert(sizeof(coff_aux_function_definition) == 18, |
489 | "auxiliary entry must be 18 bytes"); |
490 | |
491 | struct coff_aux_bf_and_ef_symbol { |
492 | char Unused1[4]; |
493 | support::ulittle16_t Linenumber; |
494 | char Unused2[6]; |
495 | support::ulittle32_t PointerToNextFunction; |
496 | char Unused3[2]; |
497 | }; |
498 | |
499 | static_assert(sizeof(coff_aux_bf_and_ef_symbol) == 18, |
500 | "auxiliary entry must be 18 bytes"); |
501 | |
502 | struct coff_aux_weak_external { |
503 | support::ulittle32_t TagIndex; |
504 | support::ulittle32_t Characteristics; |
505 | char Unused1[10]; |
506 | }; |
507 | |
508 | static_assert(sizeof(coff_aux_weak_external) == 18, |
509 | "auxiliary entry must be 18 bytes"); |
510 | |
511 | struct coff_aux_section_definition { |
512 | support::ulittle32_t Length; |
513 | support::ulittle16_t NumberOfRelocations; |
514 | support::ulittle16_t NumberOfLinenumbers; |
515 | support::ulittle32_t CheckSum; |
516 | support::ulittle16_t NumberLowPart; |
517 | uint8_t Selection; |
518 | uint8_t Unused; |
519 | support::ulittle16_t NumberHighPart; |
520 | int32_t getNumber(bool IsBigObj) const { |
521 | uint32_t Number = static_cast<uint32_t>(NumberLowPart); |
522 | if (IsBigObj) |
523 | Number |= static_cast<uint32_t>(NumberHighPart) << 16; |
524 | return static_cast<int32_t>(Number); |
525 | } |
526 | }; |
527 | |
528 | static_assert(sizeof(coff_aux_section_definition) == 18, |
529 | "auxiliary entry must be 18 bytes"); |
530 | |
531 | struct coff_aux_clr_token { |
532 | uint8_t AuxType; |
533 | uint8_t Reserved; |
534 | support::ulittle32_t SymbolTableIndex; |
535 | char MBZ[12]; |
536 | }; |
537 | |
538 | static_assert(sizeof(coff_aux_clr_token) == 18, |
539 | "auxiliary entry must be 18 bytes"); |
540 | |
541 | struct coff_import_header { |
542 | support::ulittle16_t Sig1; |
543 | support::ulittle16_t Sig2; |
544 | support::ulittle16_t Version; |
545 | support::ulittle16_t Machine; |
546 | support::ulittle32_t TimeDateStamp; |
547 | support::ulittle32_t SizeOfData; |
548 | support::ulittle16_t OrdinalHint; |
549 | support::ulittle16_t TypeInfo; |
550 | |
551 | int getType() const { return TypeInfo & 0x3; } |
552 | int getNameType() const { return (TypeInfo >> 2) & 0x7; } |
553 | }; |
554 | |
555 | struct coff_import_directory_table_entry { |
556 | support::ulittle32_t ImportLookupTableRVA; |
557 | support::ulittle32_t TimeDateStamp; |
558 | support::ulittle32_t ForwarderChain; |
559 | support::ulittle32_t NameRVA; |
560 | support::ulittle32_t ImportAddressTableRVA; |
561 | |
562 | bool isNull() const { |
563 | return ImportLookupTableRVA == 0 && TimeDateStamp == 0 && |
564 | ForwarderChain == 0 && NameRVA == 0 && ImportAddressTableRVA == 0; |
565 | } |
566 | }; |
567 | |
568 | template <typename IntTy> |
569 | struct coff_tls_directory { |
570 | IntTy StartAddressOfRawData; |
571 | IntTy EndAddressOfRawData; |
572 | IntTy AddressOfIndex; |
573 | IntTy AddressOfCallBacks; |
574 | support::ulittle32_t SizeOfZeroFill; |
575 | support::ulittle32_t Characteristics; |
576 | |
577 | uint32_t getAlignment() const { |
578 | // Bit [20:24] contains section alignment. |
579 | uint32_t Shift = (Characteristics & 0x00F00000) >> 20; |
580 | if (Shift > 0) |
581 | return 1U << (Shift - 1); |
582 | return 0; |
583 | } |
584 | }; |
585 | |
586 | using coff_tls_directory32 = coff_tls_directory<support::little32_t>; |
587 | using coff_tls_directory64 = coff_tls_directory<support::little64_t>; |
588 | |
589 | /// Bits in control flow guard flags as we understand them. |
590 | enum class coff_guard_flags : uint32_t { |
591 | CFInstrumented = 0x00000100, |
592 | HasFidTable = 0x00000400, |
593 | ProtectDelayLoadIAT = 0x00001000, |
594 | DelayLoadIATSection = 0x00002000, // Delay load in separate section |
595 | HasLongJmpTable = 0x00010000, |
596 | FidTableHasFlags = 0x10000000, // Indicates that fid tables are 5 bytes |
597 | }; |
598 | |
599 | enum class frame_type : uint16_t { Fpo = 0, Trap = 1, Tss = 2, NonFpo = 3 }; |
600 | |
601 | struct coff_load_config_code_integrity { |
602 | support::ulittle16_t Flags; |
603 | support::ulittle16_t Catalog; |
604 | support::ulittle32_t CatalogOffset; |
605 | support::ulittle32_t Reserved; |
606 | }; |
607 | |
608 | /// 32-bit load config (IMAGE_LOAD_CONFIG_DIRECTORY32) |
609 | struct coff_load_configuration32 { |
610 | support::ulittle32_t Size; |
611 | support::ulittle32_t TimeDateStamp; |
612 | support::ulittle16_t MajorVersion; |
613 | support::ulittle16_t MinorVersion; |
614 | support::ulittle32_t GlobalFlagsClear; |
615 | support::ulittle32_t GlobalFlagsSet; |
616 | support::ulittle32_t CriticalSectionDefaultTimeout; |
617 | support::ulittle32_t DeCommitFreeBlockThreshold; |
618 | support::ulittle32_t DeCommitTotalFreeThreshold; |
619 | support::ulittle32_t LockPrefixTable; |
620 | support::ulittle32_t MaximumAllocationSize; |
621 | support::ulittle32_t VirtualMemoryThreshold; |
622 | support::ulittle32_t ProcessAffinityMask; |
623 | support::ulittle32_t ProcessHeapFlags; |
624 | support::ulittle16_t CSDVersion; |
625 | support::ulittle16_t DependentLoadFlags; |
626 | support::ulittle32_t EditList; |
627 | support::ulittle32_t SecurityCookie; |
628 | support::ulittle32_t SEHandlerTable; |
629 | support::ulittle32_t SEHandlerCount; |
630 | |
631 | // Added in MSVC 2015 for /guard:cf. |
632 | support::ulittle32_t GuardCFCheckFunction; |
633 | support::ulittle32_t GuardCFCheckDispatch; |
634 | support::ulittle32_t GuardCFFunctionTable; |
635 | support::ulittle32_t GuardCFFunctionCount; |
636 | support::ulittle32_t GuardFlags; // coff_guard_flags |
637 | |
638 | // Added in MSVC 2017 |
639 | coff_load_config_code_integrity CodeIntegrity; |
640 | support::ulittle32_t GuardAddressTakenIatEntryTable; |
641 | support::ulittle32_t GuardAddressTakenIatEntryCount; |
642 | support::ulittle32_t GuardLongJumpTargetTable; |
643 | support::ulittle32_t GuardLongJumpTargetCount; |
644 | support::ulittle32_t DynamicValueRelocTable; |
645 | support::ulittle32_t CHPEMetadataPointer; |
646 | support::ulittle32_t GuardRFFailureRoutine; |
647 | support::ulittle32_t GuardRFFailureRoutineFunctionPointer; |
648 | support::ulittle32_t DynamicValueRelocTableOffset; |
649 | support::ulittle16_t DynamicValueRelocTableSection; |
650 | support::ulittle16_t Reserved2; |
651 | support::ulittle32_t GuardRFVerifyStackPointerFunctionPointer; |
652 | support::ulittle32_t HotPatchTableOffset; |
653 | }; |
654 | |
655 | /// 64-bit load config (IMAGE_LOAD_CONFIG_DIRECTORY64) |
656 | struct coff_load_configuration64 { |
657 | support::ulittle32_t Size; |
658 | support::ulittle32_t TimeDateStamp; |
659 | support::ulittle16_t MajorVersion; |
660 | support::ulittle16_t MinorVersion; |
661 | support::ulittle32_t GlobalFlagsClear; |
662 | support::ulittle32_t GlobalFlagsSet; |
663 | support::ulittle32_t CriticalSectionDefaultTimeout; |
664 | support::ulittle64_t DeCommitFreeBlockThreshold; |
665 | support::ulittle64_t DeCommitTotalFreeThreshold; |
666 | support::ulittle64_t LockPrefixTable; |
667 | support::ulittle64_t MaximumAllocationSize; |
668 | support::ulittle64_t VirtualMemoryThreshold; |
669 | support::ulittle64_t ProcessAffinityMask; |
670 | support::ulittle32_t ProcessHeapFlags; |
671 | support::ulittle16_t CSDVersion; |
672 | support::ulittle16_t DependentLoadFlags; |
673 | support::ulittle64_t EditList; |
674 | support::ulittle64_t SecurityCookie; |
675 | support::ulittle64_t SEHandlerTable; |
676 | support::ulittle64_t SEHandlerCount; |
677 | |
678 | // Added in MSVC 2015 for /guard:cf. |
679 | support::ulittle64_t GuardCFCheckFunction; |
680 | support::ulittle64_t GuardCFCheckDispatch; |
681 | support::ulittle64_t GuardCFFunctionTable; |
682 | support::ulittle64_t GuardCFFunctionCount; |
683 | support::ulittle32_t GuardFlags; |
684 | |
685 | // Added in MSVC 2017 |
686 | coff_load_config_code_integrity CodeIntegrity; |
687 | support::ulittle64_t GuardAddressTakenIatEntryTable; |
688 | support::ulittle64_t GuardAddressTakenIatEntryCount; |
689 | support::ulittle64_t GuardLongJumpTargetTable; |
690 | support::ulittle64_t GuardLongJumpTargetCount; |
691 | support::ulittle64_t DynamicValueRelocTable; |
692 | support::ulittle64_t CHPEMetadataPointer; |
693 | support::ulittle64_t GuardRFFailureRoutine; |
694 | support::ulittle64_t GuardRFFailureRoutineFunctionPointer; |
695 | support::ulittle32_t DynamicValueRelocTableOffset; |
696 | support::ulittle16_t DynamicValueRelocTableSection; |
697 | support::ulittle16_t Reserved2; |
698 | support::ulittle64_t GuardRFVerifyStackPointerFunctionPointer; |
699 | support::ulittle32_t HotPatchTableOffset; |
700 | }; |
701 | |
702 | struct coff_runtime_function_x64 { |
703 | support::ulittle32_t BeginAddress; |
704 | support::ulittle32_t EndAddress; |
705 | support::ulittle32_t UnwindInformation; |
706 | }; |
707 | |
708 | struct coff_base_reloc_block_header { |
709 | support::ulittle32_t PageRVA; |
710 | support::ulittle32_t BlockSize; |
711 | }; |
712 | |
713 | struct coff_base_reloc_block_entry { |
714 | support::ulittle16_t Data; |
715 | |
716 | int getType() const { return Data >> 12; } |
717 | int getOffset() const { return Data & ((1 << 12) - 1); } |
718 | }; |
719 | |
720 | struct coff_resource_dir_entry { |
721 | union { |
722 | support::ulittle32_t NameOffset; |
723 | support::ulittle32_t ID; |
724 | uint32_t getNameOffset() const { |
725 | return maskTrailingOnes<uint32_t>(31) & NameOffset; |
726 | } |
727 | // Even though the PE/COFF spec doesn't mention this, the high bit of a name |
728 | // offset is set. |
729 | void setNameOffset(uint32_t Offset) { NameOffset = Offset | (1 << 31); } |
730 | } Identifier; |
731 | union { |
732 | support::ulittle32_t DataEntryOffset; |
733 | support::ulittle32_t SubdirOffset; |
734 | |
735 | bool isSubDir() const { return SubdirOffset >> 31; } |
736 | uint32_t value() const { |
737 | return maskTrailingOnes<uint32_t>(31) & SubdirOffset; |
738 | } |
739 | |
740 | } Offset; |
741 | }; |
742 | |
743 | struct coff_resource_data_entry { |
744 | support::ulittle32_t DataRVA; |
745 | support::ulittle32_t DataSize; |
746 | support::ulittle32_t Codepage; |
747 | support::ulittle32_t Reserved; |
748 | }; |
749 | |
750 | struct coff_resource_dir_table { |
751 | support::ulittle32_t Characteristics; |
752 | support::ulittle32_t TimeDateStamp; |
753 | support::ulittle16_t MajorVersion; |
754 | support::ulittle16_t MinorVersion; |
755 | support::ulittle16_t NumberOfNameEntries; |
756 | support::ulittle16_t NumberOfIDEntries; |
757 | }; |
758 | |
759 | struct debug_h_header { |
760 | support::ulittle32_t Magic; |
761 | support::ulittle16_t Version; |
762 | support::ulittle16_t HashAlgorithm; |
763 | }; |
764 | |
765 | class COFFObjectFile : public ObjectFile { |
766 | private: |
767 | friend class ImportDirectoryEntryRef; |
768 | friend class ExportDirectoryEntryRef; |
769 | const coff_file_header *COFFHeader; |
770 | const coff_bigobj_file_header *COFFBigObjHeader; |
771 | const pe32_header *PE32Header; |
772 | const pe32plus_header *PE32PlusHeader; |
773 | const data_directory *DataDirectory; |
774 | const coff_section *SectionTable; |
775 | const coff_symbol16 *SymbolTable16; |
776 | const coff_symbol32 *SymbolTable32; |
777 | const char *StringTable; |
778 | uint32_t StringTableSize; |
779 | const coff_import_directory_table_entry *ImportDirectory; |
780 | const delay_import_directory_table_entry *DelayImportDirectory; |
781 | uint32_t NumberOfDelayImportDirectory; |
782 | const export_directory_table_entry *ExportDirectory; |
783 | const coff_base_reloc_block_header *BaseRelocHeader; |
784 | const coff_base_reloc_block_header *BaseRelocEnd; |
785 | const debug_directory *DebugDirectoryBegin; |
786 | const debug_directory *DebugDirectoryEnd; |
787 | // Either coff_load_configuration32 or coff_load_configuration64. |
788 | const void *LoadConfig = nullptr; |
789 | |
790 | std::error_code getString(uint32_t offset, StringRef &Res) const; |
791 | |
792 | template <typename coff_symbol_type> |
793 | const coff_symbol_type *toSymb(DataRefImpl Symb) const; |
794 | const coff_section *toSec(DataRefImpl Sec) const; |
795 | const coff_relocation *toRel(DataRefImpl Rel) const; |
796 | |
797 | std::error_code initSymbolTablePtr(); |
798 | std::error_code initImportTablePtr(); |
799 | std::error_code initDelayImportTablePtr(); |
800 | std::error_code initExportTablePtr(); |
801 | std::error_code initBaseRelocPtr(); |
802 | std::error_code initDebugDirectoryPtr(); |
803 | std::error_code initLoadConfigPtr(); |
804 | |
805 | public: |
806 | uintptr_t getSymbolTable() const { |
807 | if (SymbolTable16) |
808 | return reinterpret_cast<uintptr_t>(SymbolTable16); |
809 | if (SymbolTable32) |
810 | return reinterpret_cast<uintptr_t>(SymbolTable32); |
811 | return uintptr_t(0); |
812 | } |
813 | |
814 | uint16_t getMachine() const { |
815 | if (COFFHeader) |
816 | return COFFHeader->Machine; |
817 | if (COFFBigObjHeader) |
818 | return COFFBigObjHeader->Machine; |
819 | llvm_unreachable("no COFF header!")::llvm::llvm_unreachable_internal("no COFF header!", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Object/COFF.h" , 819); |
820 | } |
821 | |
822 | uint16_t getSizeOfOptionalHeader() const { |
823 | if (COFFHeader) |
824 | return COFFHeader->isImportLibrary() ? 0 |
825 | : COFFHeader->SizeOfOptionalHeader; |
826 | // bigobj doesn't have this field. |
827 | if (COFFBigObjHeader) |
828 | return 0; |
829 | llvm_unreachable("no COFF header!")::llvm::llvm_unreachable_internal("no COFF header!", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Object/COFF.h" , 829); |
830 | } |
831 | |
832 | uint16_t getCharacteristics() const { |
833 | if (COFFHeader) |
834 | return COFFHeader->isImportLibrary() ? 0 : COFFHeader->Characteristics; |
835 | // bigobj doesn't have characteristics to speak of, |
836 | // editbin will silently lie to you if you attempt to set any. |
837 | if (COFFBigObjHeader) |
838 | return 0; |
839 | llvm_unreachable("no COFF header!")::llvm::llvm_unreachable_internal("no COFF header!", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Object/COFF.h" , 839); |
840 | } |
841 | |
842 | uint32_t getTimeDateStamp() const { |
843 | if (COFFHeader) |
844 | return COFFHeader->TimeDateStamp; |
845 | if (COFFBigObjHeader) |
846 | return COFFBigObjHeader->TimeDateStamp; |
847 | llvm_unreachable("no COFF header!")::llvm::llvm_unreachable_internal("no COFF header!", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Object/COFF.h" , 847); |
848 | } |
849 | |
850 | uint32_t getNumberOfSections() const { |
851 | if (COFFHeader) |
852 | return COFFHeader->isImportLibrary() ? 0 : COFFHeader->NumberOfSections; |
853 | if (COFFBigObjHeader) |
854 | return COFFBigObjHeader->NumberOfSections; |
855 | llvm_unreachable("no COFF header!")::llvm::llvm_unreachable_internal("no COFF header!", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Object/COFF.h" , 855); |
856 | } |
857 | |
858 | uint32_t getPointerToSymbolTable() const { |
859 | if (COFFHeader) |
860 | return COFFHeader->isImportLibrary() ? 0 |
861 | : COFFHeader->PointerToSymbolTable; |
862 | if (COFFBigObjHeader) |
863 | return COFFBigObjHeader->PointerToSymbolTable; |
864 | llvm_unreachable("no COFF header!")::llvm::llvm_unreachable_internal("no COFF header!", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Object/COFF.h" , 864); |
865 | } |
866 | |
867 | uint32_t getRawNumberOfSymbols() const { |
868 | if (COFFHeader) |
869 | return COFFHeader->isImportLibrary() ? 0 : COFFHeader->NumberOfSymbols; |
870 | if (COFFBigObjHeader) |
871 | return COFFBigObjHeader->NumberOfSymbols; |
872 | llvm_unreachable("no COFF header!")::llvm::llvm_unreachable_internal("no COFF header!", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Object/COFF.h" , 872); |
873 | } |
874 | |
875 | uint32_t getNumberOfSymbols() const { |
876 | if (!SymbolTable16 && !SymbolTable32) |
877 | return 0; |
878 | return getRawNumberOfSymbols(); |
879 | } |
880 | |
881 | const coff_load_configuration32 *getLoadConfig32() const { |
882 | assert(!is64())((!is64()) ? static_cast<void> (0) : __assert_fail ("!is64()" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Object/COFF.h" , 882, __PRETTY_FUNCTION__)); |
883 | return reinterpret_cast<const coff_load_configuration32 *>(LoadConfig); |
884 | } |
885 | |
886 | const coff_load_configuration64 *getLoadConfig64() const { |
887 | assert(is64())((is64()) ? static_cast<void> (0) : __assert_fail ("is64()" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Object/COFF.h" , 887, __PRETTY_FUNCTION__)); |
888 | return reinterpret_cast<const coff_load_configuration64 *>(LoadConfig); |
889 | } |
890 | StringRef getRelocationTypeName(uint16_t Type) const; |
891 | |
892 | protected: |
893 | void moveSymbolNext(DataRefImpl &Symb) const override; |
894 | Expected<StringRef> getSymbolName(DataRefImpl Symb) const override; |
895 | Expected<uint64_t> getSymbolAddress(DataRefImpl Symb) const override; |
896 | uint32_t getSymbolAlignment(DataRefImpl Symb) const override; |
897 | uint64_t getSymbolValueImpl(DataRefImpl Symb) const override; |
898 | uint64_t getCommonSymbolSizeImpl(DataRefImpl Symb) const override; |
899 | uint32_t getSymbolFlags(DataRefImpl Symb) const override; |
900 | Expected<SymbolRef::Type> getSymbolType(DataRefImpl Symb) const override; |
901 | Expected<section_iterator> getSymbolSection(DataRefImpl Symb) const override; |
902 | void moveSectionNext(DataRefImpl &Sec) const override; |
903 | Expected<StringRef> getSectionName(DataRefImpl Sec) const override; |
904 | uint64_t getSectionAddress(DataRefImpl Sec) const override; |
905 | uint64_t getSectionIndex(DataRefImpl Sec) const override; |
906 | uint64_t getSectionSize(DataRefImpl Sec) const override; |
907 | Expected<ArrayRef<uint8_t>> |
908 | getSectionContents(DataRefImpl Sec) const override; |
909 | uint64_t getSectionAlignment(DataRefImpl Sec) const override; |
910 | bool isSectionCompressed(DataRefImpl Sec) const override; |
911 | bool isSectionText(DataRefImpl Sec) const override; |
912 | bool isSectionData(DataRefImpl Sec) const override; |
913 | bool isSectionBSS(DataRefImpl Sec) const override; |
914 | bool isSectionVirtual(DataRefImpl Sec) const override; |
915 | relocation_iterator section_rel_begin(DataRefImpl Sec) const override; |
916 | relocation_iterator section_rel_end(DataRefImpl Sec) const override; |
917 | |
918 | void moveRelocationNext(DataRefImpl &Rel) const override; |
919 | uint64_t getRelocationOffset(DataRefImpl Rel) const override; |
920 | symbol_iterator getRelocationSymbol(DataRefImpl Rel) const override; |
921 | uint64_t getRelocationType(DataRefImpl Rel) const override; |
922 | void getRelocationTypeName(DataRefImpl Rel, |
923 | SmallVectorImpl<char> &Result) const override; |
924 | |
925 | public: |
926 | COFFObjectFile(MemoryBufferRef Object, std::error_code &EC); |
927 | |
928 | basic_symbol_iterator symbol_begin() const override; |
929 | basic_symbol_iterator symbol_end() const override; |
930 | section_iterator section_begin() const override; |
931 | section_iterator section_end() const override; |
932 | |
933 | const coff_section *getCOFFSection(const SectionRef &Section) const; |
934 | COFFSymbolRef getCOFFSymbol(const DataRefImpl &Ref) const; |
935 | COFFSymbolRef getCOFFSymbol(const SymbolRef &Symbol) const; |
936 | const coff_relocation *getCOFFRelocation(const RelocationRef &Reloc) const; |
937 | unsigned getSectionID(SectionRef Sec) const; |
938 | unsigned getSymbolSectionID(SymbolRef Sym) const; |
939 | |
940 | uint8_t getBytesInAddress() const override; |
941 | StringRef getFileFormatName() const override; |
942 | Triple::ArchType getArch() const override; |
943 | Expected<uint64_t> getStartAddress() const override; |
944 | SubtargetFeatures getFeatures() const override { return SubtargetFeatures(); } |
945 | |
946 | import_directory_iterator import_directory_begin() const; |
947 | import_directory_iterator import_directory_end() const; |
948 | delay_import_directory_iterator delay_import_directory_begin() const; |
949 | delay_import_directory_iterator delay_import_directory_end() const; |
950 | export_directory_iterator export_directory_begin() const; |
951 | export_directory_iterator export_directory_end() const; |
952 | base_reloc_iterator base_reloc_begin() const; |
953 | base_reloc_iterator base_reloc_end() const; |
954 | const debug_directory *debug_directory_begin() const { |
955 | return DebugDirectoryBegin; |
956 | } |
957 | const debug_directory *debug_directory_end() const { |
958 | return DebugDirectoryEnd; |
959 | } |
960 | |
961 | iterator_range<import_directory_iterator> import_directories() const; |
962 | iterator_range<delay_import_directory_iterator> |
963 | delay_import_directories() const; |
964 | iterator_range<export_directory_iterator> export_directories() const; |
965 | iterator_range<base_reloc_iterator> base_relocs() const; |
966 | iterator_range<const debug_directory *> debug_directories() const { |
967 | return make_range(debug_directory_begin(), debug_directory_end()); |
968 | } |
969 | |
970 | const dos_header *getDOSHeader() const { |
971 | if (!PE32Header && !PE32PlusHeader) |
972 | return nullptr; |
973 | return reinterpret_cast<const dos_header *>(base()); |
974 | } |
975 | |
976 | const coff_file_header *getCOFFHeader() const { return COFFHeader; } |
977 | const coff_bigobj_file_header *getCOFFBigObjHeader() const { |
978 | return COFFBigObjHeader; |
979 | } |
980 | const pe32_header *getPE32Header() const { return PE32Header; } |
981 | const pe32plus_header *getPE32PlusHeader() const { return PE32PlusHeader; } |
982 | |
983 | std::error_code getDataDirectory(uint32_t index, |
984 | const data_directory *&Res) const; |
985 | std::error_code getSection(int32_t index, const coff_section *&Res) const; |
986 | std::error_code getSection(StringRef SectionName, |
987 | const coff_section *&Res) const; |
988 | |
989 | template <typename coff_symbol_type> |
990 | std::error_code getSymbol(uint32_t Index, |
991 | const coff_symbol_type *&Res) const { |
992 | if (Index >= getNumberOfSymbols()) |
993 | return object_error::parse_failed; |
994 | |
995 | Res = reinterpret_cast<coff_symbol_type *>(getSymbolTable()) + Index; |
996 | return std::error_code(); |
997 | } |
998 | Expected<COFFSymbolRef> getSymbol(uint32_t index) const { |
999 | if (SymbolTable16) { |
1000 | const coff_symbol16 *Symb = nullptr; |
1001 | if (std::error_code EC = getSymbol(index, Symb)) |
1002 | return errorCodeToError(EC); |
1003 | return COFFSymbolRef(Symb); |
1004 | } |
1005 | if (SymbolTable32) { |
1006 | const coff_symbol32 *Symb = nullptr; |
1007 | if (std::error_code EC = getSymbol(index, Symb)) |
1008 | return errorCodeToError(EC); |
1009 | return COFFSymbolRef(Symb); |
1010 | } |
1011 | return errorCodeToError(object_error::parse_failed); |
1012 | } |
1013 | |
1014 | template <typename T> |
1015 | std::error_code getAuxSymbol(uint32_t index, const T *&Res) const { |
1016 | Expected<COFFSymbolRef> S = getSymbol(index); |
1017 | if (Error E = S.takeError()) |
1018 | return errorToErrorCode(std::move(E)); |
1019 | Res = reinterpret_cast<const T *>(S->getRawPtr()); |
1020 | return std::error_code(); |
1021 | } |
1022 | |
1023 | std::error_code getSymbolName(COFFSymbolRef Symbol, StringRef &Res) const; |
1024 | std::error_code getSymbolName(const coff_symbol_generic *Symbol, |
1025 | StringRef &Res) const; |
1026 | |
1027 | ArrayRef<uint8_t> getSymbolAuxData(COFFSymbolRef Symbol) const; |
1028 | |
1029 | uint32_t getSymbolIndex(COFFSymbolRef Symbol) const; |
1030 | |
1031 | size_t getSymbolTableEntrySize() const { |
1032 | if (COFFHeader) |
1033 | return sizeof(coff_symbol16); |
1034 | if (COFFBigObjHeader) |
1035 | return sizeof(coff_symbol32); |
1036 | llvm_unreachable("null symbol table pointer!")::llvm::llvm_unreachable_internal("null symbol table pointer!" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Object/COFF.h" , 1036); |
1037 | } |
1038 | |
1039 | ArrayRef<coff_relocation> getRelocations(const coff_section *Sec) const; |
1040 | |
1041 | Expected<StringRef> getSectionName(const coff_section *Sec) const; |
1042 | uint64_t getSectionSize(const coff_section *Sec) const; |
1043 | Error getSectionContents(const coff_section *Sec, |
1044 | ArrayRef<uint8_t> &Res) const; |
1045 | |
1046 | uint64_t getImageBase() const; |
1047 | std::error_code getVaPtr(uint64_t VA, uintptr_t &Res) const; |
1048 | std::error_code getRvaPtr(uint32_t Rva, uintptr_t &Res) const; |
1049 | |
1050 | /// Given an RVA base and size, returns a valid array of bytes or an error |
1051 | /// code if the RVA and size is not contained completely within a valid |
1052 | /// section. |
1053 | std::error_code getRvaAndSizeAsBytes(uint32_t RVA, uint32_t Size, |
1054 | ArrayRef<uint8_t> &Contents) const; |
1055 | |
1056 | std::error_code getHintName(uint32_t Rva, uint16_t &Hint, |
1057 | StringRef &Name) const; |
1058 | |
1059 | /// Get PDB information out of a codeview debug directory entry. |
1060 | std::error_code getDebugPDBInfo(const debug_directory *DebugDir, |
1061 | const codeview::DebugInfo *&Info, |
1062 | StringRef &PDBFileName) const; |
1063 | |
1064 | /// Get PDB information from an executable. If the information is not present, |
1065 | /// Info will be set to nullptr and PDBFileName will be empty. An error is |
1066 | /// returned only on corrupt object files. Convenience accessor that can be |
1067 | /// used if the debug directory is not already handy. |
1068 | std::error_code getDebugPDBInfo(const codeview::DebugInfo *&Info, |
1069 | StringRef &PDBFileName) const; |
1070 | |
1071 | bool isRelocatableObject() const override; |
1072 | bool is64() const { return PE32PlusHeader; } |
1073 | |
1074 | StringRef mapDebugSectionName(StringRef Name) const override; |
1075 | |
1076 | static bool classof(const Binary *v) { return v->isCOFF(); } |
1077 | }; |
1078 | |
1079 | // The iterator for the import directory table. |
1080 | class ImportDirectoryEntryRef { |
1081 | public: |
1082 | ImportDirectoryEntryRef() = default; |
1083 | ImportDirectoryEntryRef(const coff_import_directory_table_entry *Table, |
1084 | uint32_t I, const COFFObjectFile *Owner) |
1085 | : ImportTable(Table), Index(I), OwningObject(Owner) {} |
1086 | |
1087 | bool operator==(const ImportDirectoryEntryRef &Other) const; |
1088 | void moveNext(); |
1089 | |
1090 | imported_symbol_iterator imported_symbol_begin() const; |
1091 | imported_symbol_iterator imported_symbol_end() const; |
1092 | iterator_range<imported_symbol_iterator> imported_symbols() const; |
1093 | |
1094 | imported_symbol_iterator lookup_table_begin() const; |
1095 | imported_symbol_iterator lookup_table_end() const; |
1096 | iterator_range<imported_symbol_iterator> lookup_table_symbols() const; |
1097 | |
1098 | std::error_code getName(StringRef &Result) const; |
1099 | std::error_code getImportLookupTableRVA(uint32_t &Result) const; |
1100 | std::error_code getImportAddressTableRVA(uint32_t &Result) const; |
1101 | |
1102 | std::error_code |
1103 | getImportTableEntry(const coff_import_directory_table_entry *&Result) const; |
1104 | |
1105 | private: |
1106 | const coff_import_directory_table_entry *ImportTable; |
1107 | uint32_t Index; |
1108 | const COFFObjectFile *OwningObject = nullptr; |
1109 | }; |
1110 | |
1111 | class DelayImportDirectoryEntryRef { |
1112 | public: |
1113 | DelayImportDirectoryEntryRef() = default; |
1114 | DelayImportDirectoryEntryRef(const delay_import_directory_table_entry *T, |
1115 | uint32_t I, const COFFObjectFile *Owner) |
1116 | : Table(T), Index(I), OwningObject(Owner) {} |
1117 | |
1118 | bool operator==(const DelayImportDirectoryEntryRef &Other) const; |
1119 | void moveNext(); |
1120 | |
1121 | imported_symbol_iterator imported_symbol_begin() const; |
1122 | imported_symbol_iterator imported_symbol_end() const; |
1123 | iterator_range<imported_symbol_iterator> imported_symbols() const; |
1124 | |
1125 | std::error_code getName(StringRef &Result) const; |
1126 | std::error_code getDelayImportTable( |
1127 | const delay_import_directory_table_entry *&Result) const; |
1128 | std::error_code getImportAddress(int AddrIndex, uint64_t &Result) const; |
1129 | |
1130 | private: |
1131 | const delay_import_directory_table_entry *Table; |
1132 | uint32_t Index; |
1133 | const COFFObjectFile *OwningObject = nullptr; |
1134 | }; |
1135 | |
1136 | // The iterator for the export directory table entry. |
1137 | class ExportDirectoryEntryRef { |
1138 | public: |
1139 | ExportDirectoryEntryRef() = default; |
1140 | ExportDirectoryEntryRef(const export_directory_table_entry *Table, uint32_t I, |
1141 | const COFFObjectFile *Owner) |
1142 | : ExportTable(Table), Index(I), OwningObject(Owner) {} |
1143 | |
1144 | bool operator==(const ExportDirectoryEntryRef &Other) const; |
1145 | void moveNext(); |
1146 | |
1147 | std::error_code getDllName(StringRef &Result) const; |
1148 | std::error_code getOrdinalBase(uint32_t &Result) const; |
1149 | std::error_code getOrdinal(uint32_t &Result) const; |
1150 | std::error_code getExportRVA(uint32_t &Result) const; |
1151 | std::error_code getSymbolName(StringRef &Result) const; |
1152 | |
1153 | std::error_code isForwarder(bool &Result) const; |
1154 | std::error_code getForwardTo(StringRef &Result) const; |
1155 | |
1156 | private: |
1157 | const export_directory_table_entry *ExportTable; |
1158 | uint32_t Index; |
1159 | const COFFObjectFile *OwningObject = nullptr; |
1160 | }; |
1161 | |
1162 | class ImportedSymbolRef { |
1163 | public: |
1164 | ImportedSymbolRef() = default; |
1165 | ImportedSymbolRef(const import_lookup_table_entry32 *Entry, uint32_t I, |
1166 | const COFFObjectFile *Owner) |
1167 | : Entry32(Entry), Entry64(nullptr), Index(I), OwningObject(Owner) {} |
1168 | ImportedSymbolRef(const import_lookup_table_entry64 *Entry, uint32_t I, |
1169 | const COFFObjectFile *Owner) |
1170 | : Entry32(nullptr), Entry64(Entry), Index(I), OwningObject(Owner) {} |
1171 | |
1172 | bool operator==(const ImportedSymbolRef &Other) const; |
1173 | void moveNext(); |
1174 | |
1175 | std::error_code getSymbolName(StringRef &Result) const; |
1176 | std::error_code isOrdinal(bool &Result) const; |
1177 | std::error_code getOrdinal(uint16_t &Result) const; |
1178 | std::error_code getHintNameRVA(uint32_t &Result) const; |
1179 | |
1180 | private: |
1181 | const import_lookup_table_entry32 *Entry32; |
1182 | const import_lookup_table_entry64 *Entry64; |
1183 | uint32_t Index; |
1184 | const COFFObjectFile *OwningObject = nullptr; |
1185 | }; |
1186 | |
1187 | class BaseRelocRef { |
1188 | public: |
1189 | BaseRelocRef() = default; |
1190 | BaseRelocRef(const coff_base_reloc_block_header *Header, |
1191 | const COFFObjectFile *Owner) |
1192 | : Header(Header), Index(0) {} |
1193 | |
1194 | bool operator==(const BaseRelocRef &Other) const; |
1195 | void moveNext(); |
1196 | |
1197 | std::error_code getType(uint8_t &Type) const; |
1198 | std::error_code getRVA(uint32_t &Result) const; |
1199 | |
1200 | private: |
1201 | const coff_base_reloc_block_header *Header; |
1202 | uint32_t Index; |
1203 | }; |
1204 | |
1205 | class ResourceSectionRef { |
1206 | public: |
1207 | ResourceSectionRef() = default; |
1208 | explicit ResourceSectionRef(StringRef Ref) : BBS(Ref, support::little) {} |
1209 | |
1210 | Error load(const COFFObjectFile *O); |
1211 | Error load(const COFFObjectFile *O, const SectionRef &S); |
1212 | |
1213 | Expected<ArrayRef<UTF16>> |
1214 | getEntryNameString(const coff_resource_dir_entry &Entry); |
1215 | Expected<const coff_resource_dir_table &> |
1216 | getEntrySubDir(const coff_resource_dir_entry &Entry); |
1217 | Expected<const coff_resource_data_entry &> |
1218 | getEntryData(const coff_resource_dir_entry &Entry); |
1219 | Expected<const coff_resource_dir_table &> getBaseTable(); |
1220 | Expected<const coff_resource_dir_entry &> |
1221 | getTableEntry(const coff_resource_dir_table &Table, uint32_t Index); |
1222 | |
1223 | Expected<StringRef> getContents(const coff_resource_data_entry &Entry); |
1224 | |
1225 | private: |
1226 | BinaryByteStream BBS; |
1227 | |
1228 | SectionRef Section; |
1229 | const COFFObjectFile *Obj; |
1230 | |
1231 | std::vector<const coff_relocation *> Relocs; |
1232 | |
1233 | Expected<const coff_resource_dir_table &> getTableAtOffset(uint32_t Offset); |
1234 | Expected<const coff_resource_dir_entry &> |
1235 | getTableEntryAtOffset(uint32_t Offset); |
1236 | Expected<const coff_resource_data_entry &> |
1237 | getDataEntryAtOffset(uint32_t Offset); |
1238 | Expected<ArrayRef<UTF16>> getDirStringAtOffset(uint32_t Offset); |
1239 | }; |
1240 | |
1241 | // Corresponds to `_FPO_DATA` structure in the PE/COFF spec. |
1242 | struct FpoData { |
1243 | support::ulittle32_t Offset; // ulOffStart: Offset 1st byte of function code |
1244 | support::ulittle32_t Size; // cbProcSize: # bytes in function |
1245 | support::ulittle32_t NumLocals; // cdwLocals: # bytes in locals/4 |
1246 | support::ulittle16_t NumParams; // cdwParams: # bytes in params/4 |
1247 | support::ulittle16_t Attributes; |
1248 | |
1249 | // cbProlog: # bytes in prolog |
1250 | int getPrologSize() const { return Attributes & 0xF; } |
1251 | |
1252 | // cbRegs: # regs saved |
1253 | int getNumSavedRegs() const { return (Attributes >> 8) & 0x7; } |
1254 | |
1255 | // fHasSEH: true if seh is func |
1256 | bool hasSEH() const { return (Attributes >> 9) & 1; } |
1257 | |
1258 | // fUseBP: true if EBP has been allocated |
1259 | bool useBP() const { return (Attributes >> 10) & 1; } |
1260 | |
1261 | // cbFrame: frame pointer |
1262 | frame_type getFP() const { return static_cast<frame_type>(Attributes >> 14); } |
1263 | }; |
1264 | |
1265 | } // end namespace object |
1266 | |
1267 | } // end namespace llvm |
1268 | |
1269 | #endif // LLVM_OBJECT_COFF_H |
1 | //===- Endian.h - Utilities for IO with endian specific data ----*- C++ -*-===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // |
9 | // This file declares generic functions to read and write endian specific data. |
10 | // |
11 | //===----------------------------------------------------------------------===// |
12 | |
13 | #ifndef LLVM_SUPPORT_ENDIAN_H |
14 | #define LLVM_SUPPORT_ENDIAN_H |
15 | |
16 | #include "llvm/Support/AlignOf.h" |
17 | #include "llvm/Support/Compiler.h" |
18 | #include "llvm/Support/Host.h" |
19 | #include "llvm/Support/SwapByteOrder.h" |
20 | #include <cassert> |
21 | #include <cstddef> |
22 | #include <cstdint> |
23 | #include <cstring> |
24 | #include <type_traits> |
25 | |
26 | namespace llvm { |
27 | namespace support { |
28 | |
29 | enum endianness {big, little, native}; |
30 | |
31 | // These are named values for common alignments. |
32 | enum {aligned = 0, unaligned = 1}; |
33 | |
34 | namespace detail { |
35 | |
36 | /// ::value is either alignment, or alignof(T) if alignment is 0. |
37 | template<class T, int alignment> |
38 | struct PickAlignment { |
39 | enum { value = alignment == 0 ? alignof(T) : alignment }; |
40 | }; |
41 | |
42 | } // end namespace detail |
43 | |
44 | namespace endian { |
45 | |
46 | constexpr endianness system_endianness() { |
47 | return sys::IsBigEndianHost ? big : little; |
48 | } |
49 | |
50 | template <typename value_type> |
51 | inline value_type byte_swap(value_type value, endianness endian) { |
52 | if ((endian != native) && (endian != system_endianness())) |
53 | sys::swapByteOrder(value); |
54 | return value; |
55 | } |
56 | |
57 | /// Swap the bytes of value to match the given endianness. |
58 | template<typename value_type, endianness endian> |
59 | inline value_type byte_swap(value_type value) { |
60 | return byte_swap(value, endian); |
61 | } |
62 | |
63 | /// Read a value of a particular endianness from memory. |
64 | template <typename value_type, std::size_t alignment> |
65 | inline value_type read(const void *memory, endianness endian) { |
66 | value_type ret; |
67 | |
68 | memcpy(&ret, |
69 | LLVM_ASSUME_ALIGNED(__builtin_assume_aligned(memory, (detail::PickAlignment<value_type , alignment>::value)) |
70 | memory, (detail::PickAlignment<value_type, alignment>::value))__builtin_assume_aligned(memory, (detail::PickAlignment<value_type , alignment>::value)), |
71 | sizeof(value_type)); |
72 | return byte_swap<value_type>(ret, endian); |
73 | } |
74 | |
75 | template<typename value_type, |
76 | endianness endian, |
77 | std::size_t alignment> |
78 | inline value_type read(const void *memory) { |
79 | return read<value_type, alignment>(memory, endian); |
80 | } |
81 | |
82 | /// Read a value of a particular endianness from a buffer, and increment the |
83 | /// buffer past that value. |
84 | template <typename value_type, std::size_t alignment, typename CharT> |
85 | inline value_type readNext(const CharT *&memory, endianness endian) { |
86 | value_type ret = read<value_type, alignment>(memory, endian); |
87 | memory += sizeof(value_type); |
88 | return ret; |
89 | } |
90 | |
91 | template<typename value_type, endianness endian, std::size_t alignment, |
92 | typename CharT> |
93 | inline value_type readNext(const CharT *&memory) { |
94 | return readNext<value_type, alignment, CharT>(memory, endian); |
95 | } |
96 | |
97 | /// Write a value to memory with a particular endianness. |
98 | template <typename value_type, std::size_t alignment> |
99 | inline void write(void *memory, value_type value, endianness endian) { |
100 | value = byte_swap<value_type>(value, endian); |
101 | memcpy(LLVM_ASSUME_ALIGNED(__builtin_assume_aligned(memory, (detail::PickAlignment<value_type , alignment>::value)) |
102 | memory, (detail::PickAlignment<value_type, alignment>::value))__builtin_assume_aligned(memory, (detail::PickAlignment<value_type , alignment>::value)), |
103 | &value, sizeof(value_type)); |
104 | } |
105 | |
106 | template<typename value_type, |
107 | endianness endian, |
108 | std::size_t alignment> |
109 | inline void write(void *memory, value_type value) { |
110 | write<value_type, alignment>(memory, value, endian); |
111 | } |
112 | |
113 | template <typename value_type> |
114 | using make_unsigned_t = std::make_unsigned_t<value_type>; |
115 | |
116 | /// Read a value of a particular endianness from memory, for a location |
117 | /// that starts at the given bit offset within the first byte. |
118 | template <typename value_type, endianness endian, std::size_t alignment> |
119 | inline value_type readAtBitAlignment(const void *memory, uint64_t startBit) { |
120 | assert(startBit < 8)((startBit < 8) ? static_cast<void> (0) : __assert_fail ("startBit < 8", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/Endian.h" , 120, __PRETTY_FUNCTION__)); |
121 | if (startBit == 0) |
122 | return read<value_type, endian, alignment>(memory); |
123 | else { |
124 | // Read two values and compose the result from them. |
125 | value_type val[2]; |
126 | memcpy(&val[0], |
127 | LLVM_ASSUME_ALIGNED(__builtin_assume_aligned(memory, (detail::PickAlignment<value_type , alignment>::value)) |
128 | memory, (detail::PickAlignment<value_type, alignment>::value))__builtin_assume_aligned(memory, (detail::PickAlignment<value_type , alignment>::value)), |
129 | sizeof(value_type) * 2); |
130 | val[0] = byte_swap<value_type, endian>(val[0]); |
131 | val[1] = byte_swap<value_type, endian>(val[1]); |
132 | |
133 | // Shift bits from the lower value into place. |
134 | make_unsigned_t<value_type> lowerVal = val[0] >> startBit; |
135 | // Mask off upper bits after right shift in case of signed type. |
136 | make_unsigned_t<value_type> numBitsFirstVal = |
137 | (sizeof(value_type) * 8) - startBit; |
138 | lowerVal &= ((make_unsigned_t<value_type>)1 << numBitsFirstVal) - 1; |
139 | |
140 | // Get the bits from the upper value. |
141 | make_unsigned_t<value_type> upperVal = |
142 | val[1] & (((make_unsigned_t<value_type>)1 << startBit) - 1); |
143 | // Shift them in to place. |
144 | upperVal <<= numBitsFirstVal; |
145 | |
146 | return lowerVal | upperVal; |
147 | } |
148 | } |
149 | |
150 | /// Write a value to memory with a particular endianness, for a location |
151 | /// that starts at the given bit offset within the first byte. |
152 | template <typename value_type, endianness endian, std::size_t alignment> |
153 | inline void writeAtBitAlignment(void *memory, value_type value, |
154 | uint64_t startBit) { |
155 | assert(startBit < 8)((startBit < 8) ? static_cast<void> (0) : __assert_fail ("startBit < 8", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/Endian.h" , 155, __PRETTY_FUNCTION__)); |
156 | if (startBit == 0) |
157 | write<value_type, endian, alignment>(memory, value); |
158 | else { |
159 | // Read two values and shift the result into them. |
160 | value_type val[2]; |
161 | memcpy(&val[0], |
162 | LLVM_ASSUME_ALIGNED(__builtin_assume_aligned(memory, (detail::PickAlignment<value_type , alignment>::value)) |
163 | memory, (detail::PickAlignment<value_type, alignment>::value))__builtin_assume_aligned(memory, (detail::PickAlignment<value_type , alignment>::value)), |
164 | sizeof(value_type) * 2); |
165 | val[0] = byte_swap<value_type, endian>(val[0]); |
166 | val[1] = byte_swap<value_type, endian>(val[1]); |
167 | |
168 | // Mask off any existing bits in the upper part of the lower value that |
169 | // we want to replace. |
170 | val[0] &= ((make_unsigned_t<value_type>)1 << startBit) - 1; |
171 | make_unsigned_t<value_type> numBitsFirstVal = |
172 | (sizeof(value_type) * 8) - startBit; |
173 | make_unsigned_t<value_type> lowerVal = value; |
174 | if (startBit > 0) { |
175 | // Mask off the upper bits in the new value that are not going to go into |
176 | // the lower value. This avoids a left shift of a negative value, which |
177 | // is undefined behavior. |
178 | lowerVal &= (((make_unsigned_t<value_type>)1 << numBitsFirstVal) - 1); |
179 | // Now shift the new bits into place |
180 | lowerVal <<= startBit; |
181 | } |
182 | val[0] |= lowerVal; |
183 | |
184 | // Mask off any existing bits in the lower part of the upper value that |
185 | // we want to replace. |
186 | val[1] &= ~(((make_unsigned_t<value_type>)1 << startBit) - 1); |
187 | // Next shift the bits that go into the upper value into position. |
188 | make_unsigned_t<value_type> upperVal = value >> numBitsFirstVal; |
189 | // Mask off upper bits after right shift in case of signed type. |
190 | upperVal &= ((make_unsigned_t<value_type>)1 << startBit) - 1; |
191 | val[1] |= upperVal; |
192 | |
193 | // Finally, rewrite values. |
194 | val[0] = byte_swap<value_type, endian>(val[0]); |
195 | val[1] = byte_swap<value_type, endian>(val[1]); |
196 | memcpy(LLVM_ASSUME_ALIGNED(__builtin_assume_aligned(memory, (detail::PickAlignment<value_type , alignment>::value)) |
197 | memory, (detail::PickAlignment<value_type, alignment>::value))__builtin_assume_aligned(memory, (detail::PickAlignment<value_type , alignment>::value)), |
198 | &val[0], sizeof(value_type) * 2); |
199 | } |
200 | } |
201 | |
202 | } // end namespace endian |
203 | |
204 | namespace detail { |
205 | |
206 | template <typename ValueType, endianness Endian, std::size_t Alignment, |
207 | std::size_t ALIGN = PickAlignment<ValueType, Alignment>::value> |
208 | struct packed_endian_specific_integral { |
209 | using value_type = ValueType; |
210 | static constexpr endianness endian = Endian; |
211 | static constexpr std::size_t alignment = Alignment; |
212 | |
213 | packed_endian_specific_integral() = default; |
214 | |
215 | explicit packed_endian_specific_integral(value_type val) { *this = val; } |
216 | |
217 | operator value_type() const { |
218 | return endian::read<value_type, endian, alignment>( |
219 | (const void*)Value.buffer); |
220 | } |
221 | |
222 | void operator=(value_type newValue) { |
223 | endian::write<value_type, endian, alignment>( |
224 | (void*)Value.buffer, newValue); |
225 | } |
226 | |
227 | packed_endian_specific_integral &operator+=(value_type newValue) { |
228 | *this = *this + newValue; |
229 | return *this; |
230 | } |
231 | |
232 | packed_endian_specific_integral &operator-=(value_type newValue) { |
233 | *this = *this - newValue; |
234 | return *this; |
235 | } |
236 | |
237 | packed_endian_specific_integral &operator|=(value_type newValue) { |
238 | *this = *this | newValue; |
239 | return *this; |
240 | } |
241 | |
242 | packed_endian_specific_integral &operator&=(value_type newValue) { |
243 | *this = *this & newValue; |
244 | return *this; |
245 | } |
246 | |
247 | private: |
248 | struct { |
249 | alignas(ALIGN) char buffer[sizeof(value_type)]; |
250 | } Value; |
251 | |
252 | public: |
253 | struct ref { |
254 | explicit ref(void *Ptr) : Ptr(Ptr) {} |
255 | |
256 | operator value_type() const { |
257 | return endian::read<value_type, endian, alignment>(Ptr); |
258 | } |
259 | |
260 | void operator=(value_type NewValue) { |
261 | endian::write<value_type, endian, alignment>(Ptr, NewValue); |
262 | } |
263 | |
264 | private: |
265 | void *Ptr; |
266 | }; |
267 | }; |
268 | |
269 | } // end namespace detail |
270 | |
271 | using ulittle16_t = |
272 | detail::packed_endian_specific_integral<uint16_t, little, unaligned>; |
273 | using ulittle32_t = |
274 | detail::packed_endian_specific_integral<uint32_t, little, unaligned>; |
275 | using ulittle64_t = |
276 | detail::packed_endian_specific_integral<uint64_t, little, unaligned>; |
277 | |
278 | using little16_t = |
279 | detail::packed_endian_specific_integral<int16_t, little, unaligned>; |
280 | using little32_t = |
281 | detail::packed_endian_specific_integral<int32_t, little, unaligned>; |
282 | using little64_t = |
283 | detail::packed_endian_specific_integral<int64_t, little, unaligned>; |
284 | |
285 | using aligned_ulittle16_t = |
286 | detail::packed_endian_specific_integral<uint16_t, little, aligned>; |
287 | using aligned_ulittle32_t = |
288 | detail::packed_endian_specific_integral<uint32_t, little, aligned>; |
289 | using aligned_ulittle64_t = |
290 | detail::packed_endian_specific_integral<uint64_t, little, aligned>; |
291 | |
292 | using aligned_little16_t = |
293 | detail::packed_endian_specific_integral<int16_t, little, aligned>; |
294 | using aligned_little32_t = |
295 | detail::packed_endian_specific_integral<int32_t, little, aligned>; |
296 | using aligned_little64_t = |
297 | detail::packed_endian_specific_integral<int64_t, little, aligned>; |
298 | |
299 | using ubig16_t = |
300 | detail::packed_endian_specific_integral<uint16_t, big, unaligned>; |
301 | using ubig32_t = |
302 | detail::packed_endian_specific_integral<uint32_t, big, unaligned>; |
303 | using ubig64_t = |
304 | detail::packed_endian_specific_integral<uint64_t, big, unaligned>; |
305 | |
306 | using big16_t = |
307 | detail::packed_endian_specific_integral<int16_t, big, unaligned>; |
308 | using big32_t = |
309 | detail::packed_endian_specific_integral<int32_t, big, unaligned>; |
310 | using big64_t = |
311 | detail::packed_endian_specific_integral<int64_t, big, unaligned>; |
312 | |
313 | using aligned_ubig16_t = |
314 | detail::packed_endian_specific_integral<uint16_t, big, aligned>; |
315 | using aligned_ubig32_t = |
316 | detail::packed_endian_specific_integral<uint32_t, big, aligned>; |
317 | using aligned_ubig64_t = |
318 | detail::packed_endian_specific_integral<uint64_t, big, aligned>; |
319 | |
320 | using aligned_big16_t = |
321 | detail::packed_endian_specific_integral<int16_t, big, aligned>; |
322 | using aligned_big32_t = |
323 | detail::packed_endian_specific_integral<int32_t, big, aligned>; |
324 | using aligned_big64_t = |
325 | detail::packed_endian_specific_integral<int64_t, big, aligned>; |
326 | |
327 | using unaligned_uint16_t = |
328 | detail::packed_endian_specific_integral<uint16_t, native, unaligned>; |
329 | using unaligned_uint32_t = |
330 | detail::packed_endian_specific_integral<uint32_t, native, unaligned>; |
331 | using unaligned_uint64_t = |
332 | detail::packed_endian_specific_integral<uint64_t, native, unaligned>; |
333 | |
334 | using unaligned_int16_t = |
335 | detail::packed_endian_specific_integral<int16_t, native, unaligned>; |
336 | using unaligned_int32_t = |
337 | detail::packed_endian_specific_integral<int32_t, native, unaligned>; |
338 | using unaligned_int64_t = |
339 | detail::packed_endian_specific_integral<int64_t, native, unaligned>; |
340 | |
341 | template <typename T> |
342 | using little_t = detail::packed_endian_specific_integral<T, little, unaligned>; |
343 | template <typename T> |
344 | using big_t = detail::packed_endian_specific_integral<T, big, unaligned>; |
345 | |
346 | template <typename T> |
347 | using aligned_little_t = |
348 | detail::packed_endian_specific_integral<T, little, aligned>; |
349 | template <typename T> |
350 | using aligned_big_t = detail::packed_endian_specific_integral<T, big, aligned>; |
351 | |
352 | namespace endian { |
353 | |
354 | template <typename T> inline T read(const void *P, endianness E) { |
355 | return read<T, unaligned>(P, E); |
356 | } |
357 | |
358 | template <typename T, endianness E> inline T read(const void *P) { |
359 | return *(const detail::packed_endian_specific_integral<T, E, unaligned> *)P; |
360 | } |
361 | |
362 | inline uint16_t read16(const void *P, endianness E) { |
363 | return read<uint16_t>(P, E); |
364 | } |
365 | inline uint32_t read32(const void *P, endianness E) { |
366 | return read<uint32_t>(P, E); |
367 | } |
368 | inline uint64_t read64(const void *P, endianness E) { |
369 | return read<uint64_t>(P, E); |
370 | } |
371 | |
372 | template <endianness E> inline uint16_t read16(const void *P) { |
373 | return read<uint16_t, E>(P); |
374 | } |
375 | template <endianness E> inline uint32_t read32(const void *P) { |
376 | return read<uint32_t, E>(P); |
377 | } |
378 | template <endianness E> inline uint64_t read64(const void *P) { |
379 | return read<uint64_t, E>(P); |
380 | } |
381 | |
382 | inline uint16_t read16le(const void *P) { return read16<little>(P); } |
383 | inline uint32_t read32le(const void *P) { return read32<little>(P); } |
384 | inline uint64_t read64le(const void *P) { return read64<little>(P); } |
385 | inline uint16_t read16be(const void *P) { return read16<big>(P); } |
386 | inline uint32_t read32be(const void *P) { return read32<big>(P); } |
387 | inline uint64_t read64be(const void *P) { return read64<big>(P); } |
388 | |
389 | template <typename T> inline void write(void *P, T V, endianness E) { |
390 | write<T, unaligned>(P, V, E); |
391 | } |
392 | |
393 | template <typename T, endianness E> inline void write(void *P, T V) { |
394 | *(detail::packed_endian_specific_integral<T, E, unaligned> *)P = V; |
395 | } |
396 | |
397 | inline void write16(void *P, uint16_t V, endianness E) { |
398 | write<uint16_t>(P, V, E); |
399 | } |
400 | inline void write32(void *P, uint32_t V, endianness E) { |
401 | write<uint32_t>(P, V, E); |
402 | } |
403 | inline void write64(void *P, uint64_t V, endianness E) { |
404 | write<uint64_t>(P, V, E); |
405 | } |
406 | |
407 | template <endianness E> inline void write16(void *P, uint16_t V) { |
408 | write<uint16_t, E>(P, V); |
409 | } |
410 | template <endianness E> inline void write32(void *P, uint32_t V) { |
411 | write<uint32_t, E>(P, V); |
412 | } |
413 | template <endianness E> inline void write64(void *P, uint64_t V) { |
414 | write<uint64_t, E>(P, V); |
415 | } |
416 | |
417 | inline void write16le(void *P, uint16_t V) { write16<little>(P, V); } |
418 | inline void write32le(void *P, uint32_t V) { write32<little>(P, V); } |
419 | inline void write64le(void *P, uint64_t V) { write64<little>(P, V); } |
420 | inline void write16be(void *P, uint16_t V) { write16<big>(P, V); } |
421 | inline void write32be(void *P, uint32_t V) { write32<big>(P, V); } |
422 | inline void write64be(void *P, uint64_t V) { write64<big>(P, V); } |
423 | |
424 | } // end namespace endian |
425 | |
426 | } // end namespace support |
427 | } // end namespace llvm |
428 | |
429 | #endif // LLVM_SUPPORT_ENDIAN_H |
1 | //===- llvm/Support/Error.h - Recoverable error handling --------*- C++ -*-===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // |
9 | // This file defines an API used to report recoverable errors. |
10 | // |
11 | //===----------------------------------------------------------------------===// |
12 | |
13 | #ifndef LLVM_SUPPORT_ERROR_H |
14 | #define LLVM_SUPPORT_ERROR_H |
15 | |
16 | #include "llvm-c/Error.h" |
17 | #include "llvm/ADT/STLExtras.h" |
18 | #include "llvm/ADT/SmallVector.h" |
19 | #include "llvm/ADT/StringExtras.h" |
20 | #include "llvm/ADT/Twine.h" |
21 | #include "llvm/Config/abi-breaking.h" |
22 | #include "llvm/Support/AlignOf.h" |
23 | #include "llvm/Support/Compiler.h" |
24 | #include "llvm/Support/Debug.h" |
25 | #include "llvm/Support/ErrorHandling.h" |
26 | #include "llvm/Support/ErrorOr.h" |
27 | #include "llvm/Support/Format.h" |
28 | #include "llvm/Support/raw_ostream.h" |
29 | #include <algorithm> |
30 | #include <cassert> |
31 | #include <cstdint> |
32 | #include <cstdlib> |
33 | #include <functional> |
34 | #include <memory> |
35 | #include <new> |
36 | #include <string> |
37 | #include <system_error> |
38 | #include <type_traits> |
39 | #include <utility> |
40 | #include <vector> |
41 | |
42 | namespace llvm { |
43 | |
44 | class ErrorSuccess; |
45 | |
46 | /// Base class for error info classes. Do not extend this directly: Extend |
47 | /// the ErrorInfo template subclass instead. |
48 | class ErrorInfoBase { |
49 | public: |
50 | virtual ~ErrorInfoBase() = default; |
51 | |
52 | /// Print an error message to an output stream. |
53 | virtual void log(raw_ostream &OS) const = 0; |
54 | |
55 | /// Return the error message as a string. |
56 | virtual std::string message() const { |
57 | std::string Msg; |
58 | raw_string_ostream OS(Msg); |
59 | log(OS); |
60 | return OS.str(); |
61 | } |
62 | |
63 | /// Convert this error to a std::error_code. |
64 | /// |
65 | /// This is a temporary crutch to enable interaction with code still |
66 | /// using std::error_code. It will be removed in the future. |
67 | virtual std::error_code convertToErrorCode() const = 0; |
68 | |
69 | // Returns the class ID for this type. |
70 | static const void *classID() { return &ID; } |
71 | |
72 | // Returns the class ID for the dynamic type of this ErrorInfoBase instance. |
73 | virtual const void *dynamicClassID() const = 0; |
74 | |
75 | // Check whether this instance is a subclass of the class identified by |
76 | // ClassID. |
77 | virtual bool isA(const void *const ClassID) const { |
78 | return ClassID == classID(); |
79 | } |
80 | |
81 | // Check whether this instance is a subclass of ErrorInfoT. |
82 | template <typename ErrorInfoT> bool isA() const { |
83 | return isA(ErrorInfoT::classID()); |
84 | } |
85 | |
86 | private: |
87 | virtual void anchor(); |
88 | |
89 | static char ID; |
90 | }; |
91 | |
92 | /// Lightweight error class with error context and mandatory checking. |
93 | /// |
94 | /// Instances of this class wrap a ErrorInfoBase pointer. Failure states |
95 | /// are represented by setting the pointer to a ErrorInfoBase subclass |
96 | /// instance containing information describing the failure. Success is |
97 | /// represented by a null pointer value. |
98 | /// |
99 | /// Instances of Error also contains a 'Checked' flag, which must be set |
100 | /// before the destructor is called, otherwise the destructor will trigger a |
101 | /// runtime error. This enforces at runtime the requirement that all Error |
102 | /// instances be checked or returned to the caller. |
103 | /// |
104 | /// There are two ways to set the checked flag, depending on what state the |
105 | /// Error instance is in. For Error instances indicating success, it |
106 | /// is sufficient to invoke the boolean conversion operator. E.g.: |
107 | /// |
108 | /// @code{.cpp} |
109 | /// Error foo(<...>); |
110 | /// |
111 | /// if (auto E = foo(<...>)) |
112 | /// return E; // <- Return E if it is in the error state. |
113 | /// // We have verified that E was in the success state. It can now be safely |
114 | /// // destroyed. |
115 | /// @endcode |
116 | /// |
117 | /// A success value *can not* be dropped. For example, just calling 'foo(<...>)' |
118 | /// without testing the return value will raise a runtime error, even if foo |
119 | /// returns success. |
120 | /// |
121 | /// For Error instances representing failure, you must use either the |
122 | /// handleErrors or handleAllErrors function with a typed handler. E.g.: |
123 | /// |
124 | /// @code{.cpp} |
125 | /// class MyErrorInfo : public ErrorInfo<MyErrorInfo> { |
126 | /// // Custom error info. |
127 | /// }; |
128 | /// |
129 | /// Error foo(<...>) { return make_error<MyErrorInfo>(...); } |
130 | /// |
131 | /// auto E = foo(<...>); // <- foo returns failure with MyErrorInfo. |
132 | /// auto NewE = |
133 | /// handleErrors(E, |
134 | /// [](const MyErrorInfo &M) { |
135 | /// // Deal with the error. |
136 | /// }, |
137 | /// [](std::unique_ptr<OtherError> M) -> Error { |
138 | /// if (canHandle(*M)) { |
139 | /// // handle error. |
140 | /// return Error::success(); |
141 | /// } |
142 | /// // Couldn't handle this error instance. Pass it up the stack. |
143 | /// return Error(std::move(M)); |
144 | /// ); |
145 | /// // Note - we must check or return NewE in case any of the handlers |
146 | /// // returned a new error. |
147 | /// @endcode |
148 | /// |
149 | /// The handleAllErrors function is identical to handleErrors, except |
150 | /// that it has a void return type, and requires all errors to be handled and |
151 | /// no new errors be returned. It prevents errors (assuming they can all be |
152 | /// handled) from having to be bubbled all the way to the top-level. |
153 | /// |
154 | /// *All* Error instances must be checked before destruction, even if |
155 | /// they're moved-assigned or constructed from Success values that have already |
156 | /// been checked. This enforces checking through all levels of the call stack. |
157 | class LLVM_NODISCARD[[clang::warn_unused_result]] Error { |
158 | // ErrorList needs to be able to yank ErrorInfoBase pointers out of Errors |
159 | // to add to the error list. It can't rely on handleErrors for this, since |
160 | // handleErrors does not support ErrorList handlers. |
161 | friend class ErrorList; |
162 | |
163 | // handleErrors needs to be able to set the Checked flag. |
164 | template <typename... HandlerTs> |
165 | friend Error handleErrors(Error E, HandlerTs &&... Handlers); |
166 | |
167 | // Expected<T> needs to be able to steal the payload when constructed from an |
168 | // error. |
169 | template <typename T> friend class Expected; |
170 | |
171 | // wrap needs to be able to steal the payload. |
172 | friend LLVMErrorRef wrap(Error); |
173 | |
174 | protected: |
175 | /// Create a success value. Prefer using 'Error::success()' for readability |
176 | Error() { |
177 | setPtr(nullptr); |
178 | setChecked(false); |
179 | } |
180 | |
181 | public: |
182 | /// Create a success value. |
183 | static ErrorSuccess success(); |
184 | |
185 | // Errors are not copy-constructable. |
186 | Error(const Error &Other) = delete; |
187 | |
188 | /// Move-construct an error value. The newly constructed error is considered |
189 | /// unchecked, even if the source error had been checked. The original error |
190 | /// becomes a checked Success value, regardless of its original state. |
191 | Error(Error &&Other) { |
192 | setChecked(true); |
193 | *this = std::move(Other); |
194 | } |
195 | |
196 | /// Create an error value. Prefer using the 'make_error' function, but |
197 | /// this constructor can be useful when "re-throwing" errors from handlers. |
198 | Error(std::unique_ptr<ErrorInfoBase> Payload) { |
199 | setPtr(Payload.release()); |
200 | setChecked(false); |
201 | } |
202 | |
203 | // Errors are not copy-assignable. |
204 | Error &operator=(const Error &Other) = delete; |
205 | |
206 | /// Move-assign an error value. The current error must represent success, you |
207 | /// you cannot overwrite an unhandled error. The current error is then |
208 | /// considered unchecked. The source error becomes a checked success value, |
209 | /// regardless of its original state. |
210 | Error &operator=(Error &&Other) { |
211 | // Don't allow overwriting of unchecked values. |
212 | assertIsChecked(); |
213 | setPtr(Other.getPtr()); |
214 | |
215 | // This Error is unchecked, even if the source error was checked. |
216 | setChecked(false); |
217 | |
218 | // Null out Other's payload and set its checked bit. |
219 | Other.setPtr(nullptr); |
220 | Other.setChecked(true); |
221 | |
222 | return *this; |
223 | } |
224 | |
225 | /// Destroy a Error. Fails with a call to abort() if the error is |
226 | /// unchecked. |
227 | ~Error() { |
228 | assertIsChecked(); |
229 | delete getPtr(); |
230 | } |
231 | |
232 | /// Bool conversion. Returns true if this Error is in a failure state, |
233 | /// and false if it is in an accept state. If the error is in a Success state |
234 | /// it will be considered checked. |
235 | explicit operator bool() { |
236 | setChecked(getPtr() == nullptr); |
237 | return getPtr() != nullptr; |
238 | } |
239 | |
240 | /// Check whether one error is a subclass of another. |
241 | template <typename ErrT> bool isA() const { |
242 | return getPtr() && getPtr()->isA(ErrT::classID()); |
243 | } |
244 | |
245 | /// Returns the dynamic class id of this error, or null if this is a success |
246 | /// value. |
247 | const void* dynamicClassID() const { |
248 | if (!getPtr()) |
249 | return nullptr; |
250 | return getPtr()->dynamicClassID(); |
251 | } |
252 | |
253 | private: |
254 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
255 | // assertIsChecked() happens very frequently, but under normal circumstances |
256 | // is supposed to be a no-op. So we want it to be inlined, but having a bunch |
257 | // of debug prints can cause the function to be too large for inlining. So |
258 | // it's important that we define this function out of line so that it can't be |
259 | // inlined. |
260 | LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) |
261 | void fatalUncheckedError() const; |
262 | #endif |
263 | |
264 | void assertIsChecked() { |
265 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
266 | if (LLVM_UNLIKELY(!getChecked() || getPtr())__builtin_expect((bool)(!getChecked() || getPtr()), false)) |
267 | fatalUncheckedError(); |
268 | #endif |
269 | } |
270 | |
271 | ErrorInfoBase *getPtr() const { |
272 | return reinterpret_cast<ErrorInfoBase*>( |
273 | reinterpret_cast<uintptr_t>(Payload) & |
274 | ~static_cast<uintptr_t>(0x1)); |
275 | } |
276 | |
277 | void setPtr(ErrorInfoBase *EI) { |
278 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
279 | Payload = reinterpret_cast<ErrorInfoBase*>( |
280 | (reinterpret_cast<uintptr_t>(EI) & |
281 | ~static_cast<uintptr_t>(0x1)) | |
282 | (reinterpret_cast<uintptr_t>(Payload) & 0x1)); |
283 | #else |
284 | Payload = EI; |
285 | #endif |
286 | } |
287 | |
288 | bool getChecked() const { |
289 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
290 | return (reinterpret_cast<uintptr_t>(Payload) & 0x1) == 0; |
291 | #else |
292 | return true; |
293 | #endif |
294 | } |
295 | |
296 | void setChecked(bool V) { |
297 | Payload = reinterpret_cast<ErrorInfoBase*>( |
298 | (reinterpret_cast<uintptr_t>(Payload) & |
299 | ~static_cast<uintptr_t>(0x1)) | |
300 | (V ? 0 : 1)); |
301 | } |
302 | |
303 | std::unique_ptr<ErrorInfoBase> takePayload() { |
304 | std::unique_ptr<ErrorInfoBase> Tmp(getPtr()); |
305 | setPtr(nullptr); |
306 | setChecked(true); |
307 | return Tmp; |
308 | } |
309 | |
310 | friend raw_ostream &operator<<(raw_ostream &OS, const Error &E) { |
311 | if (auto P = E.getPtr()) |
312 | P->log(OS); |
313 | else |
314 | OS << "success"; |
315 | return OS; |
316 | } |
317 | |
318 | ErrorInfoBase *Payload = nullptr; |
319 | }; |
320 | |
321 | /// Subclass of Error for the sole purpose of identifying the success path in |
322 | /// the type system. This allows to catch invalid conversion to Expected<T> at |
323 | /// compile time. |
324 | class ErrorSuccess final : public Error {}; |
325 | |
326 | inline ErrorSuccess Error::success() { return ErrorSuccess(); } |
327 | |
328 | /// Make a Error instance representing failure using the given error info |
329 | /// type. |
330 | template <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) { |
331 | return Error(std::make_unique<ErrT>(std::forward<ArgTs>(Args)...)); |
332 | } |
333 | |
334 | /// Base class for user error types. Users should declare their error types |
335 | /// like: |
336 | /// |
337 | /// class MyError : public ErrorInfo<MyError> { |
338 | /// .... |
339 | /// }; |
340 | /// |
341 | /// This class provides an implementation of the ErrorInfoBase::kind |
342 | /// method, which is used by the Error RTTI system. |
343 | template <typename ThisErrT, typename ParentErrT = ErrorInfoBase> |
344 | class ErrorInfo : public ParentErrT { |
345 | public: |
346 | using ParentErrT::ParentErrT; // inherit constructors |
347 | |
348 | static const void *classID() { return &ThisErrT::ID; } |
349 | |
350 | const void *dynamicClassID() const override { return &ThisErrT::ID; } |
351 | |
352 | bool isA(const void *const ClassID) const override { |
353 | return ClassID == classID() || ParentErrT::isA(ClassID); |
354 | } |
355 | }; |
356 | |
357 | /// Special ErrorInfo subclass representing a list of ErrorInfos. |
358 | /// Instances of this class are constructed by joinError. |
359 | class ErrorList final : public ErrorInfo<ErrorList> { |
360 | // handleErrors needs to be able to iterate the payload list of an |
361 | // ErrorList. |
362 | template <typename... HandlerTs> |
363 | friend Error handleErrors(Error E, HandlerTs &&... Handlers); |
364 | |
365 | // joinErrors is implemented in terms of join. |
366 | friend Error joinErrors(Error, Error); |
367 | |
368 | public: |
369 | void log(raw_ostream &OS) const override { |
370 | OS << "Multiple errors:\n"; |
371 | for (auto &ErrPayload : Payloads) { |
372 | ErrPayload->log(OS); |
373 | OS << "\n"; |
374 | } |
375 | } |
376 | |
377 | std::error_code convertToErrorCode() const override; |
378 | |
379 | // Used by ErrorInfo::classID. |
380 | static char ID; |
381 | |
382 | private: |
383 | ErrorList(std::unique_ptr<ErrorInfoBase> Payload1, |
384 | std::unique_ptr<ErrorInfoBase> Payload2) { |
385 | assert(!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() &&((!Payload1->isA<ErrorList>() && !Payload2-> isA<ErrorList>() && "ErrorList constructor payloads should be singleton errors" ) ? static_cast<void> (0) : __assert_fail ("!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() && \"ErrorList constructor payloads should be singleton errors\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/Error.h" , 386, __PRETTY_FUNCTION__)) |
386 | "ErrorList constructor payloads should be singleton errors")((!Payload1->isA<ErrorList>() && !Payload2-> isA<ErrorList>() && "ErrorList constructor payloads should be singleton errors" ) ? static_cast<void> (0) : __assert_fail ("!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() && \"ErrorList constructor payloads should be singleton errors\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/Error.h" , 386, __PRETTY_FUNCTION__)); |
387 | Payloads.push_back(std::move(Payload1)); |
388 | Payloads.push_back(std::move(Payload2)); |
389 | } |
390 | |
391 | static Error join(Error E1, Error E2) { |
392 | if (!E1) |
393 | return E2; |
394 | if (!E2) |
395 | return E1; |
396 | if (E1.isA<ErrorList>()) { |
397 | auto &E1List = static_cast<ErrorList &>(*E1.getPtr()); |
398 | if (E2.isA<ErrorList>()) { |
399 | auto E2Payload = E2.takePayload(); |
400 | auto &E2List = static_cast<ErrorList &>(*E2Payload); |
401 | for (auto &Payload : E2List.Payloads) |
402 | E1List.Payloads.push_back(std::move(Payload)); |
403 | } else |
404 | E1List.Payloads.push_back(E2.takePayload()); |
405 | |
406 | return E1; |
407 | } |
408 | if (E2.isA<ErrorList>()) { |
409 | auto &E2List = static_cast<ErrorList &>(*E2.getPtr()); |
410 | E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload()); |
411 | return E2; |
412 | } |
413 | return Error(std::unique_ptr<ErrorList>( |
414 | new ErrorList(E1.takePayload(), E2.takePayload()))); |
415 | } |
416 | |
417 | std::vector<std::unique_ptr<ErrorInfoBase>> Payloads; |
418 | }; |
419 | |
420 | /// Concatenate errors. The resulting Error is unchecked, and contains the |
421 | /// ErrorInfo(s), if any, contained in E1, followed by the |
422 | /// ErrorInfo(s), if any, contained in E2. |
423 | inline Error joinErrors(Error E1, Error E2) { |
424 | return ErrorList::join(std::move(E1), std::move(E2)); |
425 | } |
426 | |
427 | /// Tagged union holding either a T or a Error. |
428 | /// |
429 | /// This class parallels ErrorOr, but replaces error_code with Error. Since |
430 | /// Error cannot be copied, this class replaces getError() with |
431 | /// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the |
432 | /// error class type. |
433 | template <class T> class LLVM_NODISCARD[[clang::warn_unused_result]] Expected { |
434 | template <class T1> friend class ExpectedAsOutParameter; |
435 | template <class OtherT> friend class Expected; |
436 | |
437 | static const bool isRef = std::is_reference<T>::value; |
438 | |
439 | using wrap = std::reference_wrapper<std::remove_reference_t<T>>; |
440 | |
441 | using error_type = std::unique_ptr<ErrorInfoBase>; |
442 | |
443 | public: |
444 | using storage_type = std::conditional_t<isRef, wrap, T>; |
445 | using value_type = T; |
446 | |
447 | private: |
448 | using reference = std::remove_reference_t<T> &; |
449 | using const_reference = const std::remove_reference_t<T> &; |
450 | using pointer = std::remove_reference_t<T> *; |
451 | using const_pointer = const std::remove_reference_t<T> *; |
452 | |
453 | public: |
454 | /// Create an Expected<T> error value from the given Error. |
455 | Expected(Error Err) |
456 | : HasError(true) |
457 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
458 | // Expected is unchecked upon construction in Debug builds. |
459 | , Unchecked(true) |
460 | #endif |
461 | { |
462 | assert(Err && "Cannot create Expected<T> from Error success value.")((Err && "Cannot create Expected<T> from Error success value." ) ? static_cast<void> (0) : __assert_fail ("Err && \"Cannot create Expected<T> from Error success value.\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/Error.h" , 462, __PRETTY_FUNCTION__)); |
463 | new (getErrorStorage()) error_type(Err.takePayload()); |
464 | } |
465 | |
466 | /// Forbid to convert from Error::success() implicitly, this avoids having |
467 | /// Expected<T> foo() { return Error::success(); } which compiles otherwise |
468 | /// but triggers the assertion above. |
469 | Expected(ErrorSuccess) = delete; |
470 | |
471 | /// Create an Expected<T> success value from the given OtherT value, which |
472 | /// must be convertible to T. |
473 | template <typename OtherT> |
474 | Expected(OtherT &&Val, |
475 | std::enable_if_t<std::is_convertible<OtherT, T>::value> * = nullptr) |
476 | : HasError(false) |
477 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
478 | // Expected is unchecked upon construction in Debug builds. |
479 | , |
480 | Unchecked(true) |
481 | #endif |
482 | { |
483 | new (getStorage()) storage_type(std::forward<OtherT>(Val)); |
484 | } |
485 | |
486 | /// Move construct an Expected<T> value. |
487 | Expected(Expected &&Other) { moveConstruct(std::move(Other)); } |
488 | |
489 | /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT |
490 | /// must be convertible to T. |
491 | template <class OtherT> |
492 | Expected( |
493 | Expected<OtherT> &&Other, |
494 | std::enable_if_t<std::is_convertible<OtherT, T>::value> * = nullptr) { |
495 | moveConstruct(std::move(Other)); |
496 | } |
497 | |
498 | /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT |
499 | /// isn't convertible to T. |
500 | template <class OtherT> |
501 | explicit Expected( |
502 | Expected<OtherT> &&Other, |
503 | std::enable_if_t<!std::is_convertible<OtherT, T>::value> * = nullptr) { |
504 | moveConstruct(std::move(Other)); |
505 | } |
506 | |
507 | /// Move-assign from another Expected<T>. |
508 | Expected &operator=(Expected &&Other) { |
509 | moveAssign(std::move(Other)); |
510 | return *this; |
511 | } |
512 | |
513 | /// Destroy an Expected<T>. |
514 | ~Expected() { |
515 | assertIsChecked(); |
516 | if (!HasError) |
517 | getStorage()->~storage_type(); |
518 | else |
519 | getErrorStorage()->~error_type(); |
520 | } |
521 | |
522 | /// Return false if there is an error. |
523 | explicit operator bool() { |
524 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
525 | Unchecked = HasError; |
526 | #endif |
527 | return !HasError; |
528 | } |
529 | |
530 | /// Returns a reference to the stored T value. |
531 | reference get() { |
532 | assertIsChecked(); |
533 | return *getStorage(); |
534 | } |
535 | |
536 | /// Returns a const reference to the stored T value. |
537 | const_reference get() const { |
538 | assertIsChecked(); |
539 | return const_cast<Expected<T> *>(this)->get(); |
540 | } |
541 | |
542 | /// Check that this Expected<T> is an error of type ErrT. |
543 | template <typename ErrT> bool errorIsA() const { |
544 | return HasError && (*getErrorStorage())->template isA<ErrT>(); |
545 | } |
546 | |
547 | /// Take ownership of the stored error. |
548 | /// After calling this the Expected<T> is in an indeterminate state that can |
549 | /// only be safely destructed. No further calls (beside the destructor) should |
550 | /// be made on the Expected<T> value. |
551 | Error takeError() { |
552 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
553 | Unchecked = false; |
554 | #endif |
555 | return HasError ? Error(std::move(*getErrorStorage())) : Error::success(); |
556 | } |
557 | |
558 | /// Returns a pointer to the stored T value. |
559 | pointer operator->() { |
560 | assertIsChecked(); |
561 | return toPointer(getStorage()); |
562 | } |
563 | |
564 | /// Returns a const pointer to the stored T value. |
565 | const_pointer operator->() const { |
566 | assertIsChecked(); |
567 | return toPointer(getStorage()); |
568 | } |
569 | |
570 | /// Returns a reference to the stored T value. |
571 | reference operator*() { |
572 | assertIsChecked(); |
573 | return *getStorage(); |
574 | } |
575 | |
576 | /// Returns a const reference to the stored T value. |
577 | const_reference operator*() const { |
578 | assertIsChecked(); |
579 | return *getStorage(); |
580 | } |
581 | |
582 | private: |
583 | template <class T1> |
584 | static bool compareThisIfSameType(const T1 &a, const T1 &b) { |
585 | return &a == &b; |
586 | } |
587 | |
588 | template <class T1, class T2> |
589 | static bool compareThisIfSameType(const T1 &a, const T2 &b) { |
590 | return false; |
591 | } |
592 | |
593 | template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) { |
594 | HasError = Other.HasError; |
595 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
596 | Unchecked = true; |
597 | Other.Unchecked = false; |
598 | #endif |
599 | |
600 | if (!HasError) |
601 | new (getStorage()) storage_type(std::move(*Other.getStorage())); |
602 | else |
603 | new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage())); |
604 | } |
605 | |
606 | template <class OtherT> void moveAssign(Expected<OtherT> &&Other) { |
607 | assertIsChecked(); |
608 | |
609 | if (compareThisIfSameType(*this, Other)) |
610 | return; |
611 | |
612 | this->~Expected(); |
613 | new (this) Expected(std::move(Other)); |
614 | } |
615 | |
616 | pointer toPointer(pointer Val) { return Val; } |
617 | |
618 | const_pointer toPointer(const_pointer Val) const { return Val; } |
619 | |
620 | pointer toPointer(wrap *Val) { return &Val->get(); } |
621 | |
622 | const_pointer toPointer(const wrap *Val) const { return &Val->get(); } |
623 | |
624 | storage_type *getStorage() { |
625 | assert(!HasError && "Cannot get value when an error exists!")((!HasError && "Cannot get value when an error exists!" ) ? static_cast<void> (0) : __assert_fail ("!HasError && \"Cannot get value when an error exists!\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/Error.h" , 625, __PRETTY_FUNCTION__)); |
626 | return reinterpret_cast<storage_type *>(TStorage.buffer); |
627 | } |
628 | |
629 | const storage_type *getStorage() const { |
630 | assert(!HasError && "Cannot get value when an error exists!")((!HasError && "Cannot get value when an error exists!" ) ? static_cast<void> (0) : __assert_fail ("!HasError && \"Cannot get value when an error exists!\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/Error.h" , 630, __PRETTY_FUNCTION__)); |
631 | return reinterpret_cast<const storage_type *>(TStorage.buffer); |
632 | } |
633 | |
634 | error_type *getErrorStorage() { |
635 | assert(HasError && "Cannot get error when a value exists!")((HasError && "Cannot get error when a value exists!" ) ? static_cast<void> (0) : __assert_fail ("HasError && \"Cannot get error when a value exists!\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/Error.h" , 635, __PRETTY_FUNCTION__)); |
636 | return reinterpret_cast<error_type *>(ErrorStorage.buffer); |
637 | } |
638 | |
639 | const error_type *getErrorStorage() const { |
640 | assert(HasError && "Cannot get error when a value exists!")((HasError && "Cannot get error when a value exists!" ) ? static_cast<void> (0) : __assert_fail ("HasError && \"Cannot get error when a value exists!\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/Error.h" , 640, __PRETTY_FUNCTION__)); |
641 | return reinterpret_cast<const error_type *>(ErrorStorage.buffer); |
642 | } |
643 | |
644 | // Used by ExpectedAsOutParameter to reset the checked flag. |
645 | void setUnchecked() { |
646 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
647 | Unchecked = true; |
648 | #endif |
649 | } |
650 | |
651 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
652 | LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) |
653 | LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) |
654 | void fatalUncheckedExpected() const { |
655 | dbgs() << "Expected<T> must be checked before access or destruction.\n"; |
656 | if (HasError) { |
657 | dbgs() << "Unchecked Expected<T> contained error:\n"; |
658 | (*getErrorStorage())->log(dbgs()); |
659 | } else |
660 | dbgs() << "Expected<T> value was in success state. (Note: Expected<T> " |
661 | "values in success mode must still be checked prior to being " |
662 | "destroyed).\n"; |
663 | abort(); |
664 | } |
665 | #endif |
666 | |
667 | void assertIsChecked() { |
668 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
669 | if (LLVM_UNLIKELY(Unchecked)__builtin_expect((bool)(Unchecked), false)) |
670 | fatalUncheckedExpected(); |
671 | #endif |
672 | } |
673 | |
674 | union { |
675 | AlignedCharArrayUnion<storage_type> TStorage; |
676 | AlignedCharArrayUnion<error_type> ErrorStorage; |
677 | }; |
678 | bool HasError : 1; |
679 | #if LLVM_ENABLE_ABI_BREAKING_CHECKS1 |
680 | bool Unchecked : 1; |
681 | #endif |
682 | }; |
683 | |
684 | /// Report a serious error, calling any installed error handler. See |
685 | /// ErrorHandling.h. |
686 | LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) void report_fatal_error(Error Err, |
687 | bool gen_crash_diag = true); |
688 | |
689 | /// Report a fatal error if Err is a failure value. |
690 | /// |
691 | /// This function can be used to wrap calls to fallible functions ONLY when it |
692 | /// is known that the Error will always be a success value. E.g. |
693 | /// |
694 | /// @code{.cpp} |
695 | /// // foo only attempts the fallible operation if DoFallibleOperation is |
696 | /// // true. If DoFallibleOperation is false then foo always returns |
697 | /// // Error::success(). |
698 | /// Error foo(bool DoFallibleOperation); |
699 | /// |
700 | /// cantFail(foo(false)); |
701 | /// @endcode |
702 | inline void cantFail(Error Err, const char *Msg = nullptr) { |
703 | if (Err) { |
704 | if (!Msg) |
705 | Msg = "Failure value returned from cantFail wrapped call"; |
706 | #ifndef NDEBUG |
707 | std::string Str; |
708 | raw_string_ostream OS(Str); |
709 | OS << Msg << "\n" << Err; |
710 | Msg = OS.str().c_str(); |
711 | #endif |
712 | llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/Error.h" , 712); |
713 | } |
714 | } |
715 | |
716 | /// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and |
717 | /// returns the contained value. |
718 | /// |
719 | /// This function can be used to wrap calls to fallible functions ONLY when it |
720 | /// is known that the Error will always be a success value. E.g. |
721 | /// |
722 | /// @code{.cpp} |
723 | /// // foo only attempts the fallible operation if DoFallibleOperation is |
724 | /// // true. If DoFallibleOperation is false then foo always returns an int. |
725 | /// Expected<int> foo(bool DoFallibleOperation); |
726 | /// |
727 | /// int X = cantFail(foo(false)); |
728 | /// @endcode |
729 | template <typename T> |
730 | T cantFail(Expected<T> ValOrErr, const char *Msg = nullptr) { |
731 | if (ValOrErr) |
732 | return std::move(*ValOrErr); |
733 | else { |
734 | if (!Msg) |
735 | Msg = "Failure value returned from cantFail wrapped call"; |
736 | #ifndef NDEBUG |
737 | std::string Str; |
738 | raw_string_ostream OS(Str); |
739 | auto E = ValOrErr.takeError(); |
740 | OS << Msg << "\n" << E; |
741 | Msg = OS.str().c_str(); |
742 | #endif |
743 | llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/Error.h" , 743); |
744 | } |
745 | } |
746 | |
747 | /// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and |
748 | /// returns the contained reference. |
749 | /// |
750 | /// This function can be used to wrap calls to fallible functions ONLY when it |
751 | /// is known that the Error will always be a success value. E.g. |
752 | /// |
753 | /// @code{.cpp} |
754 | /// // foo only attempts the fallible operation if DoFallibleOperation is |
755 | /// // true. If DoFallibleOperation is false then foo always returns a Bar&. |
756 | /// Expected<Bar&> foo(bool DoFallibleOperation); |
757 | /// |
758 | /// Bar &X = cantFail(foo(false)); |
759 | /// @endcode |
760 | template <typename T> |
761 | T& cantFail(Expected<T&> ValOrErr, const char *Msg = nullptr) { |
762 | if (ValOrErr) |
763 | return *ValOrErr; |
764 | else { |
765 | if (!Msg) |
766 | Msg = "Failure value returned from cantFail wrapped call"; |
767 | #ifndef NDEBUG |
768 | std::string Str; |
769 | raw_string_ostream OS(Str); |
770 | auto E = ValOrErr.takeError(); |
771 | OS << Msg << "\n" << E; |
772 | Msg = OS.str().c_str(); |
773 | #endif |
774 | llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/Error.h" , 774); |
775 | } |
776 | } |
777 | |
778 | /// Helper for testing applicability of, and applying, handlers for |
779 | /// ErrorInfo types. |
780 | template <typename HandlerT> |
781 | class ErrorHandlerTraits |
782 | : public ErrorHandlerTraits<decltype( |
783 | &std::remove_reference<HandlerT>::type::operator())> {}; |
784 | |
785 | // Specialization functions of the form 'Error (const ErrT&)'. |
786 | template <typename ErrT> class ErrorHandlerTraits<Error (&)(ErrT &)> { |
787 | public: |
788 | static bool appliesTo(const ErrorInfoBase &E) { |
789 | return E.template isA<ErrT>(); |
790 | } |
791 | |
792 | template <typename HandlerT> |
793 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { |
794 | assert(appliesTo(*E) && "Applying incorrect handler")((appliesTo(*E) && "Applying incorrect handler") ? static_cast <void> (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/Error.h" , 794, __PRETTY_FUNCTION__)); |
795 | return H(static_cast<ErrT &>(*E)); |
796 | } |
797 | }; |
798 | |
799 | // Specialization functions of the form 'void (const ErrT&)'. |
800 | template <typename ErrT> class ErrorHandlerTraits<void (&)(ErrT &)> { |
801 | public: |
802 | static bool appliesTo(const ErrorInfoBase &E) { |
803 | return E.template isA<ErrT>(); |
804 | } |
805 | |
806 | template <typename HandlerT> |
807 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { |
808 | assert(appliesTo(*E) && "Applying incorrect handler")((appliesTo(*E) && "Applying incorrect handler") ? static_cast <void> (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/Error.h" , 808, __PRETTY_FUNCTION__)); |
809 | H(static_cast<ErrT &>(*E)); |
810 | return Error::success(); |
811 | } |
812 | }; |
813 | |
814 | /// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'. |
815 | template <typename ErrT> |
816 | class ErrorHandlerTraits<Error (&)(std::unique_ptr<ErrT>)> { |
817 | public: |
818 | static bool appliesTo(const ErrorInfoBase &E) { |
819 | return E.template isA<ErrT>(); |
820 | } |
821 | |
822 | template <typename HandlerT> |
823 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { |
824 | assert(appliesTo(*E) && "Applying incorrect handler")((appliesTo(*E) && "Applying incorrect handler") ? static_cast <void> (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/Error.h" , 824, __PRETTY_FUNCTION__)); |
825 | std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release())); |
826 | return H(std::move(SubE)); |
827 | } |
828 | }; |
829 | |
830 | /// Specialization for functions of the form 'void (std::unique_ptr<ErrT>)'. |
831 | template <typename ErrT> |
832 | class ErrorHandlerTraits<void (&)(std::unique_ptr<ErrT>)> { |
833 | public: |
834 | static bool appliesTo(const ErrorInfoBase &E) { |
835 | return E.template isA<ErrT>(); |
836 | } |
837 | |
838 | template <typename HandlerT> |
839 | static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) { |
840 | assert(appliesTo(*E) && "Applying incorrect handler")((appliesTo(*E) && "Applying incorrect handler") ? static_cast <void> (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/Error.h" , 840, __PRETTY_FUNCTION__)); |
841 | std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release())); |
842 | H(std::move(SubE)); |
843 | return Error::success(); |
844 | } |
845 | }; |
846 | |
847 | // Specialization for member functions of the form 'RetT (const ErrT&)'. |
848 | template <typename C, typename RetT, typename ErrT> |
849 | class ErrorHandlerTraits<RetT (C::*)(ErrT &)> |
850 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; |
851 | |
852 | // Specialization for member functions of the form 'RetT (const ErrT&) const'. |
853 | template <typename C, typename RetT, typename ErrT> |
854 | class ErrorHandlerTraits<RetT (C::*)(ErrT &) const> |
855 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; |
856 | |
857 | // Specialization for member functions of the form 'RetT (const ErrT&)'. |
858 | template <typename C, typename RetT, typename ErrT> |
859 | class ErrorHandlerTraits<RetT (C::*)(const ErrT &)> |
860 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; |
861 | |
862 | // Specialization for member functions of the form 'RetT (const ErrT&) const'. |
863 | template <typename C, typename RetT, typename ErrT> |
864 | class ErrorHandlerTraits<RetT (C::*)(const ErrT &) const> |
865 | : public ErrorHandlerTraits<RetT (&)(ErrT &)> {}; |
866 | |
867 | /// Specialization for member functions of the form |
868 | /// 'RetT (std::unique_ptr<ErrT>)'. |
869 | template <typename C, typename RetT, typename ErrT> |
870 | class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>)> |
871 | : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {}; |
872 | |
873 | /// Specialization for member functions of the form |
874 | /// 'RetT (std::unique_ptr<ErrT>) const'. |
875 | template <typename C, typename RetT, typename ErrT> |
876 | class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>) const> |
877 | : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {}; |
878 | |
879 | inline Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload) { |
880 | return Error(std::move(Payload)); |
881 | } |
882 | |
883 | template <typename HandlerT, typename... HandlerTs> |
884 | Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload, |
885 | HandlerT &&Handler, HandlerTs &&... Handlers) { |
886 | if (ErrorHandlerTraits<HandlerT>::appliesTo(*Payload)) |
887 | return ErrorHandlerTraits<HandlerT>::apply(std::forward<HandlerT>(Handler), |
888 | std::move(Payload)); |
889 | return handleErrorImpl(std::move(Payload), |
890 | std::forward<HandlerTs>(Handlers)...); |
891 | } |
892 | |
893 | /// Pass the ErrorInfo(s) contained in E to their respective handlers. Any |
894 | /// unhandled errors (or Errors returned by handlers) are re-concatenated and |
895 | /// returned. |
896 | /// Because this function returns an error, its result must also be checked |
897 | /// or returned. If you intend to handle all errors use handleAllErrors |
898 | /// (which returns void, and will abort() on unhandled errors) instead. |
899 | template <typename... HandlerTs> |
900 | Error handleErrors(Error E, HandlerTs &&... Hs) { |
901 | if (!E) |
902 | return Error::success(); |
903 | |
904 | std::unique_ptr<ErrorInfoBase> Payload = E.takePayload(); |
905 | |
906 | if (Payload->isA<ErrorList>()) { |
907 | ErrorList &List = static_cast<ErrorList &>(*Payload); |
908 | Error R; |
909 | for (auto &P : List.Payloads) |
910 | R = ErrorList::join( |
911 | std::move(R), |
912 | handleErrorImpl(std::move(P), std::forward<HandlerTs>(Hs)...)); |
913 | return R; |
914 | } |
915 | |
916 | return handleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...); |
917 | } |
918 | |
919 | /// Behaves the same as handleErrors, except that by contract all errors |
920 | /// *must* be handled by the given handlers (i.e. there must be no remaining |
921 | /// errors after running the handlers, or llvm_unreachable is called). |
922 | template <typename... HandlerTs> |
923 | void handleAllErrors(Error E, HandlerTs &&... Handlers) { |
924 | cantFail(handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...)); |
925 | } |
926 | |
927 | /// Check that E is a non-error, then drop it. |
928 | /// If E is an error, llvm_unreachable will be called. |
929 | inline void handleAllErrors(Error E) { |
930 | cantFail(std::move(E)); |
931 | } |
932 | |
933 | /// Handle any errors (if present) in an Expected<T>, then try a recovery path. |
934 | /// |
935 | /// If the incoming value is a success value it is returned unmodified. If it |
936 | /// is a failure value then it the contained error is passed to handleErrors. |
937 | /// If handleErrors is able to handle the error then the RecoveryPath functor |
938 | /// is called to supply the final result. If handleErrors is not able to |
939 | /// handle all errors then the unhandled errors are returned. |
940 | /// |
941 | /// This utility enables the follow pattern: |
942 | /// |
943 | /// @code{.cpp} |
944 | /// enum FooStrategy { Aggressive, Conservative }; |
945 | /// Expected<Foo> foo(FooStrategy S); |
946 | /// |
947 | /// auto ResultOrErr = |
948 | /// handleExpected( |
949 | /// foo(Aggressive), |
950 | /// []() { return foo(Conservative); }, |
951 | /// [](AggressiveStrategyError&) { |
952 | /// // Implicitly conusme this - we'll recover by using a conservative |
953 | /// // strategy. |
954 | /// }); |
955 | /// |
956 | /// @endcode |
957 | template <typename T, typename RecoveryFtor, typename... HandlerTs> |
958 | Expected<T> handleExpected(Expected<T> ValOrErr, RecoveryFtor &&RecoveryPath, |
959 | HandlerTs &&... Handlers) { |
960 | if (ValOrErr) |
961 | return ValOrErr; |
962 | |
963 | if (auto Err = handleErrors(ValOrErr.takeError(), |
964 | std::forward<HandlerTs>(Handlers)...)) |
965 | return std::move(Err); |
966 | |
967 | return RecoveryPath(); |
968 | } |
969 | |
970 | /// Log all errors (if any) in E to OS. If there are any errors, ErrorBanner |
971 | /// will be printed before the first one is logged. A newline will be printed |
972 | /// after each error. |
973 | /// |
974 | /// This function is compatible with the helpers from Support/WithColor.h. You |
975 | /// can pass any of them as the OS. Please consider using them instead of |
976 | /// including 'error: ' in the ErrorBanner. |
977 | /// |
978 | /// This is useful in the base level of your program to allow clean termination |
979 | /// (allowing clean deallocation of resources, etc.), while reporting error |
980 | /// information to the user. |
981 | void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner = {}); |
982 | |
983 | /// Write all error messages (if any) in E to a string. The newline character |
984 | /// is used to separate error messages. |
985 | inline std::string toString(Error E) { |
986 | SmallVector<std::string, 2> Errors; |
987 | handleAllErrors(std::move(E), [&Errors](const ErrorInfoBase &EI) { |
988 | Errors.push_back(EI.message()); |
989 | }); |
990 | return join(Errors.begin(), Errors.end(), "\n"); |
991 | } |
992 | |
993 | /// Consume a Error without doing anything. This method should be used |
994 | /// only where an error can be considered a reasonable and expected return |
995 | /// value. |
996 | /// |
997 | /// Uses of this method are potentially indicative of design problems: If it's |
998 | /// legitimate to do nothing while processing an "error", the error-producer |
999 | /// might be more clearly refactored to return an Optional<T>. |
1000 | inline void consumeError(Error Err) { |
1001 | handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {}); |
1002 | } |
1003 | |
1004 | /// Convert an Expected to an Optional without doing anything. This method |
1005 | /// should be used only where an error can be considered a reasonable and |
1006 | /// expected return value. |
1007 | /// |
1008 | /// Uses of this method are potentially indicative of problems: perhaps the |
1009 | /// error should be propagated further, or the error-producer should just |
1010 | /// return an Optional in the first place. |
1011 | template <typename T> Optional<T> expectedToOptional(Expected<T> &&E) { |
1012 | if (E) |
1013 | return std::move(*E); |
1014 | consumeError(E.takeError()); |
1015 | return None; |
1016 | } |
1017 | |
1018 | /// Helper for converting an Error to a bool. |
1019 | /// |
1020 | /// This method returns true if Err is in an error state, or false if it is |
1021 | /// in a success state. Puts Err in a checked state in both cases (unlike |
1022 | /// Error::operator bool(), which only does this for success states). |
1023 | inline bool errorToBool(Error Err) { |
1024 | bool IsError = static_cast<bool>(Err); |
1025 | if (IsError) |
1026 | consumeError(std::move(Err)); |
1027 | return IsError; |
1028 | } |
1029 | |
1030 | /// Helper for Errors used as out-parameters. |
1031 | /// |
1032 | /// This helper is for use with the Error-as-out-parameter idiom, where an error |
1033 | /// is passed to a function or method by reference, rather than being returned. |
1034 | /// In such cases it is helpful to set the checked bit on entry to the function |
1035 | /// so that the error can be written to (unchecked Errors abort on assignment) |
1036 | /// and clear the checked bit on exit so that clients cannot accidentally forget |
1037 | /// to check the result. This helper performs these actions automatically using |
1038 | /// RAII: |
1039 | /// |
1040 | /// @code{.cpp} |
1041 | /// Result foo(Error &Err) { |
1042 | /// ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set |
1043 | /// // <body of foo> |
1044 | /// // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed. |
1045 | /// } |
1046 | /// @endcode |
1047 | /// |
1048 | /// ErrorAsOutParameter takes an Error* rather than Error& so that it can be |
1049 | /// used with optional Errors (Error pointers that are allowed to be null). If |
1050 | /// ErrorAsOutParameter took an Error reference, an instance would have to be |
1051 | /// created inside every condition that verified that Error was non-null. By |
1052 | /// taking an Error pointer we can just create one instance at the top of the |
1053 | /// function. |
1054 | class ErrorAsOutParameter { |
1055 | public: |
1056 | ErrorAsOutParameter(Error *Err) : Err(Err) { |
1057 | // Raise the checked bit if Err is success. |
1058 | if (Err) |
1059 | (void)!!*Err; |
1060 | } |
1061 | |
1062 | ~ErrorAsOutParameter() { |
1063 | // Clear the checked bit. |
1064 | if (Err && !*Err) |
1065 | *Err = Error::success(); |
1066 | } |
1067 | |
1068 | private: |
1069 | Error *Err; |
1070 | }; |
1071 | |
1072 | /// Helper for Expected<T>s used as out-parameters. |
1073 | /// |
1074 | /// See ErrorAsOutParameter. |
1075 | template <typename T> |
1076 | class ExpectedAsOutParameter { |
1077 | public: |
1078 | ExpectedAsOutParameter(Expected<T> *ValOrErr) |
1079 | : ValOrErr(ValOrErr) { |
1080 | if (ValOrErr) |
1081 | (void)!!*ValOrErr; |
1082 | } |
1083 | |
1084 | ~ExpectedAsOutParameter() { |
1085 | if (ValOrErr) |
1086 | ValOrErr->setUnchecked(); |
1087 | } |
1088 | |
1089 | private: |
1090 | Expected<T> *ValOrErr; |
1091 | }; |
1092 | |
1093 | /// This class wraps a std::error_code in a Error. |
1094 | /// |
1095 | /// This is useful if you're writing an interface that returns a Error |
1096 | /// (or Expected) and you want to call code that still returns |
1097 | /// std::error_codes. |
1098 | class ECError : public ErrorInfo<ECError> { |
1099 | friend Error errorCodeToError(std::error_code); |
1100 | |
1101 | virtual void anchor() override; |
1102 | |
1103 | public: |
1104 | void setErrorCode(std::error_code EC) { this->EC = EC; } |
1105 | std::error_code convertToErrorCode() const override { return EC; } |
1106 | void log(raw_ostream &OS) const override { OS << EC.message(); } |
1107 | |
1108 | // Used by ErrorInfo::classID. |
1109 | static char ID; |
1110 | |
1111 | protected: |
1112 | ECError() = default; |
1113 | ECError(std::error_code EC) : EC(EC) {} |
1114 | |
1115 | std::error_code EC; |
1116 | }; |
1117 | |
1118 | /// The value returned by this function can be returned from convertToErrorCode |
1119 | /// for Error values where no sensible translation to std::error_code exists. |
1120 | /// It should only be used in this situation, and should never be used where a |
1121 | /// sensible conversion to std::error_code is available, as attempts to convert |
1122 | /// to/from this error will result in a fatal error. (i.e. it is a programmatic |
1123 | ///error to try to convert such a value). |
1124 | std::error_code inconvertibleErrorCode(); |
1125 | |
1126 | /// Helper for converting an std::error_code to a Error. |
1127 | Error errorCodeToError(std::error_code EC); |
1128 | |
1129 | /// Helper for converting an ECError to a std::error_code. |
1130 | /// |
1131 | /// This method requires that Err be Error() or an ECError, otherwise it |
1132 | /// will trigger a call to abort(). |
1133 | std::error_code errorToErrorCode(Error Err); |
1134 | |
1135 | /// Convert an ErrorOr<T> to an Expected<T>. |
1136 | template <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) { |
1137 | if (auto EC = EO.getError()) |
1138 | return errorCodeToError(EC); |
1139 | return std::move(*EO); |
1140 | } |
1141 | |
1142 | /// Convert an Expected<T> to an ErrorOr<T>. |
1143 | template <typename T> ErrorOr<T> expectedToErrorOr(Expected<T> &&E) { |
1144 | if (auto Err = E.takeError()) |
1145 | return errorToErrorCode(std::move(Err)); |
1146 | return std::move(*E); |
1147 | } |
1148 | |
1149 | /// This class wraps a string in an Error. |
1150 | /// |
1151 | /// StringError is useful in cases where the client is not expected to be able |
1152 | /// to consume the specific error message programmatically (for example, if the |
1153 | /// error message is to be presented to the user). |
1154 | /// |
1155 | /// StringError can also be used when additional information is to be printed |
1156 | /// along with a error_code message. Depending on the constructor called, this |
1157 | /// class can either display: |
1158 | /// 1. the error_code message (ECError behavior) |
1159 | /// 2. a string |
1160 | /// 3. the error_code message and a string |
1161 | /// |
1162 | /// These behaviors are useful when subtyping is required; for example, when a |
1163 | /// specific library needs an explicit error type. In the example below, |
1164 | /// PDBError is derived from StringError: |
1165 | /// |
1166 | /// @code{.cpp} |
1167 | /// Expected<int> foo() { |
1168 | /// return llvm::make_error<PDBError>(pdb_error_code::dia_failed_loading, |
1169 | /// "Additional information"); |
1170 | /// } |
1171 | /// @endcode |
1172 | /// |
1173 | class StringError : public ErrorInfo<StringError> { |
1174 | public: |
1175 | static char ID; |
1176 | |
1177 | // Prints EC + S and converts to EC |
1178 | StringError(std::error_code EC, const Twine &S = Twine()); |
1179 | |
1180 | // Prints S and converts to EC |
1181 | StringError(const Twine &S, std::error_code EC); |
1182 | |
1183 | void log(raw_ostream &OS) const override; |
1184 | std::error_code convertToErrorCode() const override; |
1185 | |
1186 | const std::string &getMessage() const { return Msg; } |
1187 | |
1188 | private: |
1189 | std::string Msg; |
1190 | std::error_code EC; |
1191 | const bool PrintMsgOnly = false; |
1192 | }; |
1193 | |
1194 | /// Create formatted StringError object. |
1195 | template <typename... Ts> |
1196 | inline Error createStringError(std::error_code EC, char const *Fmt, |
1197 | const Ts &... Vals) { |
1198 | std::string Buffer; |
1199 | raw_string_ostream Stream(Buffer); |
1200 | Stream << format(Fmt, Vals...); |
1201 | return make_error<StringError>(Stream.str(), EC); |
1202 | } |
1203 | |
1204 | Error createStringError(std::error_code EC, char const *Msg); |
1205 | |
1206 | inline Error createStringError(std::error_code EC, const Twine &S) { |
1207 | return createStringError(EC, S.str().c_str()); |
1208 | } |
1209 | |
1210 | template <typename... Ts> |
1211 | inline Error createStringError(std::errc EC, char const *Fmt, |
1212 | const Ts &... Vals) { |
1213 | return createStringError(std::make_error_code(EC), Fmt, Vals...); |
1214 | } |
1215 | |
1216 | /// This class wraps a filename and another Error. |
1217 | /// |
1218 | /// In some cases, an error needs to live along a 'source' name, in order to |
1219 | /// show more detailed information to the user. |
1220 | class FileError final : public ErrorInfo<FileError> { |
1221 | |
1222 | friend Error createFileError(const Twine &, Error); |
1223 | friend Error createFileError(const Twine &, size_t, Error); |
1224 | |
1225 | public: |
1226 | void log(raw_ostream &OS) const override { |
1227 | assert(Err && !FileName.empty() && "Trying to log after takeError().")((Err && !FileName.empty() && "Trying to log after takeError()." ) ? static_cast<void> (0) : __assert_fail ("Err && !FileName.empty() && \"Trying to log after takeError().\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/Error.h" , 1227, __PRETTY_FUNCTION__)); |
1228 | OS << "'" << FileName << "': "; |
1229 | if (Line.hasValue()) |
1230 | OS << "line " << Line.getValue() << ": "; |
1231 | Err->log(OS); |
1232 | } |
1233 | |
1234 | StringRef getFileName() { return FileName; } |
1235 | |
1236 | Error takeError() { return Error(std::move(Err)); } |
1237 | |
1238 | std::error_code convertToErrorCode() const override; |
1239 | |
1240 | // Used by ErrorInfo::classID. |
1241 | static char ID; |
1242 | |
1243 | private: |
1244 | FileError(const Twine &F, Optional<size_t> LineNum, |
1245 | std::unique_ptr<ErrorInfoBase> E) { |
1246 | assert(E && "Cannot create FileError from Error success value.")((E && "Cannot create FileError from Error success value." ) ? static_cast<void> (0) : __assert_fail ("E && \"Cannot create FileError from Error success value.\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/Error.h" , 1246, __PRETTY_FUNCTION__)); |
1247 | assert(!F.isTriviallyEmpty() &&((!F.isTriviallyEmpty() && "The file name provided to FileError must not be empty." ) ? static_cast<void> (0) : __assert_fail ("!F.isTriviallyEmpty() && \"The file name provided to FileError must not be empty.\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/Error.h" , 1248, __PRETTY_FUNCTION__)) |
1248 | "The file name provided to FileError must not be empty.")((!F.isTriviallyEmpty() && "The file name provided to FileError must not be empty." ) ? static_cast<void> (0) : __assert_fail ("!F.isTriviallyEmpty() && \"The file name provided to FileError must not be empty.\"" , "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/Error.h" , 1248, __PRETTY_FUNCTION__)); |
1249 | FileName = F.str(); |
1250 | Err = std::move(E); |
1251 | Line = std::move(LineNum); |
1252 | } |
1253 | |
1254 | static Error build(const Twine &F, Optional<size_t> Line, Error E) { |
1255 | std::unique_ptr<ErrorInfoBase> Payload; |
1256 | handleAllErrors(std::move(E), |
1257 | [&](std::unique_ptr<ErrorInfoBase> EIB) -> Error { |
1258 | Payload = std::move(EIB); |
1259 | return Error::success(); |
1260 | }); |
1261 | return Error( |
1262 | std::unique_ptr<FileError>(new FileError(F, Line, std::move(Payload)))); |
1263 | } |
1264 | |
1265 | std::string FileName; |
1266 | Optional<size_t> Line; |
1267 | std::unique_ptr<ErrorInfoBase> Err; |
1268 | }; |
1269 | |
1270 | /// Concatenate a source file path and/or name with an Error. The resulting |
1271 | /// Error is unchecked. |
1272 | inline Error createFileError(const Twine &F, Error E) { |
1273 | return FileError::build(F, Optional<size_t>(), std::move(E)); |
1274 | } |
1275 | |
1276 | /// Concatenate a source file path and/or name with line number and an Error. |
1277 | /// The resulting Error is unchecked. |
1278 | inline Error createFileError(const Twine &F, size_t Line, Error E) { |
1279 | return FileError::build(F, Optional<size_t>(Line), std::move(E)); |
1280 | } |
1281 | |
1282 | /// Concatenate a source file path and/or name with a std::error_code |
1283 | /// to form an Error object. |
1284 | inline Error createFileError(const Twine &F, std::error_code EC) { |
1285 | return createFileError(F, errorCodeToError(EC)); |
1286 | } |
1287 | |
1288 | /// Concatenate a source file path and/or name with line number and |
1289 | /// std::error_code to form an Error object. |
1290 | inline Error createFileError(const Twine &F, size_t Line, std::error_code EC) { |
1291 | return createFileError(F, Line, errorCodeToError(EC)); |
1292 | } |
1293 | |
1294 | Error createFileError(const Twine &F, ErrorSuccess) = delete; |
1295 | |
1296 | /// Helper for check-and-exit error handling. |
1297 | /// |
1298 | /// For tool use only. NOT FOR USE IN LIBRARY CODE. |
1299 | /// |
1300 | class ExitOnError { |
1301 | public: |
1302 | /// Create an error on exit helper. |
1303 | ExitOnError(std::string Banner = "", int DefaultErrorExitCode = 1) |
1304 | : Banner(std::move(Banner)), |
1305 | GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {} |
1306 | |
1307 | /// Set the banner string for any errors caught by operator(). |
1308 | void setBanner(std::string Banner) { this->Banner = std::move(Banner); } |
1309 | |
1310 | /// Set the exit-code mapper function. |
1311 | void setExitCodeMapper(std::function<int(const Error &)> GetExitCode) { |
1312 | this->GetExitCode = std::move(GetExitCode); |
1313 | } |
1314 | |
1315 | /// Check Err. If it's in a failure state log the error(s) and exit. |
1316 | void operator()(Error Err) const { checkError(std::move(Err)); } |
1317 | |
1318 | /// Check E. If it's in a success state then return the contained value. If |
1319 | /// it's in a failure state log the error(s) and exit. |
1320 | template <typename T> T operator()(Expected<T> &&E) const { |
1321 | checkError(E.takeError()); |
1322 | return std::move(*E); |
1323 | } |
1324 | |
1325 | /// Check E. If it's in a success state then return the contained reference. If |
1326 | /// it's in a failure state log the error(s) and exit. |
1327 | template <typename T> T& operator()(Expected<T&> &&E) const { |
1328 | checkError(E.takeError()); |
1329 | return *E; |
1330 | } |
1331 | |
1332 | private: |
1333 | void checkError(Error Err) const { |
1334 | if (Err) { |
1335 | int ExitCode = GetExitCode(Err); |
1336 | logAllUnhandledErrors(std::move(Err), errs(), Banner); |
1337 | exit(ExitCode); |
1338 | } |
1339 | } |
1340 | |
1341 | std::string Banner; |
1342 | std::function<int(const Error &)> GetExitCode; |
1343 | }; |
1344 | |
1345 | /// Conversion from Error to LLVMErrorRef for C error bindings. |
1346 | inline LLVMErrorRef wrap(Error Err) { |
1347 | return reinterpret_cast<LLVMErrorRef>(Err.takePayload().release()); |
1348 | } |
1349 | |
1350 | /// Conversion from LLVMErrorRef to Error for C error bindings. |
1351 | inline Error unwrap(LLVMErrorRef ErrRef) { |
1352 | return Error(std::unique_ptr<ErrorInfoBase>( |
1353 | reinterpret_cast<ErrorInfoBase *>(ErrRef))); |
1354 | } |
1355 | |
1356 | } // end namespace llvm |
1357 | |
1358 | #endif // LLVM_SUPPORT_ERROR_H |
1 | // <system_error> -*- C++ -*- |
2 | |
3 | // Copyright (C) 2007-2016 Free Software Foundation, Inc. |
4 | // |
5 | // This file is part of the GNU ISO C++ Library. This library is free |
6 | // software; you can redistribute it and/or modify it under the |
7 | // terms of the GNU General Public License as published by the |
8 | // Free Software Foundation; either version 3, or (at your option) |
9 | // any later version. |
10 | |
11 | // This library is distributed in the hope that it will be useful, |
12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of |
13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
14 | // GNU General Public License for more details. |
15 | |
16 | // Under Section 7 of GPL version 3, you are granted additional |
17 | // permissions described in the GCC Runtime Library Exception, version |
18 | // 3.1, as published by the Free Software Foundation. |
19 | |
20 | // You should have received a copy of the GNU General Public License and |
21 | // a copy of the GCC Runtime Library Exception along with this program; |
22 | // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see |
23 | // <http://www.gnu.org/licenses/>. |
24 | |
25 | /** @file include/system_error |
26 | * This is a Standard C++ Library header. |
27 | */ |
28 | |
29 | #ifndef _GLIBCXX_SYSTEM_ERROR1 |
30 | #define _GLIBCXX_SYSTEM_ERROR1 1 |
31 | |
32 | #pragma GCC system_header |
33 | |
34 | #if __cplusplus201402L < 201103L |
35 | # include <bits/c++0x_warning.h> |
36 | #else |
37 | |
38 | #include <bits/c++config.h> |
39 | #include <bits/error_constants.h> |
40 | #include <iosfwd> |
41 | #include <stdexcept> |
42 | |
43 | namespace std _GLIBCXX_VISIBILITY(default)__attribute__ ((__visibility__ ("default"))) |
44 | { |
45 | _GLIBCXX_BEGIN_NAMESPACE_VERSION |
46 | |
47 | class error_code; |
48 | class error_condition; |
49 | class system_error; |
50 | |
51 | /// is_error_code_enum |
52 | template<typename _Tp> |
53 | struct is_error_code_enum : public false_type { }; |
54 | |
55 | /// is_error_condition_enum |
56 | template<typename _Tp> |
57 | struct is_error_condition_enum : public false_type { }; |
58 | |
59 | template<> |
60 | struct is_error_condition_enum<errc> |
61 | : public true_type { }; |
62 | |
63 | inline namespace _V2 { |
64 | |
65 | /// error_category |
66 | class error_category |
67 | { |
68 | public: |
69 | constexpr error_category() noexcept = default; |
70 | |
71 | virtual ~error_category(); |
72 | |
73 | error_category(const error_category&) = delete; |
74 | error_category& operator=(const error_category&) = delete; |
75 | |
76 | virtual const char* |
77 | name() const noexcept = 0; |
78 | |
79 | // We need two different virtual functions here, one returning a |
80 | // COW string and one returning an SSO string. Their positions in the |
81 | // vtable must be consistent for dynamic dispatch to work, but which one |
82 | // the name "message()" finds depends on which ABI the caller is using. |
83 | #if _GLIBCXX_USE_CXX11_ABI1 |
84 | private: |
85 | _GLIBCXX_DEFAULT_ABI_TAG__attribute ((__abi_tag__ ("cxx11"))) |
86 | virtual __cow_string |
87 | _M_message(int) const; |
88 | |
89 | public: |
90 | _GLIBCXX_DEFAULT_ABI_TAG__attribute ((__abi_tag__ ("cxx11"))) |
91 | virtual string |
92 | message(int) const = 0; |
93 | #else |
94 | virtual string |
95 | message(int) const = 0; |
96 | |
97 | private: |
98 | virtual __sso_string |
99 | _M_message(int) const; |
100 | #endif |
101 | |
102 | public: |
103 | virtual error_condition |
104 | default_error_condition(int __i) const noexcept; |
105 | |
106 | virtual bool |
107 | equivalent(int __i, const error_condition& __cond) const noexcept; |
108 | |
109 | virtual bool |
110 | equivalent(const error_code& __code, int __i) const noexcept; |
111 | |
112 | bool |
113 | operator<(const error_category& __other) const noexcept |
114 | { return less<const error_category*>()(this, &__other); } |
115 | |
116 | bool |
117 | operator==(const error_category& __other) const noexcept |
118 | { return this == &__other; } |
119 | |
120 | bool |
121 | operator!=(const error_category& __other) const noexcept |
122 | { return this != &__other; } |
123 | }; |
124 | |
125 | // DR 890. |
126 | _GLIBCXX_CONST__attribute__ ((__const__)) const error_category& system_category() noexcept; |
127 | _GLIBCXX_CONST__attribute__ ((__const__)) const error_category& generic_category() noexcept; |
128 | |
129 | } // end inline namespace |
130 | |
131 | error_code make_error_code(errc) noexcept; |
132 | |
133 | template<typename _Tp> |
134 | struct hash; |
135 | |
136 | /// error_code |
137 | // Implementation-specific error identification |
138 | struct error_code |
139 | { |
140 | error_code() noexcept |
141 | : _M_value(0), _M_cat(&system_category()) { } |
142 | |
143 | error_code(int __v, const error_category& __cat) noexcept |
144 | : _M_value(__v), _M_cat(&__cat) { } |
145 | |
146 | template<typename _ErrorCodeEnum, typename = typename |
147 | enable_if<is_error_code_enum<_ErrorCodeEnum>::value>::type> |
148 | error_code(_ErrorCodeEnum __e) noexcept |
149 | { *this = make_error_code(__e); } |
150 | |
151 | void |
152 | assign(int __v, const error_category& __cat) noexcept |
153 | { |
154 | _M_value = __v; |
155 | _M_cat = &__cat; |
156 | } |
157 | |
158 | void |
159 | clear() noexcept |
160 | { assign(0, system_category()); } |
161 | |
162 | // DR 804. |
163 | template<typename _ErrorCodeEnum> |
164 | typename enable_if<is_error_code_enum<_ErrorCodeEnum>::value, |
165 | error_code&>::type |
166 | operator=(_ErrorCodeEnum __e) noexcept |
167 | { return *this = make_error_code(__e); } |
168 | |
169 | int |
170 | value() const noexcept { return _M_value; } |
171 | |
172 | const error_category& |
173 | category() const noexcept { return *_M_cat; } |
174 | |
175 | error_condition |
176 | default_error_condition() const noexcept; |
177 | |
178 | _GLIBCXX_DEFAULT_ABI_TAG__attribute ((__abi_tag__ ("cxx11"))) |
179 | string |
180 | message() const |
181 | { return category().message(value()); } |
182 | |
183 | explicit operator bool() const noexcept |
184 | { return _M_value != 0; } |
185 | |
186 | // DR 804. |
187 | private: |
188 | friend class hash<error_code>; |
189 | |
190 | int _M_value; |
191 | const error_category* _M_cat; |
192 | }; |
193 | |
194 | // 19.4.2.6 non-member functions |
195 | inline error_code |
196 | make_error_code(errc __e) noexcept |
197 | { return error_code(static_cast<int>(__e), generic_category()); } |
198 | |
199 | inline bool |
200 | operator<(const error_code& __lhs, const error_code& __rhs) noexcept |
201 | { |
202 | return (__lhs.category() < __rhs.category() |
203 | || (__lhs.category() == __rhs.category() |
204 | && __lhs.value() < __rhs.value())); |
205 | } |
206 | |
207 | template<typename _CharT, typename _Traits> |
208 | basic_ostream<_CharT, _Traits>& |
209 | operator<<(basic_ostream<_CharT, _Traits>& __os, const error_code& __e) |
210 | { return (__os << __e.category().name() << ':' << __e.value()); } |
211 | |
212 | error_condition make_error_condition(errc) noexcept; |
213 | |
214 | /// error_condition |
215 | // Portable error identification |
216 | struct error_condition |
217 | { |
218 | error_condition() noexcept |
219 | : _M_value(0), _M_cat(&generic_category()) { } |
220 | |
221 | error_condition(int __v, const error_category& __cat) noexcept |
222 | : _M_value(__v), _M_cat(&__cat) { } |
223 | |
224 | template<typename _ErrorConditionEnum, typename = typename |
225 | enable_if<is_error_condition_enum<_ErrorConditionEnum>::value>::type> |
226 | error_condition(_ErrorConditionEnum __e) noexcept |
227 | { *this = make_error_condition(__e); } |
228 | |
229 | void |
230 | assign(int __v, const error_category& __cat) noexcept |
231 | { |
232 | _M_value = __v; |
233 | _M_cat = &__cat; |
234 | } |
235 | |
236 | // DR 804. |
237 | template<typename _ErrorConditionEnum> |
238 | typename enable_if<is_error_condition_enum |
239 | <_ErrorConditionEnum>::value, error_condition&>::type |
240 | operator=(_ErrorConditionEnum __e) noexcept |
241 | { return *this = make_error_condition(__e); } |
242 | |
243 | void |
244 | clear() noexcept |
245 | { assign(0, generic_category()); } |
246 | |
247 | // 19.4.3.4 observers |
248 | int |
249 | value() const noexcept { return _M_value; } |
250 | |
251 | const error_category& |
252 | category() const noexcept { return *_M_cat; } |
253 | |
254 | _GLIBCXX_DEFAULT_ABI_TAG__attribute ((__abi_tag__ ("cxx11"))) |
255 | string |
256 | message() const |
257 | { return category().message(value()); } |
258 | |
259 | explicit operator bool() const noexcept |
260 | { return _M_value != 0; } |
261 | |
262 | // DR 804. |
263 | private: |
264 | int _M_value; |
265 | const error_category* _M_cat; |
266 | }; |
267 | |
268 | // 19.4.3.6 non-member functions |
269 | inline error_condition |
270 | make_error_condition(errc __e) noexcept |
271 | { return error_condition(static_cast<int>(__e), generic_category()); } |
272 | |
273 | inline bool |
274 | operator<(const error_condition& __lhs, |
275 | const error_condition& __rhs) noexcept |
276 | { |
277 | return (__lhs.category() < __rhs.category() |
278 | || (__lhs.category() == __rhs.category() |
279 | && __lhs.value() < __rhs.value())); |
280 | } |
281 | |
282 | // 19.4.4 Comparison operators |
283 | inline bool |
284 | operator==(const error_code& __lhs, const error_code& __rhs) noexcept |
285 | { return (__lhs.category() == __rhs.category() |
286 | && __lhs.value() == __rhs.value()); } |
287 | |
288 | inline bool |
289 | operator==(const error_code& __lhs, const error_condition& __rhs) noexcept |
290 | { |
291 | return (__lhs.category().equivalent(__lhs.value(), __rhs) |
292 | || __rhs.category().equivalent(__lhs, __rhs.value())); |
293 | } |
294 | |
295 | inline bool |
296 | operator==(const error_condition& __lhs, const error_code& __rhs) noexcept |
297 | { |
298 | return (__rhs.category().equivalent(__rhs.value(), __lhs) |
299 | || __lhs.category().equivalent(__rhs, __lhs.value())); |
300 | } |
301 | |
302 | inline bool |
303 | operator==(const error_condition& __lhs, |
304 | const error_condition& __rhs) noexcept |
305 | { |
306 | return (__lhs.category() == __rhs.category() |
307 | && __lhs.value() == __rhs.value()); |
308 | } |
309 | |
310 | inline bool |
311 | operator!=(const error_code& __lhs, const error_code& __rhs) noexcept |
312 | { return !(__lhs == __rhs); } |
313 | |
314 | inline bool |
315 | operator!=(const error_code& __lhs, const error_condition& __rhs) noexcept |
316 | { return !(__lhs == __rhs); } |
317 | |
318 | inline bool |
319 | operator!=(const error_condition& __lhs, const error_code& __rhs) noexcept |
320 | { return !(__lhs == __rhs); } |
321 | |
322 | inline bool |
323 | operator!=(const error_condition& __lhs, |
324 | const error_condition& __rhs) noexcept |
325 | { return !(__lhs == __rhs); } |
326 | |
327 | |
328 | /** |
329 | * @brief Thrown to indicate error code of underlying system. |
330 | * |
331 | * @ingroup exceptions |
332 | */ |
333 | class system_error : public std::runtime_error |
334 | { |
335 | private: |
336 | error_code _M_code; |
337 | |
338 | public: |
339 | system_error(error_code __ec = error_code()) |
340 | : runtime_error(__ec.message()), _M_code(__ec) { } |
341 | |
342 | system_error(error_code __ec, const string& __what) |
343 | : runtime_error(__what + ": " + __ec.message()), _M_code(__ec) { } |
344 | |
345 | system_error(error_code __ec, const char* __what) |
346 | : runtime_error(__what + (": " + __ec.message())), _M_code(__ec) { } |
347 | |
348 | system_error(int __v, const error_category& __ecat, const char* __what) |
349 | : system_error(error_code(__v, __ecat), __what) { } |
350 | |
351 | system_error(int __v, const error_category& __ecat) |
352 | : runtime_error(error_code(__v, __ecat).message()), |
353 | _M_code(__v, __ecat) { } |
354 | |
355 | system_error(int __v, const error_category& __ecat, const string& __what) |
356 | : runtime_error(__what + ": " + error_code(__v, __ecat).message()), |
357 | _M_code(__v, __ecat) { } |
358 | |
359 | virtual ~system_error() noexcept; |
360 | |
361 | const error_code& |
362 | code() const noexcept { return _M_code; } |
363 | }; |
364 | |
365 | _GLIBCXX_END_NAMESPACE_VERSION |
366 | } // namespace |
367 | |
368 | #ifndef _GLIBCXX_COMPATIBILITY_CXX0X |
369 | |
370 | #include <bits/functional_hash.h> |
371 | |
372 | namespace std _GLIBCXX_VISIBILITY(default)__attribute__ ((__visibility__ ("default"))) |
373 | { |
374 | _GLIBCXX_BEGIN_NAMESPACE_VERSION |
375 | |
376 | // DR 1182. |
377 | /// std::hash specialization for error_code. |
378 | template<> |
379 | struct hash<error_code> |
380 | : public __hash_base<size_t, error_code> |
381 | { |
382 | size_t |
383 | operator()(const error_code& __e) const noexcept |
384 | { |
385 | const size_t __tmp = std::_Hash_impl::hash(__e._M_value); |
386 | return std::_Hash_impl::__hash_combine(__e._M_cat, __tmp); |
387 | } |
388 | }; |
389 | |
390 | _GLIBCXX_END_NAMESPACE_VERSION |
391 | } // namespace |
392 | |
393 | #endif // _GLIBCXX_COMPATIBILITY_CXX0X |
394 | |
395 | #endif // C++11 |
396 | |
397 | #endif // _GLIBCXX_SYSTEM_ERROR |