Bug Summary

File:lib/Object/WindowsResource.cpp
Warning:line 110, column 7
Called C++ object pointer is uninitialized

Annotated Source Code

/build/llvm-toolchain-snapshot-6.0~svn318211/lib/Object/WindowsResource.cpp

1//===-- WindowsResource.cpp -------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the .res file class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Object/WindowsResource.h"
15#include "llvm/Object/COFF.h"
16#include "llvm/Support/FileOutputBuffer.h"
17#include "llvm/Support/MathExtras.h"
18#include <ctime>
19#include <queue>
20#include <sstream>
21#include <system_error>
22
23using namespace llvm;
24using namespace object;
25
26namespace llvm {
27namespace object {
28
29#define RETURN_IF_ERROR(X)if (auto EC = X) return EC; \
30 if (auto EC = X) \
31 return EC;
32
33const uint32_t MIN_HEADER_SIZE = 7 * sizeof(uint32_t) + 2 * sizeof(uint16_t);
34
35// COFF files seem to be inconsistent with alignment between sections, just use
36// 8-byte because it makes everyone happy.
37const uint32_t SECTION_ALIGNMENT = sizeof(uint64_t);
38
39uint32_t WindowsResourceParser::TreeNode::StringCount = 0;
40uint32_t WindowsResourceParser::TreeNode::DataCount = 0;
41
42WindowsResource::WindowsResource(MemoryBufferRef Source)
43 : Binary(Binary::ID_WinRes, Source) {
44 size_t LeadingSize = WIN_RES_MAGIC_SIZE + WIN_RES_NULL_ENTRY_SIZE;
45 BBS = BinaryByteStream(Data.getBuffer().drop_front(LeadingSize),
46 support::little);
47}
48
49Expected<std::unique_ptr<WindowsResource>>
50WindowsResource::createWindowsResource(MemoryBufferRef Source) {
51 if (Source.getBufferSize() < WIN_RES_MAGIC_SIZE + WIN_RES_NULL_ENTRY_SIZE)
52 return make_error<GenericBinaryError>(
53 "File too small to be a resource file",
54 object_error::invalid_file_type);
55 std::unique_ptr<WindowsResource> Ret(new WindowsResource(Source));
56 return std::move(Ret);
57}
58
59Expected<ResourceEntryRef> WindowsResource::getHeadEntry() {
60 if (BBS.getLength() < sizeof(WinResHeaderPrefix) + sizeof(WinResHeaderSuffix))
61 return make_error<EmptyResError>(".res contains no entries",
62 object_error::unexpected_eof);
63 return ResourceEntryRef::create(BinaryStreamRef(BBS), this);
64}
65
66ResourceEntryRef::ResourceEntryRef(BinaryStreamRef Ref,
67 const WindowsResource *Owner)
68 : Reader(Ref) {}
69
70Expected<ResourceEntryRef>
71ResourceEntryRef::create(BinaryStreamRef BSR, const WindowsResource *Owner) {
72 auto Ref = ResourceEntryRef(BSR, Owner);
73 if (auto E = Ref.loadNext())
74 return std::move(E);
75 return Ref;
76}
77
78Error ResourceEntryRef::moveNext(bool &End) {
79 // Reached end of all the entries.
80 if (Reader.bytesRemaining() == 0) {
1
Taking false branch
81 End = true;
82 return Error::success();
83 }
84 RETURN_IF_ERROR(loadNext())if (auto EC = loadNext()) return EC;;
2
Within the expansion of the macro 'RETURN_IF_ERROR':
a
Calling 'ResourceEntryRef::loadNext'
85
86 return Error::success();
87}
88
89static Error readStringOrId(BinaryStreamReader &Reader, uint16_t &ID,
90 ArrayRef<UTF16> &Str, bool &IsString) {
91 uint16_t IDFlag;
92 RETURN_IF_ERROR(Reader.readInteger(IDFlag))if (auto EC = Reader.readInteger(IDFlag)) return EC;;
93 IsString = IDFlag != 0xffff;
94
95 if (IsString) {
96 Reader.setOffset(
97 Reader.getOffset() -
98 sizeof(uint16_t)); // Re-read the bytes which we used to check the flag.
99 RETURN_IF_ERROR(Reader.readWideString(Str))if (auto EC = Reader.readWideString(Str)) return EC;;
100 } else
101 RETURN_IF_ERROR(Reader.readInteger(ID))if (auto EC = Reader.readInteger(ID)) return EC;;
102
103 return Error::success();
104}
105
106Error ResourceEntryRef::loadNext() {
107 const WinResHeaderPrefix *Prefix;
3
'Prefix' declared without an initial value
108 RETURN_IF_ERROR(Reader.readObject(Prefix))if (auto EC = Reader.readObject(Prefix)) return EC;;
4
Within the expansion of the macro 'RETURN_IF_ERROR':
a
Calling 'BinaryStreamReader::readObject'
b
Returning from 'BinaryStreamReader::readObject'
109
110 if (Prefix->HeaderSize < MIN_HEADER_SIZE)
49
Called C++ object pointer is uninitialized
111 return make_error<GenericBinaryError>("Header size is too small.",
112 object_error::parse_failed);
113
114 RETURN_IF_ERROR(readStringOrId(Reader, TypeID, Type, IsStringType))if (auto EC = readStringOrId(Reader, TypeID, Type, IsStringType
)) return EC;
;
115
116 RETURN_IF_ERROR(readStringOrId(Reader, NameID, Name, IsStringName))if (auto EC = readStringOrId(Reader, NameID, Name, IsStringName
)) return EC;
;
117
118 RETURN_IF_ERROR(Reader.padToAlignment(WIN_RES_HEADER_ALIGNMENT))if (auto EC = Reader.padToAlignment(WIN_RES_HEADER_ALIGNMENT)
) return EC;
;
119
120 RETURN_IF_ERROR(Reader.readObject(Suffix))if (auto EC = Reader.readObject(Suffix)) return EC;;
121
122 RETURN_IF_ERROR(Reader.readArray(Data, Prefix->DataSize))if (auto EC = Reader.readArray(Data, Prefix->DataSize)) return
EC;
;
123
124 RETURN_IF_ERROR(Reader.padToAlignment(WIN_RES_DATA_ALIGNMENT))if (auto EC = Reader.padToAlignment(WIN_RES_DATA_ALIGNMENT)) return
EC;
;
125
126 return Error::success();
127}
128
129WindowsResourceParser::WindowsResourceParser() : Root(false) {}
130
131Error WindowsResourceParser::parse(WindowsResource *WR) {
132 auto EntryOrErr = WR->getHeadEntry();
133 if (!EntryOrErr) {
134 auto E = EntryOrErr.takeError();
135 if (E.isA<EmptyResError>()) {
136 // Check if the .res file contains no entries. In this case we don't have
137 // to throw an error but can rather just return without parsing anything.
138 // This applies for files which have a valid PE header magic and the
139 // mandatory empty null resource entry. Files which do not fit this
140 // criteria would have already been filtered out by
141 // WindowsResource::createWindowsResource().
142 consumeError(std::move(E));
143 return Error::success();
144 }
145 return E;
146 }
147
148 ResourceEntryRef Entry = EntryOrErr.get();
149 bool End = false;
150 while (!End) {
151 Data.push_back(Entry.getData());
152
153 bool IsNewTypeString = false;
154 bool IsNewNameString = false;
155
156 Root.addEntry(Entry, IsNewTypeString, IsNewNameString);
157
158 if (IsNewTypeString)
159 StringTable.push_back(Entry.getTypeString());
160
161 if (IsNewNameString)
162 StringTable.push_back(Entry.getNameString());
163
164 RETURN_IF_ERROR(Entry.moveNext(End))if (auto EC = Entry.moveNext(End)) return EC;;
165 }
166
167 return Error::success();
168}
169
170void WindowsResourceParser::printTree(raw_ostream &OS) const {
171 ScopedPrinter Writer(OS);
172 Root.print(Writer, "Resource Tree");
173}
174
175void WindowsResourceParser::TreeNode::addEntry(const ResourceEntryRef &Entry,
176 bool &IsNewTypeString,
177 bool &IsNewNameString) {
178 TreeNode &TypeNode = addTypeNode(Entry, IsNewTypeString);
179 TreeNode &NameNode = TypeNode.addNameNode(Entry, IsNewNameString);
180 NameNode.addLanguageNode(Entry);
181}
182
183WindowsResourceParser::TreeNode::TreeNode(bool IsStringNode) {
184 if (IsStringNode)
185 StringIndex = StringCount++;
186}
187
188WindowsResourceParser::TreeNode::TreeNode(uint16_t MajorVersion,
189 uint16_t MinorVersion,
190 uint32_t Characteristics)
191 : IsDataNode(true), MajorVersion(MajorVersion), MinorVersion(MinorVersion),
192 Characteristics(Characteristics) {
193 DataIndex = DataCount++;
194}
195
196std::unique_ptr<WindowsResourceParser::TreeNode>
197WindowsResourceParser::TreeNode::createStringNode() {
198 return std::unique_ptr<TreeNode>(new TreeNode(true));
199}
200
201std::unique_ptr<WindowsResourceParser::TreeNode>
202WindowsResourceParser::TreeNode::createIDNode() {
203 return std::unique_ptr<TreeNode>(new TreeNode(false));
204}
205
206std::unique_ptr<WindowsResourceParser::TreeNode>
207WindowsResourceParser::TreeNode::createDataNode(uint16_t MajorVersion,
208 uint16_t MinorVersion,
209 uint32_t Characteristics) {
210 return std::unique_ptr<TreeNode>(
211 new TreeNode(MajorVersion, MinorVersion, Characteristics));
212}
213
214WindowsResourceParser::TreeNode &
215WindowsResourceParser::TreeNode::addTypeNode(const ResourceEntryRef &Entry,
216 bool &IsNewTypeString) {
217 if (Entry.checkTypeString())
218 return addChild(Entry.getTypeString(), IsNewTypeString);
219 else
220 return addChild(Entry.getTypeID());
221}
222
223WindowsResourceParser::TreeNode &
224WindowsResourceParser::TreeNode::addNameNode(const ResourceEntryRef &Entry,
225 bool &IsNewNameString) {
226 if (Entry.checkNameString())
227 return addChild(Entry.getNameString(), IsNewNameString);
228 else
229 return addChild(Entry.getNameID());
230}
231
232WindowsResourceParser::TreeNode &
233WindowsResourceParser::TreeNode::addLanguageNode(
234 const ResourceEntryRef &Entry) {
235 return addChild(Entry.getLanguage(), true, Entry.getMajorVersion(),
236 Entry.getMinorVersion(), Entry.getCharacteristics());
237}
238
239WindowsResourceParser::TreeNode &WindowsResourceParser::TreeNode::addChild(
240 uint32_t ID, bool IsDataNode, uint16_t MajorVersion, uint16_t MinorVersion,
241 uint32_t Characteristics) {
242 auto Child = IDChildren.find(ID);
243 if (Child == IDChildren.end()) {
244 auto NewChild =
245 IsDataNode ? createDataNode(MajorVersion, MinorVersion, Characteristics)
246 : createIDNode();
247 WindowsResourceParser::TreeNode &Node = *NewChild;
248 IDChildren.emplace(ID, std::move(NewChild));
249 return Node;
250 } else
251 return *(Child->second);
252}
253
254WindowsResourceParser::TreeNode &
255WindowsResourceParser::TreeNode::addChild(ArrayRef<UTF16> NameRef,
256 bool &IsNewString) {
257 std::string NameString;
258 ArrayRef<UTF16> CorrectedName;
259 std::vector<UTF16> EndianCorrectedName;
260 if (sys::IsBigEndianHost) {
261 EndianCorrectedName.resize(NameRef.size() + 1);
262 std::copy(NameRef.begin(), NameRef.end(), EndianCorrectedName.begin() + 1);
263 EndianCorrectedName[0] = UNI_UTF16_BYTE_ORDER_MARK_SWAPPED0xFFFE;
264 CorrectedName = makeArrayRef(EndianCorrectedName);
265 } else
266 CorrectedName = NameRef;
267 convertUTF16ToUTF8String(CorrectedName, NameString);
268
269 auto Child = StringChildren.find(NameString);
270 if (Child == StringChildren.end()) {
271 auto NewChild = createStringNode();
272 IsNewString = true;
273 WindowsResourceParser::TreeNode &Node = *NewChild;
274 StringChildren.emplace(NameString, std::move(NewChild));
275 return Node;
276 } else
277 return *(Child->second);
278}
279
280void WindowsResourceParser::TreeNode::print(ScopedPrinter &Writer,
281 StringRef Name) const {
282 ListScope NodeScope(Writer, Name);
283 for (auto const &Child : StringChildren) {
284 Child.second->print(Writer, Child.first);
285 }
286 for (auto const &Child : IDChildren) {
287 Child.second->print(Writer, to_string(Child.first));
288 }
289}
290
291// This function returns the size of the entire resource tree, including
292// directory tables, directory entries, and data entries. It does not include
293// the directory strings or the relocations of the .rsrc section.
294uint32_t WindowsResourceParser::TreeNode::getTreeSize() const {
295 uint32_t Size = (IDChildren.size() + StringChildren.size()) *
296 sizeof(coff_resource_dir_entry);
297
298 // Reached a node pointing to a data entry.
299 if (IsDataNode) {
300 Size += sizeof(coff_resource_data_entry);
301 return Size;
302 }
303
304 // If the node does not point to data, it must have a directory table pointing
305 // to other nodes.
306 Size += sizeof(coff_resource_dir_table);
307
308 for (auto const &Child : StringChildren) {
309 Size += Child.second->getTreeSize();
310 }
311 for (auto const &Child : IDChildren) {
312 Size += Child.second->getTreeSize();
313 }
314 return Size;
315}
316
317class WindowsResourceCOFFWriter {
318public:
319 WindowsResourceCOFFWriter(COFF::MachineTypes MachineType,
320 const WindowsResourceParser &Parser, Error &E);
321 std::unique_ptr<MemoryBuffer> write();
322
323private:
324 void performFileLayout();
325 void performSectionOneLayout();
326 void performSectionTwoLayout();
327 void writeCOFFHeader();
328 void writeFirstSectionHeader();
329 void writeSecondSectionHeader();
330 void writeFirstSection();
331 void writeSecondSection();
332 void writeSymbolTable();
333 void writeStringTable();
334 void writeDirectoryTree();
335 void writeDirectoryStringTable();
336 void writeFirstSectionRelocations();
337 std::unique_ptr<MemoryBuffer> OutputBuffer;
338 char *BufferStart;
339 uint64_t CurrentOffset = 0;
340 COFF::MachineTypes MachineType;
341 const WindowsResourceParser::TreeNode &Resources;
342 const ArrayRef<std::vector<uint8_t>> Data;
343 uint64_t FileSize;
344 uint32_t SymbolTableOffset;
345 uint32_t SectionOneSize;
346 uint32_t SectionOneOffset;
347 uint32_t SectionOneRelocations;
348 uint32_t SectionTwoSize;
349 uint32_t SectionTwoOffset;
350 const ArrayRef<std::vector<UTF16>> StringTable;
351 std::vector<uint32_t> StringTableOffsets;
352 std::vector<uint32_t> DataOffsets;
353 std::vector<uint32_t> RelocationAddresses;
354};
355
356WindowsResourceCOFFWriter::WindowsResourceCOFFWriter(
357 COFF::MachineTypes MachineType, const WindowsResourceParser &Parser,
358 Error &E)
359 : MachineType(MachineType), Resources(Parser.getTree()),
360 Data(Parser.getData()), StringTable(Parser.getStringTable()) {
361 performFileLayout();
362
363 OutputBuffer = MemoryBuffer::getNewMemBuffer(FileSize);
364}
365
366void WindowsResourceCOFFWriter::performFileLayout() {
367 // Add size of COFF header.
368 FileSize = COFF::Header16Size;
369
370 // one .rsrc section header for directory tree, another for resource data.
371 FileSize += 2 * COFF::SectionSize;
372
373 performSectionOneLayout();
374 performSectionTwoLayout();
375
376 // We have reached the address of the symbol table.
377 SymbolTableOffset = FileSize;
378
379 FileSize += COFF::Symbol16Size; // size of the @feat.00 symbol.
380 FileSize += 4 * COFF::Symbol16Size; // symbol + aux for each section.
381 FileSize += Data.size() * COFF::Symbol16Size; // 1 symbol per resource.
382 FileSize += 4; // four null bytes for the string table.
383}
384
385void WindowsResourceCOFFWriter::performSectionOneLayout() {
386 SectionOneOffset = FileSize;
387
388 SectionOneSize = Resources.getTreeSize();
389 uint32_t CurrentStringOffset = SectionOneSize;
390 uint32_t TotalStringTableSize = 0;
391 for (auto const &String : StringTable) {
392 StringTableOffsets.push_back(CurrentStringOffset);
393 uint32_t StringSize = String.size() * sizeof(UTF16) + sizeof(uint16_t);
394 CurrentStringOffset += StringSize;
395 TotalStringTableSize += StringSize;
396 }
397 SectionOneSize += alignTo(TotalStringTableSize, sizeof(uint32_t));
398
399 // account for the relocations of section one.
400 SectionOneRelocations = FileSize + SectionOneSize;
401 FileSize += SectionOneSize;
402 FileSize +=
403 Data.size() * COFF::RelocationSize; // one relocation for each resource.
404 FileSize = alignTo(FileSize, SECTION_ALIGNMENT);
405}
406
407void WindowsResourceCOFFWriter::performSectionTwoLayout() {
408 // add size of .rsrc$2 section, which contains all resource data on 8-byte
409 // alignment.
410 SectionTwoOffset = FileSize;
411 SectionTwoSize = 0;
412 for (auto const &Entry : Data) {
413 DataOffsets.push_back(SectionTwoSize);
414 SectionTwoSize += alignTo(Entry.size(), sizeof(uint64_t));
415 }
416 FileSize += SectionTwoSize;
417 FileSize = alignTo(FileSize, SECTION_ALIGNMENT);
418}
419
420static std::time_t getTime() {
421 std::time_t Now = time(nullptr);
422 if (Now < 0 || !isUInt<32>(Now))
423 return UINT32_MAX(4294967295U);
424 return Now;
425}
426
427std::unique_ptr<MemoryBuffer> WindowsResourceCOFFWriter::write() {
428 BufferStart = const_cast<char *>(OutputBuffer->getBufferStart());
429
430 writeCOFFHeader();
431 writeFirstSectionHeader();
432 writeSecondSectionHeader();
433 writeFirstSection();
434 writeSecondSection();
435 writeSymbolTable();
436 writeStringTable();
437
438 return std::move(OutputBuffer);
439}
440
441void WindowsResourceCOFFWriter::writeCOFFHeader() {
442 // Write the COFF header.
443 auto *Header = reinterpret_cast<coff_file_header *>(BufferStart);
444 Header->Machine = MachineType;
445 Header->NumberOfSections = 2;
446 Header->TimeDateStamp = getTime();
447 Header->PointerToSymbolTable = SymbolTableOffset;
448 // One symbol for every resource plus 2 for each section and @feat.00
449 Header->NumberOfSymbols = Data.size() + 5;
450 Header->SizeOfOptionalHeader = 0;
451 Header->Characteristics = COFF::IMAGE_FILE_32BIT_MACHINE;
452}
453
454void WindowsResourceCOFFWriter::writeFirstSectionHeader() {
455 // Write the first section header.
456 CurrentOffset += sizeof(coff_file_header);
457 auto *SectionOneHeader =
458 reinterpret_cast<coff_section *>(BufferStart + CurrentOffset);
459 strncpy(SectionOneHeader->Name, ".rsrc$01", (size_t)COFF::NameSize);
460 SectionOneHeader->VirtualSize = 0;
461 SectionOneHeader->VirtualAddress = 0;
462 SectionOneHeader->SizeOfRawData = SectionOneSize;
463 SectionOneHeader->PointerToRawData = SectionOneOffset;
464 SectionOneHeader->PointerToRelocations = SectionOneRelocations;
465 SectionOneHeader->PointerToLinenumbers = 0;
466 SectionOneHeader->NumberOfRelocations = Data.size();
467 SectionOneHeader->NumberOfLinenumbers = 0;
468 SectionOneHeader->Characteristics += COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
469 SectionOneHeader->Characteristics += COFF::IMAGE_SCN_MEM_READ;
470}
471
472void WindowsResourceCOFFWriter::writeSecondSectionHeader() {
473 // Write the second section header.
474 CurrentOffset += sizeof(coff_section);
475 auto *SectionTwoHeader =
476 reinterpret_cast<coff_section *>(BufferStart + CurrentOffset);
477 strncpy(SectionTwoHeader->Name, ".rsrc$02", (size_t)COFF::NameSize);
478 SectionTwoHeader->VirtualSize = 0;
479 SectionTwoHeader->VirtualAddress = 0;
480 SectionTwoHeader->SizeOfRawData = SectionTwoSize;
481 SectionTwoHeader->PointerToRawData = SectionTwoOffset;
482 SectionTwoHeader->PointerToRelocations = 0;
483 SectionTwoHeader->PointerToLinenumbers = 0;
484 SectionTwoHeader->NumberOfRelocations = 0;
485 SectionTwoHeader->NumberOfLinenumbers = 0;
486 SectionTwoHeader->Characteristics = COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
487 SectionTwoHeader->Characteristics += COFF::IMAGE_SCN_MEM_READ;
488}
489
490void WindowsResourceCOFFWriter::writeFirstSection() {
491 // Write section one.
492 CurrentOffset += sizeof(coff_section);
493
494 writeDirectoryTree();
495 writeDirectoryStringTable();
496 writeFirstSectionRelocations();
497
498 CurrentOffset = alignTo(CurrentOffset, SECTION_ALIGNMENT);
499}
500
501void WindowsResourceCOFFWriter::writeSecondSection() {
502 // Now write the .rsrc$02 section.
503 for (auto const &RawDataEntry : Data) {
504 std::copy(RawDataEntry.begin(), RawDataEntry.end(),
505 BufferStart + CurrentOffset);
506 CurrentOffset += alignTo(RawDataEntry.size(), sizeof(uint64_t));
507 }
508
509 CurrentOffset = alignTo(CurrentOffset, SECTION_ALIGNMENT);
510}
511
512void WindowsResourceCOFFWriter::writeSymbolTable() {
513 // Now write the symbol table.
514 // First, the feat symbol.
515 auto *Symbol = reinterpret_cast<coff_symbol16 *>(BufferStart + CurrentOffset);
516 strncpy(Symbol->Name.ShortName, "@feat.00", (size_t)COFF::NameSize);
517 Symbol->Value = 0x11;
518 Symbol->SectionNumber = 0xffff;
519 Symbol->Type = COFF::IMAGE_SYM_DTYPE_NULL;
520 Symbol->StorageClass = COFF::IMAGE_SYM_CLASS_STATIC;
521 Symbol->NumberOfAuxSymbols = 0;
522 CurrentOffset += sizeof(coff_symbol16);
523
524 // Now write the .rsrc1 symbol + aux.
525 Symbol = reinterpret_cast<coff_symbol16 *>(BufferStart + CurrentOffset);
526 strncpy(Symbol->Name.ShortName, ".rsrc$01", (size_t)COFF::NameSize);
527 Symbol->Value = 0;
528 Symbol->SectionNumber = 1;
529 Symbol->Type = COFF::IMAGE_SYM_DTYPE_NULL;
530 Symbol->StorageClass = COFF::IMAGE_SYM_CLASS_STATIC;
531 Symbol->NumberOfAuxSymbols = 1;
532 CurrentOffset += sizeof(coff_symbol16);
533 auto *Aux = reinterpret_cast<coff_aux_section_definition *>(BufferStart +
534 CurrentOffset);
535 Aux->Length = SectionOneSize;
536 Aux->NumberOfRelocations = Data.size();
537 Aux->NumberOfLinenumbers = 0;
538 Aux->CheckSum = 0;
539 Aux->NumberLowPart = 0;
540 Aux->Selection = 0;
541 CurrentOffset += sizeof(coff_aux_section_definition);
542
543 // Now write the .rsrc2 symbol + aux.
544 Symbol = reinterpret_cast<coff_symbol16 *>(BufferStart + CurrentOffset);
545 strncpy(Symbol->Name.ShortName, ".rsrc$02", (size_t)COFF::NameSize);
546 Symbol->Value = 0;
547 Symbol->SectionNumber = 2;
548 Symbol->Type = COFF::IMAGE_SYM_DTYPE_NULL;
549 Symbol->StorageClass = COFF::IMAGE_SYM_CLASS_STATIC;
550 Symbol->NumberOfAuxSymbols = 1;
551 CurrentOffset += sizeof(coff_symbol16);
552 Aux = reinterpret_cast<coff_aux_section_definition *>(BufferStart +
553 CurrentOffset);
554 Aux->Length = SectionTwoSize;
555 Aux->NumberOfRelocations = 0;
556 Aux->NumberOfLinenumbers = 0;
557 Aux->CheckSum = 0;
558 Aux->NumberLowPart = 0;
559 Aux->Selection = 0;
560 CurrentOffset += sizeof(coff_aux_section_definition);
561
562 // Now write a symbol for each relocation.
563 for (unsigned i = 0; i < Data.size(); i++) {
564 char RelocationName[9];
565 sprintf(RelocationName, "$R%06X", DataOffsets[i]);
566 Symbol = reinterpret_cast<coff_symbol16 *>(BufferStart + CurrentOffset);
567 strncpy(Symbol->Name.ShortName, RelocationName, (size_t)COFF::NameSize);
568 Symbol->Value = DataOffsets[i];
569 Symbol->SectionNumber = 2;
570 Symbol->Type = COFF::IMAGE_SYM_DTYPE_NULL;
571 Symbol->StorageClass = COFF::IMAGE_SYM_CLASS_STATIC;
572 Symbol->NumberOfAuxSymbols = 0;
573 CurrentOffset += sizeof(coff_symbol16);
574 }
575}
576
577void WindowsResourceCOFFWriter::writeStringTable() {
578 // Just 4 null bytes for the string table.
579 auto COFFStringTable = reinterpret_cast<void *>(BufferStart + CurrentOffset);
580 memset(COFFStringTable, 0, 4);
581}
582
583void WindowsResourceCOFFWriter::writeDirectoryTree() {
584 // Traverse parsed resource tree breadth-first and write the corresponding
585 // COFF objects.
586 std::queue<const WindowsResourceParser::TreeNode *> Queue;
587 Queue.push(&Resources);
588 uint32_t NextLevelOffset =
589 sizeof(coff_resource_dir_table) + (Resources.getStringChildren().size() +
590 Resources.getIDChildren().size()) *
591 sizeof(coff_resource_dir_entry);
592 std::vector<const WindowsResourceParser::TreeNode *> DataEntriesTreeOrder;
593 uint32_t CurrentRelativeOffset = 0;
594
595 while (!Queue.empty()) {
596 auto CurrentNode = Queue.front();
597 Queue.pop();
598 auto *Table = reinterpret_cast<coff_resource_dir_table *>(BufferStart +
599 CurrentOffset);
600 Table->Characteristics = CurrentNode->getCharacteristics();
601 Table->TimeDateStamp = 0;
602 Table->MajorVersion = CurrentNode->getMajorVersion();
603 Table->MinorVersion = CurrentNode->getMinorVersion();
604 auto &IDChildren = CurrentNode->getIDChildren();
605 auto &StringChildren = CurrentNode->getStringChildren();
606 Table->NumberOfNameEntries = StringChildren.size();
607 Table->NumberOfIDEntries = IDChildren.size();
608 CurrentOffset += sizeof(coff_resource_dir_table);
609 CurrentRelativeOffset += sizeof(coff_resource_dir_table);
610
611 // Write the directory entries immediately following each directory table.
612 for (auto const &Child : StringChildren) {
613 auto *Entry = reinterpret_cast<coff_resource_dir_entry *>(BufferStart +
614 CurrentOffset);
615 Entry->Identifier.setNameOffset(
616 StringTableOffsets[Child.second->getStringIndex()]);
617 if (Child.second->checkIsDataNode()) {
618 Entry->Offset.DataEntryOffset = NextLevelOffset;
619 NextLevelOffset += sizeof(coff_resource_data_entry);
620 DataEntriesTreeOrder.push_back(Child.second.get());
621 } else {
622 Entry->Offset.SubdirOffset = NextLevelOffset + (1 << 31);
623 NextLevelOffset += sizeof(coff_resource_dir_table) +
624 (Child.second->getStringChildren().size() +
625 Child.second->getIDChildren().size()) *
626 sizeof(coff_resource_dir_entry);
627 Queue.push(Child.second.get());
628 }
629 CurrentOffset += sizeof(coff_resource_dir_entry);
630 CurrentRelativeOffset += sizeof(coff_resource_dir_entry);
631 }
632 for (auto const &Child : IDChildren) {
633 auto *Entry = reinterpret_cast<coff_resource_dir_entry *>(BufferStart +
634 CurrentOffset);
635 Entry->Identifier.ID = Child.first;
636 if (Child.second->checkIsDataNode()) {
637 Entry->Offset.DataEntryOffset = NextLevelOffset;
638 NextLevelOffset += sizeof(coff_resource_data_entry);
639 DataEntriesTreeOrder.push_back(Child.second.get());
640 } else {
641 Entry->Offset.SubdirOffset = NextLevelOffset + (1 << 31);
642 NextLevelOffset += sizeof(coff_resource_dir_table) +
643 (Child.second->getStringChildren().size() +
644 Child.second->getIDChildren().size()) *
645 sizeof(coff_resource_dir_entry);
646 Queue.push(Child.second.get());
647 }
648 CurrentOffset += sizeof(coff_resource_dir_entry);
649 CurrentRelativeOffset += sizeof(coff_resource_dir_entry);
650 }
651 }
652
653 RelocationAddresses.resize(Data.size());
654 // Now write all the resource data entries.
655 for (auto DataNodes : DataEntriesTreeOrder) {
656 auto *Entry = reinterpret_cast<coff_resource_data_entry *>(BufferStart +
657 CurrentOffset);
658 RelocationAddresses[DataNodes->getDataIndex()] = CurrentRelativeOffset;
659 Entry->DataRVA = 0; // Set to zero because it is a relocation.
660 Entry->DataSize = Data[DataNodes->getDataIndex()].size();
661 Entry->Codepage = 0;
662 Entry->Reserved = 0;
663 CurrentOffset += sizeof(coff_resource_data_entry);
664 CurrentRelativeOffset += sizeof(coff_resource_data_entry);
665 }
666}
667
668void WindowsResourceCOFFWriter::writeDirectoryStringTable() {
669 // Now write the directory string table for .rsrc$01
670 uint32_t TotalStringTableSize = 0;
671 for (auto &String : StringTable) {
672 uint16_t Length = String.size();
673 support::endian::write16le(BufferStart + CurrentOffset, Length);
674 CurrentOffset += sizeof(uint16_t);
675 auto *Start = reinterpret_cast<UTF16 *>(BufferStart + CurrentOffset);
676 std::copy(String.begin(), String.end(), Start);
677 CurrentOffset += Length * sizeof(UTF16);
678 TotalStringTableSize += Length * sizeof(UTF16) + sizeof(uint16_t);
679 }
680 CurrentOffset +=
681 alignTo(TotalStringTableSize, sizeof(uint32_t)) - TotalStringTableSize;
682}
683
684void WindowsResourceCOFFWriter::writeFirstSectionRelocations() {
685
686 // Now write the relocations for .rsrc$01
687 // Five symbols already in table before we start, @feat.00 and 2 for each
688 // .rsrc section.
689 uint32_t NextSymbolIndex = 5;
690 for (unsigned i = 0; i < Data.size(); i++) {
691 auto *Reloc =
692 reinterpret_cast<coff_relocation *>(BufferStart + CurrentOffset);
693 Reloc->VirtualAddress = RelocationAddresses[i];
694 Reloc->SymbolTableIndex = NextSymbolIndex++;
695 switch (MachineType) {
696 case COFF::IMAGE_FILE_MACHINE_ARMNT:
697 Reloc->Type = COFF::IMAGE_REL_ARM_ADDR32NB;
698 break;
699 case COFF::IMAGE_FILE_MACHINE_AMD64:
700 Reloc->Type = COFF::IMAGE_REL_AMD64_ADDR32NB;
701 break;
702 case COFF::IMAGE_FILE_MACHINE_I386:
703 Reloc->Type = COFF::IMAGE_REL_I386_DIR32NB;
704 break;
705 case COFF::IMAGE_FILE_MACHINE_ARM64:
706 Reloc->Type = COFF::IMAGE_REL_ARM64_ADDR32NB;
707 break;
708 default:
709 llvm_unreachable("unknown machine type")::llvm::llvm_unreachable_internal("unknown machine type", "/build/llvm-toolchain-snapshot-6.0~svn318211/lib/Object/WindowsResource.cpp"
, 709)
;
710 }
711 CurrentOffset += sizeof(coff_relocation);
712 }
713}
714
715Expected<std::unique_ptr<MemoryBuffer>>
716writeWindowsResourceCOFF(COFF::MachineTypes MachineType,
717 const WindowsResourceParser &Parser) {
718 Error E = Error::success();
719 WindowsResourceCOFFWriter Writer(MachineType, Parser, E);
720 if (E)
721 return std::move(E);
722 return Writer.write();
723}
724
725} // namespace object
726} // namespace llvm

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

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

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

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