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
20  enum 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.
29  class ErrorErrorCategory : public std::error_category {
30  public:
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 "
39               "not be converted to a known std::error_code. Please file a "
40               "bug.";
41      case ErrorErrorCode::FileError:
42          return "A file error occurred.";
43      }
44      llvm_unreachable("Unhandled error code");
45    }
46  };
47
48}
49
50ErrorErrorCategory &getErrorErrorCat() {
51  static ErrorErrorCategory ErrorErrorCat;
52  return ErrorErrorCat;
53}
54
55namespace llvm {
56
57void ErrorInfoBase::anchor() {}
58char ErrorInfoBase::ID = 0;
59char ErrorList::ID = 0;
60void ECError::anchor() {}
61char ECError::ID = 0;
62char StringError::ID = 0;
63char FileError::ID = 0;
64
65void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner) {
66  if (!E)
67    return;
68  OS << ErrorBanner;
69  handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
70    EI.log(OS);
71    OS << "\n";
72  });
73}
74
75/// Write all error messages (if any) in E to a string. The newline character
76/// is used to separate error messages.
77std::string toString(Error E) {
78  SmallVector<std::string, 2> Errors;
79  handleAllErrors(std::move(E), [&Errors](const ErrorInfoBase &EI) {
80    Errors.push_back(EI.message());
81  });
82  return join(Errors.begin(), Errors.end(), "\n");
83}
84
85std::error_code ErrorList::convertToErrorCode() const {
86  return std::error_code(static_cast<int>(ErrorErrorCode::MultipleErrors),
87                         getErrorErrorCat());
88}
89
90std::error_code inconvertibleErrorCode() {
91  return std::error_code(static_cast<int>(ErrorErrorCode::InconvertibleError),
92                         getErrorErrorCat());
93}
94
95std::error_code FileError::convertToErrorCode() const {
96  std::error_code NestedEC = Err->convertToErrorCode();
97  if (NestedEC == inconvertibleErrorCode())
98    return std::error_code(static_cast<int>(ErrorErrorCode::FileError),
99                           getErrorErrorCat());
100  return NestedEC;
101}
102
103Error errorCodeToError(std::error_code EC) {
104  if (!EC)
105    return Error::success();
106  return Error(std::make_unique<ECError>(ECError(EC)));
107}
108
109std::error_code errorToErrorCode(Error Err) {
110  std::error_code EC;
111  handleAllErrors(std::move(Err), [&](const ErrorInfoBase &EI) {
112    EC = EI.convertToErrorCode();
113  });
114  if (EC == inconvertibleErrorCode())
115    report_fatal_error(Twine(EC.message()));
116  return EC;
117}
118
119#if LLVM_ENABLE_ABI_BREAKING_CHECKS
120void Error::fatalUncheckedError() const {
121  dbgs() << "Program aborted due to an unhandled Error:\n";
122  if (getPtr()) {
123    getPtr()->log(dbgs());
124    dbgs() << "\n";
125  }else
126    dbgs() << "Error value was Success. (Note: Success values must still be "
127              "checked prior to being destroyed).\n";
128  abort();
129}
130#endif
131
132StringError::StringError(std::error_code EC, const Twine &S)
133    : Msg(S.str()), EC(EC) {}
134
135StringError::StringError(const Twine &S, std::error_code EC)
136    : Msg(S.str()), EC(EC), PrintMsgOnly(true) {}
137
138void StringError::log(raw_ostream &OS) const {
139  if (PrintMsgOnly) {
140    OS << Msg;
141  } else {
142    OS << EC.message();
143    if (!Msg.empty())
144      OS << (" " + Msg);
145  }
146}
147
148std::error_code StringError::convertToErrorCode() const {
149  return EC;
150}
151
152Error createStringError(std::error_code EC, char const *Msg) {
153  return make_error<StringError>(Msg, EC);
154}
155
156void report_fatal_error(Error Err, bool GenCrashDiag) {
157  assert(Err && "report_fatal_error called with success value");
158  std::string ErrMsg;
159  {
160    raw_string_ostream ErrStream(ErrMsg);
161    logAllUnhandledErrors(std::move(Err), ErrStream);
162  }
163  report_fatal_error(Twine(ErrMsg), GenCrashDiag);
164}
165
166} // end namespace llvm
167
168LLVMErrorTypeId LLVMGetErrorTypeId(LLVMErrorRef Err) {
169  return reinterpret_cast<ErrorInfoBase *>(Err)->dynamicClassID();
170}
171
172void LLVMConsumeError(LLVMErrorRef Err) { consumeError(unwrap(Err)); }
173
174char *LLVMGetErrorMessage(LLVMErrorRef Err) {
175  std::string Tmp = toString(unwrap(Err));
176  char *ErrMsg = new char[Tmp.size() + 1];
177  memcpy(ErrMsg, Tmp.data(), Tmp.size());
178  ErrMsg[Tmp.size()] = '\0';
179  return ErrMsg;
180}
181
182void LLVMDisposeErrorMessage(char *ErrMsg) { delete[] ErrMsg; }
183
184LLVMErrorTypeId LLVMGetStringErrorTypeId() {
185  return reinterpret_cast<void *>(&StringError::ID);
186}
187
188LLVMErrorRef LLVMCreateStringError(const char *ErrMsg) {
189  return wrap(make_error<StringError>(ErrMsg, inconvertibleErrorCode()));
190}
191