1 //===-- Status.cpp -----------------------------------------------*- C++
2 //-*-===//
3 //
4 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5 // See https://llvm.org/LICENSE.txt for license information.
6 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "lldb/Utility/Status.h"
11 
12 #include "lldb/Utility/VASPrintf.h"
13 #include "lldb/lldb-defines.h"
14 #include "lldb/lldb-enumerations.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/StringRef.h"
17 #include "llvm/Support/Errno.h"
18 #include "llvm/Support/FormatProviders.h"
19 
20 #include <cerrno>
21 #include <cstdarg>
22 #include <string>
23 #include <system_error>
24 
25 #ifdef __APPLE__
26 #include <mach/mach.h>
27 #endif
28 
29 #ifdef _WIN32
30 #include <windows.h>
31 #endif
32 #include <stdint.h>
33 
34 namespace llvm {
35 class raw_ostream;
36 }
37 
38 using namespace lldb;
39 using namespace lldb_private;
40 
41 Status::Status() : m_code(0), m_type(eErrorTypeInvalid), m_string() {}
42 
43 Status::Status(ValueType err, ErrorType type)
44     : m_code(err), m_type(type), m_string() {}
45 
46 Status::Status(std::error_code EC)
47     : m_code(EC.value()), m_type(ErrorType::eErrorTypeGeneric),
48       m_string(EC.message()) {}
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(
91         std::error_code(m_code, std::generic_category()));
92   return llvm::make_error<llvm::StringError>(AsCString(),
93                                              llvm::inconvertibleErrorCode());
94 }
95 
96 Status::~Status() = default;
97 
98 #ifdef _WIN32
99 static std::string RetrieveWin32ErrorString(uint32_t error_code) {
100   char *buffer = nullptr;
101   std::string message;
102   // Retrieve win32 system error.
103   if (::FormatMessageA(
104           FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
105               FORMAT_MESSAGE_MAX_WIDTH_MASK,
106           NULL, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
107           (LPSTR)&buffer, 0, NULL)) {
108     message.assign(buffer);
109     ::LocalFree(buffer);
110   }
111   return message;
112 }
113 #endif
114 
115 // Get the error value as a NULL C string. The error string will be fetched and
116 // cached on demand. The cached error string value will remain until the error
117 // value is changed or cleared.
118 const char *Status::AsCString(const char *default_error_str) const {
119   if (Success())
120     return nullptr;
121 
122   if (m_string.empty()) {
123     switch (m_type) {
124     case eErrorTypeMachKernel:
125 #if defined(__APPLE__)
126       if (const char *s = ::mach_error_string(m_code))
127         m_string.assign(s);
128 #endif
129       break;
130 
131     case eErrorTypePOSIX:
132       m_string = llvm::sys::StrError(m_code);
133       break;
134 
135     case eErrorTypeWin32:
136 #if defined(_WIN32)
137       m_string = RetrieveWin32ErrorString(m_code);
138 #endif
139       break;
140 
141     default:
142       break;
143     }
144   }
145   if (m_string.empty()) {
146     if (default_error_str)
147       m_string.assign(default_error_str);
148     else
149       return nullptr; // User wanted a nullptr string back...
150   }
151   return m_string.c_str();
152 }
153 
154 // Clear the error and any cached error string that it might contain.
155 void Status::Clear() {
156   m_code = 0;
157   m_type = eErrorTypeInvalid;
158   m_string.clear();
159 }
160 
161 // Access the error value.
162 Status::ValueType Status::GetError() const { return m_code; }
163 
164 // Access the error type.
165 ErrorType Status::GetType() const { return m_type; }
166 
167 // Returns true if this object contains a value that describes an error or
168 // otherwise non-success result.
169 bool Status::Fail() const { return m_code != 0; }
170 
171 // Set accessor for the error value to "err" and the type to
172 // "eErrorTypeMachKernel"
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 // Set accessor for the error value and type.
204 void Status::SetError(ValueType err, ErrorType type) {
205   m_code = err;
206   m_type = type;
207   m_string.clear();
208 }
209 
210 // Update the error value to be "errno" and update the type to be "POSIX".
211 void Status::SetErrorToErrno() {
212   m_code = errno;
213   m_type = eErrorTypePOSIX;
214   m_string.clear();
215 }
216 
217 // Update the error value to be LLDB_GENERIC_ERROR and update the type to be
218 // "Generic".
219 void Status::SetErrorToGenericError() {
220   m_code = LLDB_GENERIC_ERROR;
221   m_type = eErrorTypeGeneric;
222   m_string.clear();
223 }
224 
225 // Set accessor for the error string value for a specific error. This allows
226 // any string to be supplied as an error explanation. The error string value
227 // will remain until the error value is cleared or a new error value/type is
228 // assigned.
229 void Status::SetErrorString(llvm::StringRef err_str) {
230   if (!err_str.empty()) {
231     // If we have an error string, we should always at least have an error set
232     // to a generic value.
233     if (Success())
234       SetErrorToGenericError();
235   }
236   m_string = err_str;
237 }
238 
239 /// Set the current error string to a formatted error string.
240 ///
241 /// \param format
242 ///     A printf style format string
243 int Status::SetErrorStringWithFormat(const char *format, ...) {
244   if (format != nullptr && format[0]) {
245     va_list args;
246     va_start(args, format);
247     int length = SetErrorStringWithVarArg(format, args);
248     va_end(args);
249     return length;
250   } else {
251     m_string.clear();
252   }
253   return 0;
254 }
255 
256 int Status::SetErrorStringWithVarArg(const char *format, va_list args) {
257   if (format != nullptr && format[0]) {
258     // If we have an error string, we should always at least have an error set
259     // to a generic value.
260     if (Success())
261       SetErrorToGenericError();
262 
263     llvm::SmallString<1024> buf;
264     VASprintf(buf, format, args);
265     m_string = buf.str();
266     return buf.size();
267   } else {
268     m_string.clear();
269   }
270   return 0;
271 }
272 
273 // Returns true if the error code in this object is considered a successful
274 // return value.
275 bool Status::Success() const { return m_code == 0; }
276 
277 bool Status::WasInterrupted() const {
278   return (m_type == eErrorTypePOSIX && m_code == EINTR);
279 }
280 
281 void llvm::format_provider<lldb_private::Status>::format(
282     const lldb_private::Status &error, llvm::raw_ostream &OS,
283     llvm::StringRef Options) {
284   llvm::format_provider<llvm::StringRef>::format(error.AsCString(), OS,
285                                                  Options);
286 }
287