1//===----- lib/Support/Error.cpp - Error and associated utilities ---------===//
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#include "llvm/Support/Error.h"
10#include "llvm/ADT/SmallVector.h"
11#include "llvm/ADT/StringExtras.h"
12#include "llvm/ADT/Twine.h"
13#include "llvm/Support/ErrorHandling.h"
14#include <system_error>
15
16using namespace llvm;
17
18namespace {
19
20enum class ErrorErrorCode : int {
21 MultipleErrors = 1,
22 FileError,
23 InconvertibleError
24};
25
26// FIXME: This class is only here to support the transition to llvm::Error. It
27// will be removed once this transition is complete. Clients should prefer to
28// deal with the Error value directly, rather than converting to error_code.
29class ErrorErrorCategory : public std::error_category {
30public:
31 const char *name() const noexcept override { return "Error"; }
32
33 std::string message(int condition) const override {
34 switch (static_cast<ErrorErrorCode>(condition)) {
35 case ErrorErrorCode::MultipleErrors:
36 return "Multiple errors";
37 case ErrorErrorCode::InconvertibleError:
38 return "Inconvertible error value. An error has occurred that could not "
39 "be converted to a known std::error_code. Please file a bug.";
40 case ErrorErrorCode::FileError:
41 return "A file error occurred.";
42 }
43 llvm_unreachable("Unhandled error code");
44 }
45};
46}
47
48static ErrorErrorCategory &getErrorErrorCat() {
49 static ErrorErrorCategory ErrorErrorCat;
50 return ErrorErrorCat;
51}
52
53void ErrorInfoBase::anchor() {}
54char ErrorInfoBase::ID = 0;
55char ErrorList::ID = 0;
56void ECError::anchor() {}
57char ECError::ID = 0;
58char StringError::ID = 0;
59char FileError::ID = 0;
60
61void llvm::logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner) {
62 if (!E)
63 return;
64 OS << ErrorBanner;
65 handleAllErrors(E: std::move(E), Handlers: [&](const ErrorInfoBase &EI) {
66 EI.log(OS);
67 OS << "\n";
68 });
69}
70
71/// Write all error messages (if any) in E to a string. The newline character
72/// is used to separate error messages.
73std::string llvm::toString(Error E) {
74 SmallVector<std::string, 2> Errors;
75 handleAllErrors(E: std::move(E), Handlers: [&Errors](const ErrorInfoBase &EI) {
76 Errors.push_back(Elt: EI.message());
77 });
78 return join(Begin: Errors.begin(), End: Errors.end(), Separator: "\n");
79}
80
81std::string llvm::toStringWithoutConsuming(const Error &E) {
82 SmallVector<std::string, 2> Errors;
83 visitErrors(E, H: [&Errors](const ErrorInfoBase &EI) {
84 Errors.push_back(Elt: EI.message());
85 });
86 return join(Begin: Errors.begin(), End: Errors.end(), Separator: "\n");
87}
88
89std::error_code ErrorList::convertToErrorCode() const {
90 return std::error_code(static_cast<int>(ErrorErrorCode::MultipleErrors),
91 getErrorErrorCat());
92}
93
94std::error_code llvm::inconvertibleErrorCode() {
95 return std::error_code(static_cast<int>(ErrorErrorCode::InconvertibleError),
96 getErrorErrorCat());
97}
98
99std::error_code FileError::convertToErrorCode() const {
100 std::error_code NestedEC = Err->convertToErrorCode();
101 if (NestedEC == inconvertibleErrorCode())
102 return std::error_code(static_cast<int>(ErrorErrorCode::FileError),
103 getErrorErrorCat());
104 return NestedEC;
105}
106
107Error llvm::errorCodeToError(std::error_code EC) {
108 if (!EC)
109 return Error::success();
110 return Error(std::make_unique<ECError>(args: ECError(EC)));
111}
112
113std::error_code llvm::errorToErrorCode(Error Err) {
114 std::error_code EC;
115 handleAllErrors(E: std::move(Err), Handlers: [&](const ErrorInfoBase &EI) {
116 EC = EI.convertToErrorCode();
117 });
118 if (EC == inconvertibleErrorCode())
119 report_fatal_error(reason: Twine(EC.message()));
120 return EC;
121}
122
123#if LLVM_ENABLE_ABI_BREAKING_CHECKS
124void Error::fatalUncheckedError() const {
125 dbgs() << "Program aborted due to an unhandled Error:\n";
126 if (getPtr()) {
127 getPtr()->log(dbgs());
128 dbgs() << "\n";
129 }else
130 dbgs() << "Error value was Success. (Note: Success values must still be "
131 "checked prior to being destroyed).\n";
132 abort();
133}
134#endif
135
136StringError::StringError(std::error_code EC, const Twine &S)
137 : Msg(S.str()), EC(EC) {}
138
139StringError::StringError(const Twine &S, std::error_code EC)
140 : Msg(S.str()), EC(EC), PrintMsgOnly(true) {}
141
142StringError::StringError(std::string &&S, std::error_code EC, bool PrintMsgOnly)
143 : Msg(std::move(S)), EC(EC), PrintMsgOnly(PrintMsgOnly) {}
144
145void StringError::log(raw_ostream &OS) const {
146 if (PrintMsgOnly) {
147 OS << Msg;
148 } else {
149 OS << EC.message();
150 if (!Msg.empty())
151 OS << (" " + Msg);
152 }
153}
154
155std::error_code StringError::convertToErrorCode() const {
156 return EC;
157}
158
159Error llvm::createStringError(std::string &&Msg, std::error_code EC) {
160 return make_error<StringError>(Args: std::move(Msg), Args&: EC, Args: true);
161}
162
163void llvm::report_fatal_error(Error Err, bool GenCrashDiag) {
164 assert(Err && "report_fatal_error called with success value");
165 std::string ErrMsg;
166 {
167 raw_string_ostream ErrStream(ErrMsg);
168 logAllUnhandledErrors(E: std::move(Err), OS&: ErrStream);
169 }
170 report_fatal_error(reason: Twine(ErrMsg), gen_crash_diag: GenCrashDiag);
171}
172
173void llvm::reportFatalInternalError(Error Err) {
174 report_fatal_error(Err: std::move(Err), /*GenCrashDiag=*/true);
175}
176
177void llvm::reportFatalUsageError(Error Err) {
178 report_fatal_error(Err: std::move(Err), /*GenCrashDiag=*/false);
179}
180
181LLVMErrorTypeId LLVMGetErrorTypeId(LLVMErrorRef Err) {
182 return reinterpret_cast<ErrorInfoBase *>(Err)->dynamicClassID();
183}
184
185void LLVMConsumeError(LLVMErrorRef Err) { consumeError(Err: unwrap(ErrRef: Err)); }
186
187void LLVMCantFail(LLVMErrorRef Err) {
188 cantFail(Err: unwrap(ErrRef: Err));
189}
190
191char *LLVMGetErrorMessage(LLVMErrorRef Err) {
192 std::string Tmp = toString(E: unwrap(ErrRef: Err));
193 char *ErrMsg = new char[Tmp.size() + 1];
194 memcpy(dest: ErrMsg, src: Tmp.data(), n: Tmp.size());
195 ErrMsg[Tmp.size()] = '\0';
196 return ErrMsg;
197}
198
199void LLVMDisposeErrorMessage(char *ErrMsg) { delete[] ErrMsg; }
200
201LLVMErrorTypeId LLVMGetStringErrorTypeId() {
202 return reinterpret_cast<void *>(&StringError::ID);
203}
204
205LLVMErrorRef LLVMCreateStringError(const char *ErrMsg) {
206 return wrap(Err: make_error<StringError>(Args&: ErrMsg, Args: inconvertibleErrorCode()));
207}
208