1 //===-- Status.cpp -----------------------------------------------*- C++
2 //-*-===//
3 //
4 //                     The LLVM Compiler Infrastructure
5 //
6 // This file is distributed under the University of Illinois Open Source
7 // License. See LICENSE.TXT for details.
8 //
9 //===----------------------------------------------------------------------===//
10 
11 #include "lldb/Utility/Status.h"
12 
13 #include "lldb/Utility/VASPrintf.h"
14 #include "lldb/lldb-defines.h"      // for LLDB_GENERIC_ERROR
15 #include "lldb/lldb-enumerations.h" // for ErrorType, ErrorType::eErr...
16 #include "llvm/ADT/SmallString.h"   // for SmallString
17 #include "llvm/ADT/StringRef.h"     // for StringRef
18 #include "llvm/Support/Errno.h"
19 #include "llvm/Support/FormatProviders.h" // for format_provider
20 
21 #include <cerrno>
22 #include <cstdarg>
23 #include <string> // for string
24 #include <system_error>
25 
26 #ifdef __APPLE__
27 #include <mach/mach.h>
28 #endif
29 
30 #include <stdint.h> // for uint32_t
31 
32 namespace llvm {
33 class raw_ostream;
34 }
35 
36 using namespace lldb;
37 using namespace lldb_private;
38 
39 Status::Status() : m_code(0), m_type(eErrorTypeInvalid), m_string() {}
40 
41 Status::Status(ValueType err, ErrorType type)
42     : m_code(err), m_type(type), m_string() {}
43 
44 Status::Status(std::error_code EC)
45     : m_code(EC.value()), m_type(ErrorType::eErrorTypeGeneric),
46       m_string(EC.message()) {}
47 
48 Status::Status(const Status &rhs) = default;
49 
50 Status::Status(const char *format, ...)
51     : m_code(0), m_type(eErrorTypeInvalid), m_string() {
52   va_list args;
53   va_start(args, format);
54   SetErrorToGenericError();
55   SetErrorStringWithVarArg(format, args);
56   va_end(args);
57 }
58 
59 const Status &Status::operator=(llvm::Error error) {
60   if (!error) {
61     Clear();
62     return *this;
63   }
64 
65   // if the error happens to be a errno error, preserve the error code
66   error = llvm::handleErrors(
67       std::move(error), [&](std::unique_ptr<llvm::ECError> e) -> llvm::Error {
68         std::error_code ec = e->convertToErrorCode();
69         if (ec.category() == std::generic_category()) {
70           m_code = ec.value();
71           m_type = ErrorType::eErrorTypePOSIX;
72           return llvm::Error::success();
73         }
74         return llvm::Error(std::move(e));
75       });
76 
77   // Otherwise, just preserve the message
78   if (error) {
79     SetErrorToGenericError();
80     SetErrorString(llvm::toString(std::move(error)));
81   }
82 
83   return *this;
84 }
85 
86 llvm::Error Status::ToError() const {
87   if (Success())
88     return llvm::Error::success();
89   if (m_type == ErrorType::eErrorTypePOSIX)
90     return llvm::errorCodeToError(std::error_code(m_code, std::generic_category()));
91   return llvm::make_error<llvm::StringError>(AsCString(),
92                                              llvm::inconvertibleErrorCode());
93 }
94 
95 //----------------------------------------------------------------------
96 // Assignment operator
97 //----------------------------------------------------------------------
98 const Status &Status::operator=(const Status &rhs) {
99   if (this != &rhs) {
100     m_code = rhs.m_code;
101     m_type = rhs.m_type;
102     m_string = rhs.m_string;
103   }
104   return *this;
105 }
106 
107 Status::~Status() = default;
108 
109 //----------------------------------------------------------------------
110 // Get the error value as a NULL C string. The error string will be
111 // fetched and cached on demand. The cached error string value will
112 // remain until the error value is changed or cleared.
113 //----------------------------------------------------------------------
114 const char *Status::AsCString(const char *default_error_str) const {
115   if (Success())
116     return nullptr;
117 
118   if (m_string.empty()) {
119     switch (m_type) {
120     case eErrorTypeMachKernel:
121 #if defined(__APPLE__)
122       if (const char *s = ::mach_error_string(m_code))
123         m_string.assign(s);
124 #endif
125       break;
126 
127     case eErrorTypePOSIX:
128       m_string = llvm::sys::StrError(m_code);
129       break;
130 
131     default:
132       break;
133     }
134   }
135   if (m_string.empty()) {
136     if (default_error_str)
137       m_string.assign(default_error_str);
138     else
139       return nullptr; // User wanted a nullptr string back...
140   }
141   return m_string.c_str();
142 }
143 
144 //----------------------------------------------------------------------
145 // Clear the error and any cached error string that it might contain.
146 //----------------------------------------------------------------------
147 void Status::Clear() {
148   m_code = 0;
149   m_type = eErrorTypeInvalid;
150   m_string.clear();
151 }
152 
153 //----------------------------------------------------------------------
154 // Access the error value.
155 //----------------------------------------------------------------------
156 Status::ValueType Status::GetError() const { return m_code; }
157 
158 //----------------------------------------------------------------------
159 // Access the error type.
160 //----------------------------------------------------------------------
161 ErrorType Status::GetType() const { return m_type; }
162 
163 //----------------------------------------------------------------------
164 // Returns true if this object contains a value that describes an
165 // error or otherwise non-success result.
166 //----------------------------------------------------------------------
167 bool Status::Fail() const { return m_code != 0; }
168 
169 //----------------------------------------------------------------------
170 // Set accesssor for the error value to "err" and the type to
171 // "eErrorTypeMachKernel"
172 //----------------------------------------------------------------------
173 void Status::SetMachError(uint32_t err) {
174   m_code = err;
175   m_type = eErrorTypeMachKernel;
176   m_string.clear();
177 }
178 
179 void Status::SetExpressionError(lldb::ExpressionResults result,
180                                 const char *mssg) {
181   m_code = result;
182   m_type = eErrorTypeExpression;
183   m_string = mssg;
184 }
185 
186 int Status::SetExpressionErrorWithFormat(lldb::ExpressionResults result,
187                                          const char *format, ...) {
188   int length = 0;
189 
190   if (format != nullptr && format[0]) {
191     va_list args;
192     va_start(args, format);
193     length = SetErrorStringWithVarArg(format, args);
194     va_end(args);
195   } else {
196     m_string.clear();
197   }
198   m_code = result;
199   m_type = eErrorTypeExpression;
200   return length;
201 }
202 
203 //----------------------------------------------------------------------
204 // Set accesssor for the error value and type.
205 //----------------------------------------------------------------------
206 void Status::SetError(ValueType err, ErrorType type) {
207   m_code = err;
208   m_type = type;
209   m_string.clear();
210 }
211 
212 //----------------------------------------------------------------------
213 // Update the error value to be "errno" and update the type to
214 // be "POSIX".
215 //----------------------------------------------------------------------
216 void Status::SetErrorToErrno() {
217   m_code = errno;
218   m_type = eErrorTypePOSIX;
219   m_string.clear();
220 }
221 
222 //----------------------------------------------------------------------
223 // Update the error value to be LLDB_GENERIC_ERROR and update the type
224 // to be "Generic".
225 //----------------------------------------------------------------------
226 void Status::SetErrorToGenericError() {
227   m_code = LLDB_GENERIC_ERROR;
228   m_type = eErrorTypeGeneric;
229   m_string.clear();
230 }
231 
232 //----------------------------------------------------------------------
233 // Set accessor for the error string value for a specific error.
234 // This allows any string to be supplied as an error explanation.
235 // The error string value will remain until the error value is
236 // cleared or a new error value/type is assigned.
237 //----------------------------------------------------------------------
238 void Status::SetErrorString(llvm::StringRef err_str) {
239   if (!err_str.empty()) {
240     // If we have an error string, we should always at least have an error
241     // set to a generic value.
242     if (Success())
243       SetErrorToGenericError();
244   }
245   m_string = err_str;
246 }
247 
248 //------------------------------------------------------------------
249 /// Set the current error string to a formatted error string.
250 ///
251 /// @param format
252 ///     A printf style format string
253 //------------------------------------------------------------------
254 int Status::SetErrorStringWithFormat(const char *format, ...) {
255   if (format != nullptr && format[0]) {
256     va_list args;
257     va_start(args, format);
258     int length = SetErrorStringWithVarArg(format, args);
259     va_end(args);
260     return length;
261   } else {
262     m_string.clear();
263   }
264   return 0;
265 }
266 
267 int Status::SetErrorStringWithVarArg(const char *format, va_list args) {
268   if (format != nullptr && format[0]) {
269     // If we have an error string, we should always at least have
270     // an error set to a generic value.
271     if (Success())
272       SetErrorToGenericError();
273 
274     llvm::SmallString<1024> buf;
275     VASprintf(buf, format, args);
276     m_string = buf.str();
277     return buf.size();
278   } else {
279     m_string.clear();
280   }
281   return 0;
282 }
283 
284 //----------------------------------------------------------------------
285 // Returns true if the error code in this object is considered a
286 // successful return value.
287 //----------------------------------------------------------------------
288 bool Status::Success() const { return m_code == 0; }
289 
290 bool Status::WasInterrupted() const {
291   return (m_type == eErrorTypePOSIX && m_code == EINTR);
292 }
293 
294 void llvm::format_provider<lldb_private::Status>::format(
295     const lldb_private::Status &error, llvm::raw_ostream &OS,
296     llvm::StringRef Options) {
297   llvm::format_provider<llvm::StringRef>::format(error.AsCString(), OS,
298                                                  Options);
299 }
300