Bug Summary

File:include/llvm/Support/Error.h
Warning:line 200, column 5
Potential leak of memory pointed to by 'Payload._M_t._M_head_impl'

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name DWARFVerifier.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-9/lib/clang/9.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/lib/DebugInfo/DWARF -I /build/llvm-toolchain-snapshot-9~svn362543/lib/DebugInfo/DWARF -I /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/include -I /build/llvm-toolchain-snapshot-9~svn362543/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/9.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-9/lib/clang/9.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/lib/DebugInfo/DWARF -fdebug-prefix-map=/build/llvm-toolchain-snapshot-9~svn362543=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2019-06-05-060531-1271-1 -x c++ /build/llvm-toolchain-snapshot-9~svn362543/lib/DebugInfo/DWARF/DWARFVerifier.cpp -faddrsig

/build/llvm-toolchain-snapshot-9~svn362543/lib/DebugInfo/DWARF/DWARFVerifier.cpp

1//===- DWARFVerifier.cpp --------------------------------------------------===//
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#include "llvm/DebugInfo/DWARF/DWARFVerifier.h"
9#include "llvm/ADT/SmallSet.h"
10#include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"
11#include "llvm/DebugInfo/DWARF/DWARFContext.h"
12#include "llvm/DebugInfo/DWARF/DWARFDebugLine.h"
13#include "llvm/DebugInfo/DWARF/DWARFDie.h"
14#include "llvm/DebugInfo/DWARF/DWARFExpression.h"
15#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
16#include "llvm/DebugInfo/DWARF/DWARFSection.h"
17#include "llvm/Support/DJB.h"
18#include "llvm/Support/FormatVariadic.h"
19#include "llvm/Support/WithColor.h"
20#include "llvm/Support/raw_ostream.h"
21#include <map>
22#include <set>
23#include <vector>
24
25using namespace llvm;
26using namespace dwarf;
27using namespace object;
28
29DWARFVerifier::DieRangeInfo::address_range_iterator
30DWARFVerifier::DieRangeInfo::insert(const DWARFAddressRange &R) {
31 auto Begin = Ranges.begin();
32 auto End = Ranges.end();
33 auto Pos = std::lower_bound(Begin, End, R);
34
35 if (Pos != End) {
36 if (Pos->intersects(R))
37 return Pos;
38 if (Pos != Begin) {
39 auto Iter = Pos - 1;
40 if (Iter->intersects(R))
41 return Iter;
42 }
43 }
44
45 Ranges.insert(Pos, R);
46 return Ranges.end();
47}
48
49DWARFVerifier::DieRangeInfo::die_range_info_iterator
50DWARFVerifier::DieRangeInfo::insert(const DieRangeInfo &RI) {
51 auto End = Children.end();
52 auto Iter = Children.begin();
53 while (Iter != End) {
54 if (Iter->intersects(RI))
55 return Iter;
56 ++Iter;
57 }
58 Children.insert(RI);
59 return Children.end();
60}
61
62bool DWARFVerifier::DieRangeInfo::contains(const DieRangeInfo &RHS) const {
63 auto I1 = Ranges.begin(), E1 = Ranges.end();
64 auto I2 = RHS.Ranges.begin(), E2 = RHS.Ranges.end();
65 if (I2 == E2)
66 return true;
67
68 DWARFAddressRange R = *I2;
69 while (I1 != E1) {
70 bool Covered = I1->LowPC <= R.LowPC;
71 if (R.LowPC == R.HighPC || (Covered && R.HighPC <= I1->HighPC)) {
72 if (++I2 == E2)
73 return true;
74 R = *I2;
75 continue;
76 }
77 if (!Covered)
78 return false;
79 if (R.LowPC < I1->HighPC)
80 R.LowPC = I1->HighPC;
81 ++I1;
82 }
83 return false;
84}
85
86bool DWARFVerifier::DieRangeInfo::intersects(const DieRangeInfo &RHS) const {
87 auto I1 = Ranges.begin(), E1 = Ranges.end();
88 auto I2 = RHS.Ranges.begin(), E2 = RHS.Ranges.end();
89 while (I1 != E1 && I2 != E2) {
90 if (I1->intersects(*I2))
91 return true;
92 if (I1->LowPC < I2->LowPC)
93 ++I1;
94 else
95 ++I2;
96 }
97 return false;
98}
99
100bool DWARFVerifier::verifyUnitHeader(const DWARFDataExtractor DebugInfoData,
101 uint32_t *Offset, unsigned UnitIndex,
102 uint8_t &UnitType, bool &isUnitDWARF64) {
103 uint64_t AbbrOffset, Length;
104 uint8_t AddrSize = 0;
105 uint16_t Version;
106 bool Success = true;
107
108 bool ValidLength = false;
109 bool ValidVersion = false;
110 bool ValidAddrSize = false;
111 bool ValidType = true;
112 bool ValidAbbrevOffset = true;
113
114 uint32_t OffsetStart = *Offset;
115 Length = DebugInfoData.getU32(Offset);
116 if (Length == UINT32_MAX(4294967295U)) {
117 Length = DebugInfoData.getU64(Offset);
118 isUnitDWARF64 = true;
119 }
120 Version = DebugInfoData.getU16(Offset);
121
122 if (Version >= 5) {
123 UnitType = DebugInfoData.getU8(Offset);
124 AddrSize = DebugInfoData.getU8(Offset);
125 AbbrOffset = isUnitDWARF64 ? DebugInfoData.getU64(Offset) : DebugInfoData.getU32(Offset);
126 ValidType = dwarf::isUnitType(UnitType);
127 } else {
128 UnitType = 0;
129 AbbrOffset = isUnitDWARF64 ? DebugInfoData.getU64(Offset) : DebugInfoData.getU32(Offset);
130 AddrSize = DebugInfoData.getU8(Offset);
131 }
132
133 if (!DCtx.getDebugAbbrev()->getAbbreviationDeclarationSet(AbbrOffset))
134 ValidAbbrevOffset = false;
135
136 ValidLength = DebugInfoData.isValidOffset(OffsetStart + Length + 3);
137 ValidVersion = DWARFContext::isSupportedVersion(Version);
138 ValidAddrSize = AddrSize == 4 || AddrSize == 8;
139 if (!ValidLength || !ValidVersion || !ValidAddrSize || !ValidAbbrevOffset ||
140 !ValidType) {
141 Success = false;
142 error() << format("Units[%d] - start offset: 0x%08x \n", UnitIndex,
143 OffsetStart);
144 if (!ValidLength)
145 note() << "The length for this unit is too "
146 "large for the .debug_info provided.\n";
147 if (!ValidVersion)
148 note() << "The 16 bit unit header version is not valid.\n";
149 if (!ValidType)
150 note() << "The unit type encoding is not valid.\n";
151 if (!ValidAbbrevOffset)
152 note() << "The offset into the .debug_abbrev section is "
153 "not valid.\n";
154 if (!ValidAddrSize)
155 note() << "The address size is unsupported.\n";
156 }
157 *Offset = OffsetStart + Length + (isUnitDWARF64 ? 12 : 4);
158 return Success;
159}
160
161unsigned DWARFVerifier::verifyUnitContents(DWARFUnit &Unit) {
162 unsigned NumUnitErrors = 0;
163 unsigned NumDies = Unit.getNumDIEs();
164 for (unsigned I = 0; I < NumDies; ++I) {
6
Assuming 'I' is >= 'NumDies'
7
Loop condition is false. Execution continues on line 178
165 auto Die = Unit.getDIEAtIndex(I);
166
167 if (Die.getTag() == DW_TAG_null)
168 continue;
169
170 for (auto AttrValue : Die.attributes()) {
171 NumUnitErrors += verifyDebugInfoAttribute(Die, AttrValue);
172 NumUnitErrors += verifyDebugInfoForm(Die, AttrValue);
173 }
174
175 NumUnitErrors += verifyDebugInfoCallSite(Die);
176 }
177
178 DWARFDie Die = Unit.getUnitDIE(/* ExtractUnitDIEOnly = */ false);
179 if (!Die) {
8
Assuming the condition is false
9
Taking false branch
180 error() << "Compilation unit without DIE.\n";
181 NumUnitErrors++;
182 return NumUnitErrors;
183 }
184
185 if (!dwarf::isUnitType(Die.getTag())) {
10
Taking true branch
186 error() << "Compilation unit root DIE is not a unit DIE: "
187 << dwarf::TagString(Die.getTag()) << ".\n";
188 NumUnitErrors++;
189 }
190
191 uint8_t UnitType = Unit.getUnitType();
192 if (!DWARFUnit::isMatchingUnitTypeAndTag(UnitType, Die.getTag())) {
11
Taking true branch
193 error() << "Compilation unit type (" << dwarf::UnitTypeString(UnitType)
194 << ") and root DIE (" << dwarf::TagString(Die.getTag())
195 << ") do not match.\n";
196 NumUnitErrors++;
197 }
198
199 DieRangeInfo RI;
200 NumUnitErrors += verifyDieRanges(Die, RI);
12
Calling 'DWARFVerifier::verifyDieRanges'
201
202 return NumUnitErrors;
203}
204
205unsigned DWARFVerifier::verifyDebugInfoCallSite(const DWARFDie &Die) {
206 if (Die.getTag() != DW_TAG_call_site)
207 return 0;
208
209 DWARFDie Curr = Die.getParent();
210 for (; Curr.isValid() && !Curr.isSubprogramDIE(); Curr = Die.getParent()) {
211 if (Curr.getTag() == DW_TAG_inlined_subroutine) {
212 error() << "Call site entry nested within inlined subroutine:";
213 Curr.dump(OS);
214 return 1;
215 }
216 }
217
218 if (!Curr.isValid()) {
219 error() << "Call site entry not nested within a valid subprogram:";
220 Die.dump(OS);
221 return 1;
222 }
223
224 Optional<DWARFFormValue> CallAttr =
225 Curr.find({DW_AT_call_all_calls, DW_AT_call_all_source_calls,
226 DW_AT_call_all_tail_calls});
227 if (!CallAttr) {
228 error() << "Subprogram with call site entry has no DW_AT_call attribute:";
229 Curr.dump(OS);
230 Die.dump(OS, /*indent*/ 1);
231 return 1;
232 }
233
234 return 0;
235}
236
237unsigned DWARFVerifier::verifyAbbrevSection(const DWARFDebugAbbrev *Abbrev) {
238 unsigned NumErrors = 0;
239 if (Abbrev) {
240 const DWARFAbbreviationDeclarationSet *AbbrDecls =
241 Abbrev->getAbbreviationDeclarationSet(0);
242 for (auto AbbrDecl : *AbbrDecls) {
243 SmallDenseSet<uint16_t> AttributeSet;
244 for (auto Attribute : AbbrDecl.attributes()) {
245 auto Result = AttributeSet.insert(Attribute.Attr);
246 if (!Result.second) {
247 error() << "Abbreviation declaration contains multiple "
248 << AttributeString(Attribute.Attr) << " attributes.\n";
249 AbbrDecl.dump(OS);
250 ++NumErrors;
251 }
252 }
253 }
254 }
255 return NumErrors;
256}
257
258bool DWARFVerifier::handleDebugAbbrev() {
259 OS << "Verifying .debug_abbrev...\n";
260
261 const DWARFObject &DObj = DCtx.getDWARFObj();
262 unsigned NumErrors = 0;
263 if (!DObj.getAbbrevSection().empty())
264 NumErrors += verifyAbbrevSection(DCtx.getDebugAbbrev());
265 if (!DObj.getAbbrevDWOSection().empty())
266 NumErrors += verifyAbbrevSection(DCtx.getDebugAbbrevDWO());
267
268 return NumErrors == 0;
269}
270
271unsigned DWARFVerifier::verifyUnitSection(const DWARFSection &S,
272 DWARFSectionKind SectionKind) {
273 const DWARFObject &DObj = DCtx.getDWARFObj();
274 DWARFDataExtractor DebugInfoData(DObj, S, DCtx.isLittleEndian(), 0);
275 unsigned NumDebugInfoErrors = 0;
276 uint32_t OffsetStart = 0, Offset = 0, UnitIdx = 0;
277 uint8_t UnitType = 0;
278 bool isUnitDWARF64 = false;
279 bool isHeaderChainValid = true;
280 bool hasDIE = DebugInfoData.isValidOffset(Offset);
281 DWARFUnitVector TypeUnitVector;
282 DWARFUnitVector CompileUnitVector;
283 while (hasDIE) {
1
Loop condition is true. Entering loop body
284 OffsetStart = Offset;
285 if (!verifyUnitHeader(DebugInfoData, &Offset, UnitIdx, UnitType,
2
Taking false branch
286 isUnitDWARF64)) {
287 isHeaderChainValid = false;
288 if (isUnitDWARF64)
289 break;
290 } else {
291 DWARFUnitHeader Header;
292 Header.extract(DCtx, DebugInfoData, &OffsetStart, SectionKind);
293 DWARFUnit *Unit;
294 switch (UnitType) {
3
Control jumps to 'case 0:' at line 310
295 case dwarf::DW_UT_type:
296 case dwarf::DW_UT_split_type: {
297 Unit = TypeUnitVector.addUnit(llvm::make_unique<DWARFTypeUnit>(
298 DCtx, S, Header, DCtx.getDebugAbbrev(), &DObj.getRangeSection(),
299 &DObj.getLocSection(), DObj.getStringSection(),
300 DObj.getStringOffsetSection(), &DObj.getAppleObjCSection(),
301 DObj.getLineSection(), DCtx.isLittleEndian(), false,
302 TypeUnitVector));
303 break;
304 }
305 case dwarf::DW_UT_skeleton:
306 case dwarf::DW_UT_split_compile:
307 case dwarf::DW_UT_compile:
308 case dwarf::DW_UT_partial:
309 // UnitType = 0 means that we are verifying a compile unit in DWARF v4.
310 case 0: {
311 Unit = CompileUnitVector.addUnit(llvm::make_unique<DWARFCompileUnit>(
312 DCtx, S, Header, DCtx.getDebugAbbrev(), &DObj.getRangeSection(),
313 &DObj.getLocSection(), DObj.getStringSection(),
314 DObj.getStringOffsetSection(), &DObj.getAppleObjCSection(),
315 DObj.getLineSection(), DCtx.isLittleEndian(), false,
316 CompileUnitVector));
317 break;
4
Execution continues on line 321
318 }
319 default: { llvm_unreachable("Invalid UnitType.")::llvm::llvm_unreachable_internal("Invalid UnitType.", "/build/llvm-toolchain-snapshot-9~svn362543/lib/DebugInfo/DWARF/DWARFVerifier.cpp"
, 319)
; }
320 }
321 NumDebugInfoErrors += verifyUnitContents(*Unit);
5
Calling 'DWARFVerifier::verifyUnitContents'
322 }
323 hasDIE = DebugInfoData.isValidOffset(Offset);
324 ++UnitIdx;
325 }
326 if (UnitIdx == 0 && !hasDIE) {
327 warn() << "Section is empty.\n";
328 isHeaderChainValid = true;
329 }
330 if (!isHeaderChainValid)
331 ++NumDebugInfoErrors;
332 NumDebugInfoErrors += verifyDebugInfoReferences();
333 return NumDebugInfoErrors;
334}
335
336bool DWARFVerifier::handleDebugInfo() {
337 const DWARFObject &DObj = DCtx.getDWARFObj();
338 unsigned NumErrors = 0;
339
340 OS << "Verifying .debug_info Unit Header Chain...\n";
341 DObj.forEachInfoSections([&](const DWARFSection &S) {
342 NumErrors += verifyUnitSection(S, DW_SECT_INFO);
343 });
344
345 OS << "Verifying .debug_types Unit Header Chain...\n";
346 DObj.forEachTypesSections([&](const DWARFSection &S) {
347 NumErrors += verifyUnitSection(S, DW_SECT_TYPES);
348 });
349 return NumErrors == 0;
350}
351
352unsigned DWARFVerifier::verifyDieRanges(const DWARFDie &Die,
353 DieRangeInfo &ParentRI) {
354 unsigned NumErrors = 0;
355
356 if (!Die.isValid())
13
Assuming the condition is false
14
Taking false branch
357 return NumErrors;
358
359 auto RangesOrError = Die.getAddressRanges();
360 if (!RangesOrError) {
15
Taking true branch
361 // FIXME: Report the error.
362 ++NumErrors;
363 llvm::consumeError(RangesOrError.takeError());
16
Calling 'consumeError'
364 return NumErrors;
365 }
366
367 DWARFAddressRangesVector Ranges = RangesOrError.get();
368 // Build RI for this DIE and check that ranges within this DIE do not
369 // overlap.
370 DieRangeInfo RI(Die);
371
372 // TODO support object files better
373 //
374 // Some object file formats (i.e. non-MachO) support COMDAT. ELF in
375 // particular does so by placing each function into a section. The DWARF data
376 // for the function at that point uses a section relative DW_FORM_addrp for
377 // the DW_AT_low_pc and a DW_FORM_data4 for the offset as the DW_AT_high_pc.
378 // In such a case, when the Die is the CU, the ranges will overlap, and we
379 // will flag valid conflicting ranges as invalid.
380 //
381 // For such targets, we should read the ranges from the CU and partition them
382 // by the section id. The ranges within a particular section should be
383 // disjoint, although the ranges across sections may overlap. We would map
384 // the child die to the entity that it references and the section with which
385 // it is associated. The child would then be checked against the range
386 // information for the associated section.
387 //
388 // For now, simply elide the range verification for the CU DIEs if we are
389 // processing an object file.
390
391 if (!IsObjectFile || IsMachOObject || Die.getTag() != DW_TAG_compile_unit) {
392 for (auto Range : Ranges) {
393 if (!Range.valid()) {
394 ++NumErrors;
395 error() << "Invalid address range " << Range << "\n";
396 continue;
397 }
398
399 // Verify that ranges don't intersect.
400 const auto IntersectingRange = RI.insert(Range);
401 if (IntersectingRange != RI.Ranges.end()) {
402 ++NumErrors;
403 error() << "DIE has overlapping address ranges: " << Range << " and "
404 << *IntersectingRange << "\n";
405 break;
406 }
407 }
408 }
409
410 // Verify that children don't intersect.
411 const auto IntersectingChild = ParentRI.insert(RI);
412 if (IntersectingChild != ParentRI.Children.end()) {
413 ++NumErrors;
414 error() << "DIEs have overlapping address ranges:";
415 dump(Die);
416 dump(IntersectingChild->Die) << '\n';
417 }
418
419 // Verify that ranges are contained within their parent.
420 bool ShouldBeContained = !Ranges.empty() && !ParentRI.Ranges.empty() &&
421 !(Die.getTag() == DW_TAG_subprogram &&
422 ParentRI.Die.getTag() == DW_TAG_subprogram);
423 if (ShouldBeContained && !ParentRI.contains(RI)) {
424 ++NumErrors;
425 error() << "DIE address ranges are not contained in its parent's ranges:";
426 dump(ParentRI.Die);
427 dump(Die, 2) << '\n';
428 }
429
430 // Recursively check children.
431 for (DWARFDie Child : Die)
432 NumErrors += verifyDieRanges(Child, RI);
433
434 return NumErrors;
435}
436
437unsigned DWARFVerifier::verifyDebugInfoAttribute(const DWARFDie &Die,
438 DWARFAttribute &AttrValue) {
439 unsigned NumErrors = 0;
440 auto ReportError = [&](const Twine &TitleMsg) {
441 ++NumErrors;
442 error() << TitleMsg << '\n';
443 dump(Die) << '\n';
444 };
445
446 const DWARFObject &DObj = DCtx.getDWARFObj();
447 const auto Attr = AttrValue.Attr;
448 switch (Attr) {
449 case DW_AT_ranges:
450 // Make sure the offset in the DW_AT_ranges attribute is valid.
451 if (auto SectionOffset = AttrValue.Value.getAsSectionOffset()) {
452 if (*SectionOffset >= DObj.getRangeSection().Data.size())
453 ReportError("DW_AT_ranges offset is beyond .debug_ranges bounds:");
454 break;
455 }
456 ReportError("DIE has invalid DW_AT_ranges encoding:");
457 break;
458 case DW_AT_stmt_list:
459 // Make sure the offset in the DW_AT_stmt_list attribute is valid.
460 if (auto SectionOffset = AttrValue.Value.getAsSectionOffset()) {
461 if (*SectionOffset >= DObj.getLineSection().Data.size())
462 ReportError("DW_AT_stmt_list offset is beyond .debug_line bounds: " +
463 llvm::formatv("{0:x8}", *SectionOffset));
464 break;
465 }
466 ReportError("DIE has invalid DW_AT_stmt_list encoding:");
467 break;
468 case DW_AT_location: {
469 auto VerifyLocationExpr = [&](StringRef D) {
470 DWARFUnit *U = Die.getDwarfUnit();
471 DataExtractor Data(D, DCtx.isLittleEndian(), 0);
472 DWARFExpression Expression(Data, U->getVersion(),
473 U->getAddressByteSize());
474 bool Error = llvm::any_of(Expression, [](DWARFExpression::Operation &Op) {
475 return Op.isError();
476 });
477 if (Error || !Expression.verify(U))
478 ReportError("DIE contains invalid DWARF expression:");
479 };
480 if (Optional<ArrayRef<uint8_t>> Expr = AttrValue.Value.getAsBlock()) {
481 // Verify inlined location.
482 VerifyLocationExpr(llvm::toStringRef(*Expr));
483 } else if (auto LocOffset = AttrValue.Value.getAsSectionOffset()) {
484 // Verify location list.
485 if (auto DebugLoc = DCtx.getDebugLoc())
486 if (auto LocList = DebugLoc->getLocationListAtOffset(*LocOffset))
487 for (const auto &Entry : LocList->Entries)
488 VerifyLocationExpr({Entry.Loc.data(), Entry.Loc.size()});
489 }
490 break;
491 }
492 case DW_AT_specification:
493 case DW_AT_abstract_origin: {
494 if (auto ReferencedDie = Die.getAttributeValueAsReferencedDie(Attr)) {
495 auto DieTag = Die.getTag();
496 auto RefTag = ReferencedDie.getTag();
497 if (DieTag == RefTag)
498 break;
499 if (DieTag == DW_TAG_inlined_subroutine && RefTag == DW_TAG_subprogram)
500 break;
501 if (DieTag == DW_TAG_variable && RefTag == DW_TAG_member)
502 break;
503 ReportError("DIE with tag " + TagString(DieTag) + " has " +
504 AttributeString(Attr) +
505 " that points to DIE with "
506 "incompatible tag " +
507 TagString(RefTag));
508 }
509 break;
510 }
511 case DW_AT_type: {
512 DWARFDie TypeDie = Die.getAttributeValueAsReferencedDie(DW_AT_type);
513 if (TypeDie && !isType(TypeDie.getTag())) {
514 ReportError("DIE has " + AttributeString(Attr) +
515 " with incompatible tag " + TagString(TypeDie.getTag()));
516 }
517 break;
518 }
519 default:
520 break;
521 }
522 return NumErrors;
523}
524
525unsigned DWARFVerifier::verifyDebugInfoForm(const DWARFDie &Die,
526 DWARFAttribute &AttrValue) {
527 const DWARFObject &DObj = DCtx.getDWARFObj();
528 auto DieCU = Die.getDwarfUnit();
529 unsigned NumErrors = 0;
530 const auto Form = AttrValue.Value.getForm();
531 switch (Form) {
532 case DW_FORM_ref1:
533 case DW_FORM_ref2:
534 case DW_FORM_ref4:
535 case DW_FORM_ref8:
536 case DW_FORM_ref_udata: {
537 // Verify all CU relative references are valid CU offsets.
538 Optional<uint64_t> RefVal = AttrValue.Value.getAsReference();
539 assert(RefVal)((RefVal) ? static_cast<void> (0) : __assert_fail ("RefVal"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/DebugInfo/DWARF/DWARFVerifier.cpp"
, 539, __PRETTY_FUNCTION__))
;
540 if (RefVal) {
541 auto CUSize = DieCU->getNextUnitOffset() - DieCU->getOffset();
542 auto CUOffset = AttrValue.Value.getRawUValue();
543 if (CUOffset >= CUSize) {
544 ++NumErrors;
545 error() << FormEncodingString(Form) << " CU offset "
546 << format("0x%08" PRIx64"l" "x", CUOffset)
547 << " is invalid (must be less than CU size of "
548 << format("0x%08" PRIx32"x", CUSize) << "):\n";
549 Die.dump(OS, 0, DumpOpts);
550 dump(Die) << '\n';
551 } else {
552 // Valid reference, but we will verify it points to an actual
553 // DIE later.
554 ReferenceToDIEOffsets[*RefVal].insert(Die.getOffset());
555 }
556 }
557 break;
558 }
559 case DW_FORM_ref_addr: {
560 // Verify all absolute DIE references have valid offsets in the
561 // .debug_info section.
562 Optional<uint64_t> RefVal = AttrValue.Value.getAsReference();
563 assert(RefVal)((RefVal) ? static_cast<void> (0) : __assert_fail ("RefVal"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/DebugInfo/DWARF/DWARFVerifier.cpp"
, 563, __PRETTY_FUNCTION__))
;
564 if (RefVal) {
565 if (*RefVal >= DieCU->getInfoSection().Data.size()) {
566 ++NumErrors;
567 error() << "DW_FORM_ref_addr offset beyond .debug_info "
568 "bounds:\n";
569 dump(Die) << '\n';
570 } else {
571 // Valid reference, but we will verify it points to an actual
572 // DIE later.
573 ReferenceToDIEOffsets[*RefVal].insert(Die.getOffset());
574 }
575 }
576 break;
577 }
578 case DW_FORM_strp: {
579 auto SecOffset = AttrValue.Value.getAsSectionOffset();
580 assert(SecOffset)((SecOffset) ? static_cast<void> (0) : __assert_fail ("SecOffset"
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/DebugInfo/DWARF/DWARFVerifier.cpp"
, 580, __PRETTY_FUNCTION__))
; // DW_FORM_strp is a section offset.
581 if (SecOffset && *SecOffset >= DObj.getStringSection().size()) {
582 ++NumErrors;
583 error() << "DW_FORM_strp offset beyond .debug_str bounds:\n";
584 dump(Die) << '\n';
585 }
586 break;
587 }
588 case DW_FORM_strx:
589 case DW_FORM_strx1:
590 case DW_FORM_strx2:
591 case DW_FORM_strx3:
592 case DW_FORM_strx4: {
593 auto Index = AttrValue.Value.getRawUValue();
594 auto DieCU = Die.getDwarfUnit();
595 // Check that we have a valid DWARF v5 string offsets table.
596 if (!DieCU->getStringOffsetsTableContribution()) {
597 ++NumErrors;
598 error() << FormEncodingString(Form)
599 << " used without a valid string offsets table:\n";
600 dump(Die) << '\n';
601 break;
602 }
603 // Check that the index is within the bounds of the section.
604 unsigned ItemSize = DieCU->getDwarfStringOffsetsByteSize();
605 // Use a 64-bit type to calculate the offset to guard against overflow.
606 uint64_t Offset =
607 (uint64_t)DieCU->getStringOffsetsBase() + Index * ItemSize;
608 if (DObj.getStringOffsetSection().Data.size() < Offset + ItemSize) {
609 ++NumErrors;
610 error() << FormEncodingString(Form) << " uses index "
611 << format("%" PRIu64"l" "u", Index) << ", which is too large:\n";
612 dump(Die) << '\n';
613 break;
614 }
615 // Check that the string offset is valid.
616 uint64_t StringOffset = *DieCU->getStringOffsetSectionItem(Index);
617 if (StringOffset >= DObj.getStringSection().size()) {
618 ++NumErrors;
619 error() << FormEncodingString(Form) << " uses index "
620 << format("%" PRIu64"l" "u", Index)
621 << ", but the referenced string"
622 " offset is beyond .debug_str bounds:\n";
623 dump(Die) << '\n';
624 }
625 break;
626 }
627 default:
628 break;
629 }
630 return NumErrors;
631}
632
633unsigned DWARFVerifier::verifyDebugInfoReferences() {
634 // Take all references and make sure they point to an actual DIE by
635 // getting the DIE by offset and emitting an error
636 OS << "Verifying .debug_info references...\n";
637 unsigned NumErrors = 0;
638 for (const std::pair<uint64_t, std::set<uint32_t>> &Pair :
639 ReferenceToDIEOffsets) {
640 if (DCtx.getDIEForOffset(Pair.first))
641 continue;
642 ++NumErrors;
643 error() << "invalid DIE reference " << format("0x%08" PRIx64"l" "x", Pair.first)
644 << ". Offset is in between DIEs:\n";
645 for (auto Offset : Pair.second)
646 dump(DCtx.getDIEForOffset(Offset)) << '\n';
647 OS << "\n";
648 }
649 return NumErrors;
650}
651
652void DWARFVerifier::verifyDebugLineStmtOffsets() {
653 std::map<uint64_t, DWARFDie> StmtListToDie;
654 for (const auto &CU : DCtx.compile_units()) {
655 auto Die = CU->getUnitDIE();
656 // Get the attribute value as a section offset. No need to produce an
657 // error here if the encoding isn't correct because we validate this in
658 // the .debug_info verifier.
659 auto StmtSectionOffset = toSectionOffset(Die.find(DW_AT_stmt_list));
660 if (!StmtSectionOffset)
661 continue;
662 const uint32_t LineTableOffset = *StmtSectionOffset;
663 auto LineTable = DCtx.getLineTableForUnit(CU.get());
664 if (LineTableOffset < DCtx.getDWARFObj().getLineSection().Data.size()) {
665 if (!LineTable) {
666 ++NumDebugLineErrors;
667 error() << ".debug_line[" << format("0x%08" PRIx32"x", LineTableOffset)
668 << "] was not able to be parsed for CU:\n";
669 dump(Die) << '\n';
670 continue;
671 }
672 } else {
673 // Make sure we don't get a valid line table back if the offset is wrong.
674 assert(LineTable == nullptr)((LineTable == nullptr) ? static_cast<void> (0) : __assert_fail
("LineTable == nullptr", "/build/llvm-toolchain-snapshot-9~svn362543/lib/DebugInfo/DWARF/DWARFVerifier.cpp"
, 674, __PRETTY_FUNCTION__))
;
675 // Skip this line table as it isn't valid. No need to create an error
676 // here because we validate this in the .debug_info verifier.
677 continue;
678 }
679 auto Iter = StmtListToDie.find(LineTableOffset);
680 if (Iter != StmtListToDie.end()) {
681 ++NumDebugLineErrors;
682 error() << "two compile unit DIEs, "
683 << format("0x%08" PRIx32"x", Iter->second.getOffset()) << " and "
684 << format("0x%08" PRIx32"x", Die.getOffset())
685 << ", have the same DW_AT_stmt_list section offset:\n";
686 dump(Iter->second);
687 dump(Die) << '\n';
688 // Already verified this line table before, no need to do it again.
689 continue;
690 }
691 StmtListToDie[LineTableOffset] = Die;
692 }
693}
694
695void DWARFVerifier::verifyDebugLineRows() {
696 for (const auto &CU : DCtx.compile_units()) {
697 auto Die = CU->getUnitDIE();
698 auto LineTable = DCtx.getLineTableForUnit(CU.get());
699 // If there is no line table we will have created an error in the
700 // .debug_info verifier or in verifyDebugLineStmtOffsets().
701 if (!LineTable)
702 continue;
703
704 // Verify prologue.
705 uint32_t MaxDirIndex = LineTable->Prologue.IncludeDirectories.size();
706 uint32_t FileIndex = 1;
707 StringMap<uint16_t> FullPathMap;
708 for (const auto &FileName : LineTable->Prologue.FileNames) {
709 // Verify directory index.
710 if (FileName.DirIdx > MaxDirIndex) {
711 ++NumDebugLineErrors;
712 error() << ".debug_line["
713 << format("0x%08" PRIx64"l" "x",
714 *toSectionOffset(Die.find(DW_AT_stmt_list)))
715 << "].prologue.file_names[" << FileIndex
716 << "].dir_idx contains an invalid index: " << FileName.DirIdx
717 << "\n";
718 }
719
720 // Check file paths for duplicates.
721 std::string FullPath;
722 const bool HasFullPath = LineTable->getFileNameByIndex(
723 FileIndex, CU->getCompilationDir(),
724 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, FullPath);
725 assert(HasFullPath && "Invalid index?")((HasFullPath && "Invalid index?") ? static_cast<void
> (0) : __assert_fail ("HasFullPath && \"Invalid index?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/lib/DebugInfo/DWARF/DWARFVerifier.cpp"
, 725, __PRETTY_FUNCTION__))
;
726 (void)HasFullPath;
727 auto It = FullPathMap.find(FullPath);
728 if (It == FullPathMap.end())
729 FullPathMap[FullPath] = FileIndex;
730 else if (It->second != FileIndex) {
731 warn() << ".debug_line["
732 << format("0x%08" PRIx64"l" "x",
733 *toSectionOffset(Die.find(DW_AT_stmt_list)))
734 << "].prologue.file_names[" << FileIndex
735 << "] is a duplicate of file_names[" << It->second << "]\n";
736 }
737
738 FileIndex++;
739 }
740
741 // Verify rows.
742 uint64_t PrevAddress = 0;
743 uint32_t RowIndex = 0;
744 for (const auto &Row : LineTable->Rows) {
745 // Verify row address.
746 if (Row.Address.Address < PrevAddress) {
747 ++NumDebugLineErrors;
748 error() << ".debug_line["
749 << format("0x%08" PRIx64"l" "x",
750 *toSectionOffset(Die.find(DW_AT_stmt_list)))
751 << "] row[" << RowIndex
752 << "] decreases in address from previous row:\n";
753
754 DWARFDebugLine::Row::dumpTableHeader(OS);
755 if (RowIndex > 0)
756 LineTable->Rows[RowIndex - 1].dump(OS);
757 Row.dump(OS);
758 OS << '\n';
759 }
760
761 // Verify file index.
762 if (!LineTable->hasFileAtIndex(Row.File)) {
763 ++NumDebugLineErrors;
764 bool isDWARF5 = LineTable->Prologue.getVersion() >= 5;
765 error() << ".debug_line["
766 << format("0x%08" PRIx64"l" "x",
767 *toSectionOffset(Die.find(DW_AT_stmt_list)))
768 << "][" << RowIndex << "] has invalid file index " << Row.File
769 << " (valid values are [" << (isDWARF5 ? "0," : "1,")
770 << LineTable->Prologue.FileNames.size()
771 << (isDWARF5 ? ")" : "]") << "):\n";
772 DWARFDebugLine::Row::dumpTableHeader(OS);
773 Row.dump(OS);
774 OS << '\n';
775 }
776 if (Row.EndSequence)
777 PrevAddress = 0;
778 else
779 PrevAddress = Row.Address.Address;
780 ++RowIndex;
781 }
782 }
783}
784
785DWARFVerifier::DWARFVerifier(raw_ostream &S, DWARFContext &D,
786 DIDumpOptions DumpOpts)
787 : OS(S), DCtx(D), DumpOpts(std::move(DumpOpts)), IsObjectFile(false),
788 IsMachOObject(false) {
789 if (const auto *F = DCtx.getDWARFObj().getFile()) {
790 IsObjectFile = F->isRelocatableObject();
791 IsMachOObject = F->isMachO();
792 }
793}
794
795bool DWARFVerifier::handleDebugLine() {
796 NumDebugLineErrors = 0;
797 OS << "Verifying .debug_line...\n";
798 verifyDebugLineStmtOffsets();
799 verifyDebugLineRows();
800 return NumDebugLineErrors == 0;
801}
802
803unsigned DWARFVerifier::verifyAppleAccelTable(const DWARFSection *AccelSection,
804 DataExtractor *StrData,
805 const char *SectionName) {
806 unsigned NumErrors = 0;
807 DWARFDataExtractor AccelSectionData(DCtx.getDWARFObj(), *AccelSection,
808 DCtx.isLittleEndian(), 0);
809 AppleAcceleratorTable AccelTable(AccelSectionData, *StrData);
810
811 OS << "Verifying " << SectionName << "...\n";
812
813 // Verify that the fixed part of the header is not too short.
814 if (!AccelSectionData.isValidOffset(AccelTable.getSizeHdr())) {
815 error() << "Section is too small to fit a section header.\n";
816 return 1;
817 }
818
819 // Verify that the section is not too short.
820 if (Error E = AccelTable.extract()) {
821 error() << toString(std::move(E)) << '\n';
822 return 1;
823 }
824
825 // Verify that all buckets have a valid hash index or are empty.
826 uint32_t NumBuckets = AccelTable.getNumBuckets();
827 uint32_t NumHashes = AccelTable.getNumHashes();
828
829 uint32_t BucketsOffset =
830 AccelTable.getSizeHdr() + AccelTable.getHeaderDataLength();
831 uint32_t HashesBase = BucketsOffset + NumBuckets * 4;
832 uint32_t OffsetsBase = HashesBase + NumHashes * 4;
833 for (uint32_t BucketIdx = 0; BucketIdx < NumBuckets; ++BucketIdx) {
834 uint32_t HashIdx = AccelSectionData.getU32(&BucketsOffset);
835 if (HashIdx >= NumHashes && HashIdx != UINT32_MAX(4294967295U)) {
836 error() << format("Bucket[%d] has invalid hash index: %u.\n", BucketIdx,
837 HashIdx);
838 ++NumErrors;
839 }
840 }
841 uint32_t NumAtoms = AccelTable.getAtomsDesc().size();
842 if (NumAtoms == 0) {
843 error() << "No atoms: failed to read HashData.\n";
844 return 1;
845 }
846 if (!AccelTable.validateForms()) {
847 error() << "Unsupported form: failed to read HashData.\n";
848 return 1;
849 }
850
851 for (uint32_t HashIdx = 0; HashIdx < NumHashes; ++HashIdx) {
852 uint32_t HashOffset = HashesBase + 4 * HashIdx;
853 uint32_t DataOffset = OffsetsBase + 4 * HashIdx;
854 uint32_t Hash = AccelSectionData.getU32(&HashOffset);
855 uint32_t HashDataOffset = AccelSectionData.getU32(&DataOffset);
856 if (!AccelSectionData.isValidOffsetForDataOfSize(HashDataOffset,
857 sizeof(uint64_t))) {
858 error() << format("Hash[%d] has invalid HashData offset: 0x%08x.\n",
859 HashIdx, HashDataOffset);
860 ++NumErrors;
861 }
862
863 uint32_t StrpOffset;
864 uint32_t StringOffset;
865 uint32_t StringCount = 0;
866 unsigned Offset;
867 unsigned Tag;
868 while ((StrpOffset = AccelSectionData.getU32(&HashDataOffset)) != 0) {
869 const uint32_t NumHashDataObjects =
870 AccelSectionData.getU32(&HashDataOffset);
871 for (uint32_t HashDataIdx = 0; HashDataIdx < NumHashDataObjects;
872 ++HashDataIdx) {
873 std::tie(Offset, Tag) = AccelTable.readAtoms(HashDataOffset);
874 auto Die = DCtx.getDIEForOffset(Offset);
875 if (!Die) {
876 const uint32_t BucketIdx =
877 NumBuckets ? (Hash % NumBuckets) : UINT32_MAX(4294967295U);
878 StringOffset = StrpOffset;
879 const char *Name = StrData->getCStr(&StringOffset);
880 if (!Name)
881 Name = "<NULL>";
882
883 error() << format(
884 "%s Bucket[%d] Hash[%d] = 0x%08x "
885 "Str[%u] = 0x%08x "
886 "DIE[%d] = 0x%08x is not a valid DIE offset for \"%s\".\n",
887 SectionName, BucketIdx, HashIdx, Hash, StringCount, StrpOffset,
888 HashDataIdx, Offset, Name);
889
890 ++NumErrors;
891 continue;
892 }
893 if ((Tag != dwarf::DW_TAG_null) && (Die.getTag() != Tag)) {
894 error() << "Tag " << dwarf::TagString(Tag)
895 << " in accelerator table does not match Tag "
896 << dwarf::TagString(Die.getTag()) << " of DIE[" << HashDataIdx
897 << "].\n";
898 ++NumErrors;
899 }
900 }
901 ++StringCount;
902 }
903 }
904 return NumErrors;
905}
906
907unsigned
908DWARFVerifier::verifyDebugNamesCULists(const DWARFDebugNames &AccelTable) {
909 // A map from CU offset to the (first) Name Index offset which claims to index
910 // this CU.
911 DenseMap<uint32_t, uint32_t> CUMap;
912 const uint32_t NotIndexed = std::numeric_limits<uint32_t>::max();
913
914 CUMap.reserve(DCtx.getNumCompileUnits());
915 for (const auto &CU : DCtx.compile_units())
916 CUMap[CU->getOffset()] = NotIndexed;
917
918 unsigned NumErrors = 0;
919 for (const DWARFDebugNames::NameIndex &NI : AccelTable) {
920 if (NI.getCUCount() == 0) {
921 error() << formatv("Name Index @ {0:x} does not index any CU\n",
922 NI.getUnitOffset());
923 ++NumErrors;
924 continue;
925 }
926 for (uint32_t CU = 0, End = NI.getCUCount(); CU < End; ++CU) {
927 uint32_t Offset = NI.getCUOffset(CU);
928 auto Iter = CUMap.find(Offset);
929
930 if (Iter == CUMap.end()) {
931 error() << formatv(
932 "Name Index @ {0:x} references a non-existing CU @ {1:x}\n",
933 NI.getUnitOffset(), Offset);
934 ++NumErrors;
935 continue;
936 }
937
938 if (Iter->second != NotIndexed) {
939 error() << formatv("Name Index @ {0:x} references a CU @ {1:x}, but "
940 "this CU is already indexed by Name Index @ {2:x}\n",
941 NI.getUnitOffset(), Offset, Iter->second);
942 continue;
943 }
944 Iter->second = NI.getUnitOffset();
945 }
946 }
947
948 for (const auto &KV : CUMap) {
949 if (KV.second == NotIndexed)
950 warn() << formatv("CU @ {0:x} not covered by any Name Index\n", KV.first);
951 }
952
953 return NumErrors;
954}
955
956unsigned
957DWARFVerifier::verifyNameIndexBuckets(const DWARFDebugNames::NameIndex &NI,
958 const DataExtractor &StrData) {
959 struct BucketInfo {
960 uint32_t Bucket;
961 uint32_t Index;
962
963 constexpr BucketInfo(uint32_t Bucket, uint32_t Index)
964 : Bucket(Bucket), Index(Index) {}
965 bool operator<(const BucketInfo &RHS) const { return Index < RHS.Index; };
966 };
967
968 uint32_t NumErrors = 0;
969 if (NI.getBucketCount() == 0) {
970 warn() << formatv("Name Index @ {0:x} does not contain a hash table.\n",
971 NI.getUnitOffset());
972 return NumErrors;
973 }
974
975 // Build up a list of (Bucket, Index) pairs. We use this later to verify that
976 // each Name is reachable from the appropriate bucket.
977 std::vector<BucketInfo> BucketStarts;
978 BucketStarts.reserve(NI.getBucketCount() + 1);
979 for (uint32_t Bucket = 0, End = NI.getBucketCount(); Bucket < End; ++Bucket) {
980 uint32_t Index = NI.getBucketArrayEntry(Bucket);
981 if (Index > NI.getNameCount()) {
982 error() << formatv("Bucket {0} of Name Index @ {1:x} contains invalid "
983 "value {2}. Valid range is [0, {3}].\n",
984 Bucket, NI.getUnitOffset(), Index, NI.getNameCount());
985 ++NumErrors;
986 continue;
987 }
988 if (Index > 0)
989 BucketStarts.emplace_back(Bucket, Index);
990 }
991
992 // If there were any buckets with invalid values, skip further checks as they
993 // will likely produce many errors which will only confuse the actual root
994 // problem.
995 if (NumErrors > 0)
996 return NumErrors;
997
998 // Sort the list in the order of increasing "Index" entries.
999 array_pod_sort(BucketStarts.begin(), BucketStarts.end());
1000
1001 // Insert a sentinel entry at the end, so we can check that the end of the
1002 // table is covered in the loop below.
1003 BucketStarts.emplace_back(NI.getBucketCount(), NI.getNameCount() + 1);
1004
1005 // Loop invariant: NextUncovered is the (1-based) index of the first Name
1006 // which is not reachable by any of the buckets we processed so far (and
1007 // hasn't been reported as uncovered).
1008 uint32_t NextUncovered = 1;
1009 for (const BucketInfo &B : BucketStarts) {
1010 // Under normal circumstances B.Index be equal to NextUncovered, but it can
1011 // be less if a bucket points to names which are already known to be in some
1012 // bucket we processed earlier. In that case, we won't trigger this error,
1013 // but report the mismatched hash value error instead. (We know the hash
1014 // will not match because we have already verified that the name's hash
1015 // puts it into the previous bucket.)
1016 if (B.Index > NextUncovered) {
1017 error() << formatv("Name Index @ {0:x}: Name table entries [{1}, {2}] "
1018 "are not covered by the hash table.\n",
1019 NI.getUnitOffset(), NextUncovered, B.Index - 1);
1020 ++NumErrors;
1021 }
1022 uint32_t Idx = B.Index;
1023
1024 // The rest of the checks apply only to non-sentinel entries.
1025 if (B.Bucket == NI.getBucketCount())
1026 break;
1027
1028 // This triggers if a non-empty bucket points to a name with a mismatched
1029 // hash. Clients are likely to interpret this as an empty bucket, because a
1030 // mismatched hash signals the end of a bucket, but if this is indeed an
1031 // empty bucket, the producer should have signalled this by marking the
1032 // bucket as empty.
1033 uint32_t FirstHash = NI.getHashArrayEntry(Idx);
1034 if (FirstHash % NI.getBucketCount() != B.Bucket) {
1035 error() << formatv(
1036 "Name Index @ {0:x}: Bucket {1} is not empty but points to a "
1037 "mismatched hash value {2:x} (belonging to bucket {3}).\n",
1038 NI.getUnitOffset(), B.Bucket, FirstHash,
1039 FirstHash % NI.getBucketCount());
1040 ++NumErrors;
1041 }
1042
1043 // This find the end of this bucket and also verifies that all the hashes in
1044 // this bucket are correct by comparing the stored hashes to the ones we
1045 // compute ourselves.
1046 while (Idx <= NI.getNameCount()) {
1047 uint32_t Hash = NI.getHashArrayEntry(Idx);
1048 if (Hash % NI.getBucketCount() != B.Bucket)
1049 break;
1050
1051 const char *Str = NI.getNameTableEntry(Idx).getString();
1052 if (caseFoldingDjbHash(Str) != Hash) {
1053 error() << formatv("Name Index @ {0:x}: String ({1}) at index {2} "
1054 "hashes to {3:x}, but "
1055 "the Name Index hash is {4:x}\n",
1056 NI.getUnitOffset(), Str, Idx,
1057 caseFoldingDjbHash(Str), Hash);
1058 ++NumErrors;
1059 }
1060
1061 ++Idx;
1062 }
1063 NextUncovered = std::max(NextUncovered, Idx);
1064 }
1065 return NumErrors;
1066}
1067
1068unsigned DWARFVerifier::verifyNameIndexAttribute(
1069 const DWARFDebugNames::NameIndex &NI, const DWARFDebugNames::Abbrev &Abbr,
1070 DWARFDebugNames::AttributeEncoding AttrEnc) {
1071 StringRef FormName = dwarf::FormEncodingString(AttrEnc.Form);
1072 if (FormName.empty()) {
1073 error() << formatv("NameIndex @ {0:x}: Abbreviation {1:x}: {2} uses an "
1074 "unknown form: {3}.\n",
1075 NI.getUnitOffset(), Abbr.Code, AttrEnc.Index,
1076 AttrEnc.Form);
1077 return 1;
1078 }
1079
1080 if (AttrEnc.Index == DW_IDX_type_hash) {
1081 if (AttrEnc.Form != dwarf::DW_FORM_data8) {
1082 error() << formatv(
1083 "NameIndex @ {0:x}: Abbreviation {1:x}: DW_IDX_type_hash "
1084 "uses an unexpected form {2} (should be {3}).\n",
1085 NI.getUnitOffset(), Abbr.Code, AttrEnc.Form, dwarf::DW_FORM_data8);
1086 return 1;
1087 }
1088 }
1089
1090 // A list of known index attributes and their expected form classes.
1091 // DW_IDX_type_hash is handled specially in the check above, as it has a
1092 // specific form (not just a form class) we should expect.
1093 struct FormClassTable {
1094 dwarf::Index Index;
1095 DWARFFormValue::FormClass Class;
1096 StringLiteral ClassName;
1097 };
1098 static constexpr FormClassTable Table[] = {
1099 {dwarf::DW_IDX_compile_unit, DWARFFormValue::FC_Constant, {"constant"}},
1100 {dwarf::DW_IDX_type_unit, DWARFFormValue::FC_Constant, {"constant"}},
1101 {dwarf::DW_IDX_die_offset, DWARFFormValue::FC_Reference, {"reference"}},
1102 {dwarf::DW_IDX_parent, DWARFFormValue::FC_Constant, {"constant"}},
1103 };
1104
1105 ArrayRef<FormClassTable> TableRef(Table);
1106 auto Iter = find_if(TableRef, [AttrEnc](const FormClassTable &T) {
1107 return T.Index == AttrEnc.Index;
1108 });
1109 if (Iter == TableRef.end()) {
1110 warn() << formatv("NameIndex @ {0:x}: Abbreviation {1:x} contains an "
1111 "unknown index attribute: {2}.\n",
1112 NI.getUnitOffset(), Abbr.Code, AttrEnc.Index);
1113 return 0;
1114 }
1115
1116 if (!DWARFFormValue(AttrEnc.Form).isFormClass(Iter->Class)) {
1117 error() << formatv("NameIndex @ {0:x}: Abbreviation {1:x}: {2} uses an "
1118 "unexpected form {3} (expected form class {4}).\n",
1119 NI.getUnitOffset(), Abbr.Code, AttrEnc.Index,
1120 AttrEnc.Form, Iter->ClassName);
1121 return 1;
1122 }
1123 return 0;
1124}
1125
1126unsigned
1127DWARFVerifier::verifyNameIndexAbbrevs(const DWARFDebugNames::NameIndex &NI) {
1128 if (NI.getLocalTUCount() + NI.getForeignTUCount() > 0) {
1129 warn() << formatv("Name Index @ {0:x}: Verifying indexes of type units is "
1130 "not currently supported.\n",
1131 NI.getUnitOffset());
1132 return 0;
1133 }
1134
1135 unsigned NumErrors = 0;
1136 for (const auto &Abbrev : NI.getAbbrevs()) {
1137 StringRef TagName = dwarf::TagString(Abbrev.Tag);
1138 if (TagName.empty()) {
1139 warn() << formatv("NameIndex @ {0:x}: Abbreviation {1:x} references an "
1140 "unknown tag: {2}.\n",
1141 NI.getUnitOffset(), Abbrev.Code, Abbrev.Tag);
1142 }
1143 SmallSet<unsigned, 5> Attributes;
1144 for (const auto &AttrEnc : Abbrev.Attributes) {
1145 if (!Attributes.insert(AttrEnc.Index).second) {
1146 error() << formatv("NameIndex @ {0:x}: Abbreviation {1:x} contains "
1147 "multiple {2} attributes.\n",
1148 NI.getUnitOffset(), Abbrev.Code, AttrEnc.Index);
1149 ++NumErrors;
1150 continue;
1151 }
1152 NumErrors += verifyNameIndexAttribute(NI, Abbrev, AttrEnc);
1153 }
1154
1155 if (NI.getCUCount() > 1 && !Attributes.count(dwarf::DW_IDX_compile_unit)) {
1156 error() << formatv("NameIndex @ {0:x}: Indexing multiple compile units "
1157 "and abbreviation {1:x} has no {2} attribute.\n",
1158 NI.getUnitOffset(), Abbrev.Code,
1159 dwarf::DW_IDX_compile_unit);
1160 ++NumErrors;
1161 }
1162 if (!Attributes.count(dwarf::DW_IDX_die_offset)) {
1163 error() << formatv(
1164 "NameIndex @ {0:x}: Abbreviation {1:x} has no {2} attribute.\n",
1165 NI.getUnitOffset(), Abbrev.Code, dwarf::DW_IDX_die_offset);
1166 ++NumErrors;
1167 }
1168 }
1169 return NumErrors;
1170}
1171
1172static SmallVector<StringRef, 2> getNames(const DWARFDie &DIE,
1173 bool IncludeLinkageName = true) {
1174 SmallVector<StringRef, 2> Result;
1175 if (const char *Str = DIE.getName(DINameKind::ShortName))
1176 Result.emplace_back(Str);
1177 else if (DIE.getTag() == dwarf::DW_TAG_namespace)
1178 Result.emplace_back("(anonymous namespace)");
1179
1180 if (IncludeLinkageName) {
1181 if (const char *Str = DIE.getName(DINameKind::LinkageName)) {
1182 if (Result.empty() || Result[0] != Str)
1183 Result.emplace_back(Str);
1184 }
1185 }
1186
1187 return Result;
1188}
1189
1190unsigned DWARFVerifier::verifyNameIndexEntries(
1191 const DWARFDebugNames::NameIndex &NI,
1192 const DWARFDebugNames::NameTableEntry &NTE) {
1193 // Verifying type unit indexes not supported.
1194 if (NI.getLocalTUCount() + NI.getForeignTUCount() > 0)
1195 return 0;
1196
1197 const char *CStr = NTE.getString();
1198 if (!CStr) {
1199 error() << formatv(
1200 "Name Index @ {0:x}: Unable to get string associated with name {1}.\n",
1201 NI.getUnitOffset(), NTE.getIndex());
1202 return 1;
1203 }
1204 StringRef Str(CStr);
1205
1206 unsigned NumErrors = 0;
1207 unsigned NumEntries = 0;
1208 uint32_t EntryID = NTE.getEntryOffset();
1209 uint32_t NextEntryID = EntryID;
1210 Expected<DWARFDebugNames::Entry> EntryOr = NI.getEntry(&NextEntryID);
1211 for (; EntryOr; ++NumEntries, EntryID = NextEntryID,
1212 EntryOr = NI.getEntry(&NextEntryID)) {
1213 uint32_t CUIndex = *EntryOr->getCUIndex();
1214 if (CUIndex > NI.getCUCount()) {
1215 error() << formatv("Name Index @ {0:x}: Entry @ {1:x} contains an "
1216 "invalid CU index ({2}).\n",
1217 NI.getUnitOffset(), EntryID, CUIndex);
1218 ++NumErrors;
1219 continue;
1220 }
1221 uint32_t CUOffset = NI.getCUOffset(CUIndex);
1222 uint64_t DIEOffset = CUOffset + *EntryOr->getDIEUnitOffset();
1223 DWARFDie DIE = DCtx.getDIEForOffset(DIEOffset);
1224 if (!DIE) {
1225 error() << formatv("Name Index @ {0:x}: Entry @ {1:x} references a "
1226 "non-existing DIE @ {2:x}.\n",
1227 NI.getUnitOffset(), EntryID, DIEOffset);
1228 ++NumErrors;
1229 continue;
1230 }
1231 if (DIE.getDwarfUnit()->getOffset() != CUOffset) {
1232 error() << formatv("Name Index @ {0:x}: Entry @ {1:x}: mismatched CU of "
1233 "DIE @ {2:x}: index - {3:x}; debug_info - {4:x}.\n",
1234 NI.getUnitOffset(), EntryID, DIEOffset, CUOffset,
1235 DIE.getDwarfUnit()->getOffset());
1236 ++NumErrors;
1237 }
1238 if (DIE.getTag() != EntryOr->tag()) {
1239 error() << formatv("Name Index @ {0:x}: Entry @ {1:x}: mismatched Tag of "
1240 "DIE @ {2:x}: index - {3}; debug_info - {4}.\n",
1241 NI.getUnitOffset(), EntryID, DIEOffset, EntryOr->tag(),
1242 DIE.getTag());
1243 ++NumErrors;
1244 }
1245
1246 auto EntryNames = getNames(DIE);
1247 if (!is_contained(EntryNames, Str)) {
1248 error() << formatv("Name Index @ {0:x}: Entry @ {1:x}: mismatched Name "
1249 "of DIE @ {2:x}: index - {3}; debug_info - {4}.\n",
1250 NI.getUnitOffset(), EntryID, DIEOffset, Str,
1251 make_range(EntryNames.begin(), EntryNames.end()));
1252 ++NumErrors;
1253 }
1254 }
1255 handleAllErrors(EntryOr.takeError(),
1256 [&](const DWARFDebugNames::SentinelError &) {
1257 if (NumEntries > 0)
1258 return;
1259 error() << formatv("Name Index @ {0:x}: Name {1} ({2}) is "
1260 "not associated with any entries.\n",
1261 NI.getUnitOffset(), NTE.getIndex(), Str);
1262 ++NumErrors;
1263 },
1264 [&](const ErrorInfoBase &Info) {
1265 error()
1266 << formatv("Name Index @ {0:x}: Name {1} ({2}): {3}\n",
1267 NI.getUnitOffset(), NTE.getIndex(), Str,
1268 Info.message());
1269 ++NumErrors;
1270 });
1271 return NumErrors;
1272}
1273
1274static bool isVariableIndexable(const DWARFDie &Die, DWARFContext &DCtx) {
1275 Optional<DWARFFormValue> Location = Die.findRecursively(DW_AT_location);
1276 if (!Location)
1277 return false;
1278
1279 auto ContainsInterestingOperators = [&](StringRef D) {
1280 DWARFUnit *U = Die.getDwarfUnit();
1281 DataExtractor Data(D, DCtx.isLittleEndian(), U->getAddressByteSize());
1282 DWARFExpression Expression(Data, U->getVersion(), U->getAddressByteSize());
1283 return any_of(Expression, [](DWARFExpression::Operation &Op) {
1284 return !Op.isError() && (Op.getCode() == DW_OP_addr ||
1285 Op.getCode() == DW_OP_form_tls_address ||
1286 Op.getCode() == DW_OP_GNU_push_tls_address);
1287 });
1288 };
1289
1290 if (Optional<ArrayRef<uint8_t>> Expr = Location->getAsBlock()) {
1291 // Inlined location.
1292 if (ContainsInterestingOperators(toStringRef(*Expr)))
1293 return true;
1294 } else if (Optional<uint64_t> Offset = Location->getAsSectionOffset()) {
1295 // Location list.
1296 if (const DWARFDebugLoc *DebugLoc = DCtx.getDebugLoc()) {
1297 if (const DWARFDebugLoc::LocationList *LocList =
1298 DebugLoc->getLocationListAtOffset(*Offset)) {
1299 if (any_of(LocList->Entries, [&](const DWARFDebugLoc::Entry &E) {
1300 return ContainsInterestingOperators({E.Loc.data(), E.Loc.size()});
1301 }))
1302 return true;
1303 }
1304 }
1305 }
1306 return false;
1307}
1308
1309unsigned DWARFVerifier::verifyNameIndexCompleteness(
1310 const DWARFDie &Die, const DWARFDebugNames::NameIndex &NI) {
1311
1312 // First check, if the Die should be indexed. The code follows the DWARF v5
1313 // wording as closely as possible.
1314
1315 // "All non-defining declarations (that is, debugging information entries
1316 // with a DW_AT_declaration attribute) are excluded."
1317 if (Die.find(DW_AT_declaration))
1318 return 0;
1319
1320 // "DW_TAG_namespace debugging information entries without a DW_AT_name
1321 // attribute are included with the name “(anonymous namespace)”.
1322 // All other debugging information entries without a DW_AT_name attribute
1323 // are excluded."
1324 // "If a subprogram or inlined subroutine is included, and has a
1325 // DW_AT_linkage_name attribute, there will be an additional index entry for
1326 // the linkage name."
1327 auto IncludeLinkageName = Die.getTag() == DW_TAG_subprogram ||
1328 Die.getTag() == DW_TAG_inlined_subroutine;
1329 auto EntryNames = getNames(Die, IncludeLinkageName);
1330 if (EntryNames.empty())
1331 return 0;
1332
1333 // We deviate from the specification here, which says:
1334 // "The name index must contain an entry for each debugging information entry
1335 // that defines a named subprogram, label, variable, type, or namespace,
1336 // subject to ..."
1337 // Instead whitelisting all TAGs representing a "type" or a "subprogram", to
1338 // make sure we catch any missing items, we instead blacklist all TAGs that we
1339 // know shouldn't be indexed.
1340 switch (Die.getTag()) {
1341 // Compile units and modules have names but shouldn't be indexed.
1342 case DW_TAG_compile_unit:
1343 case DW_TAG_module:
1344 return 0;
1345
1346 // Function and template parameters are not globally visible, so we shouldn't
1347 // index them.
1348 case DW_TAG_formal_parameter:
1349 case DW_TAG_template_value_parameter:
1350 case DW_TAG_template_type_parameter:
1351 case DW_TAG_GNU_template_parameter_pack:
1352 case DW_TAG_GNU_template_template_param:
1353 return 0;
1354
1355 // Object members aren't globally visible.
1356 case DW_TAG_member:
1357 return 0;
1358
1359 // According to a strict reading of the specification, enumerators should not
1360 // be indexed (and LLVM currently does not do that). However, this causes
1361 // problems for the debuggers, so we may need to reconsider this.
1362 case DW_TAG_enumerator:
1363 return 0;
1364
1365 // Imported declarations should not be indexed according to the specification
1366 // and LLVM currently does not do that.
1367 case DW_TAG_imported_declaration:
1368 return 0;
1369
1370 // "DW_TAG_subprogram, DW_TAG_inlined_subroutine, and DW_TAG_label debugging
1371 // information entries without an address attribute (DW_AT_low_pc,
1372 // DW_AT_high_pc, DW_AT_ranges, or DW_AT_entry_pc) are excluded."
1373 case DW_TAG_subprogram:
1374 case DW_TAG_inlined_subroutine:
1375 case DW_TAG_label:
1376 if (Die.findRecursively(
1377 {DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_entry_pc}))
1378 break;
1379 return 0;
1380
1381 // "DW_TAG_variable debugging information entries with a DW_AT_location
1382 // attribute that includes a DW_OP_addr or DW_OP_form_tls_address operator are
1383 // included; otherwise, they are excluded."
1384 //
1385 // LLVM extension: We also add DW_OP_GNU_push_tls_address to this list.
1386 case DW_TAG_variable:
1387 if (isVariableIndexable(Die, DCtx))
1388 break;
1389 return 0;
1390
1391 default:
1392 break;
1393 }
1394
1395 // Now we know that our Die should be present in the Index. Let's check if
1396 // that's the case.
1397 unsigned NumErrors = 0;
1398 uint64_t DieUnitOffset = Die.getOffset() - Die.getDwarfUnit()->getOffset();
1399 for (StringRef Name : EntryNames) {
1400 if (none_of(NI.equal_range(Name), [&](const DWARFDebugNames::Entry &E) {
1401 return E.getDIEUnitOffset() == DieUnitOffset;
1402 })) {
1403 error() << formatv("Name Index @ {0:x}: Entry for DIE @ {1:x} ({2}) with "
1404 "name {3} missing.\n",
1405 NI.getUnitOffset(), Die.getOffset(), Die.getTag(),
1406 Name);
1407 ++NumErrors;
1408 }
1409 }
1410 return NumErrors;
1411}
1412
1413unsigned DWARFVerifier::verifyDebugNames(const DWARFSection &AccelSection,
1414 const DataExtractor &StrData) {
1415 unsigned NumErrors = 0;
1416 DWARFDataExtractor AccelSectionData(DCtx.getDWARFObj(), AccelSection,
1417 DCtx.isLittleEndian(), 0);
1418 DWARFDebugNames AccelTable(AccelSectionData, StrData);
1419
1420 OS << "Verifying .debug_names...\n";
1421
1422 // This verifies that we can read individual name indices and their
1423 // abbreviation tables.
1424 if (Error E = AccelTable.extract()) {
1425 error() << toString(std::move(E)) << '\n';
1426 return 1;
1427 }
1428
1429 NumErrors += verifyDebugNamesCULists(AccelTable);
1430 for (const auto &NI : AccelTable)
1431 NumErrors += verifyNameIndexBuckets(NI, StrData);
1432 for (const auto &NI : AccelTable)
1433 NumErrors += verifyNameIndexAbbrevs(NI);
1434
1435 // Don't attempt Entry validation if any of the previous checks found errors
1436 if (NumErrors > 0)
1437 return NumErrors;
1438 for (const auto &NI : AccelTable)
1439 for (DWARFDebugNames::NameTableEntry NTE : NI)
1440 NumErrors += verifyNameIndexEntries(NI, NTE);
1441
1442 if (NumErrors > 0)
1443 return NumErrors;
1444
1445 for (const std::unique_ptr<DWARFUnit> &U : DCtx.compile_units()) {
1446 if (const DWARFDebugNames::NameIndex *NI =
1447 AccelTable.getCUNameIndex(U->getOffset())) {
1448 auto *CU = cast<DWARFCompileUnit>(U.get());
1449 for (const DWARFDebugInfoEntry &Die : CU->dies())
1450 NumErrors += verifyNameIndexCompleteness(DWARFDie(CU, &Die), *NI);
1451 }
1452 }
1453 return NumErrors;
1454}
1455
1456bool DWARFVerifier::handleAccelTables() {
1457 const DWARFObject &D = DCtx.getDWARFObj();
1458 DataExtractor StrData(D.getStringSection(), DCtx.isLittleEndian(), 0);
1459 unsigned NumErrors = 0;
1460 if (!D.getAppleNamesSection().Data.empty())
1461 NumErrors += verifyAppleAccelTable(&D.getAppleNamesSection(), &StrData,
1462 ".apple_names");
1463 if (!D.getAppleTypesSection().Data.empty())
1464 NumErrors += verifyAppleAccelTable(&D.getAppleTypesSection(), &StrData,
1465 ".apple_types");
1466 if (!D.getAppleNamespacesSection().Data.empty())
1467 NumErrors += verifyAppleAccelTable(&D.getAppleNamespacesSection(), &StrData,
1468 ".apple_namespaces");
1469 if (!D.getAppleObjCSection().Data.empty())
1470 NumErrors += verifyAppleAccelTable(&D.getAppleObjCSection(), &StrData,
1471 ".apple_objc");
1472
1473 if (!D.getDebugNamesSection().Data.empty())
1474 NumErrors += verifyDebugNames(D.getDebugNamesSection(), StrData);
1475 return NumErrors == 0;
1476}
1477
1478raw_ostream &DWARFVerifier::error() const { return WithColor::error(OS); }
1479
1480raw_ostream &DWARFVerifier::warn() const { return WithColor::warning(OS); }
1481
1482raw_ostream &DWARFVerifier::note() const { return WithColor::note(OS); }
1483
1484raw_ostream &DWARFVerifier::dump(const DWARFDie &Die, unsigned indent) const {
1485 Die.dump(OS, indent, DumpOpts);
1486 return OS;
1487}

/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h

1//===- llvm/Support/Error.h - Recoverable error handling --------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines an API used to report recoverable errors.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_SUPPORT_ERROR_H
14#define LLVM_SUPPORT_ERROR_H
15
16#include "llvm-c/Error.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/StringExtras.h"
20#include "llvm/ADT/Twine.h"
21#include "llvm/Config/abi-breaking.h"
22#include "llvm/Support/AlignOf.h"
23#include "llvm/Support/Compiler.h"
24#include "llvm/Support/Debug.h"
25#include "llvm/Support/ErrorHandling.h"
26#include "llvm/Support/ErrorOr.h"
27#include "llvm/Support/Format.h"
28#include "llvm/Support/raw_ostream.h"
29#include <algorithm>
30#include <cassert>
31#include <cstdint>
32#include <cstdlib>
33#include <functional>
34#include <memory>
35#include <new>
36#include <string>
37#include <system_error>
38#include <type_traits>
39#include <utility>
40#include <vector>
41
42namespace llvm {
43
44class ErrorSuccess;
45
46/// Base class for error info classes. Do not extend this directly: Extend
47/// the ErrorInfo template subclass instead.
48class ErrorInfoBase {
49public:
50 virtual ~ErrorInfoBase() = default;
51
52 /// Print an error message to an output stream.
53 virtual void log(raw_ostream &OS) const = 0;
54
55 /// Return the error message as a string.
56 virtual std::string message() const {
57 std::string Msg;
58 raw_string_ostream OS(Msg);
59 log(OS);
60 return OS.str();
61 }
62
63 /// Convert this error to a std::error_code.
64 ///
65 /// This is a temporary crutch to enable interaction with code still
66 /// using std::error_code. It will be removed in the future.
67 virtual std::error_code convertToErrorCode() const = 0;
68
69 // Returns the class ID for this type.
70 static const void *classID() { return &ID; }
71
72 // Returns the class ID for the dynamic type of this ErrorInfoBase instance.
73 virtual const void *dynamicClassID() const = 0;
74
75 // Check whether this instance is a subclass of the class identified by
76 // ClassID.
77 virtual bool isA(const void *const ClassID) const {
78 return ClassID == classID();
79 }
80
81 // Check whether this instance is a subclass of ErrorInfoT.
82 template <typename ErrorInfoT> bool isA() const {
83 return isA(ErrorInfoT::classID());
84 }
85
86private:
87 virtual void anchor();
88
89 static char ID;
90};
91
92/// Lightweight error class with error context and mandatory checking.
93///
94/// Instances of this class wrap a ErrorInfoBase pointer. Failure states
95/// are represented by setting the pointer to a ErrorInfoBase subclass
96/// instance containing information describing the failure. Success is
97/// represented by a null pointer value.
98///
99/// Instances of Error also contains a 'Checked' flag, which must be set
100/// before the destructor is called, otherwise the destructor will trigger a
101/// runtime error. This enforces at runtime the requirement that all Error
102/// instances be checked or returned to the caller.
103///
104/// There are two ways to set the checked flag, depending on what state the
105/// Error instance is in. For Error instances indicating success, it
106/// is sufficient to invoke the boolean conversion operator. E.g.:
107///
108/// @code{.cpp}
109/// Error foo(<...>);
110///
111/// if (auto E = foo(<...>))
112/// return E; // <- Return E if it is in the error state.
113/// // We have verified that E was in the success state. It can now be safely
114/// // destroyed.
115/// @endcode
116///
117/// A success value *can not* be dropped. For example, just calling 'foo(<...>)'
118/// without testing the return value will raise a runtime error, even if foo
119/// returns success.
120///
121/// For Error instances representing failure, you must use either the
122/// handleErrors or handleAllErrors function with a typed handler. E.g.:
123///
124/// @code{.cpp}
125/// class MyErrorInfo : public ErrorInfo<MyErrorInfo> {
126/// // Custom error info.
127/// };
128///
129/// Error foo(<...>) { return make_error<MyErrorInfo>(...); }
130///
131/// auto E = foo(<...>); // <- foo returns failure with MyErrorInfo.
132/// auto NewE =
133/// handleErrors(E,
134/// [](const MyErrorInfo &M) {
135/// // Deal with the error.
136/// },
137/// [](std::unique_ptr<OtherError> M) -> Error {
138/// if (canHandle(*M)) {
139/// // handle error.
140/// return Error::success();
141/// }
142/// // Couldn't handle this error instance. Pass it up the stack.
143/// return Error(std::move(M));
144/// );
145/// // Note - we must check or return NewE in case any of the handlers
146/// // returned a new error.
147/// @endcode
148///
149/// The handleAllErrors function is identical to handleErrors, except
150/// that it has a void return type, and requires all errors to be handled and
151/// no new errors be returned. It prevents errors (assuming they can all be
152/// handled) from having to be bubbled all the way to the top-level.
153///
154/// *All* Error instances must be checked before destruction, even if
155/// they're moved-assigned or constructed from Success values that have already
156/// been checked. This enforces checking through all levels of the call stack.
157class LLVM_NODISCARD[[clang::warn_unused_result]] Error {
158 // Both ErrorList and FileError need to be able to yank ErrorInfoBase
159 // pointers out of this class to add to the error list.
160 friend class ErrorList;
161 friend class FileError;
162
163 // handleErrors needs to be able to set the Checked flag.
164 template <typename... HandlerTs>
165 friend Error handleErrors(Error E, HandlerTs &&... Handlers);
166
167 // Expected<T> needs to be able to steal the payload when constructed from an
168 // error.
169 template <typename T> friend class Expected;
170
171 // wrap needs to be able to steal the payload.
172 friend LLVMErrorRef wrap(Error);
173
174protected:
175 /// Create a success value. Prefer using 'Error::success()' for readability
176 Error() {
177 setPtr(nullptr);
178 setChecked(false);
179 }
180
181public:
182 /// Create a success value.
183 static ErrorSuccess success();
184
185 // Errors are not copy-constructable.
186 Error(const Error &Other) = delete;
187
188 /// Move-construct an error value. The newly constructed error is considered
189 /// unchecked, even if the source error had been checked. The original error
190 /// becomes a checked Success value, regardless of its original state.
191 Error(Error &&Other) {
192 setChecked(true);
193 *this = std::move(Other);
194 }
195
196 /// Create an error value. Prefer using the 'make_error' function, but
197 /// this constructor can be useful when "re-throwing" errors from handlers.
198 Error(std::unique_ptr<ErrorInfoBase> Payload) {
199 setPtr(Payload.release());
200 setChecked(false);
34
Potential leak of memory pointed to by 'Payload._M_t._M_head_impl'
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
253private:
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.
324class ErrorSuccess final : public Error {};
325
326inline ErrorSuccess Error::success() { return ErrorSuccess(); }
327
328/// Make a Error instance representing failure using the given error info
329/// type.
330template <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) {
331 return Error(llvm::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.
343template <typename ThisErrT, typename ParentErrT = ErrorInfoBase>
344class ErrorInfo : public ParentErrT {
345public:
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.
359class 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
368public:
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
382private:
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-9~svn362543/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-9~svn362543/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)
24
Assuming the condition is false
25
Taking false branch
393 return E2;
394 if (!E2)
26
Assuming the condition is false
27
Taking false branch
395 return E1;
396 if (E1.isA<ErrorList>()) {
28
Assuming the condition is false
29
Taking false branch
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>()) {
30
Assuming the condition is false
31
Taking false branch
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>(
33
Calling constructor for 'Error'
414 new ErrorList(E1.takePayload(), E2.takePayload())));
32
Memory is allocated
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.
423inline 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.
433template <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<typename std::remove_reference<T>::type>;
440
441 using error_type = std::unique_ptr<ErrorInfoBase>;
442
443public:
444 using storage_type = typename std::conditional<isRef, wrap, T>::type;
445 using value_type = T;
446
447private:
448 using reference = typename std::remove_reference<T>::type &;
449 using const_reference = const typename std::remove_reference<T>::type &;
450 using pointer = typename std::remove_reference<T>::type *;
451 using const_pointer = const typename std::remove_reference<T>::type *;
452
453public:
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-9~svn362543/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 typename std::enable_if<std::is_convertible<OtherT, T>::value>::type
476 * = nullptr)
477 : HasError(false)
478#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
479 // Expected is unchecked upon construction in Debug builds.
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(Expected<OtherT> &&Other,
493 typename std::enable_if<std::is_convertible<OtherT, T>::value>::type
494 * = 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 typename std::enable_if<!std::is_convertible<OtherT, T>::value>::type * =
504 nullptr) {
505 moveConstruct(std::move(Other));
506 }
507
508 /// Move-assign from another Expected<T>.
509 Expected &operator=(Expected &&Other) {
510 moveAssign(std::move(Other));
511 return *this;
512 }
513
514 /// Destroy an Expected<T>.
515 ~Expected() {
516 assertIsChecked();
517 if (!HasError)
518 getStorage()->~storage_type();
519 else
520 getErrorStorage()->~error_type();
521 }
522
523 /// Return false if there is an error.
524 explicit operator bool() {
525#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
526 Unchecked = HasError;
527#endif
528 return !HasError;
529 }
530
531 /// Returns a reference to the stored T value.
532 reference get() {
533 assertIsChecked();
534 return *getStorage();
535 }
536
537 /// Returns a const reference to the stored T value.
538 const_reference get() const {
539 assertIsChecked();
540 return const_cast<Expected<T> *>(this)->get();
541 }
542
543 /// Check that this Expected<T> is an error of type ErrT.
544 template <typename ErrT> bool errorIsA() const {
545 return HasError && (*getErrorStorage())->template isA<ErrT>();
546 }
547
548 /// Take ownership of the stored error.
549 /// After calling this the Expected<T> is in an indeterminate state that can
550 /// only be safely destructed. No further calls (beside the destructor) should
551 /// be made on the Expected<T> vaule.
552 Error takeError() {
553#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
554 Unchecked = false;
555#endif
556 return HasError ? Error(std::move(*getErrorStorage())) : Error::success();
557 }
558
559 /// Returns a pointer to the stored T value.
560 pointer operator->() {
561 assertIsChecked();
562 return toPointer(getStorage());
563 }
564
565 /// Returns a const pointer to the stored T value.
566 const_pointer operator->() const {
567 assertIsChecked();
568 return toPointer(getStorage());
569 }
570
571 /// Returns a reference to the stored T value.
572 reference operator*() {
573 assertIsChecked();
574 return *getStorage();
575 }
576
577 /// Returns a const reference to the stored T value.
578 const_reference operator*() const {
579 assertIsChecked();
580 return *getStorage();
581 }
582
583private:
584 template <class T1>
585 static bool compareThisIfSameType(const T1 &a, const T1 &b) {
586 return &a == &b;
587 }
588
589 template <class T1, class T2>
590 static bool compareThisIfSameType(const T1 &a, const T2 &b) {
591 return false;
592 }
593
594 template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) {
595 HasError = Other.HasError;
596#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
597 Unchecked = true;
598 Other.Unchecked = false;
599#endif
600
601 if (!HasError)
602 new (getStorage()) storage_type(std::move(*Other.getStorage()));
603 else
604 new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage()));
605 }
606
607 template <class OtherT> void moveAssign(Expected<OtherT> &&Other) {
608 assertIsChecked();
609
610 if (compareThisIfSameType(*this, Other))
611 return;
612
613 this->~Expected();
614 new (this) Expected(std::move(Other));
615 }
616
617 pointer toPointer(pointer Val) { return Val; }
618
619 const_pointer toPointer(const_pointer Val) const { return Val; }
620
621 pointer toPointer(wrap *Val) { return &Val->get(); }
622
623 const_pointer toPointer(const wrap *Val) const { return &Val->get(); }
624
625 storage_type *getStorage() {
626 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-9~svn362543/include/llvm/Support/Error.h"
, 626, __PRETTY_FUNCTION__))
;
627 return reinterpret_cast<storage_type *>(TStorage.buffer);
628 }
629
630 const storage_type *getStorage() const {
631 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-9~svn362543/include/llvm/Support/Error.h"
, 631, __PRETTY_FUNCTION__))
;
632 return reinterpret_cast<const storage_type *>(TStorage.buffer);
633 }
634
635 error_type *getErrorStorage() {
636 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-9~svn362543/include/llvm/Support/Error.h"
, 636, __PRETTY_FUNCTION__))
;
637 return reinterpret_cast<error_type *>(ErrorStorage.buffer);
638 }
639
640 const error_type *getErrorStorage() const {
641 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-9~svn362543/include/llvm/Support/Error.h"
, 641, __PRETTY_FUNCTION__))
;
642 return reinterpret_cast<const error_type *>(ErrorStorage.buffer);
643 }
644
645 // Used by ExpectedAsOutParameter to reset the checked flag.
646 void setUnchecked() {
647#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
648 Unchecked = true;
649#endif
650 }
651
652#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
653 LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn))
654 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline))
655 void fatalUncheckedExpected() const {
656 dbgs() << "Expected<T> must be checked before access or destruction.\n";
657 if (HasError) {
658 dbgs() << "Unchecked Expected<T> contained error:\n";
659 (*getErrorStorage())->log(dbgs());
660 } else
661 dbgs() << "Expected<T> value was in success state. (Note: Expected<T> "
662 "values in success mode must still be checked prior to being "
663 "destroyed).\n";
664 abort();
665 }
666#endif
667
668 void assertIsChecked() {
669#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
670 if (LLVM_UNLIKELY(Unchecked)__builtin_expect((bool)(Unchecked), false))
671 fatalUncheckedExpected();
672#endif
673 }
674
675 union {
676 AlignedCharArrayUnion<storage_type> TStorage;
677 AlignedCharArrayUnion<error_type> ErrorStorage;
678 };
679 bool HasError : 1;
680#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
681 bool Unchecked : 1;
682#endif
683};
684
685/// Report a serious error, calling any installed error handler. See
686/// ErrorHandling.h.
687LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) void report_fatal_error(Error Err,
688 bool gen_crash_diag = true);
689
690/// Report a fatal error if Err is a failure value.
691///
692/// This function can be used to wrap calls to fallible functions ONLY when it
693/// is known that the Error will always be a success value. E.g.
694///
695/// @code{.cpp}
696/// // foo only attempts the fallible operation if DoFallibleOperation is
697/// // true. If DoFallibleOperation is false then foo always returns
698/// // Error::success().
699/// Error foo(bool DoFallibleOperation);
700///
701/// cantFail(foo(false));
702/// @endcode
703inline void cantFail(Error Err, const char *Msg = nullptr) {
704 if (Err) {
705 if (!Msg)
706 Msg = "Failure value returned from cantFail wrapped call";
707 llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h"
, 707)
;
708 }
709}
710
711/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
712/// returns the contained value.
713///
714/// This function can be used to wrap calls to fallible functions ONLY when it
715/// is known that the Error will always be a success value. E.g.
716///
717/// @code{.cpp}
718/// // foo only attempts the fallible operation if DoFallibleOperation is
719/// // true. If DoFallibleOperation is false then foo always returns an int.
720/// Expected<int> foo(bool DoFallibleOperation);
721///
722/// int X = cantFail(foo(false));
723/// @endcode
724template <typename T>
725T cantFail(Expected<T> ValOrErr, const char *Msg = nullptr) {
726 if (ValOrErr)
727 return std::move(*ValOrErr);
728 else {
729 if (!Msg)
730 Msg = "Failure value returned from cantFail wrapped call";
731 llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h"
, 731)
;
732 }
733}
734
735/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
736/// returns the contained reference.
737///
738/// This function can be used to wrap calls to fallible functions ONLY when it
739/// is known that the Error will always be a success value. E.g.
740///
741/// @code{.cpp}
742/// // foo only attempts the fallible operation if DoFallibleOperation is
743/// // true. If DoFallibleOperation is false then foo always returns a Bar&.
744/// Expected<Bar&> foo(bool DoFallibleOperation);
745///
746/// Bar &X = cantFail(foo(false));
747/// @endcode
748template <typename T>
749T& cantFail(Expected<T&> ValOrErr, const char *Msg = nullptr) {
750 if (ValOrErr)
751 return *ValOrErr;
752 else {
753 if (!Msg)
754 Msg = "Failure value returned from cantFail wrapped call";
755 llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h"
, 755)
;
756 }
757}
758
759/// Helper for testing applicability of, and applying, handlers for
760/// ErrorInfo types.
761template <typename HandlerT>
762class ErrorHandlerTraits
763 : public ErrorHandlerTraits<decltype(
764 &std::remove_reference<HandlerT>::type::operator())> {};
765
766// Specialization functions of the form 'Error (const ErrT&)'.
767template <typename ErrT> class ErrorHandlerTraits<Error (&)(ErrT &)> {
768public:
769 static bool appliesTo(const ErrorInfoBase &E) {
770 return E.template isA<ErrT>();
771 }
772
773 template <typename HandlerT>
774 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
775 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-9~svn362543/include/llvm/Support/Error.h"
, 775, __PRETTY_FUNCTION__))
;
776 return H(static_cast<ErrT &>(*E));
777 }
778};
779
780// Specialization functions of the form 'void (const ErrT&)'.
781template <typename ErrT> class ErrorHandlerTraits<void (&)(ErrT &)> {
782public:
783 static bool appliesTo(const ErrorInfoBase &E) {
784 return E.template isA<ErrT>();
785 }
786
787 template <typename HandlerT>
788 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
789 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-9~svn362543/include/llvm/Support/Error.h"
, 789, __PRETTY_FUNCTION__))
;
790 H(static_cast<ErrT &>(*E));
791 return Error::success();
792 }
793};
794
795/// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'.
796template <typename ErrT>
797class ErrorHandlerTraits<Error (&)(std::unique_ptr<ErrT>)> {
798public:
799 static bool appliesTo(const ErrorInfoBase &E) {
800 return E.template isA<ErrT>();
801 }
802
803 template <typename HandlerT>
804 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
805 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-9~svn362543/include/llvm/Support/Error.h"
, 805, __PRETTY_FUNCTION__))
;
806 std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
807 return H(std::move(SubE));
808 }
809};
810
811/// Specialization for functions of the form 'void (std::unique_ptr<ErrT>)'.
812template <typename ErrT>
813class ErrorHandlerTraits<void (&)(std::unique_ptr<ErrT>)> {
814public:
815 static bool appliesTo(const ErrorInfoBase &E) {
816 return E.template isA<ErrT>();
817 }
818
819 template <typename HandlerT>
820 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
821 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-9~svn362543/include/llvm/Support/Error.h"
, 821, __PRETTY_FUNCTION__))
;
822 std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
823 H(std::move(SubE));
824 return Error::success();
825 }
826};
827
828// Specialization for member functions of the form 'RetT (const ErrT&)'.
829template <typename C, typename RetT, typename ErrT>
830class ErrorHandlerTraits<RetT (C::*)(ErrT &)>
831 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
832
833// Specialization for member functions of the form 'RetT (const ErrT&) const'.
834template <typename C, typename RetT, typename ErrT>
835class ErrorHandlerTraits<RetT (C::*)(ErrT &) const>
836 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
837
838// Specialization for member functions of the form 'RetT (const ErrT&)'.
839template <typename C, typename RetT, typename ErrT>
840class ErrorHandlerTraits<RetT (C::*)(const ErrT &)>
841 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
842
843// Specialization for member functions of the form 'RetT (const ErrT&) const'.
844template <typename C, typename RetT, typename ErrT>
845class ErrorHandlerTraits<RetT (C::*)(const ErrT &) const>
846 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
847
848/// Specialization for member functions of the form
849/// 'RetT (std::unique_ptr<ErrT>)'.
850template <typename C, typename RetT, typename ErrT>
851class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>)>
852 : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
853
854/// Specialization for member functions of the form
855/// 'RetT (std::unique_ptr<ErrT>) const'.
856template <typename C, typename RetT, typename ErrT>
857class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>) const>
858 : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
859
860inline Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload) {
861 return Error(std::move(Payload));
862}
863
864template <typename HandlerT, typename... HandlerTs>
865Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload,
866 HandlerT &&Handler, HandlerTs &&... Handlers) {
867 if (ErrorHandlerTraits<HandlerT>::appliesTo(*Payload))
868 return ErrorHandlerTraits<HandlerT>::apply(std::forward<HandlerT>(Handler),
869 std::move(Payload));
870 return handleErrorImpl(std::move(Payload),
871 std::forward<HandlerTs>(Handlers)...);
872}
873
874/// Pass the ErrorInfo(s) contained in E to their respective handlers. Any
875/// unhandled errors (or Errors returned by handlers) are re-concatenated and
876/// returned.
877/// Because this function returns an error, its result must also be checked
878/// or returned. If you intend to handle all errors use handleAllErrors
879/// (which returns void, and will abort() on unhandled errors) instead.
880template <typename... HandlerTs>
881Error handleErrors(Error E, HandlerTs &&... Hs) {
882 if (!E)
19
Assuming the condition is false
20
Taking false branch
883 return Error::success();
884
885 std::unique_ptr<ErrorInfoBase> Payload = E.takePayload();
886
887 if (Payload->isA<ErrorList>()) {
21
Assuming the condition is true
22
Taking true branch
888 ErrorList &List = static_cast<ErrorList &>(*Payload);
889 Error R;
890 for (auto &P : List.Payloads)
891 R = ErrorList::join(
23
Calling 'ErrorList::join'
892 std::move(R),
893 handleErrorImpl(std::move(P), std::forward<HandlerTs>(Hs)...));
894 return R;
895 }
896
897 return handleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...);
898}
899
900/// Behaves the same as handleErrors, except that by contract all errors
901/// *must* be handled by the given handlers (i.e. there must be no remaining
902/// errors after running the handlers, or llvm_unreachable is called).
903template <typename... HandlerTs>
904void handleAllErrors(Error E, HandlerTs &&... Handlers) {
905 cantFail(handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...));
18
Calling 'handleErrors<(lambda at /build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h:982:35)>'
906}
907
908/// Check that E is a non-error, then drop it.
909/// If E is an error, llvm_unreachable will be called.
910inline void handleAllErrors(Error E) {
911 cantFail(std::move(E));
912}
913
914/// Handle any errors (if present) in an Expected<T>, then try a recovery path.
915///
916/// If the incoming value is a success value it is returned unmodified. If it
917/// is a failure value then it the contained error is passed to handleErrors.
918/// If handleErrors is able to handle the error then the RecoveryPath functor
919/// is called to supply the final result. If handleErrors is not able to
920/// handle all errors then the unhandled errors are returned.
921///
922/// This utility enables the follow pattern:
923///
924/// @code{.cpp}
925/// enum FooStrategy { Aggressive, Conservative };
926/// Expected<Foo> foo(FooStrategy S);
927///
928/// auto ResultOrErr =
929/// handleExpected(
930/// foo(Aggressive),
931/// []() { return foo(Conservative); },
932/// [](AggressiveStrategyError&) {
933/// // Implicitly conusme this - we'll recover by using a conservative
934/// // strategy.
935/// });
936///
937/// @endcode
938template <typename T, typename RecoveryFtor, typename... HandlerTs>
939Expected<T> handleExpected(Expected<T> ValOrErr, RecoveryFtor &&RecoveryPath,
940 HandlerTs &&... Handlers) {
941 if (ValOrErr)
942 return ValOrErr;
943
944 if (auto Err = handleErrors(ValOrErr.takeError(),
945 std::forward<HandlerTs>(Handlers)...))
946 return std::move(Err);
947
948 return RecoveryPath();
949}
950
951/// Log all errors (if any) in E to OS. If there are any errors, ErrorBanner
952/// will be printed before the first one is logged. A newline will be printed
953/// after each error.
954///
955/// This function is compatible with the helpers from Support/WithColor.h. You
956/// can pass any of them as the OS. Please consider using them instead of
957/// including 'error: ' in the ErrorBanner.
958///
959/// This is useful in the base level of your program to allow clean termination
960/// (allowing clean deallocation of resources, etc.), while reporting error
961/// information to the user.
962void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner = {});
963
964/// Write all error messages (if any) in E to a string. The newline character
965/// is used to separate error messages.
966inline std::string toString(Error E) {
967 SmallVector<std::string, 2> Errors;
968 handleAllErrors(std::move(E), [&Errors](const ErrorInfoBase &EI) {
969 Errors.push_back(EI.message());
970 });
971 return join(Errors.begin(), Errors.end(), "\n");
972}
973
974/// Consume a Error without doing anything. This method should be used
975/// only where an error can be considered a reasonable and expected return
976/// value.
977///
978/// Uses of this method are potentially indicative of design problems: If it's
979/// legitimate to do nothing while processing an "error", the error-producer
980/// might be more clearly refactored to return an Optional<T>.
981inline void consumeError(Error Err) {
982 handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {});
17
Calling 'handleAllErrors<(lambda at /build/llvm-toolchain-snapshot-9~svn362543/include/llvm/Support/Error.h:982:35)>'
983}
984
985/// Helper for converting an Error to a bool.
986///
987/// This method returns true if Err is in an error state, or false if it is
988/// in a success state. Puts Err in a checked state in both cases (unlike
989/// Error::operator bool(), which only does this for success states).
990inline bool errorToBool(Error Err) {
991 bool IsError = static_cast<bool>(Err);
992 if (IsError)
993 consumeError(std::move(Err));
994 return IsError;
995}
996
997/// Helper for Errors used as out-parameters.
998///
999/// This helper is for use with the Error-as-out-parameter idiom, where an error
1000/// is passed to a function or method by reference, rather than being returned.
1001/// In such cases it is helpful to set the checked bit on entry to the function
1002/// so that the error can be written to (unchecked Errors abort on assignment)
1003/// and clear the checked bit on exit so that clients cannot accidentally forget
1004/// to check the result. This helper performs these actions automatically using
1005/// RAII:
1006///
1007/// @code{.cpp}
1008/// Result foo(Error &Err) {
1009/// ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set
1010/// // <body of foo>
1011/// // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed.
1012/// }
1013/// @endcode
1014///
1015/// ErrorAsOutParameter takes an Error* rather than Error& so that it can be
1016/// used with optional Errors (Error pointers that are allowed to be null). If
1017/// ErrorAsOutParameter took an Error reference, an instance would have to be
1018/// created inside every condition that verified that Error was non-null. By
1019/// taking an Error pointer we can just create one instance at the top of the
1020/// function.
1021class ErrorAsOutParameter {
1022public:
1023 ErrorAsOutParameter(Error *Err) : Err(Err) {
1024 // Raise the checked bit if Err is success.
1025 if (Err)
1026 (void)!!*Err;
1027 }
1028
1029 ~ErrorAsOutParameter() {
1030 // Clear the checked bit.
1031 if (Err && !*Err)
1032 *Err = Error::success();
1033 }
1034
1035private:
1036 Error *Err;
1037};
1038
1039/// Helper for Expected<T>s used as out-parameters.
1040///
1041/// See ErrorAsOutParameter.
1042template <typename T>
1043class ExpectedAsOutParameter {
1044public:
1045 ExpectedAsOutParameter(Expected<T> *ValOrErr)
1046 : ValOrErr(ValOrErr) {
1047 if (ValOrErr)
1048 (void)!!*ValOrErr;
1049 }
1050
1051 ~ExpectedAsOutParameter() {
1052 if (ValOrErr)
1053 ValOrErr->setUnchecked();
1054 }
1055
1056private:
1057 Expected<T> *ValOrErr;
1058};
1059
1060/// This class wraps a std::error_code in a Error.
1061///
1062/// This is useful if you're writing an interface that returns a Error
1063/// (or Expected) and you want to call code that still returns
1064/// std::error_codes.
1065class ECError : public ErrorInfo<ECError> {
1066 friend Error errorCodeToError(std::error_code);
1067
1068 virtual void anchor() override;
1069
1070public:
1071 void setErrorCode(std::error_code EC) { this->EC = EC; }
1072 std::error_code convertToErrorCode() const override { return EC; }
1073 void log(raw_ostream &OS) const override { OS << EC.message(); }
1074
1075 // Used by ErrorInfo::classID.
1076 static char ID;
1077
1078protected:
1079 ECError() = default;
1080 ECError(std::error_code EC) : EC(EC) {}
1081
1082 std::error_code EC;
1083};
1084
1085/// The value returned by this function can be returned from convertToErrorCode
1086/// for Error values where no sensible translation to std::error_code exists.
1087/// It should only be used in this situation, and should never be used where a
1088/// sensible conversion to std::error_code is available, as attempts to convert
1089/// to/from this error will result in a fatal error. (i.e. it is a programmatic
1090///error to try to convert such a value).
1091std::error_code inconvertibleErrorCode();
1092
1093/// Helper for converting an std::error_code to a Error.
1094Error errorCodeToError(std::error_code EC);
1095
1096/// Helper for converting an ECError to a std::error_code.
1097///
1098/// This method requires that Err be Error() or an ECError, otherwise it
1099/// will trigger a call to abort().
1100std::error_code errorToErrorCode(Error Err);
1101
1102/// Convert an ErrorOr<T> to an Expected<T>.
1103template <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) {
1104 if (auto EC = EO.getError())
1105 return errorCodeToError(EC);
1106 return std::move(*EO);
1107}
1108
1109/// Convert an Expected<T> to an ErrorOr<T>.
1110template <typename T> ErrorOr<T> expectedToErrorOr(Expected<T> &&E) {
1111 if (auto Err = E.takeError())
1112 return errorToErrorCode(std::move(Err));
1113 return std::move(*E);
1114}
1115
1116/// This class wraps a string in an Error.
1117///
1118/// StringError is useful in cases where the client is not expected to be able
1119/// to consume the specific error message programmatically (for example, if the
1120/// error message is to be presented to the user).
1121///
1122/// StringError can also be used when additional information is to be printed
1123/// along with a error_code message. Depending on the constructor called, this
1124/// class can either display:
1125/// 1. the error_code message (ECError behavior)
1126/// 2. a string
1127/// 3. the error_code message and a string
1128///
1129/// These behaviors are useful when subtyping is required; for example, when a
1130/// specific library needs an explicit error type. In the example below,
1131/// PDBError is derived from StringError:
1132///
1133/// @code{.cpp}
1134/// Expected<int> foo() {
1135/// return llvm::make_error<PDBError>(pdb_error_code::dia_failed_loading,
1136/// "Additional information");
1137/// }
1138/// @endcode
1139///
1140class StringError : public ErrorInfo<StringError> {
1141public:
1142 static char ID;
1143
1144 // Prints EC + S and converts to EC
1145 StringError(std::error_code EC, const Twine &S = Twine());
1146
1147 // Prints S and converts to EC
1148 StringError(const Twine &S, std::error_code EC);
1149
1150 void log(raw_ostream &OS) const override;
1151 std::error_code convertToErrorCode() const override;
1152
1153 const std::string &getMessage() const { return Msg; }
1154
1155private:
1156 std::string Msg;
1157 std::error_code EC;
1158 const bool PrintMsgOnly = false;
1159};
1160
1161/// Create formatted StringError object.
1162template <typename... Ts>
1163Error createStringError(std::error_code EC, char const *Fmt,
1164 const Ts &... Vals) {
1165 std::string Buffer;
1166 raw_string_ostream Stream(Buffer);
1167 Stream << format(Fmt, Vals...);
1168 return make_error<StringError>(Stream.str(), EC);
1169}
1170
1171Error createStringError(std::error_code EC, char const *Msg);
1172
1173/// This class wraps a filename and another Error.
1174///
1175/// In some cases, an error needs to live along a 'source' name, in order to
1176/// show more detailed information to the user.
1177class FileError final : public ErrorInfo<FileError> {
1178
1179 friend Error createFileError(const Twine &, Error);
1180 friend Error createFileError(const Twine &, size_t, Error);
1181
1182public:
1183 void log(raw_ostream &OS) const override {
1184 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-9~svn362543/include/llvm/Support/Error.h"
, 1184, __PRETTY_FUNCTION__))
;
1185 OS << "'" << FileName << "': ";
1186 if (Line.hasValue())
1187 OS << "line " << Line.getValue() << ": ";
1188 Err->log(OS);
1189 }
1190
1191 Error takeError() { return Error(std::move(Err)); }
1192
1193 std::error_code convertToErrorCode() const override;
1194
1195 // Used by ErrorInfo::classID.
1196 static char ID;
1197
1198private:
1199 FileError(const Twine &F, Optional<size_t> LineNum,
1200 std::unique_ptr<ErrorInfoBase> E) {
1201 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-9~svn362543/include/llvm/Support/Error.h"
, 1201, __PRETTY_FUNCTION__))
;
1202 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-9~svn362543/include/llvm/Support/Error.h"
, 1203, __PRETTY_FUNCTION__))
1203 "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-9~svn362543/include/llvm/Support/Error.h"
, 1203, __PRETTY_FUNCTION__))
;
1204 FileName = F.str();
1205 Err = std::move(E);
1206 Line = std::move(LineNum);
1207 }
1208
1209 static Error build(const Twine &F, Optional<size_t> Line, Error E) {
1210 return Error(
1211 std::unique_ptr<FileError>(new FileError(F, Line, E.takePayload())));
1212 }
1213
1214 std::string FileName;
1215 Optional<size_t> Line;
1216 std::unique_ptr<ErrorInfoBase> Err;
1217};
1218
1219/// Concatenate a source file path and/or name with an Error. The resulting
1220/// Error is unchecked.
1221inline Error createFileError(const Twine &F, Error E) {
1222 return FileError::build(F, Optional<size_t>(), std::move(E));
1223}
1224
1225/// Concatenate a source file path and/or name with line number and an Error.
1226/// The resulting Error is unchecked.
1227inline Error createFileError(const Twine &F, size_t Line, Error E) {
1228 return FileError::build(F, Optional<size_t>(Line), std::move(E));
1229}
1230
1231/// Concatenate a source file path and/or name with a std::error_code
1232/// to form an Error object.
1233inline Error createFileError(const Twine &F, std::error_code EC) {
1234 return createFileError(F, errorCodeToError(EC));
1235}
1236
1237/// Concatenate a source file path and/or name with line number and
1238/// std::error_code to form an Error object.
1239inline Error createFileError(const Twine &F, size_t Line, std::error_code EC) {
1240 return createFileError(F, Line, errorCodeToError(EC));
1241}
1242
1243Error createFileError(const Twine &F, ErrorSuccess) = delete;
1244
1245/// Helper for check-and-exit error handling.
1246///
1247/// For tool use only. NOT FOR USE IN LIBRARY CODE.
1248///
1249class ExitOnError {
1250public:
1251 /// Create an error on exit helper.
1252 ExitOnError(std::string Banner = "", int DefaultErrorExitCode = 1)
1253 : Banner(std::move(Banner)),
1254 GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {}
1255
1256 /// Set the banner string for any errors caught by operator().
1257 void setBanner(std::string Banner) { this->Banner = std::move(Banner); }
1258
1259 /// Set the exit-code mapper function.
1260 void setExitCodeMapper(std::function<int(const Error &)> GetExitCode) {
1261 this->GetExitCode = std::move(GetExitCode);
1262 }
1263
1264 /// Check Err. If it's in a failure state log the error(s) and exit.
1265 void operator()(Error Err) const { checkError(std::move(Err)); }
1266
1267 /// Check E. If it's in a success state then return the contained value. If
1268 /// it's in a failure state log the error(s) and exit.
1269 template <typename T> T operator()(Expected<T> &&E) const {
1270 checkError(E.takeError());
1271 return std::move(*E);
1272 }
1273
1274 /// Check E. If it's in a success state then return the contained reference. If
1275 /// it's in a failure state log the error(s) and exit.
1276 template <typename T> T& operator()(Expected<T&> &&E) const {
1277 checkError(E.takeError());
1278 return *E;
1279 }
1280
1281private:
1282 void checkError(Error Err) const {
1283 if (Err) {
1284 int ExitCode = GetExitCode(Err);
1285 logAllUnhandledErrors(std::move(Err), errs(), Banner);
1286 exit(ExitCode);
1287 }
1288 }
1289
1290 std::string Banner;
1291 std::function<int(const Error &)> GetExitCode;
1292};
1293
1294/// Conversion from Error to LLVMErrorRef for C error bindings.
1295inline LLVMErrorRef wrap(Error Err) {
1296 return reinterpret_cast<LLVMErrorRef>(Err.takePayload().release());
1297}
1298
1299/// Conversion from LLVMErrorRef to Error for C error bindings.
1300inline Error unwrap(LLVMErrorRef ErrRef) {
1301 return Error(std::unique_ptr<ErrorInfoBase>(
1302 reinterpret_cast<ErrorInfoBase *>(ErrRef)));
1303}
1304
1305} // end namespace llvm
1306
1307#endif // LLVM_SUPPORT_ERROR_H